@earendil-works/pi-coding-agent 0.99.0 → 0.99.2

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.
Files changed (146) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/bundle/chunks/anthropic-messages-UID2PALB.js +6 -0
  3. package/dist/bundle/chunks/{azure-openai-responses-EN5WOBET.js → azure-openai-responses-TLHNIYZK.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-IMTXZUO7.js → chunk-3KYEVQKX.js} +3 -3
  6. package/dist/bundle/chunks/{chunk-W2DOMZSC.js → chunk-3LH3ZQKY.js} +1 -1
  7. package/dist/bundle/chunks/chunk-3NVH2HQH.js +4 -0
  8. package/dist/bundle/chunks/{chunk-4CSSZFEW.js → chunk-3YAHQSW6.js} +23 -20
  9. package/dist/bundle/chunks/{chunk-LLMKQWZS.js → chunk-45SXDISG.js} +5 -7
  10. package/dist/bundle/chunks/chunk-6D7LHLKG.js +2 -0
  11. package/dist/bundle/chunks/{chunk-AXPY26X7.js → chunk-7QSPBJKW.js} +3 -3
  12. package/dist/bundle/chunks/{chunk-EPDRUIU6.js → chunk-ECRK44UV.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-PEHWOV5U.js → chunk-G3UZ5FWD.js} +12 -23
  14. package/dist/bundle/chunks/chunk-LD2P6SFZ.js +2 -0
  15. package/dist/bundle/chunks/{chunk-J4CWPC4N.js → chunk-OSKPX3Z5.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-LRS5S6EK.js → chunk-R5J3MOBF.js} +1 -1
  17. package/dist/bundle/chunks/chunk-VIV3CWXG.js +2 -0
  18. package/dist/bundle/chunks/{cli-AZXNGIZH.js → cli-ALNBTL3U.js} +6 -4
  19. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-XJQQYGGU.js → cloudflare-workers-ai-system-one-NPQN263E.js} +1 -1
  20. package/dist/bundle/chunks/codemode-worker.js +23 -3
  21. package/dist/bundle/chunks/{execute-7XXPZAWW.js → execute-RC7W4ML3.js} +26 -6
  22. package/dist/bundle/chunks/github-copilot.js +1 -1
  23. package/dist/bundle/chunks/{google-generative-ai-CQAKKJTA.js → google-generative-ai-APTPZOQL.js} +1 -1
  24. package/dist/bundle/chunks/{google-vertex-AE36YXJU.js → google-vertex-MXCOSOY3.js} +1 -1
  25. package/dist/bundle/chunks/{llama-cpp-classify-PJJYKPLD.js → llama-cpp-classify-XT44PI3C.js} +1 -1
  26. package/dist/bundle/chunks/{mistral-conversations-KEYTXJM7.js → mistral-conversations-DKVFNQL6.js} +1 -1
  27. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  28. package/dist/bundle/chunks/{openai-codex-responses-JQTCOVEG.js → openai-codex-responses-3GKGNXC4.js} +1 -1
  29. package/dist/bundle/chunks/{openai-completions-XW2Q5HVC.js → openai-completions-JXDDPZ23.js} +1 -1
  30. package/dist/bundle/chunks/{openai-responses-6AXWFL75.js → openai-responses-S7GKCCDG.js} +1 -1
  31. package/dist/bundle/chunks/{openrouter-images-TPQ4V6OR.js → openrouter-images-ZVXWCSIM.js} +1 -1
  32. package/dist/bundle/chunks/{runtime-G5WJPRBM.js → runtime-NJPX4ID2.js} +1 -1
  33. package/dist/bundle/chunks/{typesafe-system-one-E7A4HNJI.js → typesafe-system-one-A4CZTQWZ.js} +1 -1
  34. package/dist/bundle/chunks/virtual-modules-5UGH4HRZ.js +2 -0
  35. package/dist/bundle/cli-runtime.js +1 -1
  36. package/dist/bundle/index.js +1 -1
  37. package/dist/bundle/rpc-entry.js +1 -1
  38. package/dist/config.d.ts +5 -8
  39. package/dist/config.d.ts.map +1 -1
  40. package/dist/config.js +16 -13
  41. package/dist/config.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +7 -1
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +14 -2
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/extensions/loader.d.ts.map +1 -1
  47. package/dist/core/extensions/loader.js +13 -1
  48. package/dist/core/extensions/loader.js.map +1 -1
  49. package/dist/core/extensions/types.d.ts +6 -1
  50. package/dist/core/extensions/types.d.ts.map +1 -1
  51. package/dist/core/extensions/types.js.map +1 -1
  52. package/dist/core/mcp-servers.d.ts +28 -7
  53. package/dist/core/mcp-servers.d.ts.map +1 -1
  54. package/dist/core/mcp-servers.js +45 -11
  55. package/dist/core/mcp-servers.js.map +1 -1
  56. package/dist/core/model-resolver.js +1 -1
  57. package/dist/core/model-resolver.js.map +1 -1
  58. package/dist/core/model-runtime.d.ts +6 -0
  59. package/dist/core/model-runtime.d.ts.map +1 -1
  60. package/dist/core/model-runtime.js +22 -18
  61. package/dist/core/model-runtime.js.map +1 -1
  62. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  63. package/dist/core/remote-catalog-provider.js +4 -9
  64. package/dist/core/remote-catalog-provider.js.map +1 -1
  65. package/dist/core/sdk.d.ts.map +1 -1
  66. package/dist/core/sdk.js +1 -0
  67. package/dist/core/sdk.js.map +1 -1
  68. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  69. package/dist/core/tools/renderers/bash.js +11 -31
  70. package/dist/core/tools/renderers/bash.js.map +1 -1
  71. package/dist/core/virtual-models.d.ts +2 -0
  72. package/dist/core/virtual-models.d.ts.map +1 -1
  73. package/dist/core/virtual-models.js +19 -12
  74. package/dist/core/virtual-models.js.map +1 -1
  75. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  76. package/dist/extensions/codemode/execute.js +43 -4
  77. package/dist/extensions/codemode/execute.js.map +1 -1
  78. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  79. package/dist/extensions/codemode/renderer.js +43 -25
  80. package/dist/extensions/codemode/renderer.js.map +1 -1
  81. package/dist/extensions/codemode/tool.d.ts +5 -4
  82. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  83. package/dist/extensions/codemode/tool.js +22 -31
  84. package/dist/extensions/codemode/tool.js.map +1 -1
  85. package/dist/extensions/codemode/worker.d.ts +1 -1
  86. package/dist/extensions/codemode/worker.js +1 -1
  87. package/dist/extensions/codemode/worker.js.map +1 -1
  88. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  89. package/dist/extensions/mcp/cli.js +18 -3
  90. package/dist/extensions/mcp/cli.js.map +1 -1
  91. package/dist/extensions/mcp/config.d.ts +4 -2
  92. package/dist/extensions/mcp/config.d.ts.map +1 -1
  93. package/dist/extensions/mcp/config.js +14 -2
  94. package/dist/extensions/mcp/config.js.map +1 -1
  95. package/dist/extensions/mcp/index.d.ts +32 -8
  96. package/dist/extensions/mcp/index.d.ts.map +1 -1
  97. package/dist/extensions/mcp/index.js +205 -52
  98. package/dist/extensions/mcp/index.js.map +1 -1
  99. package/dist/extensions/mcp/oauth.d.ts +2 -0
  100. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  101. package/dist/extensions/mcp/oauth.js +1 -1
  102. package/dist/extensions/mcp/oauth.js.map +1 -1
  103. package/dist/extensions/mcp/runtime.d.ts +2 -0
  104. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  105. package/dist/extensions/mcp/runtime.js +14 -8
  106. package/dist/extensions/mcp/runtime.js.map +1 -1
  107. package/dist/extensions/mcp/tools.d.ts +5 -4
  108. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  109. package/dist/extensions/mcp/tools.js +33 -15
  110. package/dist/extensions/mcp/tools.js.map +1 -1
  111. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  112. package/dist/extensions/mcp/ui.js +4 -2
  113. package/dist/extensions/mcp/ui.js.map +1 -1
  114. package/dist/extensions/tool-search/tool.d.ts +5 -4
  115. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  116. package/dist/extensions/tool-search/tool.js +7 -28
  117. package/dist/extensions/tool-search/tool.js.map +1 -1
  118. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  119. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  120. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  121. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  122. package/docs/cli.md +3 -3
  123. package/docs/extensions.md +3 -3
  124. package/docs/mcp.md +125 -82
  125. package/docs/providers.md +2 -0
  126. package/docs/sdk.md +1 -1
  127. package/docs/settings.md +3 -1
  128. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  129. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  130. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  131. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  132. package/examples/extensions/gondolin/package-lock.json +2 -2
  133. package/examples/extensions/gondolin/package.json +1 -1
  134. package/examples/extensions/minimal-mode.ts +24 -96
  135. package/examples/extensions/sandbox/package-lock.json +2 -2
  136. package/examples/extensions/sandbox/package.json +1 -1
  137. package/examples/extensions/with-deps/package-lock.json +2 -2
  138. package/examples/extensions/with-deps/package.json +1 -1
  139. package/examples/sdk/14-codemode-mcp.ts +2 -2
  140. package/npm-shrinkwrap.json +26 -26
  141. package/package.json +10 -10
  142. package/dist/bundle/chunks/anthropic-messages-A6EXUBG6.js +0 -6
  143. package/dist/bundle/chunks/chunk-GOPCREV2.js +0 -4
  144. package/dist/bundle/chunks/chunk-HSPCVFST.js +0 -2
  145. package/dist/bundle/chunks/chunk-XNGRGP62.js +0 -2
  146. package/dist/bundle/chunks/virtual-modules-AQ3FLU6H.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAIH,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAA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avaScript 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- \\`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 deferred nested tools may be omitted from this description. They are still available on the global \\`tools\\` object and listed in \\`ALL_TOOLS\\`.\nTo find one, call \\`await searchTools(query)\\`, or filter \\`ALL_TOOLS\\` by \\`name\\` and \\`description\\`.`;\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\tdeferred: boolean;\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\tconst listable = groups.map((group) => group.entries.filter((entry) => !entry.deferred));\n\tif (budget === undefined) return new Set(listable.flat().map((entry) => entry.name));\n\tconst queues = listable.map((entries) => [...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 omitted tools, the shared MCP types when\n * MCP tools are callable, the `models` API, and one section per tool, grouped by namespace. Tool\n * sections are limited to `inlineBudget`; every namespace is listed with its tool count either\n * way, and the listing states whether it is complete.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools).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({\n\t\t\tname: declaration.name,\n\t\t\tsection,\n\t\t\tcost: Math.ceil(section.length / CHARS_PER_TOKEN),\n\t\t\tdeferred: options.deferred?.has(declaration.name) === true,\n\t\t});\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\tconst complete = shown.size === declarations.length;\n\n\tconst sections = [DESCRIPTION_INTRO];\n\tif (!complete) sections.push(DEFERRED_TOOLS_GUIDANCE);\n\tif (declarations.some((declaration) => mcpStructuredContentSchema(declaration.outputSchema) !== undefined)) {\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 = [\n\t\tcomplete\n\t\t\t? `Nested tools: COMPLETE list (${declarations.length} tool${declarations.length === 1 ? \"\" : \"s\"}).`\n\t\t\t: `Nested tools: PARTIAL - ${shown.size} of ${declarations.length} shown.`,\n\t];\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\tconst count = `${entries.length} tool${entries.length === 1 ? \"\" : \"s\"}`;\n\t\t\tconst suffix =\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? \", none shown\"\n\t\t\t\t\t\t: `, ${visible.length} shown`;\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name} (${count}${suffix})${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;AAIH,OAAO,EACN,uBAAuB,EACvB,0B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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,7 +1,7 @@
1
1
  /**
2
2
  * Worker entry for the codemode sandbox in bundled builds. The Node bundle and the Bun binary
3
3
  * build this file as a separate entrypoint because pi-codemode's own worker file is not on disk
4
- * there; `getCodemodeWorkerUrl()` in config.ts resolves it.
4
+ * there; `getCodemodeWorkerSpecifier()` in config.ts resolves it.
5
5
  */
6
6
  import "@earendil-works/pi-codemode/worker";
7
7
  //# sourceMappingURL=worker.d.ts.map
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Worker entry for the codemode sandbox in bundled builds. The Node bundle and the Bun binary
3
3
  * build this file as a separate entrypoint because pi-codemode's own worker file is not on disk
4
- * there; `getCodemodeWorkerUrl()` in config.ts resolves it.
4
+ * there; `getCodemodeWorkerSpecifier()` in config.ts resolves it.
5
5
  */
6
6
  import "@earendil-works/pi-codemode/worker";
7
7
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../../src/extensions/codemode/worker.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,oCAAoC,CAAC","sourcesContent":["/**\n * Worker entry for the codemode sandbox in bundled builds. The Node bundle and the Bun binary\n * build this file as a separate entrypoint because pi-codemode's own worker file is not on disk\n * there; `getCodemodeWorkerUrl()` in config.ts resolves it.\n */\nimport \"@earendil-works/pi-codemode/worker\";\n"]}
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../../src/extensions/codemode/worker.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,oCAAoC,CAAC","sourcesContent":["/**\n * Worker entry for the codemode sandbox in bundled builds. The Node bundle and the Bun binary\n * build this file as a separate entrypoint because pi-codemode's own worker file is not on disk\n * there; `getCodemodeWorkerSpecifier()` in config.ts resolves it.\n */\nimport \"@earendil-works/pi-codemode/worker\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/cli.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAkBH,OAAO,EAEN,uBAAuB,EAKvB,MAAM,cAAc,CAAC;AA8CtB,MAAM,WAAW,iBAAiB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,WAAW,CAAC,EAAE,uBAAuB,CAAC;IACtC,wCAAwC;IACxC,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,kCAAkC;IAClC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/B;AA6FD,oDAAoD;AACpD,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CA2E/F"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/cli.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAkBH,OAAO,EAEN,uBAAuB,EAKvB,MAAM,cAAc,CAAC;AAgDtB,MAAM,WAAW,iBAAiB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,WAAW,CAAC,EAAE,uBAAuB,CAAC;IACtC,wCAAwC;IACxC,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,kCAAkC;IAClC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/B;AA6FD,oDAAoD;AACpD,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CA2E/F"}
@@ -47,8 +47,10 @@ Options for add:
47
47
  OAuth client secret (may be \${NAME} or !command)
48
48
  --oauth-callback-port <port>
49
49
  Fixed OAuth callback port
50
- --exposure <mode> codemode (default), codemode-deferred, deferred, direct,
51
- or hidden
50
+ --oauth-client-name <name>
51
+ Client name sent when registering with the OAuth server
52
+ --exposure <mode> codemode (default), deferred, direct, or hidden
53
+ --description <text> What the server offers, shown in the system prompt
52
54
 
53
55
  Other options:
54
56
  --json Print the list as JSON
@@ -217,7 +219,9 @@ function add(args, projectConfig, options, log, error) {
217
219
  "oauth-client-id": "value",
218
220
  "oauth-client-secret": "value",
219
221
  "oauth-callback-port": "value",
222
+ "oauth-client-name": "value",
220
223
  exposure: "value",
224
+ description: "value",
221
225
  }, error, 2);
222
226
  if (!parsed)
223
227
  return 1;
@@ -233,7 +237,14 @@ function add(args, projectConfig, options, log, error) {
233
237
  return typeof found === "string" ? found : undefined;
234
238
  };
235
239
  const exposure = value("exposure");
236
- const httpOnly = ["header", "bearer-token-env-var", "oauth-client-id", "oauth-client-secret", "oauth-callback-port"];
240
+ const httpOnly = [
241
+ "header",
242
+ "bearer-token-env-var",
243
+ "oauth-client-id",
244
+ "oauth-client-secret",
245
+ "oauth-callback-port",
246
+ "oauth-client-name",
247
+ ];
237
248
  const stdioOnly = ["env", "cwd"];
238
249
  const misplaced = (url === undefined ? httpOnly : stdioOnly).find((option) => values.has(option) || lists.has(option));
239
250
  if (misplaced) {
@@ -253,6 +264,7 @@ function add(args, projectConfig, options, log, error) {
253
264
  ...(value("oauth-client-id") === undefined ? {} : { clientId: value("oauth-client-id") }),
254
265
  ...(value("oauth-client-secret") === undefined ? {} : { clientSecret: value("oauth-client-secret") }),
255
266
  ...(port === undefined ? {} : { callbackPort: Number(port) }),
267
+ ...(value("oauth-client-name") === undefined ? {} : { clientName: value("oauth-client-name") }),
256
268
  };
257
269
  config = {
258
270
  url,
@@ -274,6 +286,9 @@ function add(args, projectConfig, options, log, error) {
274
286
  }
275
287
  if (exposure !== undefined)
276
288
  config.exposure = exposure;
289
+ const description = value("description");
290
+ if (description !== undefined)
291
+ config.description = description;
277
292
  const validated = validateMcpServerConfig(name, config);
278
293
  if (typeof validated === "string") {
279
294
  error(validated);
@@ -1 +1 @@
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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E,IAAI,EAAE,IAAI,EAAE,CAAC,CAC5E,CAAC;YACF,OAAO,SAAS,CAAC;QAClB,CAAC;QACD,MAAM,QAAQ,GAAG,eAAe,CAAC,EAAE,KAAK,EAAE,OAAO,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 --exposure <mode> codemode (default), codemode-deferred, deferred, direct,\n or hidden\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\texposure: \"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 = [\"header\", \"bearer-token-env-var\", \"oauth-client-id\", \"oauth-client-secret\", \"oauth-callback-port\"];\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};\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 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,CAA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CAAC,OAAO,EAAE,EAAE,CACnC,UAAU,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAC5E,CAAC;YACF,OAAO,SAAS,CAAC;QAClB,CAAC;QACD,MAAM,QAAQ,GAAG,eAAe,CAAC,EAAE,KAAK,EAAE,OAAO,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(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"]}
@@ -17,9 +17,11 @@
17
17
  * ```
18
18
  *
19
19
  * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).
20
+ * `"auth": { "provider": "<provider>" }` sends the token of a `/login` provider instead. Project files
21
+ * cannot use it, so a repository cannot pick where the credential goes.
20
22
  *
21
23
  * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server
22
- * with `codemode` or `codemode-deferred` exposure connects. A project value overrides the global one.
24
+ * with `codemode` exposure connects. A project value overrides the global one.
23
25
  */
24
26
  import { type McpExposure, type McpServerConfig } from "../../core/mcp-servers.ts";
25
27
  export type { McpExposure, McpHttpServerConfig, McpOAuthConfig, McpServerConfig, McpStdioServerConfig, } from "../../core/mcp-servers.ts";
@@ -37,7 +39,7 @@ export interface McpServerEntry {
37
39
  }
38
40
  export interface LoadedMcpConfig {
39
41
  servers: McpServerEntry[];
40
- /** Activate the codemode tool when `codemode` or `codemode-deferred` servers connect. Default: true. */
42
+ /** Activate the codemode tool when `codemode` servers connect. Default: true. */
41
43
  autoEnableCodemode?: boolean;
42
44
  errors: string[];
43
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAKH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,eAAe,EAA2B,MAAM,2BAA2B,CAAC;AAE5G,YAAY,EACX,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,oBAAoB,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,eAAe,CAAC;IACxB,2FAA2F;IAC3F,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,WAAW,CAAC;CAC3C;AAED,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,wGAAwG;IACxG,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,CAAC;CACjB;AAsCD;;;GAGG;AACH,wBAAgB,a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CAAC;IAC1B,iFAAiF;IACjF,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,CAAC;CACjB;AAgDD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,OAAO,CAAA;CAAE,GAAG,eAAe,CASlH;AAED,+GAA+G;AAC/G,MAAM,WAAW,oBAAoB;IACpC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,QAAQ,CAAC,EAAE,WAAW,CAAC;CACvB;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,IAAI,CAcnG;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAU/F;AAED,0FAA0F;AAC1F,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAUzE"}
@@ -17,14 +17,16 @@
17
17
  * ```
18
18
  *
19
19
  * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).
20
+ * `"auth": { "provider": "<provider>" }` sends the token of a `/login` provider instead. Project files
21
+ * cannot use it, so a repository cannot pick where the credential goes.
20
22
  *
21
23
  * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server
22
- * with `codemode` or `codemode-deferred` exposure connects. A project value overrides the global one.
24
+ * with `codemode` exposure connects. A project value overrides the global one.
23
25
  */
24
26
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
27
  import { dirname, join } from "node:path";
26
28
  import { CONFIG_DIR_NAME } from "../../config.js";
27
- import { validateMcpServerConfig } from "../../core/mcp-servers.js";
29
+ import { mcpNamespace, validateMcpServerConfig, } from "../../core/mcp-servers.js";
28
30
  export { getMcpToolExposure } from "../../core/mcp-servers.js";
29
31
  function isRecord(value) {
30
32
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -55,6 +57,16 @@ function readConfigFile(path, scope, state) {
55
57
  errors.push(`${path}: ${config}`);
56
58
  continue;
57
59
  }
60
+ // Names that differ only in `-` and `_` would share a namespace.
61
+ const clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name));
62
+ if (clash) {
63
+ errors.push(`${path}: server "${name}" conflicts with "${clash}"`);
64
+ continue;
65
+ }
66
+ if (scope === "project" && "url" in config && config.auth) {
67
+ errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);
68
+ continue;
69
+ }
58
70
  servers.set(name, { name, config, source: path, scope });
59
71
  }
60
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAA0C,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAS5G,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAqB/D,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAQD,SAAS,cAAc,CAAC,IAAY,EAAE,KAA2B,EAAE,KAAqB;IACvF,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;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AO,OAAO,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,SAAS,cAAc,CACtB,IAAY,EACZ,IAAgG;IAEhG,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,MAAM,MAAM,GAAY,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,UAAU,KAAK,SAAS,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;QAC5F,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,kDAAkD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5E,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC;QAAE,OAAO;IACnC,MAAM,MAAM,GAAG,CAAC,IAAI,IAAI,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;IAChE,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * MCP server configuration.\n *\n * Servers are read from `mcp.json` in the agent directory and, for trusted projects, from\n * `<project>/.pi/mcp.json`. Both use the `mcpServers` shape shared by other MCP clients, so\n * existing configurations can be copied over. Project entries replace global entries with the\n * same name.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } },\n * \"sentry\": { \"url\": \"https://mcp.sentry.dev/mcp\" }\n * }\n * }\n * ```\n *\n * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).\n *\n * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server\n * with `codemode` or `codemode-deferred` exposure connects. A project value overrides the global one.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME } from \"../../config.ts\";\nimport { type McpExposure, type McpServerConfig, validateMcpServerConfig } from \"../../core/mcp-servers.ts\";\n\nexport type {\n\tMcpExposure,\n\tMcpHttpServerConfig,\n\tMcpOAuthConfig,\n\tMcpServerConfig,\n\tMcpStdioServerConfig,\n} from \"../../core/mcp-servers.ts\";\nexport { getMcpToolExposure } from \"../../core/mcp-servers.ts\";\n\nexport interface McpServerEntry {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Config file that defined the entry, or the path of the extension that registered it. */\n\tsource: string;\n\t/**\n\t * The global or the project `mcp.json`, or `extension` for servers registered with\n\t * `pi.registerMcpServer()`. Changes to extension servers are not saved.\n\t */\n\tscope?: \"global\" | \"project\" | \"extension\";\n}\n\nexport interface LoadedMcpConfig {\n\tservers: McpServerEntry[];\n\t/** Activate the codemode tool when `codemode` or `codemode-deferred` servers connect. Default: true. */\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ninterface McpConfigState {\n\tservers: Map<string, McpServerEntry>;\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction readConfigFile(path: string, scope: \"global\" | \"project\", state: McpConfigState): void {\n\tconst { servers, errors } = state;\n\tif (!existsSync(path)) return;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch (error) {\n\t\terrors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);\n\t\treturn;\n\t}\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\terrors.push(`${path}: expected an object with an \"mcpServers\" object`);\n\t\treturn;\n\t}\n\tif (typeof parsed.autoEnableCodemode === \"boolean\") state.autoEnableCodemode = parsed.autoEnableCodemode;\n\telse if (parsed.autoEnableCodemode !== undefined) errors.push(`${path}: autoEnableCodemode must be a boolean`);\n\tfor (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {\n\t\tconst config = validateMcpServerConfig(name, value);\n\t\tif (typeof config === \"string\") {\n\t\t\terrors.push(`${path}: ${config}`);\n\t\t\tcontinue;\n\t\t}\n\t\tservers.set(name, { name, config, source: path, scope });\n\t}\n}\n\n/**\n * Load global and (when trusted) project MCP configuration. Disabled servers are included with\n * `enabled: false`, so they can be enabled again.\n */\nexport function loadMcpConfig(options: { agentDir: string; cwd: string; projectTrusted: boolean }): LoadedMcpConfig {\n\tconst state: McpConfigState = { servers: new Map(), errors: [] };\n\treadConfigFile(join(options.agentDir, \"mcp.json\"), \"global\", state);\n\tif (options.projectTrusted) readConfigFile(join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\"), \"project\", state);\n\treturn {\n\t\tservers: [...state.servers.values()],\n\t\t...(state.autoEnableCodemode === undefined ? {} : { autoEnableCodemode: state.autoEnableCodemode }),\n\t\terrors: state.errors,\n\t};\n}\n\n/** Settings `/mcp` changes. `enabled: true` and `exposure: \"codemode\"` are the defaults and remove the key. */\nexport interface McpServerConfigPatch {\n\tenabled?: boolean;\n\texposure?: McpExposure;\n}\n\n/**\n * Change one server's settings in the `mcp.json` that defines it. Other content is kept; the file is\n * rewritten with its indentation.\n */\nexport function updateMcpServerConfig(path: string, name: string, patch: McpServerConfigPatch): void {\n\teditMcpServers(path, (servers) => {\n\t\tconst server = servers?.[name];\n\t\tif (!isRecord(server)) throw new Error(`${path} does not define MCP server \"${name}\"`);\n\t\tif (patch.enabled !== undefined) {\n\t\t\tif (patch.enabled) delete server.enabled;\n\t\t\telse server.enabled = false;\n\t\t}\n\t\tif (patch.exposure !== undefined) {\n\t\t\tif (patch.exposure === \"codemode\") delete server.exposure;\n\t\t\telse server.exposure = patch.exposure;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/**\n * Add a server to an `mcp.json`, creating the file when missing. An existing entry with the same\n * name is replaced. Returns true when an entry was replaced.\n */\nexport function addMcpServerConfig(path: string, name: string, config: McpServerConfig): boolean {\n\tlet replaced = false;\n\teditMcpServers(path, (servers, parsed) => {\n\t\tconst target = servers ?? {};\n\t\treplaced = target[name] !== undefined;\n\t\ttarget[name] = config;\n\t\tparsed.mcpServers = target;\n\t\treturn true;\n\t});\n\treturn replaced;\n}\n\n/** Remove a server from an `mcp.json`. Returns false when the file does not define it. */\nexport function removeMcpServerConfig(path: string, name: string): boolean {\n\tif (!existsSync(path)) return false;\n\tlet removed = false;\n\teditMcpServers(path, (servers) => {\n\t\tif (!servers || servers[name] === undefined) return false;\n\t\tdelete servers[name];\n\t\tremoved = true;\n\t\treturn true;\n\t});\n\treturn removed;\n}\n\n/**\n * Read an `mcp.json` (an empty config when missing), let `edit` change its `mcpServers`, and write\n * it back with its indentation when `edit` returns true. Other content is kept.\n */\nfunction editMcpServers(\n\tpath: string,\n\tedit: (servers: Record<string, unknown> | undefined, parsed: Record<string, unknown>) => boolean,\n): void {\n\tconst text = existsSync(path) ? readFileSync(path, \"utf8\") : undefined;\n\tconst parsed: unknown = text === undefined ? {} : JSON.parse(text);\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\tthrow new Error(`${path}: expected an object with an \"mcpServers\" object`);\n\t}\n\tconst servers = isRecord(parsed.mcpServers) ? parsed.mcpServers : undefined;\n\tif (!edit(servers, parsed)) return;\n\tconst indent = (text && /^([ \\t]+)\\S/m.exec(text)?.[1]) || \" \";\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(parsed, null, indent)}\\n`);\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/extensions/mcp/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAGN,YAAY,EACZ,uBAAuB,GACvB,MAAM,2BAA2B,CAAC;AASnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAqB/D,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAQD,SAAS,cAAc,CAAC,IAAY,EAAE,KAA2B,EAAE,KAAqB;IACvF,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO;IAC9B,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACJ,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,CAAC,IAAI,CAAC,G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AS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * MCP server configuration.\n *\n * Servers are read from `mcp.json` in the agent directory and, for trusted projects, from\n * `<project>/.pi/mcp.json`. Both use the `mcpServers` shape shared by other MCP clients, so\n * existing configurations can be copied over. Project entries replace global entries with the\n * same name.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } },\n * \"sentry\": { \"url\": \"https://mcp.sentry.dev/mcp\" }\n * }\n * }\n * ```\n *\n * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).\n * `\"auth\": { \"provider\": \"<provider>\" }` sends the token of a `/login` provider instead. Project files\n * cannot use it, so a repository cannot pick where the credential goes.\n *\n * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server\n * with `codemode` exposure connects. A project value overrides the global one.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME } from \"../../config.ts\";\nimport {\n\ttype McpExposure,\n\ttype McpServerConfig,\n\tmcpNamespace,\n\tvalidateMcpServerConfig,\n} from \"../../core/mcp-servers.ts\";\n\nexport type {\n\tMcpExposure,\n\tMcpHttpServerConfig,\n\tMcpOAuthConfig,\n\tMcpServerConfig,\n\tMcpStdioServerConfig,\n} from \"../../core/mcp-servers.ts\";\nexport { getMcpToolExposure } from \"../../core/mcp-servers.ts\";\n\nexport interface McpServerEntry {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Config file that defined the entry, or the path of the extension that registered it. */\n\tsource: string;\n\t/**\n\t * The global or the project `mcp.json`, or `extension` for servers registered with\n\t * `pi.registerMcpServer()`. Changes to extension servers are not saved.\n\t */\n\tscope?: \"global\" | \"project\" | \"extension\";\n}\n\nexport interface LoadedMcpConfig {\n\tservers: McpServerEntry[];\n\t/** Activate the codemode tool when `codemode` servers connect. Default: true. */\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ninterface McpConfigState {\n\tservers: Map<string, McpServerEntry>;\n\tautoEnableCodemode?: boolean;\n\terrors: string[];\n}\n\nfunction readConfigFile(path: string, scope: \"global\" | \"project\", state: McpConfigState): void {\n\tconst { servers, errors } = state;\n\tif (!existsSync(path)) return;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch (error) {\n\t\terrors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);\n\t\treturn;\n\t}\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\terrors.push(`${path}: expected an object with an \"mcpServers\" object`);\n\t\treturn;\n\t}\n\tif (typeof parsed.autoEnableCodemode === \"boolean\") state.autoEnableCodemode = parsed.autoEnableCodemode;\n\telse if (parsed.autoEnableCodemode !== undefined) errors.push(`${path}: autoEnableCodemode must be a boolean`);\n\tfor (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {\n\t\tconst config = validateMcpServerConfig(name, value);\n\t\tif (typeof config === \"string\") {\n\t\t\terrors.push(`${path}: ${config}`);\n\t\t\tcontinue;\n\t\t}\n\t\t// Names that differ only in `-` and `_` would share a namespace.\n\t\tconst clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name));\n\t\tif (clash) {\n\t\t\terrors.push(`${path}: server \"${name}\" conflicts with \"${clash}\"`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (scope === \"project\" && \"url\" in config && config.auth) {\n\t\t\terrors.push(`${path}: server \"${name}\": auth is only allowed in the global mcp.json`);\n\t\t\tcontinue;\n\t\t}\n\t\tservers.set(name, { name, config, source: path, scope });\n\t}\n}\n\n/**\n * Load global and (when trusted) project MCP configuration. Disabled servers are included with\n * `enabled: false`, so they can be enabled again.\n */\nexport function loadMcpConfig(options: { agentDir: string; cwd: string; projectTrusted: boolean }): LoadedMcpConfig {\n\tconst state: McpConfigState = { servers: new Map(), errors: [] };\n\treadConfigFile(join(options.agentDir, \"mcp.json\"), \"global\", state);\n\tif (options.projectTrusted) readConfigFile(join(options.cwd, CONFIG_DIR_NAME, \"mcp.json\"), \"project\", state);\n\treturn {\n\t\tservers: [...state.servers.values()],\n\t\t...(state.autoEnableCodemode === undefined ? {} : { autoEnableCodemode: state.autoEnableCodemode }),\n\t\terrors: state.errors,\n\t};\n}\n\n/** Settings `/mcp` changes. `enabled: true` and `exposure: \"codemode\"` are the defaults and remove the key. */\nexport interface McpServerConfigPatch {\n\tenabled?: boolean;\n\texposure?: McpExposure;\n}\n\n/**\n * Change one server's settings in the `mcp.json` that defines it. Other content is kept; the file is\n * rewritten with its indentation.\n */\nexport function updateMcpServerConfig(path: string, name: string, patch: McpServerConfigPatch): void {\n\teditMcpServers(path, (servers) => {\n\t\tconst server = servers?.[name];\n\t\tif (!isRecord(server)) throw new Error(`${path} does not define MCP server \"${name}\"`);\n\t\tif (patch.enabled !== undefined) {\n\t\t\tif (patch.enabled) delete server.enabled;\n\t\t\telse server.enabled = false;\n\t\t}\n\t\tif (patch.exposure !== undefined) {\n\t\t\tif (patch.exposure === \"codemode\") delete server.exposure;\n\t\t\telse server.exposure = patch.exposure;\n\t\t}\n\t\treturn true;\n\t});\n}\n\n/**\n * Add a server to an `mcp.json`, creating the file when missing. An existing entry with the same\n * name is replaced. Returns true when an entry was replaced.\n */\nexport function addMcpServerConfig(path: string, name: string, config: McpServerConfig): boolean {\n\tlet replaced = false;\n\teditMcpServers(path, (servers, parsed) => {\n\t\tconst target = servers ?? {};\n\t\treplaced = target[name] !== undefined;\n\t\ttarget[name] = config;\n\t\tparsed.mcpServers = target;\n\t\treturn true;\n\t});\n\treturn replaced;\n}\n\n/** Remove a server from an `mcp.json`. Returns false when the file does not define it. */\nexport function removeMcpServerConfig(path: string, name: string): boolean {\n\tif (!existsSync(path)) return false;\n\tlet removed = false;\n\teditMcpServers(path, (servers) => {\n\t\tif (!servers || servers[name] === undefined) return false;\n\t\tdelete servers[name];\n\t\tremoved = true;\n\t\treturn true;\n\t});\n\treturn removed;\n}\n\n/**\n * Read an `mcp.json` (an empty config when missing), let `edit` change its `mcpServers`, and write\n * it back with its indentation when `edit` returns true. Other content is kept.\n */\nfunction editMcpServers(\n\tpath: string,\n\tedit: (servers: Record<string, unknown> | undefined, parsed: Record<string, unknown>) => boolean,\n): void {\n\tconst text = existsSync(path) ? readFileSync(path, \"utf8\") : undefined;\n\tconst parsed: unknown = text === undefined ? {} : JSON.parse(text);\n\tif (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {\n\t\tthrow new Error(`${path}: expected an object with an \"mcpServers\" object`);\n\t}\n\tconst servers = isRecord(parsed.mcpServers) ? parsed.mcpServers : undefined;\n\tif (!edit(servers, parsed)) return;\n\tconst indent = (text && /^([ \\t]+)\\S/m.exec(text)?.[1]) || \" \";\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(parsed, null, indent)}\\n`);\n}\n"]}