@earendil-works/pi-coding-agent 0.99.2 → 1.0.0
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 +46 -0
- package/dist/bundle/chunks/anthropic.js +2 -2
- package/dist/bundle/chunks/{azure-openai-responses-TLHNIYZK.js → azure-openai-responses-AFMVM6NP.js} +1 -1
- package/dist/bundle/chunks/{chunk-7QSPBJKW.js → chunk-2KTBZM5G.js} +14 -28
- package/dist/bundle/chunks/{chunk-R5J3MOBF.js → chunk-2VNGUWBO.js} +1 -1
- package/dist/bundle/chunks/chunk-33XOIQ5N.js +1204 -0
- package/dist/bundle/chunks/chunk-4KU537KD.js +2 -0
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +82 -0
- package/dist/bundle/chunks/{chunk-45SXDISG.js → chunk-IBCPYVFK.js} +4 -4
- package/dist/bundle/chunks/chunk-KDN6RCEQ.js +4 -0
- package/dist/bundle/chunks/{chunk-G3UZ5FWD.js → chunk-LTXEMVMA.js} +11 -60
- package/dist/bundle/chunks/chunk-PRD6WYBT.js +16 -0
- package/dist/bundle/chunks/{cli-ALNBTL3U.js → cli-QOMC26IJ.js} +3 -3
- package/dist/bundle/chunks/codemode-worker.js +44 -5
- package/dist/bundle/chunks/execute-GVRSEGHL.js +367 -0
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-3GKGNXC4.js → openai-codex-responses-GK67DQQJ.js} +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/{openai-responses-S7GKCCDG.js → openai-responses-CQDDLDQF.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +2 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-2SO2JDWM.js +2 -0
- package/dist/bundle/chunks/virtual-modules-6ZMK7GDO.js +2 -0
- 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.js +2 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +37 -8
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +6 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +7 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-registry.d.ts +3 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/radius.d.ts +2 -0
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +2 -0
- package/dist/core/radius.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -2
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +3 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +154 -47
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +7 -7
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +55 -102
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/cli.js +2 -2
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +23 -12
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +8 -7
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +55 -30
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +2 -1
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +6 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +8 -2
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +24 -21
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +68 -0
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.js +1086 -0
- package/dist/modes/interactive/components/pi-logo-animation.js.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +7 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +12 -0
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +1 -0
- package/dist/modes/interactive/components/pi-logo.d.ts +7 -0
- package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -1
- package/dist/modes/interactive/components/pi-logo.js +13 -1
- package/dist/modes/interactive/components/pi-logo.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/radius-login-selector.js +85 -0
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -3
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +5 -5
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +5 -4
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +10 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +153 -40
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/system-theme.d.ts +2 -1
- package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/system-theme.js +16 -5
- package/dist/modes/interactive/theme/system-theme.js.map +1 -1
- package/docs/cli.md +6 -16
- package/docs/codemode.md +207 -0
- package/docs/docs.json +5 -1
- package/docs/environment-variables.md +2 -2
- package/docs/index.md +1 -1
- package/docs/mcp.md +17 -0
- package/docs/models.md +22 -1
- package/docs/providers.md +16 -6
- package/docs/sdk.md +1 -1
- package/docs/settings.md +3 -3
- package/docs/usage.md +1 -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/npm-shrinkwrap.json +25 -30
- package/package.json +10 -10
- package/dist/bundle/chunks/chunk-3KYEVQKX.js +0 -82
- package/dist/bundle/chunks/chunk-3NVH2HQH.js +0 -4
- package/dist/bundle/chunks/chunk-3YAHQSW6.js +0 -1438
- package/dist/bundle/chunks/chunk-ECRK44UV.js +0 -2
- package/dist/bundle/chunks/execute-RC7W4ML3.js +0 -328
- package/dist/bundle/chunks/runtime-NJPX4ID2.js +0 -2
- package/dist/bundle/chunks/virtual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AC1B,wCAAwC;QACxC,QAAQ,EAAE,YAAY;QACtB,cAAc,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,OAAO,CAAC;QACrE,gFAAgF;QAChF,mBAAmB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,WAAW,EAAE,uBAAuB,EAAE,EAAE;QAC5F,8EAA8E;QAC9E,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,CAC5D,CAAC,MAAM,oBAAoB,EAAE,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;QACnG,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAA8B,EAAE,EACrC,OAAO,GAAwB,EAAE;IAEjC,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog and classifiers through\n * `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderDeclarations,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription:\n\t\t\t'Raw JavaScript source. Top-level await and return work. May start with a `// @options: {\"max_output_tokens\": 1000}` line.',\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools (chains, loops, Promise.all, filtering large results)\",\n\tguidelines: [\n\t\t\"Use codemode to batch or chain several tool calls, or to filter large tool output down to what you need, instead of issuing many individual tool calls. Batch independent calls in one codemode call using await Promise.allSettled([...]).\",\n\t],\n} as const;\n\nconst DESCRIPTION_INTRO = `Run JavaScript code to orchestrate/compose tool calls\n- Evaluates the provided JavaScript code in a fresh QuickJS sandbox as the body of an async function: top-level \\`await\\` and \\`return\\` work.\n- All nested tools are available on the global \\`tools\\` object, for example \\`await tools.read(...)\\`. Tool names are exposed as normalized JavaScript identifiers, for example \\`await tools.mcp__ologs__get_profile(...)\\`.\n- Nested tool methods take an object as their input argument.\n- Nested tools return either an object or a string, based on the description.\n- A nested tool call that fails, is blocked, or gets invalid arguments rejects with an Error carrying the tool's error text.\n- Runs raw JavaScript -- no Node, no file system, no network access, no timers.\n- Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences.\n- You may optionally start the tool input with a first line like \\`// @options: {\"max_output_tokens\": 1000, \"timeout_ms\": 60000}\\`.\n- \\`max_output_tokens\\` sets the token budget for the script's output. Defaults to 10000 tokens.\n- \\`timeout_ms\\` sets a hard deadline for the whole script. By default there is none.\n- When the JS code is fully evaluated, calls that are still running are cancelled and unawaited promises are silently discarded.\n- Tool calls are real and have side effects. If the script fails partway, earlier calls are not undone.\n- Scripts have a 256 MB memory limit; exceeding it throws \\`InternalError: out of memory\\`. Filter or aggregate large data instead of accumulating it.\n\n- Global helpers:\n- \\`exit()\\`: Immediately ends the current script successfully (like an early return from the top level).\n- \\`text(value: string | number | boolean | undefined | null)\\`: Appends a text item. Non-string values are stringified with \\`JSON.stringify(...)\\` when possible.\n- \\`image(imageUrlOrItem: string | { image_url: string } | ImageContent)\\`: Appends an image item. \\`image_url\\` should be a base64-encoded \\`data:\\` URL. To forward an MCP tool image, pass an individual \\`ImageContent\\` block from \\`result.content\\`, for example \\`image(result.content[0])\\`.\n- \\`store(key: string, value: any)\\`: stores a serializable value under a string key for later \\`codemode\\` calls in the same session. Storing \\`undefined\\` deletes the key. Writes are kept only if the script succeeds.\n- \\`load(key: string)\\`: returns the stored value for a string key, or \\`undefined\\` if it is missing.\n- \\`ALL_TOOLS\\`: metadata for the enabled nested tools as \\`{ name, description }\\` entries.\n- \\`searchTools(query: string, options?: { limit?: number; namespace?: string })\\`: resolves to the nested tools that best match the query (BM25, default limit 8), as \\`{ name, description }\\` entries like \\`ALL_TOOLS\\`.\n- \\`describeTool(name: string)\\`: resolves to the description and declaration of a nested tool, or \\`undefined\\`.\n- \\`describeNamespace(name: string)\\`: resolves to \\`{ name, description?, instructions?, tools }\\` for a namespace of nested tools, such as an MCP server: its usage instructions and the names of its tools, or \\`undefined\\`.\n- \\`console.log(...)\\` and the other \\`console\\` methods append a text item like \\`text()\\`.\n- \\`return value\\` at the top level appends the value like \\`text()\\`.`;\n\nconst MODEL_TYPES = `type ModelType = \"chat\" | \"image\" | \"classifier\";\n/** A model catalog entry. \\`provider\\` and \\`id\\` identify it; the other fields depend on the type. */\ninterface ModelInfo {\n type?: ModelType;\n provider: string;\n id: string;\n name: string;\n api: string;\n input: (\"text\" | \"image\")[];\n contextWindow?: number;\n [key: string]: unknown;\n}\ntype ClassifierQuestion =\n | { type: \"choice\"; instructions: string; criteria: Record<string, string> }\n | { type: \"score\"; instructions: string; criteria: string[] }\n | { type: \"bool\"; instructions: string; criteria: { true: string; false: string } };\ntype ClassifierAnswer =\n | { type: \"choice\"; choice: string; probabilities: Record<string, number>; confidence: number }\n | { type: \"score\"; score: number; confidence: number }\n | { type: \"bool\"; probability: number };\ninterface ClassifierContext {\n state: Record<string, unknown>;\n questions: Record<string, ClassifierQuestion>;\n}\ninterface ClassifierResult {\n api: string;\n provider: string;\n model: string;\n answers: Record<string, ClassifierAnswer>;\n /** Set when the service reports token counts. Cost is in USD. */\n usage?: { input: number; output: number; totalTokens: number; cost: { total: number } };\n stopReason: \"stop\" | \"error\" | \"aborted\";\n errorMessage?: string;\n timestamp: number;\n}`;\n\n/** Declarations of the `models` globals; codemode-execute.ts implements them. */\nexport const MODEL_GLOBAL_DECLARATIONS: readonly Omit<CodemodeTool, \"execute\">[] = [\n\t{\n\t\tname: \"models.getModelsOfType\",\n\t\tdescription: \"Every known model of a type, optionally for one provider.\",\n\t\tsignature: \"(type: ModelType, provider?: string): Promise<ModelInfo[]>\",\n\t},\n\t{\n\t\tname: \"models.getAvailableOfType\",\n\t\tdescription: \"Models of a type whose provider has working credentials.\",\n\t\tsignature: \"(type: ModelType, provider?: string): Promise<ModelInfo[]>\",\n\t},\n\t{\n\t\tname: \"models.getModelOfType\",\n\t\tdescription: \"One catalog entry, or undefined.\",\n\t\tsignature: \"(type: ModelType, provider: string, id: string): Promise<ModelInfo | undefined>\",\n\t},\n\t{\n\t\tname: \"models.classify\",\n\t\tdescription:\n\t\t\t\"Run a classifier model on one state. Only `provider` and `id` of `model` are used. Provider errors do not throw: check `stopReason` and `errorMessage`.\",\n\t\tsignature: \"(model: ModelInfo, context: ClassifierContext): Promise<ClassifierResult>\",\n\t},\n];\n\nconst DEFERRED_TOOLS_GUIDANCE = `Some nested tools may be omitted from this description, such as deferred tools and MCP tools. They are still available on the global \\`tools\\` object and listed in \\`ALL_TOOLS\\`.\nTo find one, call \\`await searchTools(query)\\` (pass \\`{ namespace }\\` to search one namespace), or filter \\`ALL_TOOLS\\` by \\`name\\` and \\`description\\`. \\`await describeNamespace(name)\\` returns a namespace's usage instructions and the names of its tools.`;\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, DEFERRED_TOOLS_GUIDANCE];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (options.models) {\n\t\tconst noop = () => undefined;\n\t\tconst models = renderDeclarations({\n\t\t\tglobals: MODEL_GLOBAL_DECLARATIONS.map((global) => ({ ...global, execute: noop })),\n\t\t});\n\t\tsections.push(`Model API:\\n\\`\\`\\`ts\\n${MODEL_TYPES}\\n\\n${models}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions get the codemode declaration appended, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = renderToolSample(toCodemodeDeclaration(tool));\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAo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AAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
@@ -171,7 +171,7 @@ export async function runMcpCommand(args, options) {
|
|
|
171
171
|
return 1;
|
|
172
172
|
}
|
|
173
173
|
if (command === "logout") {
|
|
174
|
-
const removed = credentials.remove(url);
|
|
174
|
+
const removed = credentials.remove(name, url);
|
|
175
175
|
log(removed ? `Signed out of MCP server "${name}".` : `No stored credentials for MCP server "${name}".`);
|
|
176
176
|
return 0;
|
|
177
177
|
}
|
|
@@ -438,7 +438,7 @@ async function login(entry, connection, url, timeoutMs, options, credentials, lo
|
|
|
438
438
|
try {
|
|
439
439
|
await signInMcpServer({
|
|
440
440
|
serverUrl: url,
|
|
441
|
-
store: credentials.forServer(url),
|
|
441
|
+
store: credentials.forServer(name, url),
|
|
442
442
|
settings: connection.oauthSettings(),
|
|
443
443
|
challenge: connection.challenge,
|
|
444
444
|
prompt: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceR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AC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;AACF,CAAC","sourcesContent":["/**\n * `pi mcp`: add, remove, and check MCP servers and sign in to them outside a session. Agents run it\n * through bash to configure servers, verify an `mcp.json` they wrote, and start an OAuth sign-in;\n * the user only approves access in the browser. Running sessions pick up new credentials on their\n * next turn.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport chalk from \"chalk\";\nimport { APP_NAME, CONFIG_DIR_NAME } from \"../../config.ts\";\nimport { validateMcpServerConfig } from \"../../core/mcp-servers.ts\";\nimport { ProjectTrustStore } from \"../../core/trust-manager.ts\";\nimport { openBrowser } from \"../../utils/open-browser.ts\";\nimport {\n\taddMcpServerConfig,\n\tgetMcpToolExposure,\n\ttype LoadedMcpConfig,\n\tloadMcpConfig,\n\ttype McpServerEntry,\n\tremoveMcpServerConfig,\n} from \"./config.ts\";\nimport {\n\tcreateDefaultTransport,\n\tMcpOAuthCredentialStore,\n\tMcpServerConnection,\n\tMcpServerLog,\n\tMcpSignInCancelledError,\n\tsignInMcpServer,\n} from \"./runtime.ts\";\n\nconst HELP = `${chalk.bold(\"Usage:\")}\n ${APP_NAME} mcp add <server> [options] -- <command> [args...]\n ${APP_NAME} mcp add <server> [options] --url <url>\n ${APP_NAME} mcp remove <server> [-l]\n ${APP_NAME} mcp list [--json]\n ${APP_NAME} mcp login <server> [--timeout <seconds>]\n ${APP_NAME} mcp logout <server>\n\nConfigure and check MCP servers and sign in to OAuth servers without starting a session.\nReads ~/${CONFIG_DIR_NAME}/agent/mcp.json and, in trusted projects, ${CONFIG_DIR_NAME}/mcp.json.\n\nCommands:\n add <server> Add or replace a server in mcp.json\n remove <server> Remove a server from mcp.json\n list Show state, tools, and errors (exits 1 on failure)\n login <server> Sign in through the browser\n logout <server> Delete the stored OAuth credentials\n\nOptions for add and remove:\n -l, --local Use ${CONFIG_DIR_NAME}/mcp.json in the current project instead of the global file\n\nOptions for add:\n --url <url> Streamable HTTP server URL (instead of a command)\n --env <KEY=VALUE> Environment variable for a stdio server (repeatable)\n --cwd <dir> Working directory for a stdio server\n --header <KEY=VALUE> HTTP header (repeatable)\n --bearer-token-env-var <NAME>\n Send \"Authorization: Bearer \\${NAME}\"\n --oauth-client-id <id> Pre-registered OAuth client id\n --oauth-client-secret <secret>\n OAuth client secret (may be \\${NAME} or !command)\n --oauth-callback-port <port>\n Fixed OAuth callback port\n --oauth-client-name <name>\n Client name sent when registering with the OAuth server\n --exposure <mode> codemode (default), deferred, direct, or hidden\n --description <text> What the server offers, shown in the system prompt\n\nOther options:\n --json Print the list as JSON\n --timeout <seconds> How long login waits for the browser (default: 300)`;\n\nconst HELP_HINT = chalk.dim(`Use \"${APP_NAME} mcp --help\" for usage.`);\n\nconst DEFAULT_LOGIN_TIMEOUT_SECONDS = 300;\n\nexport interface McpCommandOptions {\n\tcwd: string;\n\tagentDir: string;\n\t/** Defaults to `mcp-auth.json` in the agent directory. */\n\tcredentials?: McpOAuthCredentialStore;\n\t/** Defaults to the platform browser. */\n\topenUrl?: (url: string) => void;\n\t/** Defaults to console output. */\n\tlog?: (line: string) => void;\n\terror?: (line: string) => void;\n}\n\ninterface ServerReport {\n\tname: string;\n\tscope: string;\n\tsource: string;\n\tenabled: boolean;\n\texposure: string;\n\ttransport: string;\n\tstate: string;\n\ttools: string[];\n\t/** Tools whose exposure differs from the server's, from `toolExposure`. */\n\ttoolExposure?: Record<string, string>;\n\tresources?: number;\n\tresourceTemplates?: number;\n\terror?: string;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction describeTransport(entry: McpServerEntry): string {\n\tconst { config } = entry;\n\treturn \"url\" in config ? config.url : [config.command, ...(config.args ?? [])].join(\" \");\n}\n\nfunction createConnection(entry: McpServerEntry, options: McpCommandOptions, credentials: McpOAuthCredentialStore) {\n\treturn new McpServerConnection({\n\t\tentry,\n\t\tcwd: options.cwd,\n\t\tcreateTransport: createDefaultTransport,\n\t\tcredentials,\n\t\tlog: new McpServerLog(join(options.agentDir, \"mcp.log\")),\n\t\tonTools: () => {},\n\t});\n}\n\n/** Short spellings of options. `-l`/`--local` match `pi install`. */\nconst OPTION_ALIASES = new Map([[\"-l\", \"--local\"]]);\n\ninterface ParsedOptions {\n\tpositional: string[];\n\tvalues: Map<string, string | true>;\n\t/** Values of `list` options, in order. */\n\tlists: Map<string, string[]>;\n}\n\n/**\n * Parse `--name value` options; returns undefined and reports unknown ones. `--` ends the options,\n * as does reaching `maxPositionals` positional arguments: the remaining arguments are positional,\n * so a command's own options (`add <server> <command> --flag`) are passed through.\n */\nfunction parseOptions(\n\targs: string[],\n\tknown: Record<string, \"flag\" | \"value\" | \"list\">,\n\terror: (line: string) => void,\n\tmaxPositionals = Number.POSITIVE_INFINITY,\n): ParsedOptions | undefined {\n\tconst positional: string[] = [];\n\tconst values = new Map<string, string | true>();\n\tconst lists = new Map<string, string[]>();\n\tfor (let index = 0; index < args.length; index++) {\n\t\tconst arg = OPTION_ALIASES.get(args[index]) ?? args[index];\n\t\tif (arg === \"--\" || positional.length >= maxPositionals) {\n\t\t\tpositional.push(...args.slice(arg === \"--\" ? index + 1 : index));\n\t\t\tbreak;\n\t\t}\n\t\tif (!arg.startsWith(\"--\")) {\n\t\t\tpositional.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst name = arg.slice(2);\n\t\tconst kind = known[name];\n\t\tif (!kind) {\n\t\t\terror(`Unknown option ${arg}.\\n${HELP_HINT}`);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (kind === \"flag\") {\n\t\t\tvalues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tconst value = args[++index];\n\t\tif (value === undefined) {\n\t\t\terror(`${arg} needs a value.`);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (kind === \"list\") lists.set(name, [...(lists.get(name) ?? []), value]);\n\t\telse values.set(name, value);\n\t}\n\treturn { positional, values, lists };\n}\n\n/** Run `pi mcp <args>` and return the exit code. */\nexport async function runMcpCommand(args: string[], options: McpCommandOptions): Promise<number> {\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst error = options.error ?? ((line: string) => console.error(line));\n\tconst [command, ...rest] = args;\n\tif (command === undefined || command === \"help\" || args.includes(\"--help\") || args.includes(\"-h\")) {\n\t\tlog(HELP);\n\t\treturn 0;\n\t}\n\n\tconst projectConfig = join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\");\n\tif (command === \"add\" || command === \"remove\") {\n\t\treturn command === \"add\"\n\t\t\t? add(rest, projectConfig, options, log, error)\n\t\t\t: remove(rest, projectConfig, options, log, error);\n\t}\n\tconst projectTrusted = new ProjectTrustStore(options.agentDir).get(options.cwd) === true;\n\tconst loaded = loadMcpConfig({ agentDir: options.agentDir, cwd: options.cwd, projectTrusted });\n\tconst untrustedNote =\n\t\t!projectTrusted && existsSync(projectConfig)\n\t\t\t? `${projectConfig} is ignored because the project is not trusted. Start ${APP_NAME} in the project to trust it.`\n\t\t\t: undefined;\n\tconst credentials = options.credentials ?? new McpOAuthCredentialStore();\n\n\tswitch (command) {\n\t\tcase \"list\": {\n\t\t\tconst parsed = parseOptions(rest, { json: \"flag\" }, error);\n\t\t\tif (!parsed) return 1;\n\t\t\tif (parsed.positional.length > 0) {\n\t\t\t\terror(`Usage: ${APP_NAME} mcp list [--json]\\n${HELP_HINT}`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn list(loaded, parsed.values.has(\"json\"), untrustedNote, options, credentials, log);\n\t\t}\n\t\tcase \"login\":\n\t\tcase \"logout\": {\n\t\t\tconst parsed = parseOptions(rest, command === \"login\" ? { timeout: \"value\" } : {}, error);\n\t\t\tif (!parsed) return 1;\n\t\t\tconst [name, ...extra] = parsed.positional;\n\t\t\tif (!name || extra.length > 0) {\n\t\t\t\terror(`Usage: ${APP_NAME} mcp ${command} <server>\\n${HELP_HINT}`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tconst entry = loaded.servers.find((server) => server.name === name);\n\t\t\tif (!entry) {\n\t\t\t\terror(\n\t\t\t\t\t`No MCP server named \"${name}\".${untrustedNote ? ` ${untrustedNote}` : \"\"} Configured: ${loaded.servers.map((server) => server.name).join(\", \") || \"none\"}.`,\n\t\t\t\t);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tconst connection = createConnection(entry, options, credentials);\n\t\t\tconst url = connection.oauthUrl;\n\t\t\tif (!url) {\n\t\t\t\terror(`MCP server \"${name}\" does not use OAuth. Only HTTP servers without an Authorization header do.`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (command === \"logout\") {\n\t\t\t\tconst removed = credentials.remove(url);\n\t\t\t\tlog(removed ? `Signed out of MCP server \"${name}\".` : `No stored credentials for MCP server \"${name}\".`);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tconst timeout = Number(parsed.values.get(\"timeout\") ?? DEFAULT_LOGIN_TIMEOUT_SECONDS);\n\t\t\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\t\t\terror(\"--timeout must be a positive number of seconds.\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await login(entry, connection, url, timeout * 1000, options, credentials, log, error);\n\t\t\t} finally {\n\t\t\t\tawait connection.close();\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\terror(`Unknown mcp command \"${command}\".\\n${HELP_HINT}`);\n\t\t\treturn 1;\n\t}\n}\n\n/** Parse `KEY=VALUE` pairs of a repeatable option into a record. */\nfunction parsePairs(option: string, pairs: string[] | undefined, error: (line: string) => void) {\n\tif (!pairs) return {};\n\tconst record: Record<string, string> = {};\n\tfor (const pair of pairs) {\n\t\tconst separator = pair.indexOf(\"=\");\n\t\tif (separator <= 0) {\n\t\t\terror(`--${option} expects KEY=VALUE, got \"${pair}\".`);\n\t\t\treturn undefined;\n\t\t}\n\t\trecord[pair.slice(0, separator)] = pair.slice(separator + 1);\n\t}\n\treturn record;\n}\n\nfunction add(\n\targs: string[],\n\tprojectConfig: string,\n\toptions: McpCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): number {\n\tconst usage = `Usage: ${APP_NAME} mcp add <server> [options] (--url <url> | -- <command> [args...])\\n${HELP_HINT}`;\n\tconst parsed = parseOptions(\n\t\targs,\n\t\t{\n\t\t\tlocal: \"flag\",\n\t\t\turl: \"value\",\n\t\t\tenv: \"list\",\n\t\t\tcwd: \"value\",\n\t\t\theader: \"list\",\n\t\t\t\"bearer-token-env-var\": \"value\",\n\t\t\t\"oauth-client-id\": \"value\",\n\t\t\t\"oauth-client-secret\": \"value\",\n\t\t\t\"oauth-callback-port\": \"value\",\n\t\t\t\"oauth-client-name\": \"value\",\n\t\t\texposure: \"value\",\n\t\t\tdescription: \"value\",\n\t\t},\n\t\terror,\n\t\t2,\n\t);\n\tif (!parsed) return 1;\n\tconst { positional, values, lists } = parsed;\n\tconst [name, ...command] = positional;\n\tconst url = values.get(\"url\");\n\tif (!name || (url === undefined) === (command.length === 0)) {\n\t\terror(usage);\n\t\treturn 1;\n\t}\n\tconst value = (option: string) => {\n\t\tconst found = values.get(option);\n\t\treturn typeof found === \"string\" ? found : undefined;\n\t};\n\tconst exposure = value(\"exposure\");\n\tconst httpOnly = [\n\t\t\"header\",\n\t\t\"bearer-token-env-var\",\n\t\t\"oauth-client-id\",\n\t\t\"oauth-client-secret\",\n\t\t\"oauth-callback-port\",\n\t\t\"oauth-client-name\",\n\t];\n\tconst stdioOnly = [\"env\", \"cwd\"];\n\tconst misplaced = (url === undefined ? httpOnly : stdioOnly).find(\n\t\t(option) => values.has(option) || lists.has(option),\n\t);\n\tif (misplaced) {\n\t\terror(`--${misplaced} only applies to ${url === undefined ? \"HTTP servers (--url)\" : \"stdio servers\"}.`);\n\t\treturn 1;\n\t}\n\n\tlet config: Record<string, unknown>;\n\tif (typeof url === \"string\") {\n\t\tconst headers = parsePairs(\"header\", lists.get(\"header\"), error);\n\t\tif (!headers) return 1;\n\t\tconst bearer = value(\"bearer-token-env-var\");\n\t\tif (bearer !== undefined) headers.Authorization = `Bearer \\${${bearer}}`;\n\t\tconst port = value(\"oauth-callback-port\");\n\t\tconst oauth = {\n\t\t\t...(value(\"oauth-client-id\") === undefined ? {} : { clientId: value(\"oauth-client-id\") }),\n\t\t\t...(value(\"oauth-client-secret\") === undefined ? {} : { clientSecret: value(\"oauth-client-secret\") }),\n\t\t\t...(port === undefined ? {} : { callbackPort: Number(port) }),\n\t\t\t...(value(\"oauth-client-name\") === undefined ? {} : { clientName: value(\"oauth-client-name\") }),\n\t\t};\n\t\tconfig = {\n\t\t\turl,\n\t\t\t...(Object.keys(headers).length > 0 ? { headers } : {}),\n\t\t\t...(Object.keys(oauth).length > 0 ? { oauth } : {}),\n\t\t};\n\t} else {\n\t\tconst env = parsePairs(\"env\", lists.get(\"env\"), error);\n\t\tif (!env) return 1;\n\t\tconst [executable, ...commandArgs] = command;\n\t\tconfig = {\n\t\t\tcommand: executable,\n\t\t\t...(commandArgs.length > 0 ? { args: commandArgs } : {}),\n\t\t\t...(Object.keys(env).length > 0 ? { env } : {}),\n\t\t\t...(value(\"cwd\") === undefined ? {} : { cwd: value(\"cwd\") }),\n\t\t};\n\t}\n\tif (exposure !== undefined) config.exposure = exposure;\n\tconst description = value(\"description\");\n\tif (description !== undefined) config.description = description;\n\tconst validated = validateMcpServerConfig(name, config);\n\tif (typeof validated === \"string\") {\n\t\terror(validated);\n\t\treturn 1;\n\t}\n\n\tconst project = values.has(\"local\");\n\tconst path = project ? projectConfig : join(options.agentDir, \"mcp.json\");\n\tconst scope = project ? \"project\" : \"global\";\n\tlet replaced: boolean;\n\ttry {\n\t\treplaced = addMcpServerConfig(path, name, validated);\n\t} catch (addError) {\n\t\terror(`Could not update ${path}: ${errorMessage(addError)}`);\n\t\treturn 1;\n\t}\n\tlog(`${replaced ? \"Replaced\" : \"Added\"} ${scope} MCP server \"${name}\" in ${path}.`);\n\tif (project && new ProjectTrustStore(options.agentDir).get(options.cwd) !== true) {\n\t\tlog(`The project is not trusted, so ${path} is ignored until you start ${APP_NAME} in the project and trust it.`);\n\t}\n\t// HTTP servers without an Authorization header may use OAuth.\n\tconst mayNeedSignIn =\n\t\t\"url\" in validated &&\n\t\t!Object.keys(validated.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n\tlog(\n\t\t`Check it with: ${APP_NAME} mcp list${mayNeedSignIn ? `. If it requires sign-in: ${APP_NAME} mcp login ${name}` : \"\"}`,\n\t);\n\treturn 0;\n}\n\nfunction remove(\n\targs: string[],\n\tprojectConfig: string,\n\toptions: McpCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): number {\n\tconst parsed = parseOptions(args, { local: \"flag\" }, error);\n\tif (!parsed) return 1;\n\tconst [name, ...extra] = parsed.positional;\n\tif (!name || extra.length > 0) {\n\t\terror(`Usage: ${APP_NAME} mcp remove <server> [-l]\\n${HELP_HINT}`);\n\t\treturn 1;\n\t}\n\tconst project = parsed.values.has(\"local\");\n\tconst globalConfig = join(options.agentDir, \"mcp.json\");\n\tconst path = project ? projectConfig : globalConfig;\n\tconst scope = project ? \"project\" : \"global\";\n\tlet removed: boolean;\n\ttry {\n\t\tremoved = removeMcpServerConfig(path, name);\n\t} catch (removeError) {\n\t\terror(`Could not update ${path}: ${errorMessage(removeError)}`);\n\t\treturn 1;\n\t}\n\tif (removed) {\n\t\tlog(`Removed ${scope} MCP server \"${name}\" from ${path}.`);\n\t\treturn 0;\n\t}\n\tconst other = loadMcpConfig({ agentDir: options.agentDir, cwd: options.cwd, projectTrusted: true }).servers.find(\n\t\t(server) => server.name === name && server.scope !== scope,\n\t);\n\terror(\n\t\t`No ${scope} MCP server named \"${name}\" in ${path}.${other ? ` It is defined in ${other.source}${other.scope === \"project\" ? \"; use --local\" : \"; omit --local\"}.` : \"\"}`,\n\t);\n\treturn 1;\n}\n\nasync function list(\n\tloaded: LoadedMcpConfig,\n\tjson: boolean,\n\tuntrustedNote: string | undefined,\n\toptions: McpCommandOptions,\n\tcredentials: McpOAuthCredentialStore,\n\tlog: (line: string) => void,\n): Promise<number> {\n\tconst reports = await Promise.all(\n\t\tloaded.servers.map(async (entry): Promise<ServerReport> => {\n\t\t\tconst report: ServerReport = {\n\t\t\t\tname: entry.name,\n\t\t\t\tscope: entry.scope ?? \"global\",\n\t\t\t\tsource: entry.source,\n\t\t\t\tenabled: entry.config.enabled !== false,\n\t\t\t\texposure: entry.config.exposure ?? \"codemode\",\n\t\t\t\ttransport: describeTransport(entry),\n\t\t\t\tstate: \"disabled\",\n\t\t\t\ttools: [],\n\t\t\t};\n\t\t\tif (!report.enabled) return report;\n\t\t\tconst connection = createConnection(entry, options, credentials);\n\t\t\ttry {\n\t\t\t\tawait connection.getClient();\n\t\t\t} catch {\n\t\t\t\t// The connection records the state and error.\n\t\t\t}\n\t\t\treport.state = connection.state;\n\t\t\treport.tools = connection.tools.map((tool) => tool.name);\n\t\t\tconst overrides = connection.tools.flatMap((tool) => {\n\t\t\t\tconst exposure = getMcpToolExposure(entry.config, tool.name);\n\t\t\t\treturn exposure === report.exposure ? [] : [[tool.name, exposure] as const];\n\t\t\t});\n\t\t\tif (overrides.length > 0) report.toolExposure = Object.fromEntries(overrides);\n\t\t\tif (connection.hasResources) {\n\t\t\t\treport.resources = connection.resources.length;\n\t\t\t\treport.resourceTemplates = connection.resourceTemplates.length;\n\t\t\t}\n\t\t\tif (connection.state !== \"connected\" && connection.error) report.error = connection.error;\n\t\t\tawait connection.close();\n\t\t\treturn report;\n\t\t}),\n\t);\n\tconst failed = loaded.errors.length > 0 || reports.some((report) => report.enabled && report.state !== \"connected\");\n\n\tif (json) {\n\t\tlog(\n\t\t\tJSON.stringify(\n\t\t\t\t{ servers: reports, errors: loaded.errors, ...(untrustedNote ? { note: untrustedNote } : {}) },\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t),\n\t\t);\n\t\treturn failed ? 1 : 0;\n\t}\n\tif (reports.length === 0 && loaded.errors.length === 0) {\n\t\tlog(`No MCP servers configured. Add them to ${join(options.agentDir, \"mcp.json\")} or .pi/mcp.json.`);\n\t}\n\tfor (const report of reports) {\n\t\tconst state =\n\t\t\treport.state === \"connected\"\n\t\t\t\t? `connected, ${report.tools.length} tool${report.tools.length === 1 ? \"\" : \"s\"}`\n\t\t\t\t: report.state === \"needs-auth\"\n\t\t\t\t\t? \"needs sign-in\"\n\t\t\t\t\t: report.state;\n\t\tlog(`${report.name}: ${state} (${report.exposure}, ${report.scope})`);\n\t\tlog(` ${report.transport}`);\n\t\tif (report.state === \"needs-auth\") log(` sign in with: ${APP_NAME} mcp login ${report.name}`);\n\t\tif (report.tools.length > 0) {\n\t\t\tconst tools = report.tools.map((tool) => {\n\t\t\t\tconst exposure = report.toolExposure?.[tool];\n\t\t\t\treturn exposure ? `${tool} [${exposure}]` : tool;\n\t\t\t});\n\t\t\tlog(` tools: ${tools.join(\", \")}`);\n\t\t}\n\t\tif (report.resources !== undefined) {\n\t\t\tlog(` resources: ${report.resources}, URI templates: ${report.resourceTemplates ?? 0}`);\n\t\t}\n\t\tif (report.error) log(` ${report.error.split(\"\\n\").join(\"\\n \")}`);\n\t}\n\tfor (const configError of loaded.errors) log(`config error: ${configError}`);\n\tif (untrustedNote) log(untrustedNote);\n\treturn failed ? 1 : 0;\n}\n\nasync function login(\n\tentry: McpServerEntry,\n\tconnection: McpServerConnection,\n\turl: string,\n\ttimeoutMs: number,\n\toptions: McpCommandOptions,\n\tcredentials: McpOAuthCredentialStore,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): Promise<number> {\n\tconst { name } = entry;\n\t// Connecting first answers whether a sign-in is needed and records the server's challenge.\n\ttry {\n\t\tawait connection.getClient();\n\t\tlog(`Already signed in to MCP server \"${name}\" (${connection.tools.length} tools).`);\n\t\treturn 0;\n\t} catch {\n\t\tif (connection.state !== \"needs-auth\") {\n\t\t\terror(`MCP server \"${name}\" failed to connect: ${connection.error ?? \"unknown error\"}`);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tconst openUrl = options.openUrl ?? openBrowser;\n\tconst interactive = process.stdin.isTTY === true && options.openUrl === undefined;\n\ttry {\n\t\tawait signInMcpServer({\n\t\t\tserverUrl: url,\n\t\t\tstore: credentials.forServer(url),\n\t\t\tsettings: connection.oauthSettings(),\n\t\t\tchallenge: connection.challenge,\n\t\t\tprompt: {\n\t\t\t\tshowAuthorizationUrl: (authorizationUrl) => {\n\t\t\t\t\tlog(`Sign in to MCP server \"${name}\" in your browser:\\n${authorizationUrl.href}`);\n\t\t\t\t\topenUrl(authorizationUrl.href);\n\t\t\t\t},\n\t\t\t\tpromptForRedirectUrl: (signal) => waitForRedirectUrl(signal, timeoutMs, interactive),\n\t\t\t},\n\t\t});\n\t} catch (signInError) {\n\t\terror(\n\t\t\tsignInError instanceof McpSignInCancelledError\n\t\t\t\t? `Sign-in to MCP server \"${name}\" was cancelled or not completed within ${Math.round(timeoutMs / 1000)} seconds.`\n\t\t\t\t: `Sign-in to MCP server \"${name}\" failed: ${errorMessage(signInError)}`,\n\t\t);\n\t\treturn 1;\n\t}\n\tconnection.challenge = undefined;\n\ttry {\n\t\tawait connection.reconnect();\n\t} catch (connectError) {\n\t\terror(`Signed in, but ${errorMessage(connectError)}`);\n\t\treturn 1;\n\t}\n\tlog(`Signed in to MCP server \"${name}\" (${connection.tools.length} tools).`);\n\treturn 0;\n}\n\n/**\n * The pasted redirect URL in a terminal; otherwise only the browser callback can finish the sign-in.\n * Resolves to undefined (cancelling the sign-in) after `timeoutMs`, or when the callback arrived.\n */\nasync function waitForRedirectUrl(\n\tsignal: AbortSignal,\n\ttimeoutMs: number,\n\tinteractive: boolean,\n): Promise<string | undefined> {\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort();\n\tsignal.addEventListener(\"abort\", abort, { once: true });\n\tconst timer = setTimeout(abort, timeoutMs);\n\ttry {\n\t\tif (!interactive) {\n\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\tcontroller.signal.addEventListener(\"abort\", () => resolve(), { once: true }),\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst readline = createInterface({ input: process.stdin, output: process.stderr });\n\t\ttry {\n\t\t\treturn await readline.question(\n\t\t\t\t\"If the browser cannot reach this machine, paste the URL it was redirected to: \",\n\t\t\t\t{ signal: controller.signal },\n\t\t\t);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t} finally {\n\t\t\treadline.close();\n\t\t}\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal.removeEventListener(\"abort\", abort);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../src/extensions/mcp/cli.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAElB,aAAa,EAEb,qBAAqB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,sBAAsB,EACtB,uBAAuB,EACvB,mBAAmB,EACnB,YAAY,EACZ,uBAAuB,EACvB,eAAe,GACf,MAAM,cAAc,CAAC;AAEtB,MAAM,IAAI,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;IAChC,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;;;UAGF,eAAe,6CAA6C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AAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACnF,IAAI,CAAC;YACJ,OAAO,MAAM,QAAQ,CAAC,QAAQ,CAC7B,gFAAgF,EAChF,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAC7B,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,SAAS,CAAC;QAClB,CAAC;gBAAS,CAAC;YACV,QAAQ,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;IACF,CAAC;YAAS,CAAC;QACV,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;AACF,CAAC","sourcesContent":["/**\n * `pi mcp`: add, remove, and check MCP servers and sign in to them outside a session. Agents run it\n * through bash to configure servers, verify an `mcp.json` they wrote, and start an OAuth sign-in;\n * the user only approves access in the browser. Running sessions pick up new credentials on their\n * next turn.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport chalk from \"chalk\";\nimport { APP_NAME, CONFIG_DIR_NAME } from \"../../config.ts\";\nimport { validateMcpServerConfig } from \"../../core/mcp-servers.ts\";\nimport { ProjectTrustStore } from \"../../core/trust-manager.ts\";\nimport { openBrowser } from \"../../utils/open-browser.ts\";\nimport {\n\taddMcpServerConfig,\n\tgetMcpToolExposure,\n\ttype LoadedMcpConfig,\n\tloadMcpConfig,\n\ttype McpServerEntry,\n\tremoveMcpServerConfig,\n} from \"./config.ts\";\nimport {\n\tcreateDefaultTransport,\n\tMcpOAuthCredentialStore,\n\tMcpServerConnection,\n\tMcpServerLog,\n\tMcpSignInCancelledError,\n\tsignInMcpServer,\n} from \"./runtime.ts\";\n\nconst HELP = `${chalk.bold(\"Usage:\")}\n ${APP_NAME} mcp add <server> [options] -- <command> [args...]\n ${APP_NAME} mcp add <server> [options] --url <url>\n ${APP_NAME} mcp remove <server> [-l]\n ${APP_NAME} mcp list [--json]\n ${APP_NAME} mcp login <server> [--timeout <seconds>]\n ${APP_NAME} mcp logout <server>\n\nConfigure and check MCP servers and sign in to OAuth servers without starting a session.\nReads ~/${CONFIG_DIR_NAME}/agent/mcp.json and, in trusted projects, ${CONFIG_DIR_NAME}/mcp.json.\n\nCommands:\n add <server> Add or replace a server in mcp.json\n remove <server> Remove a server from mcp.json\n list Show state, tools, and errors (exits 1 on failure)\n login <server> Sign in through the browser\n logout <server> Delete the stored OAuth credentials\n\nOptions for add and remove:\n -l, --local Use ${CONFIG_DIR_NAME}/mcp.json in the current project instead of the global file\n\nOptions for add:\n --url <url> Streamable HTTP server URL (instead of a command)\n --env <KEY=VALUE> Environment variable for a stdio server (repeatable)\n --cwd <dir> Working directory for a stdio server\n --header <KEY=VALUE> HTTP header (repeatable)\n --bearer-token-env-var <NAME>\n Send \"Authorization: Bearer \\${NAME}\"\n --oauth-client-id <id> Pre-registered OAuth client id\n --oauth-client-secret <secret>\n OAuth client secret (may be \\${NAME} or !command)\n --oauth-callback-port <port>\n Fixed OAuth callback port\n --oauth-client-name <name>\n Client name sent when registering with the OAuth server\n --exposure <mode> codemode (default), deferred, direct, or hidden\n --description <text> What the server offers, shown in the system prompt\n\nOther options:\n --json Print the list as JSON\n --timeout <seconds> How long login waits for the browser (default: 300)`;\n\nconst HELP_HINT = chalk.dim(`Use \"${APP_NAME} mcp --help\" for usage.`);\n\nconst DEFAULT_LOGIN_TIMEOUT_SECONDS = 300;\n\nexport interface McpCommandOptions {\n\tcwd: string;\n\tagentDir: string;\n\t/** Defaults to `mcp-auth.json` in the agent directory. */\n\tcredentials?: McpOAuthCredentialStore;\n\t/** Defaults to the platform browser. */\n\topenUrl?: (url: string) => void;\n\t/** Defaults to console output. */\n\tlog?: (line: string) => void;\n\terror?: (line: string) => void;\n}\n\ninterface ServerReport {\n\tname: string;\n\tscope: string;\n\tsource: string;\n\tenabled: boolean;\n\texposure: string;\n\ttransport: string;\n\tstate: string;\n\ttools: string[];\n\t/** Tools whose exposure differs from the server's, from `toolExposure`. */\n\ttoolExposure?: Record<string, string>;\n\tresources?: number;\n\tresourceTemplates?: number;\n\terror?: string;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction describeTransport(entry: McpServerEntry): string {\n\tconst { config } = entry;\n\treturn \"url\" in config ? config.url : [config.command, ...(config.args ?? [])].join(\" \");\n}\n\nfunction createConnection(entry: McpServerEntry, options: McpCommandOptions, credentials: McpOAuthCredentialStore) {\n\treturn new McpServerConnection({\n\t\tentry,\n\t\tcwd: options.cwd,\n\t\tcreateTransport: createDefaultTransport,\n\t\tcredentials,\n\t\tlog: new McpServerLog(join(options.agentDir, \"mcp.log\")),\n\t\tonTools: () => {},\n\t});\n}\n\n/** Short spellings of options. `-l`/`--local` match `pi install`. */\nconst OPTION_ALIASES = new Map([[\"-l\", \"--local\"]]);\n\ninterface ParsedOptions {\n\tpositional: string[];\n\tvalues: Map<string, string | true>;\n\t/** Values of `list` options, in order. */\n\tlists: Map<string, string[]>;\n}\n\n/**\n * Parse `--name value` options; returns undefined and reports unknown ones. `--` ends the options,\n * as does reaching `maxPositionals` positional arguments: the remaining arguments are positional,\n * so a command's own options (`add <server> <command> --flag`) are passed through.\n */\nfunction parseOptions(\n\targs: string[],\n\tknown: Record<string, \"flag\" | \"value\" | \"list\">,\n\terror: (line: string) => void,\n\tmaxPositionals = Number.POSITIVE_INFINITY,\n): ParsedOptions | undefined {\n\tconst positional: string[] = [];\n\tconst values = new Map<string, string | true>();\n\tconst lists = new Map<string, string[]>();\n\tfor (let index = 0; index < args.length; index++) {\n\t\tconst arg = OPTION_ALIASES.get(args[index]) ?? args[index];\n\t\tif (arg === \"--\" || positional.length >= maxPositionals) {\n\t\t\tpositional.push(...args.slice(arg === \"--\" ? index + 1 : index));\n\t\t\tbreak;\n\t\t}\n\t\tif (!arg.startsWith(\"--\")) {\n\t\t\tpositional.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst name = arg.slice(2);\n\t\tconst kind = known[name];\n\t\tif (!kind) {\n\t\t\terror(`Unknown option ${arg}.\\n${HELP_HINT}`);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (kind === \"flag\") {\n\t\t\tvalues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tconst value = args[++index];\n\t\tif (value === undefined) {\n\t\t\terror(`${arg} needs a value.`);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (kind === \"list\") lists.set(name, [...(lists.get(name) ?? []), value]);\n\t\telse values.set(name, value);\n\t}\n\treturn { positional, values, lists };\n}\n\n/** Run `pi mcp <args>` and return the exit code. */\nexport async function runMcpCommand(args: string[], options: McpCommandOptions): Promise<number> {\n\tconst log = options.log ?? ((line: string) => console.log(line));\n\tconst error = options.error ?? ((line: string) => console.error(line));\n\tconst [command, ...rest] = args;\n\tif (command === undefined || command === \"help\" || args.includes(\"--help\") || args.includes(\"-h\")) {\n\t\tlog(HELP);\n\t\treturn 0;\n\t}\n\n\tconst projectConfig = join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\");\n\tif (command === \"add\" || command === \"remove\") {\n\t\treturn command === \"add\"\n\t\t\t? add(rest, projectConfig, options, log, error)\n\t\t\t: remove(rest, projectConfig, options, log, error);\n\t}\n\tconst projectTrusted = new ProjectTrustStore(options.agentDir).get(options.cwd) === true;\n\tconst loaded = loadMcpConfig({ agentDir: options.agentDir, cwd: options.cwd, projectTrusted });\n\tconst untrustedNote =\n\t\t!projectTrusted && existsSync(projectConfig)\n\t\t\t? `${projectConfig} is ignored because the project is not trusted. Start ${APP_NAME} in the project to trust it.`\n\t\t\t: undefined;\n\tconst credentials = options.credentials ?? new McpOAuthCredentialStore();\n\n\tswitch (command) {\n\t\tcase \"list\": {\n\t\t\tconst parsed = parseOptions(rest, { json: \"flag\" }, error);\n\t\t\tif (!parsed) return 1;\n\t\t\tif (parsed.positional.length > 0) {\n\t\t\t\terror(`Usage: ${APP_NAME} mcp list [--json]\\n${HELP_HINT}`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn list(loaded, parsed.values.has(\"json\"), untrustedNote, options, credentials, log);\n\t\t}\n\t\tcase \"login\":\n\t\tcase \"logout\": {\n\t\t\tconst parsed = parseOptions(rest, command === \"login\" ? { timeout: \"value\" } : {}, error);\n\t\t\tif (!parsed) return 1;\n\t\t\tconst [name, ...extra] = parsed.positional;\n\t\t\tif (!name || extra.length > 0) {\n\t\t\t\terror(`Usage: ${APP_NAME} mcp ${command} <server>\\n${HELP_HINT}`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tconst entry = loaded.servers.find((server) => server.name === name);\n\t\t\tif (!entry) {\n\t\t\t\terror(\n\t\t\t\t\t`No MCP server named \"${name}\".${untrustedNote ? ` ${untrustedNote}` : \"\"} Configured: ${loaded.servers.map((server) => server.name).join(\", \") || \"none\"}.`,\n\t\t\t\t);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tconst connection = createConnection(entry, options, credentials);\n\t\t\tconst url = connection.oauthUrl;\n\t\t\tif (!url) {\n\t\t\t\terror(`MCP server \"${name}\" does not use OAuth. Only HTTP servers without an Authorization header do.`);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (command === \"logout\") {\n\t\t\t\tconst removed = credentials.remove(name, url);\n\t\t\t\tlog(removed ? `Signed out of MCP server \"${name}\".` : `No stored credentials for MCP server \"${name}\".`);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tconst timeout = Number(parsed.values.get(\"timeout\") ?? DEFAULT_LOGIN_TIMEOUT_SECONDS);\n\t\t\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\t\t\terror(\"--timeout must be a positive number of seconds.\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await login(entry, connection, url, timeout * 1000, options, credentials, log, error);\n\t\t\t} finally {\n\t\t\t\tawait connection.close();\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\terror(`Unknown mcp command \"${command}\".\\n${HELP_HINT}`);\n\t\t\treturn 1;\n\t}\n}\n\n/** Parse `KEY=VALUE` pairs of a repeatable option into a record. */\nfunction parsePairs(option: string, pairs: string[] | undefined, error: (line: string) => void) {\n\tif (!pairs) return {};\n\tconst record: Record<string, string> = {};\n\tfor (const pair of pairs) {\n\t\tconst separator = pair.indexOf(\"=\");\n\t\tif (separator <= 0) {\n\t\t\terror(`--${option} expects KEY=VALUE, got \"${pair}\".`);\n\t\t\treturn undefined;\n\t\t}\n\t\trecord[pair.slice(0, separator)] = pair.slice(separator + 1);\n\t}\n\treturn record;\n}\n\nfunction add(\n\targs: string[],\n\tprojectConfig: string,\n\toptions: McpCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): number {\n\tconst usage = `Usage: ${APP_NAME} mcp add <server> [options] (--url <url> | -- <command> [args...])\\n${HELP_HINT}`;\n\tconst parsed = parseOptions(\n\t\targs,\n\t\t{\n\t\t\tlocal: \"flag\",\n\t\t\turl: \"value\",\n\t\t\tenv: \"list\",\n\t\t\tcwd: \"value\",\n\t\t\theader: \"list\",\n\t\t\t\"bearer-token-env-var\": \"value\",\n\t\t\t\"oauth-client-id\": \"value\",\n\t\t\t\"oauth-client-secret\": \"value\",\n\t\t\t\"oauth-callback-port\": \"value\",\n\t\t\t\"oauth-client-name\": \"value\",\n\t\t\texposure: \"value\",\n\t\t\tdescription: \"value\",\n\t\t},\n\t\terror,\n\t\t2,\n\t);\n\tif (!parsed) return 1;\n\tconst { positional, values, lists } = parsed;\n\tconst [name, ...command] = positional;\n\tconst url = values.get(\"url\");\n\tif (!name || (url === undefined) === (command.length === 0)) {\n\t\terror(usage);\n\t\treturn 1;\n\t}\n\tconst value = (option: string) => {\n\t\tconst found = values.get(option);\n\t\treturn typeof found === \"string\" ? found : undefined;\n\t};\n\tconst exposure = value(\"exposure\");\n\tconst httpOnly = [\n\t\t\"header\",\n\t\t\"bearer-token-env-var\",\n\t\t\"oauth-client-id\",\n\t\t\"oauth-client-secret\",\n\t\t\"oauth-callback-port\",\n\t\t\"oauth-client-name\",\n\t];\n\tconst stdioOnly = [\"env\", \"cwd\"];\n\tconst misplaced = (url === undefined ? httpOnly : stdioOnly).find(\n\t\t(option) => values.has(option) || lists.has(option),\n\t);\n\tif (misplaced) {\n\t\terror(`--${misplaced} only applies to ${url === undefined ? \"HTTP servers (--url)\" : \"stdio servers\"}.`);\n\t\treturn 1;\n\t}\n\n\tlet config: Record<string, unknown>;\n\tif (typeof url === \"string\") {\n\t\tconst headers = parsePairs(\"header\", lists.get(\"header\"), error);\n\t\tif (!headers) return 1;\n\t\tconst bearer = value(\"bearer-token-env-var\");\n\t\tif (bearer !== undefined) headers.Authorization = `Bearer \\${${bearer}}`;\n\t\tconst port = value(\"oauth-callback-port\");\n\t\tconst oauth = {\n\t\t\t...(value(\"oauth-client-id\") === undefined ? {} : { clientId: value(\"oauth-client-id\") }),\n\t\t\t...(value(\"oauth-client-secret\") === undefined ? {} : { clientSecret: value(\"oauth-client-secret\") }),\n\t\t\t...(port === undefined ? {} : { callbackPort: Number(port) }),\n\t\t\t...(value(\"oauth-client-name\") === undefined ? {} : { clientName: value(\"oauth-client-name\") }),\n\t\t};\n\t\tconfig = {\n\t\t\turl,\n\t\t\t...(Object.keys(headers).length > 0 ? { headers } : {}),\n\t\t\t...(Object.keys(oauth).length > 0 ? { oauth } : {}),\n\t\t};\n\t} else {\n\t\tconst env = parsePairs(\"env\", lists.get(\"env\"), error);\n\t\tif (!env) return 1;\n\t\tconst [executable, ...commandArgs] = command;\n\t\tconfig = {\n\t\t\tcommand: executable,\n\t\t\t...(commandArgs.length > 0 ? { args: commandArgs } : {}),\n\t\t\t...(Object.keys(env).length > 0 ? { env } : {}),\n\t\t\t...(value(\"cwd\") === undefined ? {} : { cwd: value(\"cwd\") }),\n\t\t};\n\t}\n\tif (exposure !== undefined) config.exposure = exposure;\n\tconst description = value(\"description\");\n\tif (description !== undefined) config.description = description;\n\tconst validated = validateMcpServerConfig(name, config);\n\tif (typeof validated === \"string\") {\n\t\terror(validated);\n\t\treturn 1;\n\t}\n\n\tconst project = values.has(\"local\");\n\tconst path = project ? projectConfig : join(options.agentDir, \"mcp.json\");\n\tconst scope = project ? \"project\" : \"global\";\n\tlet replaced: boolean;\n\ttry {\n\t\treplaced = addMcpServerConfig(path, name, validated);\n\t} catch (addError) {\n\t\terror(`Could not update ${path}: ${errorMessage(addError)}`);\n\t\treturn 1;\n\t}\n\tlog(`${replaced ? \"Replaced\" : \"Added\"} ${scope} MCP server \"${name}\" in ${path}.`);\n\tif (project && new ProjectTrustStore(options.agentDir).get(options.cwd) !== true) {\n\t\tlog(`The project is not trusted, so ${path} is ignored until you start ${APP_NAME} in the project and trust it.`);\n\t}\n\t// HTTP servers without an Authorization header may use OAuth.\n\tconst mayNeedSignIn =\n\t\t\"url\" in validated &&\n\t\t!Object.keys(validated.headers ?? {}).some((header) => header.toLowerCase() === \"authorization\");\n\tlog(\n\t\t`Check it with: ${APP_NAME} mcp list${mayNeedSignIn ? `. If it requires sign-in: ${APP_NAME} mcp login ${name}` : \"\"}`,\n\t);\n\treturn 0;\n}\n\nfunction remove(\n\targs: string[],\n\tprojectConfig: string,\n\toptions: McpCommandOptions,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): number {\n\tconst parsed = parseOptions(args, { local: \"flag\" }, error);\n\tif (!parsed) return 1;\n\tconst [name, ...extra] = parsed.positional;\n\tif (!name || extra.length > 0) {\n\t\terror(`Usage: ${APP_NAME} mcp remove <server> [-l]\\n${HELP_HINT}`);\n\t\treturn 1;\n\t}\n\tconst project = parsed.values.has(\"local\");\n\tconst globalConfig = join(options.agentDir, \"mcp.json\");\n\tconst path = project ? projectConfig : globalConfig;\n\tconst scope = project ? \"project\" : \"global\";\n\tlet removed: boolean;\n\ttry {\n\t\tremoved = removeMcpServerConfig(path, name);\n\t} catch (removeError) {\n\t\terror(`Could not update ${path}: ${errorMessage(removeError)}`);\n\t\treturn 1;\n\t}\n\tif (removed) {\n\t\tlog(`Removed ${scope} MCP server \"${name}\" from ${path}.`);\n\t\treturn 0;\n\t}\n\tconst other = loadMcpConfig({ agentDir: options.agentDir, cwd: options.cwd, projectTrusted: true }).servers.find(\n\t\t(server) => server.name === name && server.scope !== scope,\n\t);\n\terror(\n\t\t`No ${scope} MCP server named \"${name}\" in ${path}.${other ? ` It is defined in ${other.source}${other.scope === \"project\" ? \"; use --local\" : \"; omit --local\"}.` : \"\"}`,\n\t);\n\treturn 1;\n}\n\nasync function list(\n\tloaded: LoadedMcpConfig,\n\tjson: boolean,\n\tuntrustedNote: string | undefined,\n\toptions: McpCommandOptions,\n\tcredentials: McpOAuthCredentialStore,\n\tlog: (line: string) => void,\n): Promise<number> {\n\tconst reports = await Promise.all(\n\t\tloaded.servers.map(async (entry): Promise<ServerReport> => {\n\t\t\tconst report: ServerReport = {\n\t\t\t\tname: entry.name,\n\t\t\t\tscope: entry.scope ?? \"global\",\n\t\t\t\tsource: entry.source,\n\t\t\t\tenabled: entry.config.enabled !== false,\n\t\t\t\texposure: entry.config.exposure ?? \"codemode\",\n\t\t\t\ttransport: describeTransport(entry),\n\t\t\t\tstate: \"disabled\",\n\t\t\t\ttools: [],\n\t\t\t};\n\t\t\tif (!report.enabled) return report;\n\t\t\tconst connection = createConnection(entry, options, credentials);\n\t\t\ttry {\n\t\t\t\tawait connection.getClient();\n\t\t\t} catch {\n\t\t\t\t// The connection records the state and error.\n\t\t\t}\n\t\t\treport.state = connection.state;\n\t\t\treport.tools = connection.tools.map((tool) => tool.name);\n\t\t\tconst overrides = connection.tools.flatMap((tool) => {\n\t\t\t\tconst exposure = getMcpToolExposure(entry.config, tool.name);\n\t\t\t\treturn exposure === report.exposure ? [] : [[tool.name, exposure] as const];\n\t\t\t});\n\t\t\tif (overrides.length > 0) report.toolExposure = Object.fromEntries(overrides);\n\t\t\tif (connection.hasResources) {\n\t\t\t\treport.resources = connection.resources.length;\n\t\t\t\treport.resourceTemplates = connection.resourceTemplates.length;\n\t\t\t}\n\t\t\tif (connection.state !== \"connected\" && connection.error) report.error = connection.error;\n\t\t\tawait connection.close();\n\t\t\treturn report;\n\t\t}),\n\t);\n\tconst failed = loaded.errors.length > 0 || reports.some((report) => report.enabled && report.state !== \"connected\");\n\n\tif (json) {\n\t\tlog(\n\t\t\tJSON.stringify(\n\t\t\t\t{ servers: reports, errors: loaded.errors, ...(untrustedNote ? { note: untrustedNote } : {}) },\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t),\n\t\t);\n\t\treturn failed ? 1 : 0;\n\t}\n\tif (reports.length === 0 && loaded.errors.length === 0) {\n\t\tlog(`No MCP servers configured. Add them to ${join(options.agentDir, \"mcp.json\")} or .pi/mcp.json.`);\n\t}\n\tfor (const report of reports) {\n\t\tconst state =\n\t\t\treport.state === \"connected\"\n\t\t\t\t? `connected, ${report.tools.length} tool${report.tools.length === 1 ? \"\" : \"s\"}`\n\t\t\t\t: report.state === \"needs-auth\"\n\t\t\t\t\t? \"needs sign-in\"\n\t\t\t\t\t: report.state;\n\t\tlog(`${report.name}: ${state} (${report.exposure}, ${report.scope})`);\n\t\tlog(` ${report.transport}`);\n\t\tif (report.state === \"needs-auth\") log(` sign in with: ${APP_NAME} mcp login ${report.name}`);\n\t\tif (report.tools.length > 0) {\n\t\t\tconst tools = report.tools.map((tool) => {\n\t\t\t\tconst exposure = report.toolExposure?.[tool];\n\t\t\t\treturn exposure ? `${tool} [${exposure}]` : tool;\n\t\t\t});\n\t\t\tlog(` tools: ${tools.join(\", \")}`);\n\t\t}\n\t\tif (report.resources !== undefined) {\n\t\t\tlog(` resources: ${report.resources}, URI templates: ${report.resourceTemplates ?? 0}`);\n\t\t}\n\t\tif (report.error) log(` ${report.error.split(\"\\n\").join(\"\\n \")}`);\n\t}\n\tfor (const configError of loaded.errors) log(`config error: ${configError}`);\n\tif (untrustedNote) log(untrustedNote);\n\treturn failed ? 1 : 0;\n}\n\nasync function login(\n\tentry: McpServerEntry,\n\tconnection: McpServerConnection,\n\turl: string,\n\ttimeoutMs: number,\n\toptions: McpCommandOptions,\n\tcredentials: McpOAuthCredentialStore,\n\tlog: (line: string) => void,\n\terror: (line: string) => void,\n): Promise<number> {\n\tconst { name } = entry;\n\t// Connecting first answers whether a sign-in is needed and records the server's challenge.\n\ttry {\n\t\tawait connection.getClient();\n\t\tlog(`Already signed in to MCP server \"${name}\" (${connection.tools.length} tools).`);\n\t\treturn 0;\n\t} catch {\n\t\tif (connection.state !== \"needs-auth\") {\n\t\t\terror(`MCP server \"${name}\" failed to connect: ${connection.error ?? \"unknown error\"}`);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tconst openUrl = options.openUrl ?? openBrowser;\n\tconst interactive = process.stdin.isTTY === true && options.openUrl === undefined;\n\ttry {\n\t\tawait signInMcpServer({\n\t\t\tserverUrl: url,\n\t\t\tstore: credentials.forServer(name, url),\n\t\t\tsettings: connection.oauthSettings(),\n\t\t\tchallenge: connection.challenge,\n\t\t\tprompt: {\n\t\t\t\tshowAuthorizationUrl: (authorizationUrl) => {\n\t\t\t\t\tlog(`Sign in to MCP server \"${name}\" in your browser:\\n${authorizationUrl.href}`);\n\t\t\t\t\topenUrl(authorizationUrl.href);\n\t\t\t\t},\n\t\t\t\tpromptForRedirectUrl: (signal) => waitForRedirectUrl(signal, timeoutMs, interactive),\n\t\t\t},\n\t\t});\n\t} catch (signInError) {\n\t\terror(\n\t\t\tsignInError instanceof McpSignInCancelledError\n\t\t\t\t? `Sign-in to MCP server \"${name}\" was cancelled or not completed within ${Math.round(timeoutMs / 1000)} seconds.`\n\t\t\t\t: `Sign-in to MCP server \"${name}\" failed: ${errorMessage(signInError)}`,\n\t\t);\n\t\treturn 1;\n\t}\n\tconnection.challenge = undefined;\n\ttry {\n\t\tawait connection.reconnect();\n\t} catch (connectError) {\n\t\terror(`Signed in, but ${errorMessage(connectError)}`);\n\t\treturn 1;\n\t}\n\tlog(`Signed in to MCP server \"${name}\" (${connection.tools.length} tools).`);\n\treturn 0;\n}\n\n/**\n * The pasted redirect URL in a terminal; otherwise only the browser callback can finish the sign-in.\n * Resolves to undefined (cancelling the sign-in) after `timeoutMs`, or when the callback arrived.\n */\nasync function waitForRedirectUrl(\n\tsignal: AbortSignal,\n\ttimeoutMs: number,\n\tinteractive: boolean,\n): Promise<string | undefined> {\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort();\n\tsignal.addEventListener(\"abort\", abort, { once: true });\n\tconst timer = setTimeout(abort, timeoutMs);\n\ttry {\n\t\tif (!interactive) {\n\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\tcontroller.signal.addEventListener(\"abort\", () => resolve(), { once: true }),\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst readline = createInterface({ input: process.stdin, output: process.stderr });\n\t\ttry {\n\t\t\treturn await readline.question(\n\t\t\t\t\"If the browser cannot reach this machine, paste the URL it was redirected to: \",\n\t\t\t\t{ signal: controller.signal },\n\t\t\t);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t} finally {\n\t\t\treadline.close();\n\t\t}\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal.removeEventListener(\"abort\", abort);\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAMH,OAAO,KAAK,EAGX,gBAAgB,EAChB,gBAAgB,EAEhB,MAAM,gCAAgC,CAAC;AAMxC,OAAO,EAEN,KAAK,eAAe,EAGpB,KAAK,oBAAoB,EACzB,KAAK,cAAc,EAEnB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,uBAAuB,EAAmB,MAAM,YAAY,CAAC;AAS3E,OAAO,KAAK,EAAqC,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAI3F,YAAY,EAAE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CAAC;IACxD,qFAAqF;IACrF,eAAe,CAAC,EAAE,mBAAmB,CAAC;IACtC,0DAA0D;IAC1D,WAAW,CAAC,EAAE,uBAAuB,CAAC;IACtC,8FAA8F;IAC9F,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,4FAA4F;IAC5F,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC5E;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AA4DD,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AAGjD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,OAAO,CAAC;AAe9C,wDAAwD;AACxD,MAAM,WAAW,gBAAgB;IAChC,KAAK,EAAE,cAAc,CAAC;IACtB,UAAU,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvC;AAQD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,SAAS,gBAAgB,EAAE,GAAG,MAAM,GAAG,SAAS,CA0B7F;AA2DD,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,gBAAgB,CAs4BtF"}
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
* current session for registered servers.
|
|
27
27
|
*/
|
|
28
28
|
import { join, resolve } from "node:path";
|
|
29
|
+
import { hyperlink } from "@earendil-works/pi-tui";
|
|
29
30
|
import { getAgentDir } from "../../config.js";
|
|
30
31
|
import { mcpNamespace } from "../../core/mcp-servers.js";
|
|
31
32
|
import { openBrowser } from "../../utils/open-browser.js";
|
|
@@ -81,7 +82,15 @@ const MAX_SERVER_DESCRIPTION_CHARS = 250;
|
|
|
81
82
|
* fit, the last servers are left out and counted in a closing line.
|
|
82
83
|
*/
|
|
83
84
|
export const MAX_SERVERS_SECTION_CHARS = 4096;
|
|
84
|
-
|
|
85
|
+
/** The section's first line. It explains only the ways of reaching tools that the listed servers use. */
|
|
86
|
+
function serversSectionIntro(reaches) {
|
|
87
|
+
let intro = "MCP servers whose tools are not declared to you.";
|
|
88
|
+
if (reaches.has("codemode"))
|
|
89
|
+
intro += " Call the tools of `codemode` servers from codemode scripts.";
|
|
90
|
+
if (reaches.has("tool_search"))
|
|
91
|
+
intro += " Load the tools of `tool_search` servers with `tool_search`.";
|
|
92
|
+
return intro;
|
|
93
|
+
}
|
|
85
94
|
function truncate(text, max) {
|
|
86
95
|
if (text.length <= max)
|
|
87
96
|
return text;
|
|
@@ -103,14 +112,12 @@ export function renderServersSection(servers) {
|
|
|
103
112
|
.sort((a, b) => a.entry.name.localeCompare(b.entry.name));
|
|
104
113
|
if (listed.length === 0)
|
|
105
114
|
return undefined;
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return `- ${mcpNamespace(server.entry.name)} (${reach})`;
|
|
110
|
-
});
|
|
115
|
+
const reaches = listed.map((server) => configuredExposures(server.entry).has("codemode") ? "codemode" : "tool_search");
|
|
116
|
+
const intro = serversSectionIntro(new Set(reaches));
|
|
117
|
+
const heads = listed.map((server, index) => `- ${mcpNamespace(server.entry.name)} (${reaches[index]})`);
|
|
111
118
|
const omitted = (count) => count > 0 ? [`- … ${count} more server${count === 1 ? "" : "s"}; find their tools with searchTools()`] : [];
|
|
112
119
|
// Characters of the intro, the first `kept` server lines without descriptions, and the omission line.
|
|
113
|
-
const size = (kept) => [
|
|
120
|
+
const size = (kept) => [intro, ...heads.slice(0, kept), ...omitted(listed.length - kept)].join("\n").length;
|
|
114
121
|
let kept = listed.length;
|
|
115
122
|
while (kept > 0 && size(kept) > MAX_SERVERS_SECTION_CHARS)
|
|
116
123
|
kept--;
|
|
@@ -122,7 +129,7 @@ export function renderServersSection(servers) {
|
|
|
122
129
|
const summary = perServer > 0 ? truncate(serverSummary(server), perServer) : "";
|
|
123
130
|
return summary ? `${heads[index]}: ${summary}` : heads[index];
|
|
124
131
|
});
|
|
125
|
-
return [
|
|
132
|
+
return [intro, ...lines, ...omitted(listed.length - kept)].join("\n");
|
|
126
133
|
}
|
|
127
134
|
/**
|
|
128
135
|
* Whether a codemode script needs the server: it names the server's namespace, or searches,
|
|
@@ -387,7 +394,7 @@ export function createMcpExtension(options = {}) {
|
|
|
387
394
|
const tokensAtSignIn = new Map();
|
|
388
395
|
const storedTokens = (connection) => {
|
|
389
396
|
const url = connection.oauthUrl;
|
|
390
|
-
return url && credentials ? JSON.stringify(credentials.tokens(url) ?? null) : "null";
|
|
397
|
+
return url && credentials ? JSON.stringify(credentials.tokens(connection.name, url) ?? null) : "null";
|
|
391
398
|
};
|
|
392
399
|
const onConnectionChange = (connection) => {
|
|
393
400
|
if (connection.state !== "needs-auth")
|
|
@@ -497,7 +504,7 @@ export function createMcpExtension(options = {}) {
|
|
|
497
504
|
try {
|
|
498
505
|
await runtime.signInMcpServer({
|
|
499
506
|
serverUrl: url,
|
|
500
|
-
store: getCredentials(runtime).forServer(url),
|
|
507
|
+
store: getCredentials(runtime).forServer(server.entry.name, url),
|
|
501
508
|
settings: connection.oauthSettings(),
|
|
502
509
|
challenge: connection.challenge,
|
|
503
510
|
prompt,
|
|
@@ -523,7 +530,7 @@ export function createMcpExtension(options = {}) {
|
|
|
523
530
|
const url = connection?.oauthUrl;
|
|
524
531
|
if (!connection || !url)
|
|
525
532
|
return false;
|
|
526
|
-
const removed = getCredentials(await loadMcpRuntime()).remove(url);
|
|
533
|
+
const removed = getCredentials(await loadMcpRuntime()).remove(server.entry.name, url);
|
|
527
534
|
await connection.signOut();
|
|
528
535
|
return removed;
|
|
529
536
|
};
|
|
@@ -814,7 +821,11 @@ export function createMcpExtension(options = {}) {
|
|
|
814
821
|
}
|
|
815
822
|
const failure = await signIn(server, {
|
|
816
823
|
showAuthorizationUrl: (url) => {
|
|
817
|
-
|
|
824
|
+
// Long URLs wrap, which some terminals cannot open; a short link line stays on one line.
|
|
825
|
+
const lines = ctx.mode === "tui"
|
|
826
|
+
? `${hyperlink(url.href, url.href)}\n${hyperlink(process.platform === "darwin" ? "Cmd+click to open" : "Ctrl+click to open", url.href)}`
|
|
827
|
+
: url.href;
|
|
828
|
+
ctx.ui.notify(`Sign in to MCP server "${name}" in your browser:\n${lines}`, "info");
|
|
818
829
|
openUrl(url.href);
|
|
819
830
|
},
|
|
820
831
|
promptForRedirectUrl: (signal) => ctx.ui.input(`Waiting for sign-in to "${name}". If the browser cannot reach this machine, paste the URL it was redirected to.`, "http://127.0.0.1:.../callback?code=...", { signal }),
|