@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.31

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 (84) hide show
  1. package/README.md +110 -3
  2. package/dist/credentials/addresses.d.ts +20 -0
  3. package/dist/credentials/addresses.js +93 -2
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/errors.d.ts +6 -3
  8. package/dist/errors.js +5 -2
  9. package/dist/errors.js.map +1 -1
  10. package/dist/extensions/load.js +5 -2
  11. package/dist/extensions/load.js.map +1 -1
  12. package/dist/extensions/lock.d.ts +16 -2
  13. package/dist/extensions/lock.js +155 -21
  14. package/dist/extensions/lock.js.map +1 -1
  15. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  16. package/dist/extensions/mcp-pins-node.js +18 -0
  17. package/dist/extensions/mcp-pins-node.js.map +1 -0
  18. package/dist/extensions/node.d.ts +4 -2
  19. package/dist/extensions/node.js +4 -2
  20. package/dist/extensions/node.js.map +1 -1
  21. package/dist/harness.d.ts +7 -1
  22. package/dist/harness.js.map +1 -1
  23. package/dist/mcp/connection.d.ts +9 -3
  24. package/dist/mcp/connection.js +192 -25
  25. package/dist/mcp/connection.js.map +1 -1
  26. package/dist/mcp/errors.d.ts +5 -2
  27. package/dist/mcp/errors.js.map +1 -1
  28. package/dist/mcp/guarded-fetch.d.ts +33 -0
  29. package/dist/mcp/guarded-fetch.js +391 -0
  30. package/dist/mcp/guarded-fetch.js.map +1 -0
  31. package/dist/mcp/http-node.d.ts +15 -0
  32. package/dist/mcp/http-node.js +179 -0
  33. package/dist/mcp/http-node.js.map +1 -0
  34. package/dist/mcp/index.d.ts +6 -3
  35. package/dist/mcp/index.js +5 -2
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/mcp/manager.d.ts +4 -3
  38. package/dist/mcp/manager.js +432 -47
  39. package/dist/mcp/manager.js.map +1 -1
  40. package/dist/mcp/pins.d.ts +9 -0
  41. package/dist/mcp/pins.js +54 -0
  42. package/dist/mcp/pins.js.map +1 -0
  43. package/dist/mcp/record.js +6 -0
  44. package/dist/mcp/record.js.map +1 -1
  45. package/dist/mcp/remote-config.d.ts +20 -0
  46. package/dist/mcp/remote-config.js +208 -0
  47. package/dist/mcp/remote-config.js.map +1 -0
  48. package/dist/mcp/remote.d.ts +20 -0
  49. package/dist/mcp/remote.js +146 -0
  50. package/dist/mcp/remote.js.map +1 -0
  51. package/dist/mcp/types.d.ts +198 -8
  52. package/dist/mcp/types.js.map +1 -1
  53. package/dist/sandbox/escalation-table.d.ts +38 -0
  54. package/dist/sandbox/escalation-table.js +95 -0
  55. package/dist/sandbox/escalation-table.js.map +1 -0
  56. package/dist/sandbox/escalation.d.ts +191 -0
  57. package/dist/sandbox/escalation.js +370 -0
  58. package/dist/sandbox/escalation.js.map +1 -0
  59. package/dist/sandbox/index.d.ts +6 -3
  60. package/dist/sandbox/index.js +6 -3
  61. package/dist/sandbox/index.js.map +1 -1
  62. package/dist/sandbox/widen.d.ts +10 -0
  63. package/dist/sandbox/widen.js +150 -0
  64. package/dist/sandbox/widen.js.map +1 -0
  65. package/dist/server/protocol.schema.json +6 -3
  66. package/dist/session/approvals.d.ts +30 -1
  67. package/dist/session/approvals.js +12 -4
  68. package/dist/session/approvals.js.map +1 -1
  69. package/dist/session/code-call.d.ts +15 -1
  70. package/dist/session/code-call.js +2 -1
  71. package/dist/session/code-call.js.map +1 -1
  72. package/dist/session/escalation-log.d.ts +65 -0
  73. package/dist/session/escalation-log.js +84 -0
  74. package/dist/session/escalation-log.js.map +1 -0
  75. package/dist/session/rebuild.js +12 -3
  76. package/dist/session/rebuild.js.map +1 -1
  77. package/dist/session/runner.js +39 -6
  78. package/dist/session/runner.js.map +1 -1
  79. package/dist/tools/index.d.ts +1 -1
  80. package/dist/tools/index.js.map +1 -1
  81. package/dist/tools/types.d.ts +16 -0
  82. package/dist/tools/types.js.map +1 -1
  83. package/llms.txt +36 -2
  84. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/mcp/manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,UAAU,EAAuB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAU1C,4GAA4G;AAC5G,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC,gHAAgH;AAChH,SAAS,YAAY,CAAC,UAAyB,EAAE,IAAa;IAC5D,OAAO,UAAU,CAA4B;QAC3C,IAAI,EAAE,gBAAgB;QACtB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,IAAI,EAAE,SAAS;QACf,6EAA6E;QAC7E,WAAW,EAAE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAsC;QAC9E,UAAU,EAAE,KAAK;QACjB,yGAAyG;QACzG,MAAM,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;QACzB,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG;YACtB,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACvE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;QACnF,CAAC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,oBAAoB,EAAE,iDAAiD,MAAM,IAAI,CAAC,CAAC;QAC5G,CAAC;IACH,CAAC;IACD,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9B,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * `createMcpManager()`: the MCP client as one removable component. It connects each server on its own, so one slow or\n * broken server never holds back the others, and registers each server's tools with the registry under the source\n * `mcp:<name>`, which names them `mcp__<name>__<tool>` and defers them by default.\n *\n * A server's tools are registered all or none: the list is checked, then registered through `registerAll()`, which\n * removes the tools it added when any one is refused, so a list the registry would refuse halfway leaves nothing\n * behind. Every tool is marked as not first-party and as a write, whatever its annotations say, so a server's\n * `readOnlyHint` can't make the loop run its calls together or run one again after a crash. The calls reach the server\n * only through the turn's tool pipeline, so the permission gate and the write cap apply to them as to any tool.\n */\nimport { defineTool, type ToolDefinition } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { ToolRegistration } from \"../tools/types.js\";\nimport { checkServerConfig, connectMcpServer } from \"./connection.js\";\nimport { safeSchema } from \"./content.js\";\nimport { McpError } from \"./errors.js\";\nimport { mcpRecordOf } from \"./record.js\";\nimport type {\n McpConnection,\n McpManager,\n McpManagerOptions,\n McpServerConfig,\n McpServerStatus,\n McpTool,\n} from \"./types.js\";\n\n// A placeholder that passes defineTool()'s name check; the registry names every tool by its canonical name.\nconst PLACEHOLDER_NAME = \"mcp_tool\";\n\n/** The definition of one server tool. Its `execute` calls the tool by the name the server listed at connect. */\nfunction definitionOf(connection: McpConnection, tool: McpTool): ToolDefinition<unknown, unknown, unknown> {\n return defineTool<unknown, unknown, unknown>({\n name: PLACEHOLDER_NAME,\n description: tool.description,\n kind: \"dynamic\",\n // The server's own schema runs no regular expression here: see safeSchema().\n inputSchema: safeSchema(tool.inputSchema) as Readonly<Record<string, unknown>>,\n firstParty: false,\n // A server's hints are claims by code the harness does not control, so every call is treated as a write.\n effect: { kind: \"write\" },\n async execute(input, ctx) {\n const result = await connection.callTool(tool.name, input, ctx.signal);\n return { content: result.content, ...(result.isError ? { isError: true } : {}) };\n },\n });\n}\n\nfunction registrationOf(config: McpServerConfig, connection: McpConnection, tool: McpTool): ToolRegistration {\n return {\n name: tool.name,\n source: `mcp:${config.name}`,\n ...(config.exposure === undefined ? {} : { exposure: config.exposure }),\n definition: definitionOf(connection, tool),\n };\n}\n\n/** The server's registrations, built before any is registered, so a tool the SDK refuses fails the whole list. */\nfunction registrationsOf(config: McpServerConfig, connection: McpConnection, tools: readonly McpTool[]) {\n return tools.map((tool) => {\n try {\n return registrationOf(config, connection, tool);\n } catch (error) {\n throw refused(config.name, error);\n }\n });\n}\n\nfunction refused(server: string, error: unknown): McpError {\n const why = error instanceof Error ? error.message : String(error);\n return new McpError(\n \"mcp_tool_list_refused\",\n server,\n `its tool list was refused, so none of its tools was registered: ${why}`,\n { cause: error },\n );\n}\n\nfunction checkServers(servers: readonly McpServerConfig[]): void {\n if (!Array.isArray(servers)) throw new HarnessError(\"invalid_mcp_config\", \"servers must be a list\");\n const names = new Set<string>();\n for (const config of servers) {\n checkServerConfig(config);\n const key = config.name.toLowerCase();\n if (names.has(key)) {\n throw new HarnessError(\"invalid_mcp_config\", `two MCP servers are named \"${config.name}\", in some letter case`);\n }\n names.add(key);\n }\n}\n\nclass Manager implements McpManager {\n readonly #options: McpManagerOptions;\n readonly #connections = new Map<string, McpConnection>();\n readonly #records = new Map<string, ExtensionLoadedRecord>();\n // Every connection that exists, registered or not, so a close can end one whose tool list is still being read.\n readonly #open = new Set<McpConnection>();\n readonly #abort = new AbortController();\n #connecting: Promise<readonly McpServerStatus[]> | undefined;\n #closing: Promise<void> | undefined;\n\n constructor(options: McpManagerOptions) {\n this.#options = options;\n }\n\n connect(): Promise<readonly McpServerStatus[]> {\n if (this.#closing !== undefined) {\n return Promise.reject(new HarnessError(\"invalid_mcp_config\", \"the MCP manager was closed\"));\n }\n this.#connecting ??=\n this.#options.mcp === false\n ? Promise.resolve([])\n : Promise.all(this.#options.servers.map((config) => this.#connectOne(config)));\n return this.#connecting;\n }\n\n async #connectOne(config: McpServerConfig): Promise<McpServerStatus> {\n const log = this.#options.log ?? (() => {});\n let connection: McpConnection | undefined;\n try {\n connection = await connectMcpServer(config, { log, signal: this.#abort.signal });\n this.#open.add(connection);\n // A close that began during the handshake must still end this server.\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n const listed = await connection.listTools();\n const registrations = registrationsOf(config, connection, listed);\n let record: ExtensionLoadedRecord;\n try {\n record = await mcpRecordOf(config, connection, listed);\n } catch (error) {\n throw refused(config.name, error);\n }\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n // Nothing awaits between this check and the registration, so another manager on the same registry can't\n // register the source in between, and registerAll() leaves nothing behind when any tool is refused.\n const source = `mcp:${config.name}`;\n if (this.#options.registry.list().some((tool) => tool.source === source)) {\n throw new McpError(\"mcp_tool_list_refused\", config.name, `the registry already holds tools from ${source}`);\n }\n let tools: string[];\n try {\n tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);\n } catch (error) {\n throw refused(config.name, error);\n }\n this.#connections.set(config.name, connection);\n this.#records.set(config.name, record);\n return { server: config.name, status: \"connected\", era: connection.era, tools };\n } catch (error) {\n if (connection !== undefined) this.#open.delete(connection);\n await connection?.close();\n const failure = error instanceof Error ? error : new Error(String(error));\n log(`the MCP server \"${config.name}\" was not connected: ${failure.message}`);\n return { server: config.name, status: \"failed\", error: failure };\n }\n }\n\n records(): readonly ExtensionLoadedRecord[] {\n return this.#options.servers.flatMap((config) => this.#records.get(config.name) ?? []);\n }\n\n connection(server: string): McpConnection | undefined {\n return this.#connections.get(server);\n }\n\n close(): Promise<void> {\n this.#closing ??= (async () => {\n // Aborting ends every handshake still running, and closing every open connection fails any tool list still being\n // read, so a server that hangs can't hold the others up.\n this.#abort.abort();\n await Promise.all([...this.#open].map((connection) => connection.close()));\n await this.#connecting?.catch(() => {});\n })();\n return this.#closing;\n }\n}\n\n/**\n * Creates the MCP client for a set of servers. It checks every config now and starts nothing until `connect()`.\n * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, two servers with one name, or a\n * registry without `register()`, `registerAll()` and `list()`.\n */\nexport function createMcpManager(options: McpManagerOptions): McpManager {\n const registry = options?.registry;\n for (const method of [\"register\", \"registerAll\", \"list\"] as const) {\n if (typeof registry?.[method] !== \"function\") {\n throw new HarnessError(\"invalid_mcp_config\", `createMcpManager() needs a tool registry with ${method}()`);\n }\n }\n checkServers(options.servers);\n return new Manager(options);\n}\n"]}
1
+ {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/mcp/manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,UAAU,EAAuB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAY1C,4GAA4G;AAC5G,MAAM,gBAAgB,GAAG,UAAU,CAAC;AACpC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AACtC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AACzC,iHAAiH;AACjH,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AA8CjC,wHAAwH;AACxH,SAAS,YAAY,CACnB,KAAkB,EAClB,U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McpManager()`: the MCP client as one removable component. It connects each server on its own, so one slow or\n * broken server never holds back the others, and registers each server's tools with the registry under the source\n * `mcp:<name>`, which names them `mcp__<name>__<tool>` and defers them by default.\n *\n * A server's tools are registered all or none: the list is checked, then registered through `registerAll()`, which\n * removes the tools it added when any one is refused, so a list the registry would refuse halfway leaves nothing\n * behind. Every tool is marked as not first-party and as a write, whatever its annotations say, so a server's\n * `readOnlyHint` can't make the loop run its calls together or run one again after a crash. The calls reach the server\n * only through the turn's tool pipeline, so the permission gate and the write cap apply to them as to any tool.\n *\n * Servers connect in the background, and everything that changes a session's tools waits for a turn boundary:\n * `beginTurn()` registers the servers that connected since the last turn, sets which tools may run, and writes a\n * notice of what changed. A tool runs only while its server's current definition matches its pin, so a server that\n * changes a tool after it was approved gets the tool disabled at the next turn, never mid-turn, and never silently.\n */\nimport { defineTool, type ToolDefinition } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { HookDecision, PermissionHook } from \"../permissions/types.js\";\nimport type { ToolRegistration } from \"../tools/types.js\";\nimport { checkServerConfig, connectMcpServer, systemTimers } from \"./connection.js\";\nimport { safeSchema } from \"./content.js\";\nimport { McpError } from \"./errors.js\";\nimport { checkPins, toolPinOf } from \"./pins.js\";\nimport { mcpRecordOf } from \"./record.js\";\nimport type {\n McpConnection,\n McpManager,\n McpManagerOptions,\n McpPendingTool,\n McpServerConfig,\n McpServerStatus,\n McpTimers,\n McpTool,\n} from \"./types.js\";\n\n// A placeholder that passes defineTool()'s name check; the registry names every tool by its canonical name.\nconst PLACEHOLDER_NAME = \"mcp_tool\";\nconst DEFAULT_DIRECT_WAIT_MS = 10_000;\nconst DEFAULT_RELIST_INTERVAL_MS = 2_000;\n// The most lines one notice holds; the rest are counted, so a server that changes many tools can't flood a turn.\nconst MAX_NOTICE_LINES = 20;\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/** One tool as its server lists it now, with the hash of its definition. */\ninterface Listed {\n readonly tool: McpTool;\n readonly hash: string;\n}\n\n/** What a turn was last told about one registered tool. */\ntype Label = \"enabled\" | \"new\" | \"changed\" | \"removed\" | \"unreadable\" | \"stale\";\n\n/** One server's state for the life of the manager. */\ninterface ServerState {\n readonly config: McpServerConfig;\n status: \"connecting\" | \"connected\" | \"registered\" | \"failed\";\n done: Promise<void>;\n connection?: McpConnection;\n error?: Error;\n /** The approved hash of each tool, by its name on the server. */\n pinned: Map<string, string>;\n /** The server's current list. */\n latest: Map<string, Listed>;\n /** True while the newest re-read of the list failed, so no current definition is known. */\n unreadable: boolean;\n /** The registrations built at connect, registered at the next turn boundary. */\n staged?:\n | {\n readonly registrations: readonly ToolRegistration[];\n readonly record: ExtensionLoadedRecord;\n /** Each staged tool's definition hash, taken from the same list the registrations were built from. */\n readonly hashes: ReadonlyMap<string, string>;\n }\n | undefined;\n /** Each registered tool's canonical name, by its name on the server, in registration order. */\n registered: Map<string, string>;\n /** The hash of each registered tool's definition as registered: the one the model reads for the whole session. */\n registeredHash: Map<string, string>;\n /** The tools that may run this turn, by name on the server. Replaced only at a turn boundary. */\n enabled: ReadonlySet<string>;\n announced: Map<string, Label>;\n /** How many tools the server added mid-session, as last announced. */\n announcedAdded: number;\n relist: { timer: unknown; running: boolean; dirty: boolean; last: number };\n pinWrites: Promise<void>;\n}\n\n/** The definition of one server tool. Its `execute` refuses a disabled tool and calls the rest by their listed name. */\nfunction definitionOf(\n state: ServerState,\n connection: McpConnection,\n tool: McpTool,\n): ToolDefinition<unknown, unknown, unknown> {\n return defineTool<unknown, unknown, unknown>({\n name: PLACEHOLDER_NAME,\n description: tool.description,\n kind: \"dynamic\",\n // The server's own schema runs no regular expression here: see safeSchema().\n inputSchema: safeSchema(tool.inputSchema) as Readonly<Record<string, unknown>>,\n firstParty: false,\n // A server's hints are claims by code the harness does not control, so every call is treated as a write.\n effect: { kind: \"write\" },\n async execute(input, ctx) {\n if (!state.enabled.has(tool.name)) {\n throw new McpError(\n \"mcp_call_failed\",\n state.config.name,\n \"the tool is disabled: its definition is new, changed or gone since it was pinned, and no person has approved it\",\n { failure: \"disabled\" },\n );\n }\n const result = await connection.callTool(tool.name, input, ctx.signal);\n return { content: result.content, ...(result.isError ? { isError: true } : {}) };\n },\n });\n}\n\n/** The server's registrations, built before any is registered, so a tool the SDK refuses fails the whole list. */\nfunction registrationsOf(state: ServerState, connection: McpConnection, tools: readonly McpTool[]) {\n const { config } = state;\n return tools.map((tool): ToolRegistration => {\n try {\n return {\n name: tool.name,\n source: `mcp:${config.name}`,\n ...(config.exposure === undefined ? {} : { exposure: config.exposure }),\n definition: definitionOf(state, connection, tool),\n };\n } catch (error) {\n throw refused(config.name, error);\n }\n });\n}\n\nfunction refused(server: string, error: unknown): McpError {\n const why = error instanceof Error ? error.message : String(error);\n return new McpError(\n \"mcp_tool_list_refused\",\n server,\n `its tool list was refused, so none of its tools was registered: ${why}`,\n { cause: error },\n );\n}\n\nfunction checkServers(servers: readonly McpServerConfig[]): void {\n if (!Array.isArray(servers)) throw new HarnessError(\"invalid_mcp_config\", \"servers must be a list\");\n const names = new Set<string>();\n for (const config of servers) {\n checkServerConfig(config);\n const key = config.name.toLowerCase();\n if (names.has(key)) {\n throw new HarnessError(\"invalid_mcp_config\", `two MCP servers are named \"${config.name}\", in some letter case`);\n }\n names.add(key);\n }\n}\n\nfunction wait(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!(Number.isInteger(value) && value >= 0 && value <= MAX_TIMER_MS)) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `${name} must be a whole number of milliseconds from 0 to ${MAX_TIMER_MS}`,\n );\n }\n return value;\n}\n\n/** The hashes of a list, by tool name. */\nasync function listedOf(tools: readonly McpTool[]): Promise<Map<string, Listed>> {\n const hashes = await Promise.all(tools.map(toolPinOf));\n return new Map(tools.map((tool, index) => [tool.name, { tool, hash: hashes[index] as string }]));\n}\n\n/** The label a registered tool has now. */\nfunction labelOf(state: ServerState, name: string): Label {\n if (state.enabled.has(name)) return \"enabled\";\n if (state.unreadable) return \"unreadable\";\n const now = state.latest.get(name);\n if (now === undefined) return \"removed\";\n const pin = state.pinned.get(name);\n if (pin === undefined) return \"new\";\n return pin === now.hash ? \"stale\" : \"changed\";\n}\n\nconst SENTENCES: Record<Label, string> = {\n enabled: \"was approved and may be called again\",\n new: \"is new on its server and is disabled until a person approves it\",\n changed: \"changed its definition on its server and is disabled until a person approves it\",\n removed: \"was removed by its server and is disabled\",\n unreadable: \"is disabled, because its server's tool list could not be read\",\n stale:\n \"is disabled for this session, because the definition it was registered with is not the approved one; a new session registers the approved one\",\n};\n\n/** The notice lines of one server: each tool whose label changed, and the count of tools it added mid-session. */\nfunction noticeLinesOf(state: ServerState, commits: (() => void)[]): string[] {\n const lines: string[] = [];\n for (const [name, canonical] of state.registered) {\n const label = labelOf(state, name);\n if (label === (state.announced.get(name) ?? \"enabled\")) continue;\n commits.push(() => state.announced.set(name, label));\n lines.push(`- ${canonical} ${SENTENCES[label]}.`);\n }\n const added = state.unreadable ? 0 : [...state.latest.keys()].filter((name) => !state.registered.has(name)).length;\n if (added === state.announcedAdded) return lines;\n commits.push(() => {\n state.announcedAdded = added;\n });\n // The server's name comes from the host's config; the new tools' names are the server's text, so only their number\n // is given.\n if (added > 0) {\n const tools = added === 1 ? \"1 tool\" : `${added} tools`;\n const them = added === 1 ? \"it\" : \"them\";\n lines.push(\n `- The server \"${state.config.name}\" lists ${tools} this session does not have; a person may approve ${them} for a later session.`,\n );\n }\n return lines;\n}\n\nconst newState = (config: McpServerConfig): ServerState => ({\n config,\n status: \"connecting\",\n done: Promise.resolve(),\n pinned: new Map(),\n latest: new Map(),\n unreadable: false,\n registered: new Map(),\n registeredHash: new Map(),\n enabled: new Set(),\n announced: new Map(),\n announcedAdded: 0,\n relist: { timer: undefined, running: false, dirty: false, last: Number.NEGATIVE_INFINITY },\n pinWrites: Promise.resolve(),\n});\n\nclass Manager implements McpManager {\n readonly #options: McpManagerOptions;\n readonly #timers: McpTimers;\n readonly #directWaitMs: number;\n readonly #relistMs: number;\n readonly #states: ServerState[];\n readonly #records = new Map<string, ExtensionLoadedRecord>();\n // Every connection that exists, registered or not, so a close can end one whose tool list is still being read.\n readonly #open = new Set<McpConnection>();\n readonly #abort = new AbortController();\n #started = false;\n #firstTurnDone = false;\n // What the last notice told, kept back until the turn has written it, so a turn that fails first loses no notice.\n #uncommitted: (() => void)[] = [];\n #connecting: Promise<readonly McpServerStatus[]> | undefined;\n #closing: Promise<void> | undefined;\n\n constructor(options: McpManagerOptions) {\n this.#options = options;\n this.#timers = options.timers ?? systemTimers;\n this.#directWaitMs = wait(\"directWaitMs\", options.directWaitMs, DEFAULT_DIRECT_WAIT_MS);\n this.#relistMs = wait(\"relistIntervalMs\", options.relistIntervalMs, DEFAULT_RELIST_INTERVAL_MS);\n this.#states = options.servers.map(newState);\n }\n\n #log(line: string): void {\n try {\n this.#options.log?.(line);\n } catch {\n // A logger that throws must not stop a connect.\n }\n }\n\n start(): void {\n if (this.#started || this.#options.mcp === false || this.#closing !== undefined) return;\n this.#started = true;\n for (const state of this.#states) state.done = this.#connectOne(state);\n }\n\n connect(): Promise<readonly McpServerStatus[]> {\n if (this.#closing !== undefined) {\n return Promise.reject(new HarnessError(\"invalid_mcp_config\", \"the MCP manager was closed\"));\n }\n this.#connecting ??= (async () => {\n if (this.#options.mcp === false) return [];\n this.start();\n // Each server is registered as soon as it connects, so one that hangs holds back no other.\n await Promise.all(this.#states.map((state) => state.done.then(() => this.#registerReady(this.#firstTurnDone))));\n // Every server has connected or failed by now, and registerReady() registered or failed each connected one.\n return this.statuses().filter((status): status is McpServerStatus => status.status !== \"connecting\");\n })();\n return this.#connecting;\n }\n\n statuses(): readonly (McpServerStatus | { readonly server: string; readonly status: \"connecting\" })[] {\n if (this.#options.mcp === false) return [];\n return this.#states.map((state) => {\n const server = state.config.name;\n if (state.status === \"failed\") return { server, status: \"failed\", error: state.error as Error };\n if (state.status !== \"registered\" || state.connection === undefined) return { server, status: \"connecting\" };\n const names = [...state.registered];\n return {\n server,\n status: \"connected\",\n era: state.connection.era,\n tools: names.map(([, canonical]) => canonical),\n disabled: names.filter(([name]) => !state.enabled.has(name)).map(([, canonical]) => canonical),\n };\n });\n }\n\n async #connectOne(state: ServerState): Promise<void> {\n const { config } = state;\n let connection: McpConnection | undefined;\n try {\n connection = await connectMcpServer(config, {\n log: (line) => this.#log(line),\n signal: this.#abort.signal,\n timers: this.#timers,\n });\n this.#open.add(connection);\n // A close that began during the handshake must still end this server.\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n // A notice that comes while the first list is read is kept, and the list is read again once it is in.\n connection.watchTools(() => this.#scheduleRelist(state));\n const tools = await connection.listTools();\n const registrations = registrationsOf(state, connection, tools);\n let record: ExtensionLoadedRecord;\n let latest: Map<string, Listed>;\n try {\n record = await mcpRecordOf(config, connection, tools);\n latest = await listedOf(tools);\n } catch (error) {\n throw refused(config.name, error);\n }\n const pinned = await this.#pinsOf(config.name, latest);\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n // The hashes come from the list the registrations were built from, never from a later re-read, so a server that\n // lists another definition before the turn boundary can't make the registered one look approved.\n const hashes = new Map([...latest].map(([name, listed]) => [name, listed.hash]));\n Object.assign(state, {\n connection,\n latest,\n pinned,\n staged: { registrations, record, hashes },\n status: \"connected\",\n });\n if (state.relist.dirty) this.#scheduleRelist(state);\n } catch (error) {\n if (connection !== undefined) this.#open.delete(connection);\n await connection?.close();\n this.#fail(state, error);\n }\n }\n\n /** The server's pins: the store's, or the list it gave at connect when the manager has no store. */\n async #pinsOf(server: string, latest: ReadonlyMap<string, Listed>): Promise<Map<string, string>> {\n const store = this.#options.pins;\n if (store === undefined) return new Map([...latest].map(([name, listed]) => [name, listed.hash]));\n const stored = await store.read(server);\n return stored === undefined ? new Map() : checkPins(server, stored);\n }\n\n #fail(state: ServerState, error: unknown): void {\n const failure = error instanceof Error ? error : new Error(String(error));\n state.status = \"failed\";\n state.error = failure;\n this.#log(`the MCP server \"${state.config.name}\" was not connected: ${failure.message}`);\n }\n\n /**\n * Registers every server that has connected and is not registered yet. `late` is true after the first turn's wait,\n * when a `direct` server is registered as `deferred`, so the tools a request sends never change mid-session.\n */\n #registerReady(late: boolean): void {\n for (const state of this.#states) {\n const staged = state.staged;\n const connection = state.connection;\n if (state.status !== \"connected\" || staged === undefined || connection === undefined) continue;\n state.staged = undefined;\n try {\n this.#register(state, staged, late && state.config.exposure === \"direct\");\n } catch (error) {\n this.#open.delete(connection);\n void connection.close();\n this.#fail(state, error);\n }\n }\n }\n\n #register(state: ServerState, staged: NonNullable<ServerState[\"staged\"]>, demote: boolean): void {\n const { config } = state;\n if (demote) {\n this.#log(`the direct MCP server \"${config.name}\" connected after the first turn, so its tools are deferred`);\n }\n // Nothing awaits between this check and the registration, so another manager on the same registry can't register\n // the source in between, and registerAll() leaves nothing behind when any tool is refused.\n const source = `mcp:${config.name}`;\n if (this.#options.registry.list().some((tool) => tool.source === source)) {\n throw new McpError(\"mcp_tool_list_refused\", config.name, `the registry already holds tools from ${source}`);\n }\n const registrations = demote\n ? staged.registrations.map((registration) => ({ ...registration, exposure: \"deferred\" as const }))\n : staged.registrations;\n let tools: string[];\n try {\n tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);\n } catch (error) {\n throw refused(config.name, error);\n }\n state.registered = new Map(registrations.map((registration, index) => [registration.name, tools[index] as string]));\n state.registeredHash = new Map(registrations.map(({ name }) => [name, staged.hashes.get(name) ?? \"\"]));\n state.status = \"registered\";\n this.#records.set(config.name, staged.record);\n this.#settle(state);\n }\n\n /** Sets which of a server's tools may run: those whose current definition matches their pin. */\n #settle(state: ServerState): void {\n const enabled = new Set<string>();\n if (!state.unreadable) {\n for (const name of state.registered.keys()) {\n const now = state.latest.get(name);\n // The model reads the definition registered at connect, so that one must be the approved one too, or a server\n // could register an unapproved definition and then list the approved one to have it enabled.\n const pin = state.pinned.get(name);\n if (now !== undefined && pin === now.hash && pin === state.registeredHash.get(name)) enabled.add(name);\n }\n }\n state.enabled = enabled;\n }\n\n async beginTurn(signal: AbortSignal = new AbortController().signal): Promise<readonly string[]> {\n if (this.#options.mcp === false || this.#closing !== undefined) return [];\n this.start();\n if (!this.#firstTurnDone) {\n await this.#waitForDirect(signal);\n this.#registerReady(false);\n this.#firstTurnDone = true;\n } else {\n this.#registerReady(true);\n }\n for (const state of this.#states) if (state.status === \"registered\") this.#settle(state);\n this.#uncommitted = [];\n const lines = this.#noticeLines(this.#uncommitted);\n if (lines.length === 0) return [];\n const shown = lines.slice(0, MAX_NOTICE_LINES);\n if (lines.length > shown.length) shown.push(`- and ${lines.length - shown.length} more changes.`);\n return [\n [\n \"Harness notice: the MCP tools changed since the last turn. The tools you were given are the same, and a\",\n \"disabled tool's call is refused before it reaches its server.\",\n ...shown,\n ].join(\"\\n\"),\n ];\n }\n\n /** Waits, once, for every `direct` server to connect or fail, up to `directWaitMs`, or until `signal` aborts. */\n async #waitForDirect(signal: AbortSignal): Promise<void> {\n const direct = this.#states.filter((state) => state.config.exposure === \"direct\");\n if (direct.length === 0 || signal.aborted) return;\n let handle: unknown;\n let onAbort: (() => void) | undefined;\n await new Promise<void>((resolve) => {\n handle = this.#timers.setTimeout(resolve, this.#directWaitMs);\n onAbort = () => resolve();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n void Promise.all(direct.map((state) => state.done)).then(() => resolve());\n });\n this.#timers.clearTimeout(handle);\n if (onAbort !== undefined) signal.removeEventListener(\"abort\", onAbort);\n }\n\n /** One line per tool whose label changed since the last notice, naming it by canonical name only. */\n #noticeLines(commits: (() => void)[]): string[] {\n return this.#states\n .filter((state) => state.status === \"registered\")\n .flatMap((state) => noticeLinesOf(state, commits));\n }\n\n commitNotices(): void {\n for (const commit of this.#uncommitted.splice(0)) commit();\n }\n\n /** Reads a server's list again after it said the list changed, at most once per `relistIntervalMs`. */\n #scheduleRelist(state: ServerState): void {\n if (this.#closing !== undefined || state.status === \"failed\") return;\n const relist = state.relist;\n if (state.status === \"connecting\" || relist.running || relist.timer !== undefined) {\n relist.dirty = true;\n return;\n }\n const delay = Math.max(0, relist.last + this.#relistMs - this.#timers.now());\n relist.timer = this.#timers.setTimeout(() => {\n relist.timer = undefined;\n void this.#relist(state);\n }, delay);\n }\n\n async #relist(state: ServerState): Promise<void> {\n const relist = state.relist;\n const connection = state.connection;\n if (connection === undefined || this.#closing !== undefined) return;\n relist.running = true;\n relist.dirty = false;\n relist.last = this.#timers.now();\n try {\n state.latest = await listedOf(await connection.listTools());\n state.unreadable = false;\n } catch (error) {\n if (!state.unreadable) {\n const why = error instanceof Error ? error.message : String(error);\n this.#log(\n `the changed tool list of \"${state.config.name}\" could not be read, so its tools are disabled from the next turn: ${why}`,\n );\n }\n state.unreadable = true;\n } finally {\n relist.running = false;\n }\n if (relist.dirty) this.#scheduleRelist(state);\n }\n\n pending(): readonly McpPendingTool[] {\n const waiting: McpPendingTool[] = [];\n for (const state of this.#states) {\n for (const [name, listed] of state.latest) {\n if (state.pinned.get(name) === listed.hash) continue;\n const canonicalName = state.registered.get(name);\n waiting.push({\n server: state.config.name,\n tool: name,\n ...(canonicalName === undefined ? {} : { canonicalName }),\n state: state.pinned.has(name) ? \"changed\" : \"new\",\n hash: listed.hash,\n definition: listed.tool,\n });\n }\n }\n return waiting;\n }\n\n async approve(server: string, tool: string, hash: string): Promise<void> {\n const state = this.#states.find((candidate) => candidate.config.name === server);\n const listed = state?.latest.get(tool);\n if (state === undefined || listed === undefined || listed.hash !== hash) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n \"that tool's current definition does not have this hash, so it was not approved; read pending() again\",\n );\n }\n const store = this.#options.pins;\n if (store === undefined) {\n state.pinned.set(tool, hash);\n return;\n }\n // Writes of one server run one after another, and each builds its pins when its turn comes, so a later approval\n // never lands under an earlier one. The pin is held in memory only once the store has it, so a failed write\n // enables nothing.\n const write = state.pinWrites.then(async () => {\n await store.write(server, Object.fromEntries([...state.pinned, [tool, hash]]));\n state.pinned.set(tool, hash);\n });\n state.pinWrites = write.catch(() => {});\n await write;\n }\n\n permissionHook(): PermissionHook {\n return async (call): Promise<HookDecision | undefined> => {\n const canonical = this.#options.registry.get?.(call.tool)?.canonicalName ?? call.tool;\n for (const state of this.#states) {\n for (const [name, registered] of state.registered) {\n if (registered !== canonical) continue;\n if (state.enabled.has(name)) return undefined;\n return {\n decision: \"deny\",\n reason: `${canonical} is disabled: its definition is new, changed or gone since it was pinned, and no person has approved it`,\n rule: \"mcp_pin\",\n };\n }\n }\n return undefined;\n };\n }\n\n records(): readonly ExtensionLoadedRecord[] {\n return this.#states.flatMap((state) => this.#records.get(state.config.name) ?? []);\n }\n\n connection(server: string): McpConnection | undefined {\n const state = this.#states.find((candidate) => candidate.config.name === server);\n return state?.status === \"registered\" ? state.connection : undefined;\n }\n\n close(): Promise<void> {\n this.#closing ??= (async () => {\n // Aborting ends every handshake still running, and closing every open connection fails any tool list still being\n // read, so a server that hangs can't hold the others up.\n this.#abort.abort();\n for (const state of this.#states) {\n if (state.relist.timer !== undefined) this.#timers.clearTimeout(state.relist.timer);\n state.relist.timer = undefined;\n }\n await Promise.all([...this.#open].map((connection) => connection.close()));\n await Promise.all(this.#states.map((state) => state.done));\n await this.#connecting?.catch(() => {});\n })();\n return this.#closing;\n }\n}\n\n/**\n * Creates the MCP client for a set of servers. It checks every config now and starts nothing until `start()`,\n * `connect()` or the first `beginTurn()`. Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be\n * used, two servers with one name, a registry without `register()`, `registerAll()` and `list()`, a pin store\n * without `read()` and `write()`, or a wait that is not a whole number of milliseconds.\n */\nexport function createMcpManager(options: McpManagerOptions): McpManager {\n const registry = options?.registry;\n for (const method of [\"register\", \"registerAll\", \"list\"] as const) {\n if (typeof registry?.[method] !== \"function\") {\n throw new HarnessError(\"invalid_mcp_config\", `createMcpManager() needs a tool registry with ${method}()`);\n }\n }\n checkServers(options.servers);\n const pins = options.pins;\n if (pins !== undefined && (typeof pins.read !== \"function\" || typeof pins.write !== \"function\")) {\n throw new HarnessError(\"invalid_mcp_config\", \"createMcpManager() needs a pin store with read() and write()\");\n }\n return new Manager(options);\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import type { McpPinStore, McpTool, McpToolState } from "./types.js";
2
+ /** The hash of one tool's definition, its pin once a person approves it. */
3
+ export declare function toolPinOf(tool: McpTool): Promise<string>;
4
+ /** Each tool of `current` and of `pinned`, by name, with how its current definition compares with its pin. */
5
+ export declare function diffTools(pinned: ReadonlyMap<string, string>, current: ReadonlyMap<string, string>): Map<string, McpToolState>;
6
+ /** Checks pins a store returned, so a corrupt entry is refused and not compared. */
7
+ export declare function checkPins(server: string, pins: unknown): Map<string, string>;
8
+ /** A pin store in memory, for a host that keeps approvals for the life of the process, and for tests. */
9
+ export declare function memoryMcpPinStore(initial?: Readonly<Record<string, Readonly<Record<string, string>>>>): McpPinStore;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Pins for MCP tool definitions. A tool's pin is the hash of its definition as a person approved it: `sha256:` and the
3
+ * hex SHA-256 of the canonical JSON (RFC 8785) of `{ name, description, inputSchema }`, the fields the record's tools
4
+ * hash covers. The annotations are left out, because they change nothing the harness does. A diff compares a server's
5
+ * current list with its pins and classifies each tool as unchanged, new, changed or removed.
6
+ */
7
+ import { canonicalInputHash } from "@buildanagent/sdk";
8
+ import { HarnessError } from "../errors.js";
9
+ const PIN = /^sha256:[0-9a-f]{64}$/;
10
+ /** The hash of one tool's definition, its pin once a person approves it. */
11
+ export async function toolPinOf(tool) {
12
+ const { name, description, inputSchema } = tool;
13
+ return `sha256:${await canonicalInputHash({ name, description, inputSchema })}`;
14
+ }
15
+ /** Each tool of `current` and of `pinned`, by name, with how its current definition compares with its pin. */
16
+ export function diffTools(pinned, current) {
17
+ const states = new Map();
18
+ for (const [name, hash] of current) {
19
+ const pin = pinned.get(name);
20
+ states.set(name, pin === undefined ? "new" : pin === hash ? "unchanged" : "changed");
21
+ }
22
+ for (const name of pinned.keys())
23
+ if (!current.has(name))
24
+ states.set(name, "removed");
25
+ return states;
26
+ }
27
+ /** Checks pins a store returned, so a corrupt entry is refused and not compared. */
28
+ export function checkPins(server, pins) {
29
+ if (typeof pins !== "object" || pins === null || Array.isArray(pins)) {
30
+ throw new HarnessError("invalid_mcp_config", `the pins of the MCP server "${server}" are not an object`);
31
+ }
32
+ const checked = new Map();
33
+ for (const [name, hash] of Object.entries(pins)) {
34
+ if (typeof hash !== "string" || !PIN.test(hash)) {
35
+ throw new HarnessError("invalid_mcp_config", `a pin of the MCP server "${server}" is not a sha256 hash`);
36
+ }
37
+ checked.set(name, hash);
38
+ }
39
+ return checked;
40
+ }
41
+ /** A pin store in memory, for a host that keeps approvals for the life of the process, and for tests. */
42
+ export function memoryMcpPinStore(initial = {}) {
43
+ const servers = new Map(Object.entries(initial).map(([server, pins]) => [server, { ...pins }]));
44
+ return {
45
+ async read(server) {
46
+ const pins = servers.get(server);
47
+ return pins === undefined ? undefined : { ...pins };
48
+ },
49
+ async write(server, pins) {
50
+ servers.set(server, { ...pins });
51
+ },
52
+ };
53
+ }
54
+ //# sourceMappingURL=pins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pins.js","sourceRoot":"","sources":["../../src/mcp/pins.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,MAAM,GAAG,GAAG,uBAAuB,CAAC;AAEpC,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,IAAa;IAC3C,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IAChD,OAAO,UAAU,MAAM,kBAAkB,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC,EAA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AE,4BAA4B,MAAM,wBAAwB,CAAC,CAAC;QAC3G,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC1B,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,iBAAiB,CAC/B,OAAO,GAA+D,EAAE;IAExE,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IAChG,OAAO;QACL,KAAK,CAAC,IAAI,CAAC,MAAM;YACf,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC;QACtD,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI;YACtB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Pins for MCP tool definitions. A tool's pin is the hash of its definition as a person approved it: `sha256:` and the\n * hex SHA-256 of the canonical JSON (RFC 8785) of `{ name, description, inputSchema }`, the fields the record's tools\n * hash covers. The annotations are left out, because they change nothing the harness does. A diff compares a server's\n * current list with its pins and classifies each tool as unchanged, new, changed or removed.\n */\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { McpPinStore, McpTool, McpToolState } from \"./types.js\";\n\nconst PIN = /^sha256:[0-9a-f]{64}$/;\n\n/** The hash of one tool's definition, its pin once a person approves it. */\nexport async function toolPinOf(tool: McpTool): Promise<string> {\n const { name, description, inputSchema } = tool;\n return `sha256:${await canonicalInputHash({ name, description, inputSchema })}`;\n}\n\n/** Each tool of `current` and of `pinned`, by name, with how its current definition compares with its pin. */\nexport function diffTools(\n pinned: ReadonlyMap<string, string>,\n current: ReadonlyMap<string, string>,\n): Map<string, McpToolState> {\n const states = new Map<string, McpToolState>();\n for (const [name, hash] of current) {\n const pin = pinned.get(name);\n states.set(name, pin === undefined ? \"new\" : pin === hash ? \"unchanged\" : \"changed\");\n }\n for (const name of pinned.keys()) if (!current.has(name)) states.set(name, \"removed\");\n return states;\n}\n\n/** Checks pins a store returned, so a corrupt entry is refused and not compared. */\nexport function checkPins(server: string, pins: unknown): Map<string, string> {\n if (typeof pins !== \"object\" || pins === null || Array.isArray(pins)) {\n throw new HarnessError(\"invalid_mcp_config\", `the pins of the MCP server \"${server}\" are not an object`);\n }\n const checked = new Map<string, string>();\n for (const [name, hash] of Object.entries(pins)) {\n if (typeof hash !== \"string\" || !PIN.test(hash)) {\n throw new HarnessError(\"invalid_mcp_config\", `a pin of the MCP server \"${server}\" is not a sha256 hash`);\n }\n checked.set(name, hash);\n }\n return checked;\n}\n\n/** A pin store in memory, for a host that keeps approvals for the life of the process, and for tests. */\nexport function memoryMcpPinStore(\n initial: Readonly<Record<string, Readonly<Record<string, string>>>> = {},\n): McpPinStore {\n const servers = new Map(Object.entries(initial).map(([server, pins]) => [server, { ...pins }]));\n return {\n async read(server) {\n const pins = servers.get(server);\n return pins === undefined ? undefined : { ...pins };\n },\n async write(server, pins) {\n servers.set(server, { ...pins });\n },\n };\n}\n"]}
@@ -12,6 +12,12 @@ export async function mcpRecordOf(config, connection, tools) {
12
12
  const mcp = {
13
13
  transport: transport.kind,
14
14
  ...(transport.kind === "stdio" ? { commandHash: await hash([transport.command, ...(transport.args ?? [])]) } : {}),
15
+ // The URL as `URL` normalises it, so two spellings of one endpoint hash alike. Its query can hold a secret the
16
+ // config check did not recognise, and a hash can be confirmed by guessing, so the README says to keep secrets in
17
+ // headers, which the record never covers.
18
+ ...(transport.kind === "http" || transport.kind === "sse"
19
+ ? { urlHash: await hash(new URL(transport.url).href) }
20
+ : {}),
15
21
  era: connection.era,
16
22
  toolsHash: await hash(listed),
17
23
  };
@@ -1 +1 @@
1
- {"version":3,"file":"record.js","sourceRoot":"","sources":["../../src/mcp/record.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAIvD,MAAM,IAAI,GAAG,KAAK,EAAE,KAAc,EAAmB,EAAE,CAAC,UAAU,MAAM,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;AAEpG;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAuB,EACvB,UAAyB,EACzB,KAAyB;IAEzB,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAChE,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;IACrF,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IACnC,MAAM,GAAG,GAAoB;QAC3B,SAAS,EAAE,SAAS,CAAC,IAAI;QACzB,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClH,GAAG,EAAE,UAAU,CAAC,GAAG;QACnB,SAAS,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC;KAC9B,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * The `extension_loaded` record of a connected MCP server. It holds hashes and never a raw argument or an environment\n * value, because a server's command line or variables can carry a token. Every hash is `sha256:` and the hex SHA-256 of\n * canonical JSON (RFC 8785), the hash the permission pipeline uses for tool inputs, so the record is the same on every\n * runtime and across reconnects of an unchanged server.\n */\nimport type { McpServerRecord } from \"@buildanagent/protocol\";\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { McpConnection, McpServerConfig, McpTool } from \"./types.js\";\n\nconst hash = async (value: unknown): Promise<string> => `sha256:${await canonicalInputHash(value)}`;\n\n/**\n * The record for a server whose tools were registered. The tools hash covers each tool's name, description and input\n * schema, sorted by name, and leaves out the annotations, which change nothing the harness does.\n */\nexport async function mcpRecordOf(\n config: McpServerConfig,\n connection: McpConnection,\n tools: readonly McpTool[],\n): Promise<ExtensionLoadedRecord> {\n const listed = [...tools]\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n .map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));\n const transport = config.transport;\n const mcp: McpServerRecord = {\n transport: transport.kind,\n ...(transport.kind === \"stdio\" ? { commandHash: await hash([transport.command, ...(transport.args ?? [])]) } : {}),\n era: connection.era,\n toolsHash: await hash(listed),\n };\n return { name: config.name, tier: \"mcp\", contentHash: await hash(mcp), mcp };\n}\n"]}
1
+ {"version":3,"file":"record.js","sourceRoot":"","sources":["../../src/mcp/record.ts"],"names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MAAM,IAAI,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE;YACtD,CAAC,CAAC,EAAE,CAAC;QACP,GAAG,EAAE,UAAU,CAAC,GAAG;QACnB,SAAS,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC;KAC9B,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * The `extension_loaded` record of a connected MCP server. It holds hashes and never a raw argument, an environment\n * value, a URL or a header, because a server's command line, variables, URL or headers can carry a token. Every hash is `sha256:` and the hex SHA-256 of\n * canonical JSON (RFC 8785), the hash the permission pipeline uses for tool inputs, so the record is the same on every\n * runtime and across reconnects of an unchanged server.\n */\nimport type { McpServerRecord } from \"@buildanagent/protocol\";\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { McpConnection, McpServerConfig, McpTool } from \"./types.js\";\n\nconst hash = async (value: unknown): Promise<string> => `sha256:${await canonicalInputHash(value)}`;\n\n/**\n * The record for a server whose tools were registered. The tools hash covers each tool's name, description and input\n * schema, sorted by name, and leaves out the annotations, which change nothing the harness does.\n */\nexport async function mcpRecordOf(\n config: McpServerConfig,\n connection: McpConnection,\n tools: readonly McpTool[],\n): Promise<ExtensionLoadedRecord> {\n const listed = [...tools]\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n .map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));\n const transport = config.transport;\n const mcp: McpServerRecord = {\n transport: transport.kind,\n ...(transport.kind === \"stdio\" ? { commandHash: await hash([transport.command, ...(transport.args ?? [])]) } : {}),\n // The URL as `URL` normalises it, so two spellings of one endpoint hash alike. Its query can hold a secret the\n // config check did not recognise, and a hash can be confirmed by guessing, so the README says to keep secrets in\n // headers, which the record never covers.\n ...(transport.kind === \"http\" || transport.kind === \"sse\"\n ? { urlHash: await hash(new URL(transport.url).href) }\n : {}),\n era: connection.era,\n toolsHash: await hash(listed),\n };\n return { name: config.name, tier: \"mcp\", contentHash: await hash(mcp), mcp };\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import type { McpHttpTransport, McpSseTransport } from "./types.js";
2
+ /** A remote transport's settings with their defaults, checked, and the policy for the addresses it may reach. */
3
+ export interface RemoteSettings {
4
+ readonly kind: "http" | "sse";
5
+ readonly url: URL;
6
+ readonly headers: Readonly<Record<string, string>>;
7
+ readonly allows: (address: string) => boolean;
8
+ readonly maxMessageBytes: number;
9
+ readonly maxStreamBytes: number;
10
+ readonly headersTimeoutMs: number;
11
+ readonly streamIdleMs: number;
12
+ readonly maxStreamMs: number;
13
+ readonly maxStreams: number;
14
+ /** The text a log line or an error must never show: the URL and every header value. */
15
+ readonly secrets: readonly string[];
16
+ }
17
+ /** Checks a remote transport's config. Throws a `HarnessError`, code `invalid_mcp_config`. */
18
+ export declare function checkRemoteTransport(transport: McpHttpTransport | McpSseTransport): RemoteSettings;
19
+ /** `text` with every secret of a remote server replaced, for a log line or an error message. */
20
+ export declare function redact(text: string, secrets: readonly string[]): string;
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The checks on a remote server's config, made when the manager is created, so a bad URL or header fails before any
3
+ * request: the URL's scheme and form, the headers the host supplies, the address ranges it allows and the bounds. The
4
+ * address policy built here decides, for every address a name resolves to and every address a request reaches, whether
5
+ * the request may go on.
6
+ */
7
+ import { inAddressRange, isAddressRange, isLoopbackAddress, isPublicAddress } from "../credentials/addresses.js";
8
+ import { HarnessError } from "../errors.js";
9
+ const DEFAULTS = {
10
+ maxMessageBytes: 8 * 1024 * 1024,
11
+ maxStreamBytes: 64 * 1024 * 1024,
12
+ headersTimeoutMs: 30_000,
13
+ streamIdleMs: 120_000,
14
+ maxStreamMs: 3_600_000,
15
+ maxStreams: 8,
16
+ };
17
+ // The longest delay a timer takes: a larger one fires at once.
18
+ const MAX_TIMER_MS = 2 ** 31 - 1;
19
+ const MAX_URL_CHARS = 2048;
20
+ const MAX_HEADER_VALUE_CHARS = 8192;
21
+ const MAX_HEADERS = 32;
22
+ // RFC 9110's token: the characters a header name may hold.
23
+ const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]{1,64}$/;
24
+ // Headers the transport, the HTTP stack or MCP itself sets, which a config may not replace.
25
+ const RESERVED_HEADERS = new Set([
26
+ "host",
27
+ "content-length",
28
+ "content-type",
29
+ "content-encoding",
30
+ "transfer-encoding",
31
+ "connection",
32
+ "keep-alive",
33
+ "upgrade",
34
+ "te",
35
+ "trailer",
36
+ "proxy-authorization",
37
+ "proxy-connection",
38
+ "accept",
39
+ "accept-encoding",
40
+ "last-event-id",
41
+ "mcp-session-id",
42
+ "mcp-protocol-version",
43
+ "mcp-method",
44
+ "mcp-name",
45
+ ]);
46
+ // A query parameter whose name says it holds a credential. A token belongs in a header, because a URL ends up in logs,
47
+ // proxies and error messages.
48
+ const CREDENTIAL_PART = /^(token|key|secret|password|passwd|pass|pwd|auth|authorization|code|sig|signature|credential|credentials|session|sessionid|apikey|jwt|bearer)$/i;
49
+ const CREDENTIAL_ENDING = /(key|token|secret|password)$/i;
50
+ const invalid = (why) => {
51
+ throw new HarnessError("invalid_mcp_config", `a remote MCP server ${why}`);
52
+ };
53
+ function bound(name, value, fallback) {
54
+ if (value === undefined)
55
+ return fallback;
56
+ if (!(Number.isInteger(value) && value >= 1 && value <= MAX_TIMER_MS)) {
57
+ invalid(`needs ${name} to be a whole number from 1 to ${MAX_TIMER_MS}`);
58
+ }
59
+ return value;
60
+ }
61
+ // The control characters of ASCII, which no URL or header value may hold: a line break would split a header.
62
+ const hasControl = (text) => [...text].some((char) => (char.codePointAt(0) ?? 0) <= 0x1f || char === "\u007f");
63
+ function credentialName(name) {
64
+ return name.split(/[-_.]/).some((part) => CREDENTIAL_PART.test(part) || CREDENTIAL_ENDING.test(part));
65
+ }
66
+ /** Parses and checks the URL. A secret is never quoted back, so a refusal names the rule and not the text. */
67
+ function checkUrl(text, loopback) {
68
+ if (typeof text !== "string" || text === "" || text.length > MAX_URL_CHARS) {
69
+ invalid(`needs a url of 1 to ${MAX_URL_CHARS} characters`);
70
+ }
71
+ // `URL` removes tabs and line breaks before it parses, so they are refused here, where they can still be seen.
72
+ if (hasControl(text))
73
+ invalid("has a url with a control character, which no URL may hold");
74
+ let url;
75
+ try {
76
+ url = new URL(text);
77
+ }
78
+ catch {
79
+ return invalid("has a url that is not an absolute URL");
80
+ }
81
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
82
+ invalid("needs an https: url; plain http: is accepted only with unsafeAllowLoopback, for a test server");
83
+ }
84
+ if (url.username !== "" || url.password !== "") {
85
+ invalid("has a user name or password in its url; send a credential in headers instead");
86
+ }
87
+ if (url.hash !== "")
88
+ invalid("has a fragment in its url, which no request sends");
89
+ for (const name of url.searchParams.keys()) {
90
+ if (credentialName(name))
91
+ invalid("has a query parameter whose name looks like a credential; send it in headers");
92
+ }
93
+ return url;
94
+ }
95
+ function checkHeaders(headers) {
96
+ if (headers === undefined)
97
+ return {};
98
+ if (typeof headers !== "object" || headers === null || Array.isArray(headers))
99
+ invalid("needs headers to be an object");
100
+ const entries = Object.entries(headers);
101
+ if (entries.length > MAX_HEADERS)
102
+ invalid(`has more than ${MAX_HEADERS} headers`);
103
+ const checked = {};
104
+ const seen = new Set();
105
+ for (const [name, value] of entries) {
106
+ if (!HEADER_NAME.test(name))
107
+ invalid(`has a header name that is not an HTTP token: ${JSON.stringify(name)}`);
108
+ const lower = name.toLowerCase();
109
+ if (RESERVED_HEADERS.has(lower))
110
+ invalid(`sets the header ${name}, which the transport sets itself`);
111
+ if (seen.has(lower))
112
+ invalid(`sets the header ${name} twice, in some letter case`);
113
+ seen.add(lower);
114
+ // The value is a secret, so the refusal names the header and never its value.
115
+ if (typeof value !== "string" || value.length > MAX_HEADER_VALUE_CHARS || hasControl(value)) {
116
+ invalid(`has a value for ${name} that is not a string of at most ${MAX_HEADER_VALUE_CHARS} characters without control characters`);
117
+ }
118
+ checked[lower] = value;
119
+ }
120
+ return checked;
121
+ }
122
+ // One address in each IPv6 form that wraps an IPv4 address, at its zero end: mapped, compatible, translated, NAT64
123
+ // and 6to4. An IPv6 range that holds one is IPv4 written another way, and is refused, so IPv4 is written as IPv4.
124
+ const WRAPPED_IPV4 = ["::ffff:0.0.0.0", "::0.0.0.2", "::ffff:0:0.0.0.0", "64:ff9b::0.0.0.0", "2002::"];
125
+ /**
126
+ * Refuses a range that allows far more than it seems to: `/0`, and an IPv6 range that holds the base of a form that
127
+ * wraps IPv4, such as `::ffff:0:0/96`, which is all of IPv4, or `::ffff:10.0.0.0/8`, which is `::/8`.
128
+ */
129
+ function checkBreadth(range) {
130
+ const [address = "", prefix] = range.split("/");
131
+ if (prefix !== undefined && Number(prefix) === 0) {
132
+ invalid(`has the allowAddresses entry ${JSON.stringify(range)}, which allows every address`);
133
+ }
134
+ if (address.includes(":") && WRAPPED_IPV4.some((base) => inAddressRange(base, range))) {
135
+ invalid(`has the allowAddresses entry ${JSON.stringify(range)}, an IPv6 range that holds IPv4 addresses in a wrapped form; write the IPv4 range itself`);
136
+ }
137
+ }
138
+ function checkRanges(ranges) {
139
+ if (ranges === undefined)
140
+ return [];
141
+ if (!Array.isArray(ranges))
142
+ invalid("needs allowAddresses to be a list of address ranges");
143
+ for (const range of ranges) {
144
+ if (typeof range !== "string" || !isAddressRange(range)) {
145
+ invalid(`has an allowAddresses entry that is not an address or CIDR range: ${JSON.stringify(range)}`);
146
+ }
147
+ checkBreadth(range);
148
+ }
149
+ return ranges;
150
+ }
151
+ /**
152
+ * The policy for the addresses a request may reach: a public address, an address in `allowAddresses` that is not
153
+ * loopback, or, with `unsafeAllowLoopback`, a loopback address. A plain-`http:` URL reaches loopback addresses only.
154
+ */
155
+ function policyOf(ranges, loopback, plain) {
156
+ return (address) => {
157
+ if (isLoopbackAddress(address))
158
+ return loopback;
159
+ if (plain)
160
+ return false;
161
+ return isPublicAddress(address) || ranges.some((range) => inAddressRange(address, range));
162
+ };
163
+ }
164
+ /** Checks a remote transport's config. Throws a `HarnessError`, code `invalid_mcp_config`. */
165
+ export function checkRemoteTransport(transport) {
166
+ if (transport.unsafeAllowLoopback !== undefined && typeof transport.unsafeAllowLoopback !== "boolean") {
167
+ invalid("needs unsafeAllowLoopback to be true or false");
168
+ }
169
+ const loopback = transport.unsafeAllowLoopback === true;
170
+ const url = checkUrl(transport.url, loopback);
171
+ const headers = checkHeaders(transport.headers);
172
+ const ranges = checkRanges(transport.allowAddresses);
173
+ if (transport.proxy !== undefined && typeof transport.proxy?.fetch !== "function") {
174
+ invalid("needs a proxy with a fetch(), such as the one startEgressProxy() returns");
175
+ }
176
+ if (transport.proxy !== undefined && url.protocol !== "https:")
177
+ invalid("needs an https: url to go through a proxy");
178
+ if (transport.resolve !== undefined && typeof transport.resolve !== "function")
179
+ invalid("needs resolve to be a function");
180
+ const ca = transport.ca;
181
+ if (ca !== undefined &&
182
+ typeof ca !== "string" &&
183
+ !(Array.isArray(ca) && ca.every((one) => typeof one === "string"))) {
184
+ invalid("needs ca to be a certificate or a list of them, as PEM text");
185
+ }
186
+ const secrets = [url.href, url.search, ...Object.values(headers)].filter((text) => text.length >= 4);
187
+ return {
188
+ kind: transport.kind,
189
+ url,
190
+ headers,
191
+ allows: policyOf(ranges, loopback, url.protocol === "http:"),
192
+ maxMessageBytes: bound("maxMessageBytes", transport.maxMessageBytes, DEFAULTS.maxMessageBytes),
193
+ maxStreamBytes: bound("maxStreamBytes", transport.maxStreamBytes, DEFAULTS.maxStreamBytes),
194
+ headersTimeoutMs: bound("headersTimeoutMs", transport.headersTimeoutMs, DEFAULTS.headersTimeoutMs),
195
+ streamIdleMs: bound("streamIdleMs", transport.streamIdleMs, DEFAULTS.streamIdleMs),
196
+ maxStreamMs: bound("maxStreamMs", transport.maxStreamMs, DEFAULTS.maxStreamMs),
197
+ maxStreams: bound("maxStreams", transport.maxStreams, DEFAULTS.maxStreams),
198
+ secrets: [...new Set(secrets)].sort((a, b) => b.length - a.length),
199
+ };
200
+ }
201
+ /** `text` with every secret of a remote server replaced, for a log line or an error message. */
202
+ export function redact(text, secrets) {
203
+ let out = text;
204
+ for (const secret of secrets)
205
+ out = out.split(secret).join("[redacted]");
206
+ return out;
207
+ }
208
+ //# sourceMappingURL=remote-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-config.js","sourceRoot":"","sources":["../../src/mcp/remote-config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACjH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IAChC,cAAc,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;IAChC,gBAAgB,EAAE,MAAM;IACxB,YAAY,EAAE,OAAO;IACrB,WAAW,EAAE,SAAS;IACtB,UAAU,EAAE,CAAC;CACL,CAAC;AACX,+DAA+D;AAC/D,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACjC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,2DAA2D;AAC3D,MAAM,WAAW,GAAG,qCAAqC,CAAC;AAC1D,4FAA4F;AAC5F,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,MAAM;IACN,gBAAgB;IAChB,cAAc;IACd,kBAAkB;IAClB,mBAAmB;IACnB,YAAY;IACZ,YAAY;IACZ,SAAS;IACT,IAAI;IACJ,SAAS;IACT,qBAAqB;IACrB,kBAA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G,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,gGAAgG;AAChG,MAAM,UAAU,MAAM,CAAC,IAAY,EAAE,OAA0B;IAC7D,IAAI,GAAG,GAAG,IAAI,CAAC;IACf,KAAK,MAAM,MAAM,IAAI,OAAO;QAAE,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACzE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * The checks on a remote server's config, made when the manager is created, so a bad URL or header fails before any\n * request: the URL's scheme and form, the headers the host supplies, the address ranges it allows and the bounds. The\n * address policy built here decides, for every address a name resolves to and every address a request reaches, whether\n * the request may go on.\n */\nimport { inAddressRange, isAddressRange, isLoopbackAddress, isPublicAddress } from \"../credentials/addresses.js\";\nimport { HarnessError } from \"../errors.js\";\nimport type { McpHttpTransport, McpSseTransport } from \"./types.js\";\n\nconst DEFAULTS = {\n maxMessageBytes: 8 * 1024 * 1024,\n maxStreamBytes: 64 * 1024 * 1024,\n headersTimeoutMs: 30_000,\n streamIdleMs: 120_000,\n maxStreamMs: 3_600_000,\n maxStreams: 8,\n} as const;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst MAX_URL_CHARS = 2048;\nconst MAX_HEADER_VALUE_CHARS = 8192;\nconst MAX_HEADERS = 32;\n// RFC 9110's token: the characters a header name may hold.\nconst HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]{1,64}$/;\n// Headers the transport, the HTTP stack or MCP itself sets, which a config may not replace.\nconst RESERVED_HEADERS = new Set([\n \"host\",\n \"content-length\",\n \"content-type\",\n \"content-encoding\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n \"upgrade\",\n \"te\",\n \"trailer\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"accept\",\n \"accept-encoding\",\n \"last-event-id\",\n \"mcp-session-id\",\n \"mcp-protocol-version\",\n \"mcp-method\",\n \"mcp-name\",\n]);\n// A query parameter whose name says it holds a credential. A token belongs in a header, because a URL ends up in logs,\n// proxies and error messages.\nconst CREDENTIAL_PART =\n /^(token|key|secret|password|passwd|pass|pwd|auth|authorization|code|sig|signature|credential|credentials|session|sessionid|apikey|jwt|bearer)$/i;\nconst CREDENTIAL_ENDING = /(key|token|secret|password)$/i;\n\n/** A remote transport's settings with their defaults, checked, and the policy for the addresses it may reach. */\nexport interface RemoteSettings {\n readonly kind: \"http\" | \"sse\";\n readonly url: URL;\n readonly headers: Readonly<Record<string, string>>;\n readonly allows: (address: string) => boolean;\n readonly maxMessageBytes: number;\n readonly maxStreamBytes: number;\n readonly headersTimeoutMs: number;\n readonly streamIdleMs: number;\n readonly maxStreamMs: number;\n readonly maxStreams: number;\n /** The text a log line or an error must never show: the URL and every header value. */\n readonly secrets: readonly string[];\n}\n\nconst invalid = (why: string): never => {\n throw new HarnessError(\"invalid_mcp_config\", `a remote MCP server ${why}`);\n};\n\nfunction bound(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!(Number.isInteger(value) && value >= 1 && value <= MAX_TIMER_MS)) {\n invalid(`needs ${name} to be a whole number from 1 to ${MAX_TIMER_MS}`);\n }\n return value as number;\n}\n\n// The control characters of ASCII, which no URL or header value may hold: a line break would split a header.\nconst hasControl = (text: string): boolean =>\n [...text].some((char) => (char.codePointAt(0) ?? 0) <= 0x1f || char === \"\\u007f\");\n\nfunction credentialName(name: string): boolean {\n return name.split(/[-_.]/).some((part) => CREDENTIAL_PART.test(part) || CREDENTIAL_ENDING.test(part));\n}\n\n/** Parses and checks the URL. A secret is never quoted back, so a refusal names the rule and not the text. */\nfunction checkUrl(text: unknown, loopback: boolean): URL {\n if (typeof text !== \"string\" || text === \"\" || text.length > MAX_URL_CHARS) {\n invalid(`needs a url of 1 to ${MAX_URL_CHARS} characters`);\n }\n // `URL` removes tabs and line breaks before it parses, so they are refused here, where they can still be seen.\n if (hasControl(text as string)) invalid(\"has a url with a control character, which no URL may hold\");\n let url: URL;\n try {\n url = new URL(text as string);\n } catch {\n return invalid(\"has a url that is not an absolute URL\");\n }\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && loopback)) {\n invalid(\"needs an https: url; plain http: is accepted only with unsafeAllowLoopback, for a test server\");\n }\n if (url.username !== \"\" || url.password !== \"\") {\n invalid(\"has a user name or password in its url; send a credential in headers instead\");\n }\n if (url.hash !== \"\") invalid(\"has a fragment in its url, which no request sends\");\n for (const name of url.searchParams.keys()) {\n if (credentialName(name)) invalid(\"has a query parameter whose name looks like a credential; send it in headers\");\n }\n return url;\n}\n\nfunction checkHeaders(headers: unknown): Record<string, string> {\n if (headers === undefined) return {};\n if (typeof headers !== \"object\" || headers === null || Array.isArray(headers))\n invalid(\"needs headers to be an object\");\n const entries = Object.entries(headers as Record<string, unknown>);\n if (entries.length > MAX_HEADERS) invalid(`has more than ${MAX_HEADERS} headers`);\n const checked: Record<string, string> = {};\n const seen = new Set<string>();\n for (const [name, value] of entries) {\n if (!HEADER_NAME.test(name)) invalid(`has a header name that is not an HTTP token: ${JSON.stringify(name)}`);\n const lower = name.toLowerCase();\n if (RESERVED_HEADERS.has(lower)) invalid(`sets the header ${name}, which the transport sets itself`);\n if (seen.has(lower)) invalid(`sets the header ${name} twice, in some letter case`);\n seen.add(lower);\n // The value is a secret, so the refusal names the header and never its value.\n if (typeof value !== \"string\" || value.length > MAX_HEADER_VALUE_CHARS || hasControl(value)) {\n invalid(\n `has a value for ${name} that is not a string of at most ${MAX_HEADER_VALUE_CHARS} characters without control characters`,\n );\n }\n checked[lower] = value as string;\n }\n return checked;\n}\n\n// One address in each IPv6 form that wraps an IPv4 address, at its zero end: mapped, compatible, translated, NAT64\n// and 6to4. An IPv6 range that holds one is IPv4 written another way, and is refused, so IPv4 is written as IPv4.\nconst WRAPPED_IPV4 = [\"::ffff:0.0.0.0\", \"::0.0.0.2\", \"::ffff:0:0.0.0.0\", \"64:ff9b::0.0.0.0\", \"2002::\"];\n\n/**\n * Refuses a range that allows far more than it seems to: `/0`, and an IPv6 range that holds the base of a form that\n * wraps IPv4, such as `::ffff:0:0/96`, which is all of IPv4, or `::ffff:10.0.0.0/8`, which is `::/8`.\n */\nfunction checkBreadth(range: string): void {\n const [address = \"\", prefix] = range.split(\"/\");\n if (prefix !== undefined && Number(prefix) === 0) {\n invalid(`has the allowAddresses entry ${JSON.stringify(range)}, which allows every address`);\n }\n if (address.includes(\":\") && WRAPPED_IPV4.some((base) => inAddressRange(base, range))) {\n invalid(\n `has the allowAddresses entry ${JSON.stringify(range)}, an IPv6 range that holds IPv4 addresses in a wrapped form; write the IPv4 range itself`,\n );\n }\n}\n\nfunction checkRanges(ranges: unknown): readonly string[] {\n if (ranges === undefined) return [];\n if (!Array.isArray(ranges)) invalid(\"needs allowAddresses to be a list of address ranges\");\n for (const range of ranges as unknown[]) {\n if (typeof range !== \"string\" || !isAddressRange(range)) {\n invalid(`has an allowAddresses entry that is not an address or CIDR range: ${JSON.stringify(range)}`);\n }\n checkBreadth(range as string);\n }\n return ranges as string[];\n}\n\n/**\n * The policy for the addresses a request may reach: a public address, an address in `allowAddresses` that is not\n * loopback, or, with `unsafeAllowLoopback`, a loopback address. A plain-`http:` URL reaches loopback addresses only.\n */\nfunction policyOf(ranges: readonly string[], loopback: boolean, plain: boolean): (address: string) => boolean {\n return (address) => {\n if (isLoopbackAddress(address)) return loopback;\n if (plain) return false;\n return isPublicAddress(address) || ranges.some((range) => inAddressRange(address, range));\n };\n}\n\n/** Checks a remote transport's config. Throws a `HarnessError`, code `invalid_mcp_config`. */\nexport function checkRemoteTransport(transport: McpHttpTransport | McpSseTransport): RemoteSettings {\n if (transport.unsafeAllowLoopback !== undefined && typeof transport.unsafeAllowLoopback !== \"boolean\") {\n invalid(\"needs unsafeAllowLoopback to be true or false\");\n }\n const loopback = transport.unsafeAllowLoopback === true;\n const url = checkUrl(transport.url, loopback);\n const headers = checkHeaders(transport.headers);\n const ranges = checkRanges(transport.allowAddresses);\n if (transport.proxy !== undefined && typeof transport.proxy?.fetch !== \"function\") {\n invalid(\"needs a proxy with a fetch(), such as the one startEgressProxy() returns\");\n }\n if (transport.proxy !== undefined && url.protocol !== \"https:\") invalid(\"needs an https: url to go through a proxy\");\n if (transport.resolve !== undefined && typeof transport.resolve !== \"function\")\n invalid(\"needs resolve to be a function\");\n const ca = transport.ca;\n if (\n ca !== undefined &&\n typeof ca !== \"string\" &&\n !(Array.isArray(ca) && ca.every((one) => typeof one === \"string\"))\n ) {\n invalid(\"needs ca to be a certificate or a list of them, as PEM text\");\n }\n const secrets = [url.href, url.search, ...Object.values(headers)].filter((text) => text.length >= 4);\n return {\n kind: transport.kind,\n url,\n headers,\n allows: policyOf(ranges, loopback, url.protocol === \"http:\"),\n maxMessageBytes: bound(\"maxMessageBytes\", transport.maxMessageBytes, DEFAULTS.maxMessageBytes),\n maxStreamBytes: bound(\"maxStreamBytes\", transport.maxStreamBytes, DEFAULTS.maxStreamBytes),\n headersTimeoutMs: bound(\"headersTimeoutMs\", transport.headersTimeoutMs, DEFAULTS.headersTimeoutMs),\n streamIdleMs: bound(\"streamIdleMs\", transport.streamIdleMs, DEFAULTS.streamIdleMs),\n maxStreamMs: bound(\"maxStreamMs\", transport.maxStreamMs, DEFAULTS.maxStreamMs),\n maxStreams: bound(\"maxStreams\", transport.maxStreams, DEFAULTS.maxStreams),\n secrets: [...new Set(secrets)].sort((a, b) => b.length - a.length),\n };\n}\n\n/** `text` with every secret of a remote server replaced, for a log line or an error message. */\nexport function redact(text: string, secrets: readonly string[]): string {\n let out = text;\n for (const secret of secrets) out = out.split(secret).join(\"[redacted]\");\n return out;\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { type FetchLike, RemoteRefusal } from "./guarded-fetch.js";
2
+ import { type RemoteSettings } from "./remote-config.js";
3
+ import type { McpChannel, McpHttpTransport, McpSseTransport, McpTimers } from "./types.js";
4
+ /**
5
+ * The platform's fetch, for a runtime without Node's network modules. It can't resolve a name, so it checks a literal
6
+ * address, counts `localhost` and a name under `.localhost` as loopback, and leaves where any other name goes to the
7
+ * platform. Plain `http:` reaches a loopback literal or a localhost name only.
8
+ */
9
+ export declare function platformFetch(settings: RemoteSettings): FetchLike;
10
+ /** A remote channel and what the connection needs to know about it. */
11
+ export interface RemoteChannel {
12
+ readonly channel: McpChannel;
13
+ readonly settings: RemoteSettings;
14
+ /** The bound a response broke that closed the connection, if one did. */
15
+ readonly refusal: () => RemoteRefusal | undefined;
16
+ /** Whether the listen stream that just ended was the harness's own cut; true spends that cut. */
17
+ readonly plannedListenCut: () => boolean;
18
+ }
19
+ /** Builds the channel for a remote server. Nothing is sent until the client starts it. */
20
+ export declare function remoteChannel(transport: McpHttpTransport | McpSseTransport, log: (line: string) => void, timers: McpTimers): RemoteChannel;