@earendil-works/pi-coding-agent 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/bundle/chunks/{chunk-PSQJVYXD.js → chunk-2QSWSXFK.js} +4 -4
- package/dist/bundle/chunks/{chunk-AXOERKKW.js → chunk-64GOPQSC.js} +3 -1
- package/dist/bundle/chunks/{chunk-UBHCV62G.js → chunk-F4TCZWQO.js} +1 -1
- package/dist/bundle/chunks/{chunk-7TP2J6F2.js → chunk-FKGBRPJC.js} +1 -1
- package/dist/bundle/chunks/{chunk-BFNE7BHG.js → chunk-H33F2TZD.js} +28 -24
- package/dist/bundle/chunks/{chunk-J52J6TFP.js → chunk-KIPSWGXN.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSQEXT6X.js → chunk-VLMAON6X.js} +4 -4
- package/dist/bundle/chunks/{chunk-6DBOMCBS.js → chunk-XXKX4I4Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-2VBQLN7Y.js → chunk-YKYP4C4A.js} +8 -5
- package/dist/bundle/chunks/{cli-HTJP6F6Z.js → cli-FRW732V6.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +99 -3
- package/dist/bundle/chunks/{easter-egg-3d-6YCNESG3.js → easter-egg-3d-GBYHZI2E.js} +1 -1
- package/dist/bundle/chunks/{execute-JRUOLYDA.js → execute-MNHU53Y5.js} +101 -5
- package/dist/bundle/chunks/{runtime-NW7GPWKS.js → runtime-FW2HXAJ6.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-CFHJO5SY.js → virtual-modules-LQIMBBGM.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +11 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +26 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +47 -14
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +8 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +30 -7
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/resource-loader.d.ts +3 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +9 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/skills.d.ts +4 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +6 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +9 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/read.d.ts +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +18 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +2 -1
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +1 -0
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +9 -2
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +12 -4
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +3 -4
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +3 -4
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +22 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +2 -1
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +6 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/cli.md +15 -3
- package/docs/codemode.md +3 -2
- package/docs/extensions.md +1 -1
- package/docs/mcp.md +3 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/extensions/mcp/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,aAAa,E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EAAE,CAAC;IACpC,CAAC;CACD","sourcesContent":["/**\n * The part of the MCP integration that talks to servers: connections, transports, and OAuth\n * sign-in. It pulls in the MCP client, so index.ts loads it through runtime.lazy.ts only when a\n * server is configured.\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n\ttype AuthProvider,\n\ttype CallToolResult,\n\tJSON_RPC_ERROR_CODES,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tMcpAuthRequiredError,\n\tMcpClient,\n\tMcpError,\n\tMcpHttpError,\n\ttype McpRequestOptions,\n\tMcpSessionExpiredError,\n\ttype Tool as McpTool,\n\ttype McpTransport,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\tStdioTransport,\n\tStreamableHttpTransport,\n} from \"@earendil-works/pi-mcp\";\nimport { McpOAuthAuthorizationRequiredError, type OAuthChallenge } from \"@earendil-works/pi-mcp/oauth\";\nimport { VERSION } from \"../../config.ts\";\nimport { resolveConfigValueOrThrow, resolveHeadersOrThrow } from \"../../core/resolve-config-value.ts\";\nimport type { McpServerEntry } from \"./config.ts\";\nimport type { McpServerLog } from \"./log.ts\";\nimport {\n\tcreateMcpAuthProvider,\n\ttype McpAuthProvider,\n\ttype McpOAuthCredentialStore,\n\ttype McpOAuthSettings,\n} from \"./oauth.ts\";\nimport { isMcpAppResource, type McpResourceServer } from \"./resources.ts\";\nimport type { McpToolCaller } from \"./tools.ts\";\n\nexport { McpServerLog } from \"./log.ts\";\nexport { McpOAuthCredentialStore, McpSignInCancelledError, signInMcpServer } from \"./oauth.ts\";\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\nconst STDERR_TAIL_CHARS = 2_000;\n/** Delays between attempts to connect to an HTTP server that failed with a transient error. */\nconst CONNECT_RETRY_DELAYS_MS = [250, 1_000];\n\n/**\n * `disconnected`: the connection dropped (for example the stdio server exited); the next call\n * reconnects.\n */\ntype ServerState = \"connecting\" | \"connected\" | \"disconnected\" | \"needs-auth\" | \"failed\" | \"closed\";\n\nexport type McpTransportFactory = (\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n) => McpTransport;\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Network failures and overloaded or restarting servers, which are worth another attempt. */\nfunction isTransientError(error: unknown): boolean {\n\tif (error instanceof McpHttpError) {\n\t\treturn error.status === 408 || error.status === 429 || (error.status >= 500 && error.status !== 501);\n\t}\n\treturn error instanceof TypeError;\n}\n\nfunction signInRequiredMessage(entry: McpServerEntry): string {\n\tconst provider = \"url\" in entry.config ? entry.config.auth?.provider : undefined;\n\treturn `MCP server \"${entry.name}\" requires sign-in. Run ${provider ? `/login ${provider}` : \"/mcp\"} to sign in.`;\n}\n\n/** HTTP servers authenticate with OAuth unless the config supplies an `Authorization` header or `auth`. */\nfunction usesOAuth(entry: McpServerEntry): boolean {\n\tconst { config } = entry;\n\tif (!(\"url\" in config) || config.auth) return false;\n\treturn !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n}\n\n/** `~` and `~/…` (also `~\\…` on Windows) name the home directory, like in a shell. */\nfunction expandHome(value: string): string {\n\tif (value === \"~\") return homedir();\n\tif (value.startsWith(\"~/\") || (process.platform === \"win32\" && value.startsWith(\"~\\\\\"))) {\n\t\treturn join(homedir(), value.slice(2));\n\t}\n\treturn value;\n}\n\nexport function createDefaultTransport(\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n): McpTransport {\n\tconst { config, name } = entry;\n\tif (\"url\" in config) {\n\t\treturn new StreamableHttpTransport({\n\t\t\turl: config.url,\n\t\t\theaders: resolveHeadersOrThrow(config.headers, `MCP server \"${name}\"`),\n\t\t\tauthProvider,\n\t\t});\n\t}\n\tconst env: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(config.env ?? {})) {\n\t\tenv[key] = resolveConfigValueOrThrow(value, `MCP server \"${name}\" env \"${key}\"`);\n\t}\n\treturn new StdioTransport({\n\t\tcommand: expandHome(config.command),\n\t\targs: config.args?.map(expandHome),\n\t\tcwd: resolve(cwd, expandHome(config.cwd ?? \".\")),\n\t\tenv,\n\t\tstderr: \"pipe\",\n\t});\n}\n\n/** Servers that do not implement `resources/templates/list` have no templates. */\nasync function withoutTemplates<T>(list: () => Promise<T>, empty: T): Promise<T> {\n\ttry {\n\t\treturn await list();\n\t} catch (error) {\n\t\tif (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound) return empty;\n\t\tthrow error;\n\t}\n}\n\nfunction listTemplates(client: McpClient, options: McpRequestOptions = {}): Promise<ResourceTemplate[]> {\n\treturn withoutTemplates(() => client.listResourceTemplates(options), []);\n}\n\n/**\n * Resources and templates at connect time, for the counts in `/mcp` and `pi mcp list`. A server\n * whose lists fail still connects: the resource tools list and read its resources on demand.\n */\nasync function fetchResources(\n\tclient: McpClient,\n): Promise<{ resources: Resource[]; resourceTemplates: ResourceTemplate[] }> {\n\tconst [resources, resourceTemplates] = await Promise.all([\n\t\tclient.listResources().catch(() => []),\n\t\tlistTemplates(client).catch(() => []),\n\t]);\n\treturn {\n\t\tresources: resources.filter((resource) => !isMcpAppResource(resource)),\n\t\tresourceTemplates: resourceTemplates.filter((template) => !isMcpAppResource(template)),\n\t};\n}\n\n/** One configured server. Reconnects lazily when a call finds the connection gone. */\nexport class McpServerConnection implements McpToolCaller, McpResourceServer {\n\treadonly entry: McpServerEntry;\n\tstate: ServerState = \"connecting\";\n\terror: string | undefined;\n\ttools: McpTool[] = [];\n\t/**\n\t * Whether the server offers resources. The lists below are what it listed at the last connect or\n\t * change, without MCP App resources.\n\t */\n\thasResources = false;\n\tresources: Resource[] = [];\n\tresourceTemplates: ResourceTemplate[] = [];\n\t/** Server instructions from `initialize`, describing its tools as a group. */\n\tinstructions: string | undefined;\n\t/** Last OAuth challenge from the server; sign-in uses its resource metadata URL and scope. */\n\tchallenge: OAuthChallenge | undefined;\n\tprivate client: McpClient | undefined;\n\tprivate opening: Promise<McpClient> | undefined;\n\tprivate closed = false;\n\t/** Stderr of the last stdio server that failed to connect. */\n\tprivate stderrTail: string | undefined;\n\tprivate readonly cwd: string;\n\tprivate readonly createTransport: McpTransportFactory;\n\tprivate readonly authProvider: McpAuthProvider | undefined;\n\tprivate readonly onTools: (connection: McpServerConnection) => void;\n\tprivate readonly onChange: ((connection: McpServerConnection) => void) | undefined;\n\tprivate readonly log: McpServerLog | undefined;\n\n\tconstructor(options: {\n\t\tentry: McpServerEntry;\n\t\tcwd: string;\n\t\tcreateTransport: McpTransportFactory;\n\t\tcredentials: McpOAuthCredentialStore;\n\t\t/** The current token of a pi provider, for servers with `auth.provider`. */\n\t\tproviderToken?: (provider: string) => Promise<string | undefined>;\n\t\tonTools: (connection: McpServerConnection) => void;\n\t\t/** Called when `state`, `error`, or `tools` change. */\n\t\tonChange?: (connection: McpServerConnection) => void;\n\t\t/** Receives the server's log messages (`notifications/message`). */\n\t\tlog?: McpServerLog;\n\t}) {\n\t\tthis.entry = options.entry;\n\t\tthis.cwd = options.cwd;\n\t\tthis.createTransport = options.createTransport;\n\t\tthis.onTools = options.onTools;\n\t\tthis.onChange = options.onChange;\n\t\tthis.log = options.log;\n\t\tconst url = this.oauthUrl;\n\t\tconst provider = \"url\" in this.entry.config ? this.entry.config.auth?.provider : undefined;\n\t\tthis.authProvider = url\n\t\t\t? createMcpAuthProvider({\n\t\t\t\t\tserverUrl: url,\n\t\t\t\t\tstore: options.credentials.forServer(this.entry.name, url),\n\t\t\t\t\tsettings: () => this.oauthSettings(),\n\t\t\t\t\tonChallenge: (challenge) => {\n\t\t\t\t\t\tthis.challenge = challenge;\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: provider\n\t\t\t\t? // Read on every request, so the provider's refreshes apply; MCP stores no copy.\n\t\t\t\t\t{ token: async () => options.providerToken?.(provider), settled: async () => {} }\n\t\t\t\t: undefined;\n\t}\n\n\tget name(): string {\n\t\treturn this.entry.name;\n\t}\n\n\tget timeoutMs(): number {\n\t\treturn (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n\t}\n\n\t/** Server URL when the server authenticates with OAuth. */\n\tget oauthUrl(): string | undefined {\n\t\treturn usesOAuth(this.entry) && \"url\" in this.entry.config ? this.entry.config.url : undefined;\n\t}\n\n\toauthSettings(): McpOAuthSettings {\n\t\tconst oauth = \"url\" in this.entry.config ? this.entry.config.oauth : undefined;\n\t\tif (!oauth) return {};\n\t\treturn {\n\t\t\tclientId: oauth.clientId,\n\t\t\tclientSecret:\n\t\t\t\toauth.clientSecret === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resolveConfigValueOrThrow(oauth.clientSecret, `MCP server \"${this.entry.name}\" oauth.clientSecret`),\n\t\t\tcallbackPort: oauth.callbackPort,\n\t\t\tcallbackUrl: oauth.callbackUrl,\n\t\t\tscope: oauth.scope,\n\t\t\tclientName: oauth.clientName,\n\t\t\tclientRegistration: oauth.clientRegistration,\n\t\t\tauthServerMetadataUrl: oauth.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : undefined,\n\t\t};\n\t}\n\n\tgetClient(): Promise<McpClient> {\n\t\tif (this.closed) return Promise.reject(new Error(`MCP server \"${this.entry.name}\" is shut down`));\n\t\tif (this.client?.connectionState === \"connected\") return Promise.resolve(this.client);\n\t\tthis.opening ??= this.open().finally(() => {\n\t\t\tthis.opening = undefined;\n\t\t});\n\t\treturn this.opening;\n\t}\n\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult> {\n\t\treturn this.withClient((client) => client.callTool(name, args, options));\n\t}\n\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult> {\n\t\treturn this.withClient((client) => client.readResource(uri, options), true);\n\t}\n\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult> {\n\t\treturn this.withClient((client) => client.listResourcesPage(cursor, options), true);\n\t}\n\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult> {\n\t\treturn this.withClient(\n\t\t\t(client) =>\n\t\t\t\twithoutTemplates(() => client.listResourceTemplatesPage(cursor, options), { resourceTemplates: [] }),\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tallResources(options: McpRequestOptions): Promise<Resource[]> {\n\t\treturn this.withClient((client) => client.listResources(options), true);\n\t}\n\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]> {\n\t\treturn this.withClient((client) => listTemplates(client, options), true);\n\t}\n\n\t/**\n\t * Run a request, reconnecting when needed. `readOnly` requests are retried once after a transient\n\t * HTTP error; tool calls are not, since they may have run.\n\t */\n\tprivate async withClient<T>(run: (client: McpClient) => Promise<T>, readOnly = false): Promise<T> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst client = await this.getClient();\n\t\t\ttry {\n\t\t\t\treturn await run(client);\n\t\t\t} catch (error) {\n\t\t\t\tif (readOnly && attempt === 1 && error instanceof McpHttpError && isTransientError(error)) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_DELAYS_MS[0]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error instanceof McpSessionExpiredError && attempt === 1) {\n\t\t\t\t\t// The server no longer knows the session (restart, deploy), so it did not run the request.\n\t\t\t\t\t// Retry once on a new session. The old client is detached but not closed: closing would\n\t\t\t\t\t// fail its other in-flight calls, which instead get the same 404 and retry the same way.\n\t\t\t\t\tif (this.client === client) this.client = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!this.needsSignIn(error)) throw error;\n\t\t\t\tawait this.dropClient(client);\n\t\t\t\tthis.markNeedsAuth();\n\t\t\t\tthrow new Error(signInRequiredMessage(this.entry));\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Connect again with fresh credentials, for example after signing in. */\n\tasync reconnect(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tawait this.getClient();\n\t}\n\n\t/** Disconnect after the stored credentials were removed. */\n\tasync signOut(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tif (!this.closed) this.markNeedsAuth();\n\t}\n\n\t/** OAuth servers that still reject the request after a refresh need the user to sign in again. */\n\tprivate needsSignIn(error: unknown): boolean {\n\t\treturn (\n\t\t\terror instanceof McpOAuthAuthorizationRequiredError ||\n\t\t\t(this.authProvider !== undefined && error instanceof McpAuthRequiredError)\n\t\t);\n\t}\n\n\tprivate markNeedsAuth(): void {\n\t\tthis.state = \"needs-auth\";\n\t\tthis.error = undefined;\n\t\tthis.changed();\n\t}\n\n\tprivate changed(): void {\n\t\tthis.onChange?.(this);\n\t}\n\n\tprivate async dropClient(client: McpClient): Promise<void> {\n\t\tif (this.client === client) this.client = undefined;\n\t\tawait client.close().catch(() => undefined);\n\t}\n\n\tprivate async open(): Promise<McpClient> {\n\t\tthis.state = \"connecting\";\n\t\tthis.changed();\n\t\tconst retries = \"url\" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tthis.stderrTail = undefined;\n\t\t\ttry {\n\t\t\t\treturn await this.connectOnce();\n\t\t\t} catch (error) {\n\t\t\t\tconst delay = retries[attempt];\n\t\t\t\tif (this.closed || delay === undefined || !isTransientError(error)) {\n\t\t\t\t\tthrow this.connectFailed(error);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t\tif (this.closed) throw this.connectFailed(error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async connectOnce(): Promise<McpClient> {\n\t\tconst client = new McpClient({\n\t\t\tname: \"pi\",\n\t\t\tversion: VERSION,\n\t\t\trequestTimeoutMs: this.timeoutMs,\n\t\t\troots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }],\n\t\t});\n\t\tconst log = this.log;\n\t\tif (log) client.onNotification(\"notifications/message\", (params) => log.write(this.entry.name, params));\n\t\tlet transport: McpTransport | undefined;\n\t\ttry {\n\t\t\ttransport = this.createTransport(this.entry, this.cwd, this.authProvider);\n\t\t\tawait client.connect(transport);\n\t\t\tclient.onNotification(\"notifications/tools/list_changed\", () => {\n\t\t\t\tvoid this.refreshTools(client);\n\t\t\t});\n\t\t\tclient.onNotification(\"notifications/resources/list_changed\", () => {\n\t\t\t\tvoid this.refreshResources(client);\n\t\t\t});\n\t\t\tconst stdio = transport instanceof StdioTransport ? transport : undefined;\n\t\t\tclient.onClose(() => this.handleClientClose(client, stdio));\n\t\t\t// Servers without the tools capability (prompts or resources only) do not answer tools/list.\n\t\t\tconst hasResources = client.serverCapabilities?.resources !== undefined;\n\t\t\tconst [tools, resources] = await Promise.all([\n\t\t\t\tclient.serverCapabilities?.tools ? client.listTools() : [],\n\t\t\t\thasResources ? fetchResources(client) : { resources: [], resourceTemplates: [] },\n\t\t\t]);\n\t\t\tif (this.closed) throw new Error(\"shut down while connecting\");\n\t\t\tif (client.connectionState !== \"connected\") throw new Error(\"connection closed during setup\");\n\t\t\tthis.client = client;\n\t\t\tthis.tools = tools;\n\t\t\tthis.hasResources = hasResources;\n\t\t\tthis.resources = resources.resources;\n\t\t\tthis.resourceTemplates = resources.resourceTemplates;\n\t\t\tthis.instructions = client.instructions?.trim() || undefined;\n\t\t\tthis.state = \"connected\";\n\t\t\tthis.error = undefined;\n\t\t\tthis.onTools(this);\n\t\t\tthis.changed();\n\t\t\treturn client;\n\t\t} catch (error) {\n\t\t\tawait client.close().catch(() => undefined);\n\t\t\tif (transport instanceof StdioTransport) {\n\t\t\t\tthis.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate connectFailed(error: unknown): Error {\n\t\tif (this.needsSignIn(error) && !this.closed) {\n\t\t\tthis.markNeedsAuth();\n\t\t\treturn new Error(signInRequiredMessage(this.entry));\n\t\t}\n\t\tthis.state = this.closed ? \"closed\" : \"failed\";\n\t\tthis.error = this.stderrTail ? `${errorMessage(error)}\\n${this.stderrTail}` : errorMessage(error);\n\t\tthis.changed();\n\t\treturn new Error(`MCP server \"${this.entry.name}\" failed to connect: ${this.error}`);\n\t}\n\n\t/** The transport dropped. The next call reconnects; until then the status shows why. */\n\tprivate handleClientClose(client: McpClient, stdio: StdioTransport | undefined): void {\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.client = undefined;\n\t\tthis.state = \"disconnected\";\n\t\tconst stderr = stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);\n\t\tthis.error = stderr ? `Connection closed\\n${stderr}` : \"Connection closed\";\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshTools(client: McpClient): Promise<void> {\n\t\ttry {\n\t\t\tconst tools = await client.listTools();\n\t\t\tif (this.client !== client || this.closed) return;\n\t\t\tthis.tools = tools;\n\t\t\tthis.onTools(this);\n\t\t} catch (error) {\n\t\t\tthis.error = `Failed to refresh tools: ${errorMessage(error)}`;\n\t\t}\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshResources(client: McpClient): Promise<void> {\n\t\tconst { resources, resourceTemplates } = await fetchResources(client);\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.resources = resources;\n\t\tthis.resourceTemplates = resourceTemplates;\n\t\tthis.onTools(this);\n\t\tthis.changed();\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tthis.state = \"closed\";\n\t\tthis.changed();\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tawait client?.close().catch(() => undefined);\n\t\t// A refresh the server already answered may have rotated the refresh token; exiting before the\n\t\t// new tokens are saved would lose the grant.\n\t\tawait this.authProvider?.settled();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/ext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,IAAI,CAAC,OAAO,EAAE,CAAC;IAChB,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,MAAiB;QAC/C,MAAM,EAAE,SAAS,EAAE,iBAAiB,EAAE,GAAG,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC;QACtE,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QAClD,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,EAAE,CAAC;IAChB,CAAC;IAED,kGAAkG;IAClG,KAAK,CAAC,KAAK;QACV,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC;QACtB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAClG,+FAA+F;QAC/F,6CAA6C;QAC7C,MAAM,IAAI,CAAC,YAAY,EAAE,OAAO,EAAE,CAAC;IACpC,CAAC;CACD","sourcesContent":["/**\n * The part of the MCP integration that talks to servers: connections, transports, and OAuth\n * sign-in. It pulls in the MCP client, so index.ts loads it through runtime.lazy.ts only when a\n * server is configured.\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n\ttype AuthProvider,\n\ttype CallToolResult,\n\tJSON_RPC_ERROR_CODES,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\tMcpAuthRequiredError,\n\tMcpClient,\n\tMcpError,\n\tMcpHttpError,\n\ttype McpRequestOptions,\n\tMcpSessionExpiredError,\n\ttype Tool as McpTool,\n\ttype McpTransport,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\tStdioTransport,\n\tStreamableHttpTransport,\n} from \"@earendil-works/pi-mcp\";\nimport { McpOAuthAuthorizationRequiredError, type OAuthChallenge } from \"@earendil-works/pi-mcp/oauth\";\nimport { VERSION } from \"../../config.ts\";\nimport { resolveConfigValueOrThrow, resolveHeadersOrThrow } from \"../../core/resolve-config-value.ts\";\nimport type { McpServerEntry } from \"./config.ts\";\nimport type { McpServerLog } from \"./log.ts\";\nimport {\n\tcreateMcpAuthProvider,\n\ttype McpAuthProvider,\n\ttype McpOAuthCredentialStore,\n\ttype McpOAuthSettings,\n} from \"./oauth.ts\";\nimport { isMcpAppResource, type McpResourceServer } from \"./resources.ts\";\nimport type { McpToolCaller } from \"./tools.ts\";\n\nexport { McpServerLog } from \"./log.ts\";\nexport { McpOAuthCredentialStore, McpSignInCancelledError, signInMcpServer } from \"./oauth.ts\";\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\nconst STDERR_TAIL_CHARS = 2_000;\n/** Delays between attempts to connect to an HTTP server that failed with a transient error. */\nconst CONNECT_RETRY_DELAYS_MS = [250, 1_000];\n\n/**\n * `disconnected`: the connection dropped (for example the stdio server exited); the next call\n * reconnects.\n */\ntype ServerState = \"connecting\" | \"connected\" | \"disconnected\" | \"needs-auth\" | \"failed\" | \"closed\";\n\nexport type McpTransportFactory = (\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n) => McpTransport;\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Network failures and overloaded or restarting servers, which are worth another attempt. */\nfunction isTransientError(error: unknown): boolean {\n\tif (error instanceof McpHttpError) {\n\t\treturn error.status === 408 || error.status === 429 || (error.status >= 500 && error.status !== 501);\n\t}\n\treturn error instanceof TypeError;\n}\n\nfunction signInRequiredMessage(entry: McpServerEntry): string {\n\tconst provider = \"url\" in entry.config ? entry.config.auth?.provider : undefined;\n\treturn `MCP server \"${entry.name}\" requires sign-in. Run ${provider ? `/login ${provider}` : \"/mcp\"} to sign in.`;\n}\n\n/** HTTP servers authenticate with OAuth unless the config supplies an `Authorization` header or `auth`. */\nfunction usesOAuth(entry: McpServerEntry): boolean {\n\tconst { config } = entry;\n\tif (!(\"url\" in config) || config.auth) return false;\n\treturn !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n}\n\n/** `~` and `~/…` (also `~\\…` on Windows) name the home directory, like in a shell. */\nfunction expandHome(value: string): string {\n\tif (value === \"~\") return homedir();\n\tif (value.startsWith(\"~/\") || (process.platform === \"win32\" && value.startsWith(\"~\\\\\"))) {\n\t\treturn join(homedir(), value.slice(2));\n\t}\n\treturn value;\n}\n\nexport function createDefaultTransport(\n\tentry: McpServerEntry,\n\tcwd: string,\n\tauthProvider: AuthProvider | undefined,\n): McpTransport {\n\tconst { config, name } = entry;\n\tif (\"url\" in config) {\n\t\treturn new StreamableHttpTransport({\n\t\t\turl: config.url,\n\t\t\theaders: resolveHeadersOrThrow(config.headers, `MCP server \"${name}\"`),\n\t\t\tauthProvider,\n\t\t});\n\t}\n\tconst env: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(config.env ?? {})) {\n\t\tenv[key] = resolveConfigValueOrThrow(value, `MCP server \"${name}\" env \"${key}\"`);\n\t}\n\treturn new StdioTransport({\n\t\tcommand: expandHome(config.command),\n\t\targs: config.args?.map(expandHome),\n\t\tcwd: resolve(cwd, expandHome(config.cwd ?? \".\")),\n\t\tenv,\n\t\tstderr: \"pipe\",\n\t});\n}\n\n/** Servers that do not implement `resources/templates/list` have no templates. */\nasync function withoutTemplates<T>(list: () => Promise<T>, empty: T): Promise<T> {\n\ttry {\n\t\treturn await list();\n\t} catch (error) {\n\t\tif (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound) return empty;\n\t\tthrow error;\n\t}\n}\n\nfunction listTemplates(client: McpClient, options: McpRequestOptions = {}): Promise<ResourceTemplate[]> {\n\treturn withoutTemplates(() => client.listResourceTemplates(options), []);\n}\n\n/**\n * Resources and templates at connect time, for the counts in `/mcp` and `pi mcp list`. A server\n * whose lists fail still connects: the resource tools list and read its resources on demand.\n */\nasync function fetchResources(\n\tclient: McpClient,\n): Promise<{ resources: Resource[]; resourceTemplates: ResourceTemplate[] }> {\n\tconst [resources, resourceTemplates] = await Promise.all([\n\t\tclient.listResources().catch(() => []),\n\t\tlistTemplates(client).catch(() => []),\n\t]);\n\treturn {\n\t\tresources: resources.filter((resource) => !isMcpAppResource(resource)),\n\t\tresourceTemplates: resourceTemplates.filter((template) => !isMcpAppResource(template)),\n\t};\n}\n\n/** One configured server. Reconnects lazily when a call finds the connection gone. */\nexport class McpServerConnection implements McpToolCaller, McpResourceServer {\n\treadonly entry: McpServerEntry;\n\tstate: ServerState = \"connecting\";\n\terror: string | undefined;\n\ttools: McpTool[] = [];\n\t/**\n\t * Whether the server offers resources. The lists below are what it listed at the last connect or\n\t * change, without MCP App resources.\n\t */\n\thasResources = false;\n\tresources: Resource[] = [];\n\tresourceTemplates: ResourceTemplate[] = [];\n\t/** Server instructions from `initialize`, describing its tools as a group. */\n\tinstructions: string | undefined;\n\t/** Last OAuth challenge from the server; sign-in uses its resource metadata URL and scope. */\n\tchallenge: OAuthChallenge | undefined;\n\tprivate client: McpClient | undefined;\n\tprivate opening: Promise<McpClient> | undefined;\n\t/** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */\n\tprivate readonly shutdown = new AbortController();\n\t/** Stderr of the last stdio server that failed to connect. */\n\tprivate stderrTail: string | undefined;\n\tprivate readonly cwd: string;\n\tprivate readonly createTransport: McpTransportFactory;\n\tprivate readonly authProvider: McpAuthProvider | undefined;\n\tprivate readonly onTools: (connection: McpServerConnection) => void;\n\tprivate readonly onChange: ((connection: McpServerConnection) => void) | undefined;\n\tprivate readonly log: McpServerLog | undefined;\n\n\tconstructor(options: {\n\t\tentry: McpServerEntry;\n\t\tcwd: string;\n\t\tcreateTransport: McpTransportFactory;\n\t\tcredentials: McpOAuthCredentialStore;\n\t\t/** The current token of a pi provider, for servers with `auth.provider`. */\n\t\tproviderToken?: (provider: string) => Promise<string | undefined>;\n\t\tonTools: (connection: McpServerConnection) => void;\n\t\t/** Called when `state`, `error`, or `tools` change. */\n\t\tonChange?: (connection: McpServerConnection) => void;\n\t\t/** Receives the server's log messages (`notifications/message`). */\n\t\tlog?: McpServerLog;\n\t}) {\n\t\tthis.entry = options.entry;\n\t\tthis.cwd = options.cwd;\n\t\tthis.createTransport = options.createTransport;\n\t\tthis.onTools = options.onTools;\n\t\tthis.onChange = options.onChange;\n\t\tthis.log = options.log;\n\t\tconst url = this.oauthUrl;\n\t\tconst provider = \"url\" in this.entry.config ? this.entry.config.auth?.provider : undefined;\n\t\tthis.authProvider = url\n\t\t\t? createMcpAuthProvider({\n\t\t\t\t\tserverUrl: url,\n\t\t\t\t\tstore: options.credentials.forServer(this.entry.name, url),\n\t\t\t\t\tsettings: () => this.oauthSettings(),\n\t\t\t\t\tonChallenge: (challenge) => {\n\t\t\t\t\t\tthis.challenge = challenge;\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: provider\n\t\t\t\t? // Read on every request, so the provider's refreshes apply; MCP stores no copy.\n\t\t\t\t\t{ token: async () => options.providerToken?.(provider), settled: async () => {} }\n\t\t\t\t: undefined;\n\t}\n\n\tget name(): string {\n\t\treturn this.entry.name;\n\t}\n\n\tprivate get closed(): boolean {\n\t\treturn this.shutdown.signal.aborted;\n\t}\n\n\tget timeoutMs(): number {\n\t\treturn (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n\t}\n\n\t/** Server URL when the server authenticates with OAuth. */\n\tget oauthUrl(): string | undefined {\n\t\treturn usesOAuth(this.entry) && \"url\" in this.entry.config ? this.entry.config.url : undefined;\n\t}\n\n\toauthSettings(): McpOAuthSettings {\n\t\tconst oauth = \"url\" in this.entry.config ? this.entry.config.oauth : undefined;\n\t\tif (!oauth) return {};\n\t\treturn {\n\t\t\tclientId: oauth.clientId,\n\t\t\tclientSecret:\n\t\t\t\toauth.clientSecret === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resolveConfigValueOrThrow(oauth.clientSecret, `MCP server \"${this.entry.name}\" oauth.clientSecret`),\n\t\t\tcallbackPort: oauth.callbackPort,\n\t\t\tcallbackUrl: oauth.callbackUrl,\n\t\t\tscope: oauth.scope,\n\t\t\tclientName: oauth.clientName,\n\t\t\tclientRegistration: oauth.clientRegistration,\n\t\t\tauthServerMetadataUrl: oauth.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : undefined,\n\t\t};\n\t}\n\n\tgetClient(): Promise<McpClient> {\n\t\tif (this.closed) return Promise.reject(new Error(`MCP server \"${this.entry.name}\" is shut down`));\n\t\tif (this.client?.connectionState === \"connected\") return Promise.resolve(this.client);\n\t\tthis.opening ??= this.open().finally(() => {\n\t\t\tthis.opening = undefined;\n\t\t});\n\t\treturn this.opening;\n\t}\n\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult> {\n\t\treturn this.withClient((client) => client.callTool(name, args, options));\n\t}\n\n\treadResource(uri: string, options: McpRequestOptions): Promise<ReadResourceResult> {\n\t\treturn this.withClient((client) => client.readResource(uri, options), true);\n\t}\n\n\tresourcesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourcesResult> {\n\t\treturn this.withClient((client) => client.listResourcesPage(cursor, options), true);\n\t}\n\n\tresourceTemplatesPage(cursor: string | undefined, options: McpRequestOptions): Promise<ListResourceTemplatesResult> {\n\t\treturn this.withClient(\n\t\t\t(client) =>\n\t\t\t\twithoutTemplates(() => client.listResourceTemplatesPage(cursor, options), { resourceTemplates: [] }),\n\t\t\ttrue,\n\t\t);\n\t}\n\n\tallResources(options: McpRequestOptions): Promise<Resource[]> {\n\t\treturn this.withClient((client) => client.listResources(options), true);\n\t}\n\n\tallResourceTemplates(options: McpRequestOptions): Promise<ResourceTemplate[]> {\n\t\treturn this.withClient((client) => listTemplates(client, options), true);\n\t}\n\n\t/**\n\t * Run a request, reconnecting when needed. `readOnly` requests are retried once after a transient\n\t * HTTP error; tool calls are not, since they may have run.\n\t */\n\tprivate async withClient<T>(run: (client: McpClient) => Promise<T>, readOnly = false): Promise<T> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst client = await this.getClient();\n\t\t\ttry {\n\t\t\t\treturn await run(client);\n\t\t\t} catch (error) {\n\t\t\t\tif (readOnly && attempt === 1 && error instanceof McpHttpError && isTransientError(error)) {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_DELAYS_MS[0]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (error instanceof McpSessionExpiredError && attempt === 1) {\n\t\t\t\t\t// The server no longer knows the session (restart, deploy), so it did not run the request.\n\t\t\t\t\t// Retry once on a new session. The old client is detached but not closed: closing would\n\t\t\t\t\t// fail its other in-flight calls, which instead get the same 404 and retry the same way.\n\t\t\t\t\tif (this.client === client) this.client = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!this.needsSignIn(error)) throw error;\n\t\t\t\tawait this.dropClient(client);\n\t\t\t\tthis.markNeedsAuth();\n\t\t\t\tthrow new Error(signInRequiredMessage(this.entry));\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Connect again with fresh credentials, for example after signing in. */\n\tasync reconnect(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tawait this.getClient();\n\t}\n\n\t/** Disconnect after the stored credentials were removed. */\n\tasync signOut(): Promise<void> {\n\t\tawait this.opening?.catch(() => undefined);\n\t\tif (this.client) await this.dropClient(this.client);\n\t\tif (!this.closed) this.markNeedsAuth();\n\t}\n\n\t/** OAuth servers that still reject the request after a refresh need the user to sign in again. */\n\tprivate needsSignIn(error: unknown): boolean {\n\t\treturn (\n\t\t\terror instanceof McpOAuthAuthorizationRequiredError ||\n\t\t\t(this.authProvider !== undefined && error instanceof McpAuthRequiredError)\n\t\t);\n\t}\n\n\tprivate markNeedsAuth(): void {\n\t\tthis.state = \"needs-auth\";\n\t\tthis.error = undefined;\n\t\tthis.changed();\n\t}\n\n\tprivate changed(): void {\n\t\tthis.onChange?.(this);\n\t}\n\n\tprivate async dropClient(client: McpClient): Promise<void> {\n\t\tif (this.client === client) this.client = undefined;\n\t\tawait client.close().catch(() => undefined);\n\t}\n\n\tprivate async open(): Promise<McpClient> {\n\t\tthis.state = \"connecting\";\n\t\tthis.changed();\n\t\tconst retries = \"url\" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tthis.stderrTail = undefined;\n\t\t\ttry {\n\t\t\t\treturn await this.connectOnce();\n\t\t\t} catch (error) {\n\t\t\t\tconst delay = retries[attempt];\n\t\t\t\tif (this.closed || delay === undefined || !isTransientError(error)) {\n\t\t\t\t\tthrow this.connectFailed(error);\n\t\t\t\t}\n\t\t\t\tawait sleep(delay, undefined, { signal: this.shutdown.signal }).catch(() => undefined);\n\t\t\t\tif (this.closed) throw this.connectFailed(error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async connectOnce(): Promise<McpClient> {\n\t\tconst client = new McpClient({\n\t\t\tname: \"pi\",\n\t\t\tversion: VERSION,\n\t\t\trequestTimeoutMs: this.timeoutMs,\n\t\t\troots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }],\n\t\t});\n\t\tconst log = this.log;\n\t\tif (log) client.onNotification(\"notifications/message\", (params) => log.write(this.entry.name, params));\n\t\t// Closing the client fails its pending initialize or discovery requests and closes the transport.\n\t\t// Memoized: a second `client.close()` returns before the first finished closing the transport.\n\t\tlet closing: Promise<void> | undefined;\n\t\tconst closeClient = () => {\n\t\t\tclosing ??= client.close().catch(() => undefined);\n\t\t\treturn closing;\n\t\t};\n\t\tthis.shutdown.signal.addEventListener(\"abort\", closeClient, { once: true });\n\t\tlet transport: McpTransport | undefined;\n\t\ttry {\n\t\t\ttransport = this.createTransport(this.entry, this.cwd, this.authProvider);\n\t\t\tawait client.connect(transport);\n\t\t\tclient.onNotification(\"notifications/tools/list_changed\", () => {\n\t\t\t\tvoid this.refreshTools(client);\n\t\t\t});\n\t\t\tclient.onNotification(\"notifications/resources/list_changed\", () => {\n\t\t\t\tvoid this.refreshResources(client);\n\t\t\t});\n\t\t\tconst stdio = transport instanceof StdioTransport ? transport : undefined;\n\t\t\tclient.onClose(() => this.handleClientClose(client, stdio));\n\t\t\t// Servers without the tools capability (prompts or resources only) do not answer tools/list.\n\t\t\tconst hasResources = client.serverCapabilities?.resources !== undefined;\n\t\t\tconst [tools, resources] = await Promise.all([\n\t\t\t\tclient.serverCapabilities?.tools ? client.listTools() : [],\n\t\t\t\thasResources ? fetchResources(client) : { resources: [], resourceTemplates: [] },\n\t\t\t]);\n\t\t\tif (this.closed) throw new Error(\"shut down while connecting\");\n\t\t\tif (client.connectionState !== \"connected\") throw new Error(\"connection closed during setup\");\n\t\t\tthis.client = client;\n\t\t\tthis.tools = tools;\n\t\t\tthis.hasResources = hasResources;\n\t\t\tthis.resources = resources.resources;\n\t\t\tthis.resourceTemplates = resources.resourceTemplates;\n\t\t\tthis.instructions = client.instructions?.trim() || undefined;\n\t\t\tthis.state = \"connected\";\n\t\t\tthis.error = undefined;\n\t\t\tthis.onTools(this);\n\t\t\tthis.changed();\n\t\t\treturn client;\n\t\t} catch (error) {\n\t\t\tawait closeClient();\n\t\t\tif (transport instanceof StdioTransport) {\n\t\t\t\tthis.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.shutdown.signal.removeEventListener(\"abort\", closeClient);\n\t\t}\n\t}\n\n\tprivate connectFailed(error: unknown): Error {\n\t\tif (this.needsSignIn(error) && !this.closed) {\n\t\t\tthis.markNeedsAuth();\n\t\t\treturn new Error(signInRequiredMessage(this.entry));\n\t\t}\n\t\tthis.state = this.closed ? \"closed\" : \"failed\";\n\t\tthis.error = this.stderrTail ? `${errorMessage(error)}\\n${this.stderrTail}` : errorMessage(error);\n\t\tthis.changed();\n\t\treturn new Error(`MCP server \"${this.entry.name}\" failed to connect: ${this.error}`);\n\t}\n\n\t/** The transport dropped. The next call reconnects; until then the status shows why. */\n\tprivate handleClientClose(client: McpClient, stdio: StdioTransport | undefined): void {\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.client = undefined;\n\t\tthis.state = \"disconnected\";\n\t\tconst stderr = stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);\n\t\tthis.error = stderr ? `Connection closed\\n${stderr}` : \"Connection closed\";\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshTools(client: McpClient): Promise<void> {\n\t\ttry {\n\t\t\tconst tools = await client.listTools();\n\t\t\tif (this.client !== client || this.closed) return;\n\t\t\tthis.tools = tools;\n\t\t\tthis.onTools(this);\n\t\t} catch (error) {\n\t\t\tthis.error = `Failed to refresh tools: ${errorMessage(error)}`;\n\t\t}\n\t\tthis.changed();\n\t}\n\n\tprivate async refreshResources(client: McpClient): Promise<void> {\n\t\tconst { resources, resourceTemplates } = await fetchResources(client);\n\t\tif (this.client !== client || this.closed) return;\n\t\tthis.resources = resources;\n\t\tthis.resourceTemplates = resourceTemplates;\n\t\tthis.onTools(this);\n\t\tthis.changed();\n\t}\n\n\t/** Resolves once no transport of this server is open, including one that was still connecting. */\n\tasync close(): Promise<void> {\n\t\tthis.shutdown.abort();\n\t\tthis.state = \"closed\";\n\t\tthis.changed();\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tawait Promise.all([client?.close().catch(() => undefined), this.opening?.catch(() => undefined)]);\n\t\t// A refresh the server already answered may have rotated the refresh token; exiting before the\n\t\t// new tokens are saved would lose the grant.\n\t\tawait this.authProvider?.settled();\n\t}\n}\n"]}
|
|
@@ -14,6 +14,7 @@ import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
|
|
|
14
14
|
import { type CallToolResult, type ContentBlock, type McpRequestOptions, type Tool as McpTool } from "@earendil-works/pi-mcp";
|
|
15
15
|
import type { TSchema } from "typebox";
|
|
16
16
|
import type { ToolDefinition, ToolExposure, ToolNamespace, ToolRenderers } from "../../core/extensions/types.ts";
|
|
17
|
+
import { READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.ts";
|
|
17
18
|
import type { McpExposure } from "./config.ts";
|
|
18
19
|
/**
|
|
19
20
|
* Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode
|
|
@@ -23,7 +24,7 @@ export declare function toToolExposure(exposure: McpExposure): ToolExposure;
|
|
|
23
24
|
/** Model-facing text of an MCP result beyond this is cut in the middle. */
|
|
24
25
|
export declare const MCP_OUTPUT_MAX_BYTES: number;
|
|
25
26
|
/** Tool that reads the resources named by resource links. */
|
|
26
|
-
export
|
|
27
|
+
export { READ_MCP_RESOURCE_TOOL };
|
|
27
28
|
export interface McpToolDetails {
|
|
28
29
|
server: string;
|
|
29
30
|
tool: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,YAAY,EAAa,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAClF,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,IAA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ACrC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,uBAA4B,GACnC,OAAO,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,CAe1C;AA0BD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,WAAW,CAAC;IACtB,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,mEAAmE;IACnE,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC;CAClC,GAAG,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,CA6B1C;AAED,yGAAyG;AACzG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAqCnE"}
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
13
|
import { toLlmContent, } from "@earendil-works/pi-mcp";
|
|
14
14
|
import { Container, Spacer, Text } from "@earendil-works/pi-tui";
|
|
15
|
+
import { READ_MCP_RESOURCE_TOOL } from "../../core/mcp-servers.js";
|
|
15
16
|
import { formatToolCallWithArgs, getTextOutput, replaceTabs } from "../../core/tools/render-utils.js";
|
|
16
17
|
import { formatSize, truncateMiddle } from "../../core/tools/truncate.js";
|
|
17
18
|
import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
|
|
@@ -31,7 +32,7 @@ export const MCP_OUTPUT_MAX_BYTES = 20 * 1024;
|
|
|
31
32
|
/** Visual (wrapped) result lines shown before the output is expanded. */
|
|
32
33
|
const OUTPUT_PREVIEW_LINES = 5;
|
|
33
34
|
/** Tool that reads the resources named by resource links. */
|
|
34
|
-
export
|
|
35
|
+
export { READ_MCP_RESOURCE_TOOL };
|
|
35
36
|
export function saveToTempFile(data, extension) {
|
|
36
37
|
return writeOutputFile("pi-mcp", extension, data);
|
|
37
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAKN,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC;AAED,2EAA2E;AAC3E,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,yEAAyE;AACzE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,6DAA6D;AAC7D,MAAM,CAAC,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AAe1D,MAAM,UAAU,cAAc,CAAC,IAAyB,EAAE,SAAiB;IAC1E,OAAO,eAAe,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AACnD,CAAC;AAMD;;;;;GAK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,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\ttype ContentBlock,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\ttoLlmContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { formatSize, truncateMiddle } from \"../../core/tools/truncate.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Provider tool names are limited to 64 characters of `[A-Za-z0-9_-]`. */\nconst MAX_TOOL_NAME_LENGTH = 64;\n/** Model-facing text of an MCP result beyond this is cut in the middle. */\nexport const MCP_OUTPUT_MAX_BYTES = 20 * 1024;\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport const READ_MCP_RESOURCE_TOOL = \"read_mcp_resource\";\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/**\n * Saves the full text of a truncated result, or a binary resource, and returns the file path.\n * `extension` includes the dot, for example `.txt`.\n */\nexport type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;\n\nexport function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\treturn writeOutputFile(\"pi-mcp\", extension, data);\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\n/**\n * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,\n * everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts\n * call it by. `isTaken` reports names used by a different MCP tool: sanitizing can map two tools to\n * one name (`a-b` and `a_b`), which then get the hash suffix.\n */\nexport function createMcpToolName(\n\tserver: string,\n\ttool: string,\n\tisTaken: (name: string) => boolean = () => false,\n): string {\n\tconst name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n\tif (name.length <= MAX_TOOL_NAME_LENGTH && !isTaken(name)) return name;\n\tconst hash = createHash(\"sha256\").update(`${server}\\0${tool}`).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_TOOL_NAME_LENGTH - hash.length - 1)}_${hash}`;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\n/**\n * Output schema of every MCP tool: the `CallToolResult` scripts receive, with the tool's own output\n * schema as `structuredContent`. Codemode detects this shape to render `CallToolResult<T>`\n * declarations.\n */\nexport function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tcontent: { type: \"array\", items: { type: \"object\" } },\n\t\t\t...(structuredContentSchema ? { structuredContent: structuredContentSchema } : {}),\n\t\t\tisError: { type: \"boolean\" },\n\t\t\t_meta: { type: \"object\" },\n\t\t},\n\t\trequired: [\"content\"],\n\t} as unknown as TSchema;\n}\n\n/**\n * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in\n * Codex's truncation format, followed by the path of the file with the full text; images follow it.\n */\nexport async function limitMcpContent(\n\tcontent: (TextContent | ImageContent)[],\n\tsaveOutput: McpOutputSaver = saveToTempFile,\n): Promise<{ content: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst combined = textOf(content);\n\tconst truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);\n\tif (!truncation.truncated) return { content };\n\tlet fullOutputPath: string | undefined;\n\tlet where: string;\n\ttry {\n\t\tfullOutputPath = await saveOutput(combined, \".txt\");\n\t\twhere = `[Full output: ${fullOutputPath} (read it with offset/limit)]`;\n\t} catch (error) {\n\t\twhere = `[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;\n\t}\n\tconst tokens = Math.ceil(truncation.totalBytes / 4);\n\tconst text = `Warning: truncated output (original token count: ${tokens})\\nTotal output lines: ${truncation.totalLines}\\n\\n${truncation.content}\\n\\n${where}`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text }, ...content.filter((block) => block.type === \"image\")],\n\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t};\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */\nfunction extensionOf(uri: string): string {\n\tconst path = URL.canParse(uri) ? new URL(uri).pathname : uri;\n\treturn /\\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? \".bin\";\n}\n\n/** Blobs of these types are shown as text. */\nfunction isTextMimeType(mimeType: string | undefined): boolean {\n\tif (!mimeType) return false;\n\tconst type = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\treturn type.startsWith(\"text/\") || type === \"application/json\" || type.endsWith(\"+json\") || type.endsWith(\"+xml\");\n}\n\n/** Model-facing content of one block of `server`'s result. */\nasync function blockToContent(\n\tserver: string,\n\tblock: ContentBlock,\n\toptions: ConvertMcpResultOptions,\n): Promise<(TextContent | ImageContent)[]> {\n\tif (block.type === \"resource_link\") {\n\t\tconst details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);\n\t\tconst read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server \"${server}\")` : \"\";\n\t\tconst description = block.description ? `: ${block.description}` : \"\";\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[Resource ${block.uri} \"${block.title ?? block.name}\"${details.length > 0 ? ` (${details.join(\", \")})` : \"\"}${description}${read}]`,\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === \"resource\" && \"blob\" in block.resource && !block.resource.mimeType?.startsWith(\"image/\")) {\n\t\tconst { uri, mimeType, blob } = block.resource;\n\t\tconst data = Buffer.from(blob, \"base64\");\n\t\tif (isTextMimeType(mimeType)) return [{ type: \"text\", text: data.toString(\"utf8\") }];\n\t\tconst kind = `${mimeType ?? \"unknown type\"}, ${formatSize(data.length)}`;\n\t\ttry {\n\t\t\tconst path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];\n\t\t}\n\t}\n\treturn toLlmContent({ content: [block] });\n}\n\n/** Model-facing content of `server`'s content blocks, before the output limit. */\nexport async function toModelContent(\n\tserver: string,\n\tblocks: readonly ContentBlock[],\n\toptions: ConvertMcpResultOptions = {},\n): Promise<(TextContent | ImageContent)[]> {\n\treturn (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\t// Without content blocks, toLlmContent falls back to the structured content as JSON.\n\tconst converted: (TextContent | ImageContent)[] =\n\t\tresult.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\n/**\n * Tool input schemas must be objects. MCP servers may omit `type`, and some providers reject object\n * schemas without `properties`.\n */\nfunction toParameters(schema: Record<string, unknown>): TSchema {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\t...(schema.properties === undefined ? { properties: {} } : {}),\n\t} as unknown as TSchema;\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\tparameters: toParameters(tool.inputSchema),\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema),\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/extensions/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAKN,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AASjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAqB;IACnD,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxD,CAAC;AAED,2EAA2E;AAC3E,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,yEAAyE;AACzE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAelC,MAAM,UAAU,cAAc,CAAC,IAAyB,EAA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EAAE;iBAC1H,CAAC,CACF,CAAC;gBACF,MAAM,cAAc,GAAI,MAAM,CAAC,OAAsC,EAAE,cAAc,CAAC;gBACtF,IAAI,cAAc;oBAAE,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Adapts MCP tools to pi tool definitions.\n *\n * Results map onto pi's model-facing content (text and images). Text over 20KB keeps its start and\n * end with the middle cut out, like Codex does, and the full text is saved to a temp file the model\n * can read. Binary resources other than images are saved to temp files too, and resource links name\n * the `read_mcp_resource` tool. Codemode scripts receive the whole `CallToolResult` without `_meta`\n * (`content` blocks as sent by the server, `structuredContent`, `isError`), never truncated: it is\n * the tool's `structuredContent`, and every MCP tool declares a `CallToolResult` output schema. MCP\n * errors (`isError`) are error results for the model, but scripts still resolve to the result.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, JsonValue, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CallToolResult,\n\ttype ContentBlock,\n\ttype McpRequestOptions,\n\ttype Tool as McpTool,\n\ttoLlmContent,\n} from \"@earendil-works/pi-mcp\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type {\n\tToolAnnotations,\n\tToolDefinition,\n\tToolExposure,\n\tToolNamespace,\n\tToolRenderers,\n} from \"../../core/extensions/types.ts\";\nimport { READ_MCP_RESOURCE_TOOL } from \"../../core/mcp-servers.ts\";\nimport { formatToolCallWithArgs, getTextOutput, replaceTabs } from \"../../core/tools/render-utils.ts\";\nimport { formatSize, truncateMiddle } from \"../../core/tools/truncate.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { VisualLinePreview } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { writeOutputFile } from \"../../utils/output-files.ts\";\nimport type { McpExposure } from \"./config.ts\";\n\n/**\n * Tool exposure of an MCP exposure. `codemode` and `deferred` both leave tools out of the codemode\n * description; they differ only in which tool the MCP extension activates to reach them.\n */\nexport function toToolExposure(exposure: McpExposure): ToolExposure {\n\treturn exposure === \"codemode\" ? \"deferred\" : exposure;\n}\n\n/** Provider tool names are limited to 64 characters of `[A-Za-z0-9_-]`. */\nconst MAX_TOOL_NAME_LENGTH = 64;\n/** Model-facing text of an MCP result beyond this is cut in the middle. */\nexport const MCP_OUTPUT_MAX_BYTES = 20 * 1024;\n/** Visual (wrapped) result lines shown before the output is expanded. */\nconst OUTPUT_PREVIEW_LINES = 5;\n/** Tool that reads the resources named by resource links. */\nexport { READ_MCP_RESOURCE_TOOL };\n\nexport interface McpToolDetails {\n\tserver: string;\n\ttool: string;\n\t/** Temp file with the full text output, when the model-facing text was truncated. */\n\tfullOutputPath?: string;\n}\n\n/**\n * Saves the full text of a truncated result, or a binary resource, and returns the file path.\n * `extension` includes the dot, for example `.txt`.\n */\nexport type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;\n\nexport function saveToTempFile(data: string | Uint8Array, extension: string): Promise<string> {\n\treturn writeOutputFile(\"pi-mcp\", extension, data);\n}\n\nexport interface McpToolCaller {\n\tcallTool(name: string, args: Record<string, unknown>, options: McpRequestOptions): Promise<CallToolResult>;\n}\n\n/**\n * `mcp__<server>__<tool>`, sanitized and shortened with a hash suffix when too long. Like Codex,\n * everything but `[A-Za-z0-9_]` becomes `_`, so the name is also the identifier codemode scripts\n * call it by. `isTaken` reports names used by a different MCP tool: sanitizing can map two tools to\n * one name (`a-b` and `a_b`), which then get the hash suffix.\n */\nexport function createMcpToolName(\n\tserver: string,\n\ttool: string,\n\tisTaken: (name: string) => boolean = () => false,\n): string {\n\tconst name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n\tif (name.length <= MAX_TOOL_NAME_LENGTH && !isTaken(name)) return name;\n\tconst hash = createHash(\"sha256\").update(`${server}\\0${tool}`).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_TOOL_NAME_LENGTH - hash.length - 1)}_${hash}`;\n}\n\nfunction textOf(content: readonly (TextContent | ImageContent)[]): string {\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\n/**\n * Output schema of every MCP tool: the `CallToolResult` scripts receive, with the tool's own output\n * schema as `structuredContent`. Codemode detects this shape to render `CallToolResult<T>`\n * declarations.\n */\nexport function createMcpResultSchema(structuredContentSchema: Record<string, unknown> | undefined): TSchema {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {\n\t\t\tcontent: { type: \"array\", items: { type: \"object\" } },\n\t\t\t...(structuredContentSchema ? { structuredContent: structuredContentSchema } : {}),\n\t\t\tisError: { type: \"boolean\" },\n\t\t\t_meta: { type: \"object\" },\n\t\t},\n\t\trequired: [\"content\"],\n\t} as unknown as TSchema;\n}\n\n/**\n * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in\n * Codex's truncation format, followed by the path of the file with the full text; images follow it.\n */\nexport async function limitMcpContent(\n\tcontent: (TextContent | ImageContent)[],\n\tsaveOutput: McpOutputSaver = saveToTempFile,\n): Promise<{ content: (TextContent | ImageContent)[]; fullOutputPath?: string }> {\n\tconst combined = textOf(content);\n\tconst truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);\n\tif (!truncation.truncated) return { content };\n\tlet fullOutputPath: string | undefined;\n\tlet where: string;\n\ttry {\n\t\tfullOutputPath = await saveOutput(combined, \".txt\");\n\t\twhere = `[Full output: ${fullOutputPath} (read it with offset/limit)]`;\n\t} catch (error) {\n\t\twhere = `[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;\n\t}\n\tconst tokens = Math.ceil(truncation.totalBytes / 4);\n\tconst text = `Warning: truncated output (original token count: ${tokens})\\nTotal output lines: ${truncation.totalLines}\\n\\n${truncation.content}\\n\\n${where}`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text }, ...content.filter((block) => block.type === \"image\")],\n\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t};\n}\n\nexport interface ConvertMcpResultOptions {\n\t/** Saves truncated text and binary resources. Default: a temp file. */\n\tsaveOutput?: McpOutputSaver;\n\t/** Whether the server's resources can be read with `read_mcp_resource`, which resource links then name. */\n\treadableResources?: boolean;\n}\n\n/** File extension for a saved binary resource: the one its URI ends in, else `.bin`. */\nfunction extensionOf(uri: string): string {\n\tconst path = URL.canParse(uri) ? new URL(uri).pathname : uri;\n\treturn /\\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0] ?? \".bin\";\n}\n\n/** Blobs of these types are shown as text. */\nfunction isTextMimeType(mimeType: string | undefined): boolean {\n\tif (!mimeType) return false;\n\tconst type = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\treturn type.startsWith(\"text/\") || type === \"application/json\" || type.endsWith(\"+json\") || type.endsWith(\"+xml\");\n}\n\n/** Model-facing content of one block of `server`'s result. */\nasync function blockToContent(\n\tserver: string,\n\tblock: ContentBlock,\n\toptions: ConvertMcpResultOptions,\n): Promise<(TextContent | ImageContent)[]> {\n\tif (block.type === \"resource_link\") {\n\t\tconst details = [block.mimeType, block.size === undefined ? undefined : formatSize(block.size)].filter(Boolean);\n\t\tconst read = options.readableResources ? `. Read it with ${READ_MCP_RESOURCE_TOOL} (server \"${server}\")` : \"\";\n\t\tconst description = block.description ? `: ${block.description}` : \"\";\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[Resource ${block.uri} \"${block.title ?? block.name}\"${details.length > 0 ? ` (${details.join(\", \")})` : \"\"}${description}${read}]`,\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === \"resource\" && \"blob\" in block.resource && !block.resource.mimeType?.startsWith(\"image/\")) {\n\t\tconst { uri, mimeType, blob } = block.resource;\n\t\tconst data = Buffer.from(blob, \"base64\");\n\t\tif (isTextMimeType(mimeType)) return [{ type: \"text\", text: data.toString(\"utf8\") }];\n\t\tconst kind = `${mimeType ?? \"unknown type\"}, ${formatSize(data.length)}`;\n\t\ttry {\n\t\t\tconst path = await (options.saveOutput ?? saveToTempFile)(data, extensionOf(uri));\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) saved to ${path}]` }];\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\treturn [{ type: \"text\", text: `[Binary resource ${uri} (${kind}) could not be saved: ${reason}]` }];\n\t\t}\n\t}\n\treturn toLlmContent({ content: [block] });\n}\n\n/** Model-facing content of `server`'s content blocks, before the output limit. */\nexport async function toModelContent(\n\tserver: string,\n\tblocks: readonly ContentBlock[],\n\toptions: ConvertMcpResultOptions = {},\n): Promise<(TextContent | ImageContent)[]> {\n\treturn (await Promise.all(blocks.map((block) => blockToContent(server, block, options)))).flat();\n}\n\n/** Convert an MCP result. `isError` results become error results that keep the structured result. */\nexport async function convertMcpResult(\n\tserver: string,\n\ttool: string,\n\tresult: CallToolResult,\n\toptions: ConvertMcpResultOptions = {},\n): Promise<AgentToolResult<McpToolDetails>> {\n\t// Without content blocks, toLlmContent falls back to the structured content as JSON.\n\tconst converted: (TextContent | ImageContent)[] =\n\t\tresult.content.length > 0 ? await toModelContent(server, result.content, options) : toLlmContent(result);\n\tif (result.isError && textOf(converted) === \"\") {\n\t\tconverted.push({ type: \"text\", text: `MCP tool ${server}/${tool} returned an error` });\n\t}\n\tconst { content, fullOutputPath } = await limitMcpContent(converted, options.saveOutput);\n\tconst { _meta: _ignored, ...scriptResult } = result;\n\treturn {\n\t\tcontent,\n\t\tdetails: { server, tool, ...(fullOutputPath ? { fullOutputPath } : {}) },\n\t\tstructuredContent: scriptResult as unknown as JsonValue,\n\t\t...(result.isError ? { isError: true } : {}),\n\t};\n}\n\n/**\n * Tool input schemas must be objects. MCP servers may omit `type`, and some providers reject object\n * schemas without `properties`.\n */\nfunction toParameters(schema: Record<string, unknown>): TSchema {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\t...(schema.properties === undefined ? { properties: {} } : {}),\n\t} as unknown as TSchema;\n}\n\nconst ANNOTATION_HINTS = [\"readOnlyHint\", \"destructiveHint\", \"idempotentHint\", \"openWorldHint\"] as const;\n\n/** The boolean hints of an MCP tool's annotations, or undefined when it has none. */\nfunction toToolAnnotations(tool: McpTool): ToolAnnotations | undefined {\n\tconst annotations: ToolAnnotations = {};\n\tfor (const hint of ANNOTATION_HINTS) {\n\t\tconst value = tool.annotations?.[hint];\n\t\tif (typeof value === \"boolean\") annotations[hint] = value;\n\t}\n\treturn Object.keys(annotations).length > 0 ? annotations : undefined;\n}\n\nexport function createMcpToolDefinition(options: {\n\tserver: string;\n\ttool: McpTool;\n\tname: string;\n\texposure: McpExposure;\n\tnamespace: ToolNamespace;\n\ttimeoutMs: number;\n\tgetClient: () => Promise<McpToolCaller>;\n\t/** Whether `read_mcp_resource` can read the server's resources. */\n\treadableResources?: () => boolean;\n}): ToolDefinition<TSchema, McpToolDetails> {\n\tconst { server, tool } = options;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst annotations = toToolAnnotations(tool);\n\tconst label = `${server}/${tool.name}`;\n\treturn {\n\t\tname: options.name,\n\t\tlabel,\n\t\tdescription: tool.description?.trim() || title || `MCP tool ${tool.name} from server ${server}`,\n\t\tparameters: toParameters(tool.inputSchema),\n\t\toutputSchema: createMcpResultSchema(tool.outputSchema),\n\t\texposure: toToolExposure(options.exposure),\n\t\tnamespace: options.namespace,\n\t\t...(annotations ? { annotations } : {}),\n\t\t...createMcpToolRenderers(label),\n\t\tasync execute(_toolCallId, params, signal, onUpdate) {\n\t\t\tconst client = await options.getClient();\n\t\t\tconst result = await client.callTool(tool.name, (params ?? {}) as Record<string, unknown>, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\t\tonProgress: (progress) => {\n\t\t\t\t\tconst total = progress.total === undefined ? \"\" : `/${progress.total}`;\n\t\t\t\t\tconst text = progress.message ?? `Progress ${progress.progress}${total}`;\n\t\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text }], details: { server, tool: tool.name } });\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn convertMcpResult(server, tool.name, result, { readableResources: options.readableResources?.() });\n\t\t},\n\t};\n}\n\n/** Renderers of calls to an MCP tool, labeled `server/tool`, also used before the tool is registered. */\nexport function createMcpToolRenderers(label: string): ToolRenderers {\n\treturn {\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tcomponent.setText(formatToolCallWithArgs(label, args, theme, context.expanded));\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tconst output = getTextOutput(result, context.showImages).trim();\n\t\t\tif (!output) return component;\n\t\t\tconst color = context.isError ? \"error\" : \"toolOutput\";\n\t\t\tconst styled = replaceTabs(output)\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(color, line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tif (options.expanded) {\n\t\t\t\tcomponent.addChild(new Text(styled, 0, 0));\n\t\t\t} else {\n\t\t\t\t// Limit wrapped lines, not logical ones: MCP results are often one long JSON line.\n\t\t\t\tcomponent.addChild(\n\t\t\t\t\tnew VisualLinePreview({\n\t\t\t\t\t\ttext: styled,\n\t\t\t\t\t\tmaxVisualLines: OUTPUT_PREVIEW_LINES,\n\t\t\t\t\t\tkeep: \"start\",\n\t\t\t\t\t\tformatHint: (hidden) =>\n\t\t\t\t\t\t\t`${theme.fg(\"muted\", `... (${hidden} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fullOutputPath = (result.details as McpToolDetails | undefined)?.fullOutputPath;\n\t\t\t\tif (fullOutputPath) component.addChild(new Text(theme.fg(\"muted\", `Full output: ${fullOutputPath}`), 0, 0));\n\t\t\t}\n\t\t\treturn component;\n\t\t},\n\t};\n}\n"]}
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,KAAK,IAAI,EAAyD,MAAM,eAAe,CAAC;AAkCjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAalE,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAyS7D,wBAAsB,oBAAoB,CACzC,MAAM,EAAE,IAAI,EACZ,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,eAAe,EAAE,eAAe,GAC9B,OAAO,CAAC,cAAc,CAAC,CAsFzB;AAwHD,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,eAAe,EAAE,CAAC;CACvC;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,KAAK,IAAI,EAAyD,MAAM,eAAe,CAAC;AAkCjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAalE,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAyS7D,wBAAsB,oBAAoB,CACzC,MAAM,EAAE,IAAI,EACZ,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,eAAe,EAAE,eAAe,GAC9B,OAAO,CAAC,cAAc,CAAC,CAsFzB;AAwHD,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,eAAe,EAAE,CAAC;CACvC;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBA0a/D"}
|
package/dist/main.js
CHANGED
|
@@ -631,6 +631,7 @@ export async function main(args, options) {
|
|
|
631
631
|
additionalPromptTemplatePaths: resolvedPromptTemplatePaths,
|
|
632
632
|
additionalThemePaths: resolvedThemePaths,
|
|
633
633
|
noExtensions: parsed.noExtensions,
|
|
634
|
+
disabledBuiltinExtensions: parsed.noMcp ? ["mcp"] : undefined,
|
|
634
635
|
noSkills: parsed.noSkills,
|
|
635
636
|
noPromptTemplates: parsed.noPromptTemplates,
|
|
636
637
|
noThemes: parsed.noThemes,
|