UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

165 lines • 8.41 kB
// MCP resources (todo 39): list/read/subscribe + @mcp: input-mention expansion. // // Model-facing access is two utility tools — mcp_list_resources and // mcp_read_resource — registered ONLY when at least one connected server // actually lists resources (no dead tools). User-facing convenience is the // `@mcp:<server>/<uri>` mention, expanded through the sanctioned `input` event // transform: recognized mentions are replaced inline with the fetched resource // body (output-guarded); unrecognized or failing mentions pass through // UNCHANGED with a one-line notice, never blocking the submission. Servers // declaring the resources.subscribe capability get per-resource subscriptions; // updated/list_changed notifications flow into the existing tools-changed // refresh path, so the catalog cache stays current. import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import { redactResolvedReferenceData, redactResolvedReferenceValues } from "../../../config-reference-redaction.js"; import { ToolExecError } from "./errors.js"; import { applyMcpOutputGuard } from "./guard/output-guard.js"; import { ResourceUpdatedNotificationSchema, registerMcpNotificationHandler } from "./notification-schemas.js"; import { mcpRequestOptions } from "./request-origin.js"; import { McpMrtrError } from "./modern/errors.js"; import { ensureMcpToolCallConnection } from "./health.js"; import { isModernMcpClient } from "./modern/request.js"; /** Route resource updated notifications into the shared refresh path. */ export function subscribeMcpResourceUpdated(client, onChange) { registerMcpNotificationHandler(client, ResourceUpdatedNotificationSchema, () => { onChange(); }); } /** Best-effort per-resource subscriptions when the server declares support. */ export async function ensureMcpResourceSubscriptions(client, resources) { // Modern streams derive their resource URI filter from resources/list results. if (isModernMcpClient(client)) return; if (client.getServerCapabilities()?.resources?.subscribe !== true) return; await Promise.all(resources.map((resource) => client.subscribeResource({ uri: resource.uri }).catch(() => undefined))); } /** Read one resource and flatten its contents to guarded text. */ export async function readMcpResourceAsText(server, uri, signal) { let contents; try { if (server.requestOrigin) await ensureMcpToolCallConnection(server.connection, server.ensureFresh); const result = await server.connection.client.readResource({ uri }, mcpRequestOptions(server.requestOrigin?.(), { timeout: server.requestTimeoutMs, ...(signal === undefined ? {} : { signal }), })); contents = result.contents; } catch (error) { if (error instanceof McpMrtrError) throw error; throw new ToolExecError(redactResolvedReferenceValues(`Failed to read MCP resource ${uri}: ${error instanceof Error ? error.message : String(error)}`), { phase: "call", serverName: server.server, }); } const parts = contents.map((content) => { if ("text" in content && typeof content.text === "string") return content.text; const blob = "blob" in content && typeof content.blob === "string" ? content.blob : ""; return `[binary resource ${content.uri} (${content.mimeType ?? "unknown"}), ~${Math.round((blob.length * 3) / 4)} bytes]`; }); const guarded = await applyMcpOutputGuard([{ type: "text", text: parts.join("\n") }], { agentDir: server.agentDir, artifacts: server.artifacts, outputGuard: server.outputGuard, server: server.server, }); return guarded.map((block) => ("text" in block && typeof block.text === "string" ? block.text : "")).join("\n"); } const ListParams = Type.Object({ server: Type.Optional(Type.String({ description: "Restrict to one MCP server name." })), }); const ReadParams = Type.Object({ server: Type.String({ description: "MCP server name (from mcp_list_resources)." }), uri: Type.String({ description: "Resource URI to read." }), }); /** The two model-facing utility tools. Register only when servers() is non-empty. */ export function createMcpResourceTools(servers) { const list = { name: "mcp_list_resources", label: "List MCP resources", description: "List resources exposed by connected MCP servers (URI, name, mime type).", parameters: ListParams, executionMode: "parallel", async execute(_id, params) { const scoped = servers().filter((entry) => params.server === undefined || entry.server === params.server); const lines = scoped.flatMap((entry) => entry.resources.map((resource) => `- @mcp:${entry.server}/${resource.uri} - ${resource.name ?? resource.uri}${resource.mimeType ? ` (${resource.mimeType})` : ""}`)); const text = lines.length === 0 ? "No MCP resources available." : lines.join("\n"); return { content: [{ type: "text", text: redactResolvedReferenceValues(text) }], details: { preview: `${lines.length} resource(s)`, server: params.server ?? "*", tool: "mcp_list_resources", }, }; }, renderCall(args, theme) { return new Text(theme.fg("toolTitle", theme.bold(`mcp_list_resources ${args.server ?? ""}`.trim())), 0, 0); }, }; const read = { name: "mcp_read_resource", label: "Read MCP resource", description: "Read one MCP resource by server name and URI; returns its (guarded) content.", parameters: ReadParams, executionMode: "parallel", async execute(_id, params, signal) { const entry = servers().find((candidate) => candidate.server === params.server); if (entry === undefined) { throw new ToolExecError(redactResolvedReferenceValues(`Unknown MCP server '${params.server}' for resource ${params.uri}.`), { phase: "call", serverName: params.server, }); } const text = await readMcpResourceAsText(entry, params.uri, signal); return { content: [{ type: "text", text }], details: redactResolvedReferenceData({ preview: params.uri, server: params.server, tool: "mcp_read_resource", }), }; }, renderCall(args, theme) { return new Text(theme.fg("toolTitle", theme.bold(`mcp_read_resource ${args.server}/${args.uri}`)), 0, 0); }, }; return [list, read]; } const MENTION_PATTERN = /@mcp:([A-Za-z0-9._-]+)\/(\S+)/g; /** Expand `@mcp:<server>/<uri>` mentions; failures leave the mention intact. */ export async function expandMcpResourceMentions(text, servers) { const matches = [...text.matchAll(MENTION_PATTERN)]; if (matches.length === 0) return { changed: false, notices: [], text }; const notices = []; let expanded = text; for (const match of matches) { const [mention, serverName, uri] = match; const entry = servers().find((candidate) => candidate.server === serverName); if (entry === undefined) { notices.push(`@mcp mention left as-is: unknown server '${serverName}'.`); continue; } try { const body = await readMcpResourceAsText(entry, uri); expanded = expanded.replace(mention, `<mcp-resource server="${serverName}" uri="${uri}">\n${body}\n</mcp-resource>`); } catch (error) { if (error instanceof McpMrtrError && ["MCP_MRTR_CANCELLED", "MCP_MRTR_CONTEXT_CHANGED", "MCP_MRTR_TIMEOUT"].includes(error.code)) { notices.push("MCP resource request canceled; mention left unchanged."); continue; } notices.push(`@mcp mention left as-is: ${error instanceof Error ? error.message : String(error)}`); } } const redacted = redactResolvedReferenceValues(expanded); return { changed: redacted !== text, notices: redactResolvedReferenceData(notices), text: redacted }; } //# sourceMappingURL=resources.js.map