zidane 5.8.0 → 5.8.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 (56) hide show
  1. package/dist/{agent-DYghZGC8.d.ts → agent-acjWZ_4E.d.ts} +12 -2
  2. package/dist/{agent-DYghZGC8.d.ts.map → agent-acjWZ_4E.d.ts.map} +1 -1
  3. package/dist/chat/pure.d.ts +3 -3
  4. package/dist/chat.d.ts +6 -6
  5. package/dist/chat.js +2 -2
  6. package/dist/{headless-DnjYDckH.js → headless-CJFFU6DI.js} +3 -3
  7. package/dist/{headless-DnjYDckH.js.map → headless-CJFFU6DI.js.map} +1 -1
  8. package/dist/headless.d.ts +1 -1
  9. package/dist/headless.js +1 -1
  10. package/dist/{index-CVzpMtdq.d.ts → index-Cgr_mbMJ.d.ts} +2 -2
  11. package/dist/{index-CVzpMtdq.d.ts.map → index-Cgr_mbMJ.d.ts.map} +1 -1
  12. package/dist/{index-B2cMuK6S.d.ts → index-zy4OtFSv.d.ts} +2 -2
  13. package/dist/{index-B2cMuK6S.d.ts.map → index-zy4OtFSv.d.ts.map} +1 -1
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +5 -296
  16. package/dist/index.js.map +1 -1
  17. package/dist/{login-D-3A5CK7.js → login-BjY_sBdn.js} +301 -4
  18. package/dist/login-BjY_sBdn.js.map +1 -0
  19. package/dist/{mcp-Kqzz-Rs_.js → mcp-Br3b1Xm3.js} +50 -8
  20. package/dist/mcp-Br3b1Xm3.js.map +1 -0
  21. package/dist/mcp.d.ts +2 -2
  22. package/dist/mcp.js +2 -2
  23. package/dist/{presets-B1gWui0v.js → presets-BmsTNxjR.js} +2 -2
  24. package/dist/{presets-B1gWui0v.js.map → presets-BmsTNxjR.js.map} +1 -1
  25. package/dist/presets.d.ts +2 -2
  26. package/dist/presets.js +1 -1
  27. package/dist/providers.d.ts +1 -1
  28. package/dist/restate.d.ts +1 -1
  29. package/dist/session/sqlite.d.ts +1 -1
  30. package/dist/session.d.ts +1 -1
  31. package/dist/skills.d.ts +2 -2
  32. package/dist/{tool-formatters-0FEGRd6w.d.ts → tool-formatters-B5UNV_sy.d.ts} +2 -2
  33. package/dist/{tool-formatters-0FEGRd6w.d.ts.map → tool-formatters-B5UNV_sy.d.ts.map} +1 -1
  34. package/dist/tools/fetch-url.d.ts +1 -1
  35. package/dist/tools/web-search.d.ts +1 -1
  36. package/dist/{tools-BmPeBGU1.js → tools-BzQtic6M.js} +16 -3
  37. package/dist/tools-BzQtic6M.js.map +1 -0
  38. package/dist/tools.d.ts +2 -2
  39. package/dist/tools.js +1 -1
  40. package/dist/{transcript-anchors-Bp5bV0Bv.js → transcript-anchors-C571npbs.js} +18 -5
  41. package/dist/transcript-anchors-C571npbs.js.map +1 -0
  42. package/dist/{transcript-anchors-D2erm5iS.d.ts → transcript-anchors-Dtz6U4GW.d.ts} +5 -5
  43. package/dist/{transcript-anchors-D2erm5iS.d.ts.map → transcript-anchors-Dtz6U4GW.d.ts.map} +1 -1
  44. package/dist/tui.d.ts +14 -4
  45. package/dist/tui.d.ts.map +1 -1
  46. package/dist/tui.js +282 -76
  47. package/dist/tui.js.map +1 -1
  48. package/dist/{turn-operations-CeUrtsaM.d.ts → turn-operations-CqJAEzoe.d.ts} +3 -3
  49. package/dist/{turn-operations-CeUrtsaM.d.ts.map → turn-operations-CqJAEzoe.d.ts.map} +1 -1
  50. package/dist/types.d.ts +2 -2
  51. package/docs/ARCHITECTURE.md +2 -1
  52. package/package.json +1 -1
  53. package/dist/login-D-3A5CK7.js.map +0 -1
  54. package/dist/mcp-Kqzz-Rs_.js.map +0 -1
  55. package/dist/tools-BmPeBGU1.js.map +0 -1
  56. package/dist/transcript-anchors-Bp5bV0Bv.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-Kqzz-Rs_.js","names":[],"sources":["../src/mcp/oauth-provider.ts","../src/mcp/sse-to-json-fetch.ts","../src/mcp/tolerant-client.ts","../src/mcp/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 client provider for MCP servers.\n *\n * Implements the MCP SDK's `OAuthClientProvider` interface — the SDK handles\n * the protocol (PKCE, RFC 9728 protected-resource discovery, RFC 8414 / OIDC\n * authorization-server metadata, RFC 7591 dynamic client registration, token\n * refresh). This class provides the two halves the SDK delegates to consumers:\n *\n * - **Persistence** — tokens, registered client info, optional discovery\n * state cache, and PKCE code verifier. Storage is injected via the\n * `McpCredentialStore` interface so the SDK adapter has no FS dependency;\n * the chat layer wires a file-backed store, tests use the in-memory one.\n *\n * - **Redirect** — when the SDK wants the user agent to navigate to the\n * authorization URL, we hand the URL to the host (the TUI opens a\n * browser + surfaces the URL in a status row). The PKCE code verifier\n * stays in process memory for the lifetime of the flow; persisting it\n * across process restarts would expose it on disk for no real benefit\n * since the loopback callback server is also process-local.\n *\n * Two modes by `redirectUri`:\n *\n * - **Non-interactive** (`redirectUri: undefined`) — used during bootstrap.\n * The SDK will use stored tokens, auto-refresh on expiry, but cannot\n * trigger a browser flow. Missing tokens cause the SDK to throw\n * `UnauthorizedError`, which the caller catches and converts to a\n * `mcp:auth:required` signal.\n *\n * - **Interactive** (`redirectUri: 'http://127.0.0.1:<port>/callback'`) —\n * used when the user explicitly triggers login. The caller has already\n * stood up a loopback callback server (see `oauth-callback.ts`) and\n * orchestrates: `client.connect()` → catches `UnauthorizedError` →\n * waits on the callback for the `code` → `transport.finishAuth(code)`\n * → retry `client.connect()`.\n */\n\nimport type {\n OAuthClientProvider,\n OAuthDiscoveryState,\n} from '@modelcontextprotocol/sdk/client/auth.js'\nimport type {\n OAuthClientInformationMixed,\n OAuthClientMetadata,\n OAuthTokens,\n} from '@modelcontextprotocol/sdk/shared/auth.js'\n\n/**\n * Per-server persisted state. Subfields are optional so a partial save\n * (e.g. `saveCodeVerifier` arriving before `saveTokens`) doesn't blow away\n * earlier subfields — the provider always patches, never replaces.\n */\nexport interface McpCredentialEntry {\n tokens?: OAuthTokens\n clientInformation?: OAuthClientInformationMixed\n discoveryState?: OAuthDiscoveryState\n}\n\nexport interface McpCredentialStore {\n load: (name: string) => McpCredentialEntry | undefined\n save: (name: string, entry: McpCredentialEntry) => void\n delete: (name: string) => void\n}\n\n/**\n * In-memory store — primarily for tests, but valid as a no-persistence option\n * (tokens evaporate on process exit, the user re-auths every cold start).\n */\nexport function createMemoryMcpCredentialStore(seed?: Record<string, McpCredentialEntry>): McpCredentialStore {\n const state = new Map<string, McpCredentialEntry>(Object.entries(seed ?? {}))\n return {\n load: name => state.get(name),\n save: (name, entry) => { state.set(name, entry) },\n delete: (name) => { state.delete(name) },\n }\n}\n\nexport interface McpOAuthProviderOptions {\n /** Server name — used as the storage key. */\n name: string\n /** Persistence backend. */\n store: McpCredentialStore\n /**\n * Loopback callback URI. Pass `undefined` for bootstrap (non-interactive\n * mode — stored tokens + refresh only, never opens a browser).\n */\n redirectUri?: string\n /**\n * Invoked when the SDK wants the user agent to navigate to the authorization\n * URL. Typically the host opens the browser AND emits a hook so the TUI can\n * render the URL in a status row. No-op in non-interactive mode (the SDK\n * still calls this before throwing `UnauthorizedError` from connect).\n */\n onAuthorizationUrl?: (url: URL) => void | Promise<void>\n /**\n * `client_name` used in dynamic client registration. Defaults to `'zidane'`.\n * Some servers display this string to the user on the consent screen.\n */\n clientName?: string\n /**\n * Override the requested OAuth scope. Default: unset (the SDK negotiates\n * via the server's metadata).\n */\n scope?: string\n}\n\nconst DEFAULT_CLIENT_NAME = 'zidane'\n\nexport class McpOAuthProvider implements OAuthClientProvider {\n private readonly name: string\n private readonly store: McpCredentialStore\n private readonly _redirectUri?: string\n private readonly onAuthorizationUrl?: (url: URL) => void | Promise<void>\n private readonly clientName: string\n private readonly _scope?: string\n // PKCE verifier is process-local — see file header. Module-scoped Map would\n // leak across concurrent flows for different servers; per-instance is the\n // right granularity.\n private codeVerifierValue: string | undefined\n\n constructor(opts: McpOAuthProviderOptions) {\n this.name = opts.name\n this.store = opts.store\n this._redirectUri = opts.redirectUri\n this.onAuthorizationUrl = opts.onAuthorizationUrl\n this.clientName = opts.clientName ?? DEFAULT_CLIENT_NAME\n this._scope = opts.scope\n }\n\n get redirectUrl(): string | URL | undefined {\n return this._redirectUri\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n // The SDK validates `redirect_uris` non-empty; we use a placeholder\n // when running non-interactively (no callback server is up). The\n // server won't actually redirect anywhere because the SDK throws\n // `UnauthorizedError` before any browser navigation in that mode.\n redirect_uris: [this._redirectUri ?? 'http://127.0.0.1:0/callback'],\n client_name: this.clientName,\n // PKCE-only public client — no client_secret. RFC 8252 native-app pattern.\n token_endpoint_auth_method: 'none',\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n ...(this._scope ? { scope: this._scope } : {}),\n }\n }\n\n tokens(): OAuthTokens | undefined {\n return this.store.load(this.name)?.tokens\n }\n\n saveTokens(tokens: OAuthTokens): void {\n this.patch({ tokens })\n }\n\n clientInformation(): OAuthClientInformationMixed | undefined {\n return this.store.load(this.name)?.clientInformation\n }\n\n saveClientInformation(info: OAuthClientInformationMixed): void {\n this.patch({ clientInformation: info })\n }\n\n discoveryState(): OAuthDiscoveryState | undefined {\n return this.store.load(this.name)?.discoveryState\n }\n\n saveDiscoveryState(state: OAuthDiscoveryState): void {\n this.patch({ discoveryState: state })\n }\n\n saveCodeVerifier(verifier: string): void {\n this.codeVerifierValue = verifier\n }\n\n codeVerifier(): string {\n if (!this.codeVerifierValue) {\n // Spec-correct error — the SDK would otherwise complete the code\n // exchange with an empty verifier and the auth server would 400.\n throw new Error(\n `MCP OAuth: code verifier missing for \"${this.name}\" — `\n + 'the flow must call saveCodeVerifier() before the redirect',\n )\n }\n return this.codeVerifierValue\n }\n\n async redirectToAuthorization(url: URL): Promise<void> {\n await this.onAuthorizationUrl?.(url)\n }\n\n /**\n * Wipe stored credentials when the server reports the cached state is no\n * longer valid. The SDK calls this with a scope hint:\n * - `'tokens'` → access/refresh revoked, keep client registration\n * - `'client'` → client registration invalidated, reset everything\n * - `'verifier'`→ PKCE state stale (e.g. mismatched state param)\n * - `'discovery'` → discovery metadata stale (servers re-keyed)\n * - `'all'` → full reset\n */\n async invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void> {\n if (scope === 'verifier') {\n this.codeVerifierValue = undefined\n return\n }\n const current = this.store.load(this.name)\n if (!current)\n return\n if (scope === 'all') {\n this.codeVerifierValue = undefined\n this.store.delete(this.name)\n return\n }\n const next: McpCredentialEntry = { ...current }\n if (scope === 'tokens')\n delete next.tokens\n if (scope === 'client') {\n delete next.clientInformation\n // Client identity changed; previously-issued tokens and discovery\n // are no longer valid against the new registration.\n delete next.tokens\n delete next.discoveryState\n }\n if (scope === 'discovery')\n delete next.discoveryState\n this.store.save(this.name, next)\n }\n\n private patch(updates: Partial<McpCredentialEntry>): void {\n const existing = this.store.load(this.name) ?? {}\n this.store.save(this.name, { ...existing, ...updates })\n }\n}\n\n/**\n * True when an HTTP transport's auth headers already include an explicit\n * Authorization. Used by the bootstrap escape-hatch: a user who provided\n * their own bearer token shouldn't be auto-promoted to OAuth on a 401.\n *\n * Case-insensitive — Node normalizes outgoing headers to lowercase but\n * users hand-write `Authorization` in configs.\n */\nexport function hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {\n if (!headers)\n return false\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization')\n return true\n }\n return false\n}\n","/**\n * `fetch` shim that converts streamable-http POST responses with\n * `Content-Type: text/event-stream` into synthetic `application/json`\n * responses, preserving every original header (notably `mcp-session-id`).\n *\n * Why this exists\n * ----------------\n * The MCP SDK's streamable-http transport handles POST responses two ways\n * depending on `content-type`:\n *\n * - `application/json` → `await response.json()` (works on every runtime).\n * - `text/event-stream` → `body.pipeThrough(TextDecoderStream)\n * .pipeThrough(EventSourceParserStream)`\n * and forward each parsed event to `onmessage`.\n *\n * On Bun + MCP SDK 1.29.x the second pipeline silently drops the parsed\n * event: the full `event: message\\ndata: {...}\\n\\n` arrives intact, the\n * stream closes, but `onmessage` is never called. Bootstrap then waits the\n * full `bootstrapTimeout` (10s default) and the agent loses every tool the\n * server would have exposed.\n *\n * The MCP spec lets clients accept either content type\n * (`Accept: application/json, text/event-stream`), so flipping the stream\n * to JSON at the boundary is a transparent, server-agnostic workaround.\n *\n * Scope of the shim\n * -----------------\n * - POST + `text/event-stream` → drain, parse SSE message events, return\n * a synthetic `application/json` response. Single event becomes a JSON\n * object (matching the shape the SDK expects from non-streaming\n * servers); multiple events become a JSON array (the SDK already\n * iterates `Array.isArray(data)` from a JSON response).\n * - GET (long-lived `_startOrAuthSse` listener) → untouched. Per-event\n * latency matters there and the SSE pipeline isn't always broken on\n * GET in the same way (different code path inside Bun's stream impl).\n * - 202 / non-SSE / malformed SSE / no body → passthrough.\n *\n * Runtime gating\n * --------------\n * `sseToJsonFetchIfNeeded()` only returns a wrapper on Bun. Node + browser\n * runtimes get `undefined` and the SDK uses global `fetch` directly — no\n * extra buffer-and-redrain on the happy path, and no risk of collapsing a\n * future progress-streaming response into a single batched array. If you\n * need to apply the shim unconditionally (testing, custom hosts), call\n * `sseToJsonFetch()` directly.\n *\n * Cleanup\n * -------\n * Remove this file and its `fetch:` injection in `createTransport` once\n * either Bun fixes the `pipeThrough` chain or the SDK switches off the\n * streaming pipeline by default.\n */\n\n/**\n * Detect whether we're running on Bun. The `Bun` global is set by the\n * runtime itself and isn't faked by Bun's Node-compat layer.\n */\nfunction isBunRuntime(): boolean {\n return typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n}\n\n/**\n * Returns the `sseToJsonFetch` wrapper only on runtimes that need it\n * (currently Bun). Returns `undefined` everywhere else, which makes the\n * SDK fall back to the global `fetch` and keeps the streaming pipeline\n * intact on Node where it works correctly.\n *\n * Designed as the value to pass directly to `StreamableHTTPClientTransport`'s\n * `fetch` option:\n *\n * new StreamableHTTPClientTransport(url, {\n * fetch: sseToJsonFetchIfNeeded(),\n * })\n */\nexport function sseToJsonFetchIfNeeded(): typeof fetch | undefined {\n return isBunRuntime() ? sseToJsonFetch() : undefined\n}\n\n/**\n * Wrap a `fetch` implementation so streamable-http POST responses that come\n * back as `text/event-stream` are converted to JSON. Pass the result as\n * `opts.fetch` to `StreamableHTTPClientTransport`.\n *\n * Always-on (i.e. unconditional) — for the runtime-gated entry point,\n * use {@link sseToJsonFetchIfNeeded} instead.\n */\nexport function sseToJsonFetch(baseFetch: typeof fetch = fetch): typeof fetch {\n return async function sseToJsonWrappedFetch(input, init) {\n const response = await baseFetch(input, init)\n\n // Only intercept POSTs. The SDK's GET path opens a long-lived SSE\n // listener (`_startOrAuthSse`) that we must not buffer-drain.\n const method = (init?.method ?? 'GET').toString().toUpperCase()\n if (method !== 'POST')\n return response\n\n const contentType = response.headers.get('content-type')\n if (!contentType || !contentType.includes('text/event-stream'))\n return response\n\n if (!response.body)\n return response\n\n let raw: string\n try {\n raw = await response.text()\n }\n catch {\n // Bun edge case: if even .text() fails, surrender — the original\n // response is already drained, so we can't recover. Return it; the\n // SDK will surface the underlying read error.\n return response\n }\n\n const events = parseSseDataEvents(raw)\n // Single event → bare object; multi-event or zero → array. The SDK's\n // JSON branch handles both shapes (`Array.isArray(data) ? data.map(…) : …`).\n const payload = events.length === 1 ? events[0] : events\n return synthesizeJsonResponse(response, payload)\n } as typeof fetch\n}\n\n/**\n * Parse a buffered SSE body into the JSON payloads of its `message` events.\n *\n * Skips:\n * - SSE comments (lines starting with `:`).\n * - Non-default event types (`event: foo` ≠ `message`). The MCP server\n * only ever emits `message` events for JSON-RPC; anything else is out of\n * band and the SDK wouldn't have surfaced it to `onmessage` either.\n * - Malformed `data:` payloads (anything that fails `JSON.parse`).\n */\nfunction parseSseDataEvents(raw: string): unknown[] {\n const events: unknown[] = []\n for (const block of raw.split(/\\r?\\n\\r?\\n/)) {\n if (!block.trim())\n continue\n\n const dataLines: string[] = []\n let isMessageEvent = true\n for (const line of block.split(/\\r?\\n/)) {\n if (line.startsWith(':'))\n continue\n if (line.startsWith('event:')) {\n const eventType = line.slice('event:'.length).trim()\n if (eventType && eventType !== 'message')\n isMessageEvent = false\n }\n else if (line.startsWith('data:')) {\n // Per SSE spec: a single leading space after `data:` is part of the\n // separator, not the payload. Anything beyond it is.\n const value = line.slice('data:'.length)\n dataLines.push(value.startsWith(' ') ? value.slice(1) : value)\n }\n }\n\n if (!isMessageEvent || dataLines.length === 0)\n continue\n\n try {\n events.push(JSON.parse(dataLines.join('\\n')))\n }\n catch {\n // Drop malformed events. The SDK's broken pipe would have dropped\n // them too — staying silent here matches that baseline.\n }\n }\n return events\n}\n\n/**\n * Build a `Response` mirroring the original's status / statusText / headers\n * but with a JSON body and `content-type: application/json`. Header\n * preservation is the whole point — `mcp-session-id` is set by the server\n * on the initialize POST and must round-trip into the SDK's\n * `_sessionId` capture (`response.headers.get('mcp-session-id')`).\n */\nfunction synthesizeJsonResponse(original: Response, payload: unknown): Response {\n const headers = new Headers(original.headers)\n headers.set('content-type', 'application/json')\n return new Response(JSON.stringify(payload), {\n status: original.status,\n statusText: original.statusText,\n headers,\n })\n}\n","/**\n * Drop-in `Client` subclass whose `connect()` mirrors the upstream MCP SDK\n * sequence but treats `notifications/initialized` as best-effort.\n *\n * The MCP spec marks that notification fire-and-forget, but the SDK awaits\n * the underlying transport `send()` and rethrows on any HTTP 4xx. Several\n * real-world streamable-http servers (e.g. browser-codemode, custom MCPs\n * that gate non-initialize routes on a session id that didn't yet exist when\n * the notification posted) reject the notification with a 4xx and still\n * accept every subsequent request. The base `Client.connect()` then closes\n * the transport, the bootstrap fails, and the agent silently loses every\n * tool the server would have exposed.\n *\n * This module changes only that single step — log + continue if the\n * notification throws. Initialize, capability/version capture,\n * `setProtocolVersion`, listChanged handler wiring, and the close-on-failure\n * path for everything else are preserved verbatim from the SDK.\n *\n * Lazy SDK load: `@modelcontextprotocol/sdk` is an *optional* peer dep, so\n * the class is built inside `createTolerantClient()` via dynamic imports.\n * Importing this module does NOT trigger SDK resolution — callers only\n * incur the cost when they actually instantiate a client.\n *\n * Should be removed when the SDK lands an opt-in tolerance flag upstream.\n */\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { errorMessage } from '../errors'\n\n// Private fields the override needs to read/write to mirror upstream behavior.\n// Cast surface is isolated to this one type so the rest of the file stays clean.\ninterface ClientPrivates {\n _capabilities: unknown\n _clientInfo: unknown\n _serverCapabilities: unknown\n _serverVersion: unknown\n _instructions: unknown\n _pendingListChangedConfig?: unknown\n _setupListChangedHandlers: (config: unknown) => void\n}\n\ninterface MaybeSessionedTransport {\n sessionId?: unknown\n setProtocolVersion?: (v: string) => void\n}\n\n/**\n * Options forwarded to the upstream `Client` constructor. Mirrors the\n * publicly-observable shape so we don't have to re-export `Client`'s\n * private `ClientOptions` type (which would force consumers of the lazy\n * factory below to install the SDK at type-check time too).\n */\nexport interface TolerantClientOptions {\n /** Capabilities advertised to the server on `initialize`. */\n capabilities?: Record<string, unknown>\n /** When true, the SDK rejects requests for methods the server didn't advertise. */\n enforceStrictCapabilities?: boolean\n /** Per-request timeout in ms; the SDK falls back to its own default when unset. */\n defaultRequestTimeout?: number\n /**\n * Best-effort notification sink. Fires once if the server rejected\n * `notifications/initialized` with a 4xx — the connection survived but\n * the client wants to know it deviated from the spec. Default: no-op.\n *\n * Routing this through a callback (instead of a hard-coded\n * `console.warn`) is what lets `connectMcpServers` collect the warning,\n * include it on the `mcp:bootstrap:end` payload, and keep hosts that\n * don't care from seeing stray stderr.\n */\n onWarning?: (message: string) => void\n}\n\n/**\n * Async factory — builds an instance of the tolerant MCP client. The\n * actual `Client` subclass definition lives inside the factory so the\n * `@modelcontextprotocol/sdk` import only resolves when MCP is in use.\n *\n * Second `options` arg forwards directly into the upstream `Client`\n * constructor so tests / advanced consumers can supply capabilities,\n * `enforceStrictCapabilities`, etc.\n */\nexport async function createTolerantClient(\n info: { name: string, version: string },\n options?: TolerantClientOptions,\n): Promise<Client> {\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { Protocol } = await import('@modelcontextprotocol/sdk/shared/protocol.js')\n const { InitializeResultSchema, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } = await import('@modelcontextprotocol/sdk/types.js')\n\n // Capture once; the override below mustn't re-read `options.onWarning` per\n // connect because hosts may not consider `options` long-lived.\n const onWarning = options?.onWarning\n\n class TolerantMcpClient extends Client {\n async connect(\n transport: Parameters<Client['connect']>[0],\n options?: Parameters<Client['connect']>[1],\n ): Promise<void> {\n // Wire the transport (Protocol.connect — onmessage/onclose/onerror hooks\n // and transport.start) without sending any messages. We MUST NOT call\n // `super.connect()` here — that's `Client.connect`, which would\n // re-execute the very initialize+notification dance we're overriding.\n await Protocol.prototype.connect.call(this as never, transport)\n\n // Reconnect path: the upstream client short-circuits on a transport that\n // already carries a session id, so do we.\n if ((transport as MaybeSessionedTransport).sessionId !== undefined)\n return\n\n const self = this as unknown as ClientPrivates\n\n try {\n const result = await this.request(\n {\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: self._capabilities,\n clientInfo: self._clientInfo,\n },\n },\n InitializeResultSchema,\n options,\n )\n\n if (result === undefined)\n throw new Error(`Server sent invalid initialize result: ${result}`)\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`)\n\n self._serverCapabilities = result.capabilities\n self._serverVersion = result.serverInfo\n\n const setProtocolVersion = (transport as MaybeSessionedTransport).setProtocolVersion\n if (setProtocolVersion)\n setProtocolVersion.call(transport, result.protocolVersion)\n\n self._instructions = result.instructions\n\n // Best-effort. The session id (if any) is already captured by the\n // transport from the `initialize` response headers, so subsequent\n // requests like `tools/list` still authenticate. Don't bring down the\n // whole connection on a 4xx for a fire-and-forget notification.\n try {\n await this.notification({ method: 'notifications/initialized' })\n }\n catch (notifyError) {\n // Hosts opt in to the signal via `onWarning`; default is silent\n // so a plain `new Client()` doesn't leak stderr into every host.\n onWarning?.(`server rejected notifications/initialized (continuing): ${errorMessage(notifyError)}`)\n }\n\n if (self._pendingListChangedConfig) {\n self._setupListChangedHandlers(self._pendingListChangedConfig)\n self._pendingListChangedConfig = undefined\n }\n }\n catch (error) {\n // Same failure path as upstream Client — anything *other* than the\n // tolerated notification failure tears the transport down so the\n // bootstrap surfaces a clear error.\n void this.close()\n throw error\n }\n }\n }\n\n return new TolerantMcpClient(info, options)\n}\n","/**\n * MCP (Model Context Protocol) server support.\n *\n * Connects to one or more MCP servers, discovers their tools,\n * and wraps them as zidane ToolDefs for use in agent loops.\n */\n\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { ToolContext, ToolDef } from '../tools/types'\nimport type { McpServerConfig, McpToolHookContext, McpToolSchema, ToolResultContent } from '../types'\nimport { Buffer } from 'node:buffer'\nimport { errorMessage } from '../errors'\nimport { reconcileImageMediaType } from '../tools/image-sniff'\nimport { toolOutputByteLength } from '../types'\nimport { hasAuthorizationHeader } from './oauth-provider'\nimport { sseToJsonFetchIfNeeded } from './sse-to-json-fetch'\nimport { createTolerantClient } from './tolerant-client'\n\n/**\n * Subset of the MCP SDK's `Transport` interface that `bootstrapServer` needs\n * to clean up. Typed structurally so a failed `createTransport()` doesn't\n * force us to pull the SDK's full transport type into our static graph.\n */\ninterface ClosableTransport {\n close: () => void | Promise<void>\n}\n\n// NOTE: `@modelcontextprotocol/sdk` is an *optional* peer dependency\n// (see package.json). Static imports here would force every consumer of\n// `zidane` to install the SDK even if they never wire any MCP servers —\n// which fails on install with `--no-optional` or in restricted CI\n// environments. All runtime imports are inside `createTransport` /\n// `loadTolerantClient` below so the SDK is only resolved when MCP is\n// actually used. Type-only imports above are erased at compile time.\n\nexport type { McpServerConfig, McpToolSchema } from '../types'\n\nexport interface McpConnection {\n tools: Record<string, ToolDef>\n /**\n * Per-server `instructions` payload from the MCP `initialize` handshake,\n * keyed by server name. Each server may return free-form guidance the\n * model is meant to read alongside the tool catalog — typical content\n * is \"the database is already provisioned, use `apply_migration`\n * directly\" or \"always wrap SELECTs in a transaction\". The agent\n * renders these into a system-prompt section when\n * `behavior.surfaceMcpInstructions` is on (default).\n *\n * Servers that omit the field, return an empty string, or fail to\n * connect contribute no entry. Lazy-connected servers contribute an\n * entry only once their first connect resolves — until then the model\n * never sees their instructions, matching the schema-loading semantics\n * of `lazyConnect`.\n *\n * Map (not Record) so insertion order matches server config order and\n * the rendered section is byte-stable for the cache breakpoint.\n *\n * Optional so custom `mcpConnector` implementations from before this\n * field existed still type-check; the framework's own\n * `connectMcpServers` always returns a Map (possibly empty).\n */\n instructions?: Map<string, string>\n close: () => Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Shape normalization\n// ---------------------------------------------------------------------------\n\ninterface RawServerShape {\n name?: string\n transport?: string\n type?: string\n command?: string\n args?: string[]\n env?: Record<string, string>\n strictEnv?: boolean\n cwd?: string\n url?: string\n httpUrl?: string\n sseUrl?: string\n headers?: Record<string, string>\n bootstrapTimeout?: number\n toolTimeout?: number\n enabledTools?: string[]\n disabledTools?: string[]\n toolFilter?: McpServerConfig['toolFilter']\n /** Canonical OAuth flag. */\n auth?: McpServerConfig['auth']\n /** Cursor runtime-state alias for `auth: 'oauth'`. */\n authMethod?: string\n [key: string]: unknown\n}\n\nconst DEFAULT_MCP_BOOTSTRAP_TIMEOUT_MS = 10_000\n\n// ---------------------------------------------------------------------------\n// Bootstrap-internal helpers (hook safety + cleanup + error hints)\n//\n// These keep `bootstrapServer` and `connectMcpServers` readable while\n// providing three guarantees the bootstrap contract relies on:\n//\n// 1. A misbehaving hook handler MUST NOT take down the whole batch — the\n// partial-failure tolerance (`Promise.allSettled` in the caller plus\n// this safe-fire helper) means one bad listener degrades to a debug\n// log instead of \"no MCP tools at all\".\n// 2. A timed-out / failed bootstrap MUST close its transport explicitly,\n// not just the SDK client. Until `Protocol.connect(transport)` has\n// wired the transport into the client, `client.close()` doesn't know\n// about it and the underlying stdio subprocess / HTTP connection\n// lingers until GC.\n// 3. Transport-mismatch failures (the common `type: 'http'` vs SSE-only\n// server case from downstream reports) MUST surface an actionable\n// hint in the error message, not just `HTTP 405`.\n// ---------------------------------------------------------------------------\n\n/**\n * Fire a hook without letting a listener's rejection escape. A throwing\n * listener used to bring down the whole `Promise.all` in\n * `connectMcpServers`, defeating the batch's partial-failure tolerance.\n *\n * Failures are swallowed; under `ZIDANE_DEBUG` they're traced to stderr\n * so the misbehaving listener is still discoverable when a host opts in.\n *\n * `args` is variadic to match `Hookable.callHook`'s spread shape; in\n * practice every `AgentHooks` event takes a single context object.\n */\nasync function safeCallHook<K extends keyof AgentHooks & string>(\n hooks: Hookable<AgentHooks> | undefined,\n event: K,\n ...args: Parameters<AgentHooks[K]>\n): Promise<void> {\n if (!hooks)\n return\n try {\n await hooks.callHook(event, ...args)\n }\n catch (err) {\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/mcp] hook \"${event}\" listener rejected: ${errorMessage(err)}\\n`)\n }\n}\n\n/**\n * Close a transport best-effort. The catch swallows everything — by the\n * time we're closing, the bootstrap has already failed and the only thing\n * worse than a leaked transport is a leaked transport AND a new error\n * masking the original cause.\n */\nasync function closeTransportQuietly(transport: ClosableTransport | null): Promise<void> {\n if (!transport)\n return\n try {\n await transport.close()\n }\n catch {\n // Original bootstrap error is more actionable.\n }\n}\n\n/**\n * Detect failure signatures that point at a transport mismatch and return\n * an actionable hint string. Conservative — only matches the signals we've\n * actually observed in the wild against MCP servers, so a real outage on\n * the right transport doesn't get misdiagnosed.\n *\n * Streamable-HTTP against an SSE-only endpoint:\n * - The transport opens an `initialize` POST. SSE-only servers respond\n * with `405 Method Not Allowed` or `404 Not Found` (their `/sse` GET\n * endpoint is the only handler). The SDK wraps these as\n * `Error POSTing to endpoint (HTTP 40X): ...`.\n * - Some proxies return `400` with a `text/event-stream` mismatch on\n * POST; same root cause, same fix.\n */\nfunction buildTransportMismatchHint(transport: McpServerConfig['transport'], err: Error): string | null {\n const msg = err.message\n if (transport === 'streamable-http') {\n if (/\\bHTTP\\s*40[45]\\b/i.test(msg) || /\\(40[45]\\)/.test(msg))\n return 'This server may not implement the streamable-HTTP transport. Try `transport: \\'sse\\'` (or `sseUrl` instead of `url`) on this server\\'s config.'\n }\n return null\n}\n\n/**\n * Wrap a bootstrap failure so the surfaced `Error` carries an actionable\n * hint while preserving the original message + stack + cause. Returns the\n * input error verbatim when no hint applies.\n *\n * `cause` (ES2022) gives hosts that introspect a way back to the raw SDK\n * error; the human-readable hint is the new message body that lands in\n * logs / hook payloads.\n */\nfunction withTransportMismatchHint(transport: McpServerConfig['transport'], err: Error): Error {\n const hint = buildTransportMismatchHint(transport, err)\n if (!hint)\n return err\n const augmented = new Error(`${err.message}\\nHint: ${hint}`, { cause: err })\n if (err.stack)\n augmented.stack = err.stack\n return augmented\n}\n\nfunction inferTransport(raw: RawServerShape): McpServerConfig['transport'] {\n if (raw.transport === 'stdio' || raw.transport === 'sse' || raw.transport === 'streamable-http')\n return raw.transport\n if (raw.type === 'stdio' || raw.type === 'sse' || raw.type === 'streamable-http' || raw.type === 'http')\n return raw.type === 'http' ? 'streamable-http' : raw.type\n if (raw.command)\n return 'stdio'\n if (raw.httpUrl)\n return 'streamable-http'\n if (raw.sseUrl)\n return 'sse'\n if (raw.url)\n return 'streamable-http'\n throw new Error(`Cannot infer MCP transport from config: ${JSON.stringify(raw)}`)\n}\n\nfunction normalizeOne(name: string, raw: RawServerShape): McpServerConfig {\n const transport = inferTransport(raw)\n const url = raw.url ?? raw.httpUrl ?? raw.sseUrl\n\n const config: McpServerConfig = { name, transport }\n if (raw.command)\n config.command = raw.command\n if (raw.args)\n config.args = raw.args\n if (raw.env)\n config.env = raw.env\n if (raw.strictEnv === true)\n config.strictEnv = true\n if (typeof raw.cwd === 'string' && raw.cwd.length > 0)\n config.cwd = raw.cwd\n if (url)\n config.url = url\n if (raw.headers)\n config.headers = raw.headers\n if (typeof raw.bootstrapTimeout === 'number')\n config.bootstrapTimeout = raw.bootstrapTimeout\n if (typeof raw.toolTimeout === 'number')\n config.toolTimeout = raw.toolTimeout\n if (Array.isArray(raw.enabledTools))\n config.enabledTools = raw.enabledTools\n if (Array.isArray(raw.disabledTools))\n config.disabledTools = raw.disabledTools\n if (typeof raw.toolFilter === 'function')\n config.toolFilter = raw.toolFilter\n // Canonical `auth` field; also recognize Cursor's `authMethod: 'mcpOAuth'`\n // runtime-state shape so pasted ~/.cursor/mcp.json entries Just Work.\n if (raw.auth === 'oauth' || raw.authMethod === 'mcpOAuth')\n config.auth = 'oauth'\n\n return config\n}\n\n/**\n * True when the input looks like a single config object (flat fields like `command`,\n * `transport`, `url`) rather than a record whose values are configs.\n */\nfunction looksLikeSingleConfig(obj: Record<string, unknown>): boolean {\n const singleConfigKeys = ['transport', 'type', 'command', 'url', 'httpUrl', 'sseUrl']\n return singleConfigKeys.some(key => typeof obj[key] === 'string')\n}\n\n/**\n * Normalize MCP server configs from any common shape to `McpServerConfig[]`.\n *\n * Accepts:\n * - `McpServerConfig[]` — zidane native (pass-through).\n * - `McpServerConfig` — a single config object (wrapped to a 1-element array).\n * - `Record<string, RawShape>` — name-keyed map (common in host-SDK configs), where the key is the server name.\n * - Mixed shapes with `type` vs `transport`, `httpUrl`/`sseUrl` vs `url`.\n *\n * Returns `[]` when `input` is nullish. Throws a descriptive error when the transport\n * cannot be inferred from a given entry, or when the input shape is unsupported.\n */\nexport function normalizeMcpServers(input: unknown): McpServerConfig[] {\n if (input == null)\n return []\n\n if (Array.isArray(input)) {\n return input.map((raw, idx) => {\n const obj = raw as RawServerShape\n const name = obj.name ?? `mcp_${idx}`\n return normalizeOne(name, obj)\n })\n }\n\n if (typeof input === 'object') {\n const obj = input as Record<string, unknown>\n // Single-config heuristic: flat fields like `transport`/`command`/`url` at the top\n // level indicate a single McpServerConfig, not a record of configs.\n if (looksLikeSingleConfig(obj)) {\n const raw = obj as RawServerShape\n const name = raw.name ?? 'mcp_0'\n return [normalizeOne(name, raw)]\n }\n return Object.entries(obj as Record<string, RawServerShape>).map(\n ([name, raw]) => normalizeOne(name, raw ?? {}),\n )\n }\n\n throw new Error(`Unsupported MCP server config shape: ${typeof input}`)\n}\n\n/**\n * Lossy flattener — converts MCP `CallToolResult.content` blocks to a single\n * string. Text blocks are extracted; non-text blocks are JSON-stringified.\n *\n * Use this only at UI / log boundaries that require a string. The agent\n * loop itself routes through {@link normalizeMcpBlocks} so image blocks\n * survive into provider-native tool_result content (Anthropic blocks,\n * OpenAI companion-user-message).\n */\nexport function resultToString(content: unknown): string {\n if (!content || !Array.isArray(content))\n return ''\n return content\n .map((block) => {\n if (block && typeof block === 'object' && (block as { type?: unknown }).type === 'text') {\n const text = (block as { text?: unknown }).text\n if (typeof text === 'string')\n return text\n }\n return JSON.stringify(block)\n })\n .join('\\n')\n}\n\n/**\n * Normalize MCP `CallToolResult.content` to zidane's {@link ToolResultContent[]} shape.\n *\n * Handles the four MCP content block types:\n * - `text` → preserved as `{type:'text', text}`\n * - `image` → preserved as `{type:'image', mediaType, data}` (MCP uses `mimeType`)\n * - `resource` with embedded text → flattened to a text block\n * - `resource` with embedded blob whose `mimeType` is `image/*` → flattened to an image block\n * - Any unrecognized block → JSON-stringified fallback text block (lossy but safe)\n *\n * Returns `null` when the input is not an array — callers should fall back to an empty\n * result in that case.\n */\nexport function normalizeMcpBlocks(content: unknown): ToolResultContent[] | null {\n if (!Array.isArray(content))\n return null\n\n const out: ToolResultContent[] = []\n for (const raw of content) {\n if (!raw || typeof raw !== 'object')\n continue\n const block = raw as Record<string, unknown>\n\n if (block.type === 'text' && typeof block.text === 'string') {\n out.push({ type: 'text', text: block.text })\n continue\n }\n\n if (block.type === 'image' && typeof block.data === 'string') {\n const declared = typeof block.mimeType === 'string'\n ? block.mimeType\n : (typeof block.mediaType === 'string' ? block.mediaType : 'image/png')\n // Anthropic rejects the request when `media_type` disagrees with the\n // magic bytes. Some MCP servers (browser/screenshot bridges) declare\n // `image/webp` while actually serving JPEG; reconcile here so the\n // wrong label never reaches the provider.\n const mediaType = reconcileImageMediaType(declared, block.data)\n out.push({ type: 'image', mediaType, data: block.data })\n continue\n }\n\n if (block.type === 'resource' && block.resource && typeof block.resource === 'object') {\n const res = block.resource as Record<string, unknown>\n if (typeof res.text === 'string') {\n out.push({ type: 'text', text: res.text })\n continue\n }\n if (typeof res.blob === 'string' && typeof res.mimeType === 'string' && res.mimeType.startsWith('image/')) {\n const mediaType = reconcileImageMediaType(res.mimeType, res.blob)\n out.push({ type: 'image', mediaType, data: res.blob })\n continue\n }\n }\n\n // Audio, resource_link, and unknown block shapes — fall back to a JSON-stringified\n // text block. Lossy but keeps the information addressable by the model.\n out.push({ type: 'text', text: JSON.stringify(block) })\n }\n\n return out\n}\n\n/**\n * Route the MCP result content through the narrowest appropriate zidane shape:\n *\n * - All blocks are `text` → return a joined string (smaller wire payload,\n * string-friendly for hook consumers that don't need structured access).\n * - Any block is non-text → return a structured `ToolResultContent[]`.\n * - Empty / non-array input → return `''`.\n */\nfunction packMcpResult(content: unknown): string | ToolResultContent[] {\n const normalized = normalizeMcpBlocks(content)\n if (!normalized || normalized.length === 0)\n return ''\n\n // Single pass: build the joined string as we go. Bail to the structured array\n // the moment we hit a non-text block.\n const parts: string[] = []\n for (const block of normalized) {\n if (block.type !== 'text')\n return normalized\n parts.push(block.text)\n }\n return parts.join('\\n')\n}\n\n/**\n * Create the appropriate MCP transport for a server config.\n *\n * For stdio: when `config.env` is provided, it is merged on top of the MCP SDK's\n * `getDefaultEnvironment()` whitelist (`PATH`, `HOME`, `LANG`, `SHELL`, `USER` on\n * POSIX; `APPDATA`, `PATH`, ... on Win32). Without this defensive merge, older\n * MCP SDK versions strip `PATH` the moment a consumer sets any env, breaking\n * `spawn('node', ...)` with ENOENT. Pass `strictEnv: true` to opt out and send\n * `env` verbatim.\n *\n * `config.cwd` is forwarded to `StdioClientTransport` (→ `spawn`'s `cwd`).\n * Without this, the child inherits the agent's cwd, breaking servers that\n * resolve paths relative to their own working directory (e.g. project-root\n * MCPs reading `<root>/supabase/functions/...`).\n */\nasync function createTransport(config: McpServerConfig, authProvider?: OAuthClientProvider) {\n switch (config.transport) {\n case 'stdio': {\n // Routed through `./stdio-loader.ts` so the SDK's stdio transport\n // lives in zidane's static module graph at build time. That lets the\n // `cross-spawn` → shim alias in `tsdown.config.ts` fire and removes\n // the bare `require('child_process')` from the chunk that downstream\n // consumers re-bundle. See `./stdio-loader.ts` for the full story.\n const { StdioClientTransport, getDefaultEnvironment } = await import('./stdio-loader')\n const mergedEnv = config.env && !config.strictEnv\n ? { ...getDefaultEnvironment(), ...config.env }\n : config.env\n return new StdioClientTransport({\n command: config.command!,\n args: config.args,\n env: mergedEnv,\n ...(config.cwd ? { cwd: config.cwd } : {}),\n })\n }\n case 'sse': {\n const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js')\n return new SSEClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n authProvider,\n })\n }\n case 'streamable-http': {\n // `fetch: sseToJsonFetchIfNeeded()` works around a Bun + MCP SDK\n // 1.29.x bug where `text/event-stream` POST responses are buffered\n // correctly but never surface to `onmessage`, dead-locking bootstrap.\n // The helper returns the wrapper only on Bun and `undefined` on Node\n // (so the SDK's streaming pipeline stays intact where it works).\n // See ./sse-to-json-fetch.ts.\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n return new StreamableHTTPClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n fetch: sseToJsonFetchIfNeeded(),\n authProvider,\n })\n }\n default:\n throw new Error(`Unknown MCP transport: ${config.transport}`)\n }\n}\n\n/**\n * True when an error from `client.connect()` indicates the user needs to\n * (re-)authenticate against the MCP server. Two signal families:\n *\n * 1. **SDK-formal** — the MCP SDK confirmed the resource is OAuth-protected\n * (RFC 9728 metadata advertised) and threw `UnauthorizedError`. Detected\n * by class name + \"Unauthorized\" message prefix, since the SDK's\n * `UnauthorizedError` class isn't a stable export across versions.\n *\n * 2. **Raw HTTP 401 with token-rejection signal** — some real-world servers\n * (Linear is one) skip the RFC 9728 dance and just return `HTTP 401`\n * with an OAuth-style JSON body (`{\"error\":\"invalid_token\"}` /\n * `\"invalid_grant\"` / `\"insufficient_scope\"`). The MCP SDK wraps that\n * into `\"Error POSTing to endpoint (HTTP 401): { ... }\"`. Without\n * promotion, a stale Linear token reads as a generic `mcp:error`\n * bootstrap failure instead of \"needs login\" — the user gets a noisy\n * red banner instead of a re-login affordance.\n *\n * Promotion to the skip+auth-required path is still gated on\n * `explicitAuth || eligibleAutoPromote` in the caller, so a server that\n * legitimately requires a static `Authorization: Bearer …` header (no\n * `auth: 'oauth'` flag, host-provided header) won't be mis-promoted into\n * a doomed OAuth flow.\n */\nfunction isUnauthorizedError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const e = err as { name?: string, message?: string, constructor?: { name?: string } }\n if (e.name === 'UnauthorizedError' || e.constructor?.name === 'UnauthorizedError')\n return true\n const message = typeof e.message === 'string' ? e.message : ''\n if (message.toLowerCase().startsWith('unauthorized'))\n return true\n // Raw HTTP 401 with an OAuth-style token-rejection body — the\n // streamable-http transport surfaces these as `Error POSTing to endpoint\n // (HTTP 401): {\"error\":\"invalid_token\",\"error_description\":\"…\"}`.\n if (/\\bHTTP\\s*401\\b/i.test(message) || /\\b\\(401\\)/.test(message)) {\n if (/\"error\"\\s*:\\s*\"(?:invalid_token|invalid_grant|insufficient_scope|invalid_client)\"/i.test(message))\n return true\n }\n return false\n}\n\n/**\n * Optional knobs threaded into per-server bootstrap. Reserved for runtime\n * concerns the agent shell injects (credential storage, OAuth providers);\n * the `McpServerConfig` shape stays pure data.\n */\nexport interface ConnectMcpServersOptions {\n /**\n * Build a non-interactive `OAuthClientProvider` for a given server. Called\n * lazily — only invoked when the bootstrap actually needs auth (explicit\n * `auth: 'oauth'` flag, or a UnauthorizedError that meets the auto-detect\n * criteria). Return `undefined` to opt this server out of OAuth even if it\n * was requested (e.g. the host doesn't have a credential store for it).\n *\n * \"Non-interactive\" — the provider must NOT trigger a browser flow during\n * bootstrap. Use a `redirectUri` of `undefined` so the SDK reads stored\n * tokens, refreshes on expiry, and throws `UnauthorizedError` if tokens\n * are missing or refresh fails. The host then surfaces an\n * `mcp:auth:required` event so the user can opt in to interactive login.\n */\n buildAuthProvider?: (config: McpServerConfig) => OAuthClientProvider | undefined\n}\n\n/**\n * Internal: shape received by the `_clientFactory` test-injection seam.\n * Mirrors the subset of `TolerantClientOptions` the bootstrap path forwards\n * so a mock client can opt into the same lifecycle wiring (warning sink,\n * future seams) instead of silently bypassing it.\n */\ninterface McpClientFactoryOptions {\n /** See `TolerantClientOptions.onWarning`. */\n onWarning?: (message: string) => void\n}\n\ntype McpClientFactory = (opts?: McpClientFactoryOptions) => Client\n\n/**\n * Connect to MCP servers and discover their tools.\n *\n * Each tool is namespaced as `mcp_{serverName}_{toolName}` to avoid\n * collisions with agent tools or tools from other servers.\n *\n * @param configs - Array of MCP server configurations\n * @param _clientFactory - Internal: override client construction for testing\n * @param hooks - Optional agent hooks for firing mcp:connect, mcp:error, mcp:close events\n * @param options - Optional bootstrap knobs (e.g. OAuth provider injection)\n */\nexport async function connectMcpServers(\n configs: McpServerConfig[],\n _clientFactory?: McpClientFactory,\n hooks?: Hookable<AgentHooks>,\n options?: ConnectMcpServersOptions,\n): Promise<McpConnection> {\n // Per-server cleanup closure. Eager entries always have a live client; lazy\n // entries may or may not have connected — `closeIfConnected` short-circuits\n // when nothing was opened, and awaits any in-flight connect to avoid\n // leaking the resulting client past `close()`.\n const connections: { name: string, closeIfConnected: () => Promise<void> }[] = []\n const tools: Record<string, ToolDef> = {}\n // Insertion-ordered (config order) so the rendered system-prompt section is\n // byte-stable across runs. Only populated from eager-connect successes;\n // `lazyConnect: true` servers do NOT contribute here because pulling their\n // instructions would force the connection the host asked to defer.\n const instructions = new Map<string, string>()\n const errors: { name: string, error: Error }[] = []\n let closed = false\n\n // Bootstrap every server in parallel. Previously this was a sequential for-loop,\n // which meant a single slow server (GitHub MCP, cold streamable-http endpoints,\n // anything on a flaky network) blocked the whole first `agent.run()` for up to\n // N × bootstrapTimeout.\n //\n // `Promise.allSettled` (not `Promise.all`) is the final safety net for the\n // partial-failure tolerance: `bootstrapServer` already internalises every\n // expected throw, but a future regression (or a misbehaving hook that\n // sneaks past `safeCallHook`) would otherwise reject the whole batch and\n // wipe out every other server's connection. Converting a rejection back\n // into an `{ ok: false }` result keeps the batch alive.\n const settled = await Promise.allSettled(configs.map(config => bootstrapServer(config, _clientFactory, hooks, options)))\n const bootstrapResults: BootstrapResult[] = settled.map((result, idx) => {\n if (result.status === 'fulfilled')\n return result.value\n const error = result.reason instanceof Error ? result.reason : new Error(String(result.reason))\n return { ok: false, name: configs[idx]!.name, error }\n })\n\n for (const result of bootstrapResults) {\n if (result.skipped) {\n // Auth required but no tokens — already emitted `mcp:auth:required`.\n // Bootstrap continues with the other servers; the user opts in via\n // the host's interactive login path (`loginMcpServer`).\n continue\n }\n if (!result.ok) {\n errors.push({ name: result.name, error: result.error })\n await safeCallHook(hooks, 'mcp:error', { name: result.name, error: result.error })\n continue\n }\n\n const toolNames: string[] = result.tools.map(t => `mcp_${result.config.name}_${t.name}`)\n // Build a per-server `getClient` resolver before assembling the tool\n // defs. Lazy servers wrap it with a one-shot `mcp:connect` emitter so\n // the hook fires on the first successful connect (concurrent first\n // calls converge on the same connector — the wrapper guards against\n // double-fires). Eager servers fire `mcp:connect` synchronously below.\n const getClient = result.lazy\n ? wrapConnectWithHookFire(\n () => result.handle.connect(),\n onceFireConnect(result.name, result.config.transport, toolNames, hooks),\n )\n : (() => {\n const client = result.client\n return () => Promise.resolve(client)\n })()\n\n for (let i = 0; i < result.tools.length; i++) {\n tools[toolNames[i]!] = buildMcpToolDef(result.config, getClient, result.tools[i]!, toolNames[i]!, hooks)\n }\n\n if (result.lazy) {\n // No `mcp:connect` here — fires on first call via the wrapper above.\n const handle = result.handle\n const name = result.name\n connections.push({\n name,\n closeIfConnected: async () => {\n // Probe lazy state BEFORE emitting `mcp:close` so a server that\n // was never used produces no close-noise. The handle's\n // `closeIfConnected` is a no-op when nothing was started; we\n // emit the hook only when a real close is about to happen.\n await safeCallHook(hooks, 'mcp:close', { name })\n await handle.closeIfConnected()\n },\n })\n }\n else {\n const eagerClient = result.client\n connections.push({\n name: result.name,\n closeIfConnected: async () => {\n await safeCallHook(hooks, 'mcp:close', { name: result.name })\n await eagerClient.close()\n },\n })\n // Eager-only — see `instructions` declaration above for the lazy\n // exclusion rationale.\n if (result.instructions !== undefined)\n instructions.set(result.name, result.instructions)\n await safeCallHook(hooks, 'mcp:connect', {\n name: result.name,\n transport: result.config.transport,\n tools: toolNames,\n })\n }\n }\n\n // Total failure is tolerated the same way partial failure is — every server\n // already fired `mcp:error` (and `mcp:bootstrap:end` with `ok: false`), so\n // the host can render status / re-auth UI from the hook stream. Throwing\n // here used to wedge `agent.run()` on the user's first message whenever a\n // single misconfigured / expired-token server was the only MCP configured\n // (e.g. Linear's stored token expired → HTTP 401 doesn't match our\n // \"Unauthorized\" prefix check → all-failed → throw → chat shows red bubble\n // instead of the assistant reply). Returning an empty toolset lets the\n // run proceed with no MCP tools; the next bootstrap retries automatically\n // (see `mcpWarmupPromise` reset in `agent.ts`).\n\n return {\n tools,\n instructions,\n close: async () => {\n // Idempotent — double-close on `agent.destroy()` retry should not\n // re-fire the hook or call `client.close()` twice (the stdio transport\n // treats a second close as a no-op but some transports throw).\n if (closed)\n return\n closed = true\n await Promise.allSettled(connections.map(c => c.closeIfConnected()))\n },\n }\n}\n\n/**\n * Build a one-shot `mcp:connect` emitter for a lazy server. The wrapper\n * around the connector calls this on the first successful connect;\n * concurrent first calls converge on the connector's in-flight promise\n * so the hook still fires exactly once.\n */\nfunction onceFireConnect(\n name: string,\n transport: McpServerConfig['transport'],\n toolNames: string[],\n hooks: Hookable<AgentHooks> | undefined,\n): () => Promise<void> {\n let fired = false\n return async () => {\n if (fired)\n return\n fired = true\n await safeCallHook(hooks, 'mcp:connect', { name, transport, tools: toolNames, lazy: true })\n }\n}\n\n/**\n * Wrap a lazy connector so the first successful resolution fires\n * `mcp:connect` exactly once. Failures don't fire the hook — the\n * connection isn't live yet and a retry will eventually run through the\n * wrapper again. Both the eager and lazy paths reach the tool builder\n * through this resolver shape so `buildMcpToolDef` stays mode-agnostic.\n */\nfunction wrapConnectWithHookFire(\n connect: () => Promise<Client>,\n fire: () => Promise<void>,\n): () => Promise<Client> {\n return async () => {\n const client = await connect()\n await fire()\n return client\n }\n}\n\n/**\n * Discriminated result returned by `bootstrapServer` so `connectMcpServers` can\n * aggregate successes + failures without letting a rejected promise tear down\n * the whole parallel batch.\n *\n * `skipped` is the third state: server needs OAuth login but has no tokens.\n * Not an error (we don't want a noisy `mcp:error`), not a success (no\n * connection). Caller already heard `mcp:auth:required` and decides whether\n * to surface a status row, prompt for login, etc.\n */\n/**\n * Discriminated result returned by `bootstrapServer`. Success carries either\n * an already-connected `client` (the eager path) or a `connect` thunk that\n * builds + connects a fresh client on first call (the `lazyConnect: true`\n * path). The collector translates both into a uniform `getClient` closure\n * for the tool builder so the call-site stays branch-free.\n */\ntype BootstrapResult\n = | { ok: true, skipped?: false, name: string, config: McpServerConfig, lazy: false, client: Client, tools: Array<{ name: string, description?: string | null, inputSchema?: unknown }>, instructions?: string }\n | { ok: true, skipped?: false, name: string, config: McpServerConfig, lazy: true, handle: LazyConnectHandle, tools: Array<{ name: string, description?: string | null, inputSchema?: unknown }> }\n | { ok: false, skipped?: false, name: string, error: Error }\n | { ok: false, skipped: true, name: string }\n\n/**\n * Connect one MCP server and list its tools, wrapped in a single race against\n * `config.bootstrapTimeout` (default 10s). Always emits `mcp:bootstrap:start`\n * before network I/O and `mcp:bootstrap:end` with `durationMs` + outcome, so a\n * host can build a timing view even when every server succeeds.\n *\n * Errors are captured into the `{ ok: false }` result rather than thrown — the\n * parent uses `Promise.all` across every server and we can't let one rejection\n * short-circuit the batch.\n */\nasync function bootstrapServer(\n config: McpServerConfig,\n _clientFactory: McpClientFactory | undefined,\n hooks: Hookable<AgentHooks> | undefined,\n options: ConnectMcpServersOptions | undefined,\n): Promise<BootstrapResult> {\n const start = Date.now()\n // Validate mutually-exclusive filter fields up-front so the consumer gets a\n // typed `mcp:bootstrap:end` failure rather than a silent later-stage drop.\n if (config.enabledTools && config.disabledTools) {\n return emitConfigFailure(\n config,\n hooks,\n `MCP server \"${config.name}\": enabledTools and disabledTools are mutually exclusive — set one or the other, not both.`,\n )\n }\n // Lazy connect requires schemas in hand — without them there's nothing to\n // advertise to the model, so deferring the connection has no purpose.\n if (config.lazyConnect && (!config.cachedTools || config.cachedTools.length === 0)) {\n return emitConfigFailure(\n config,\n hooks,\n `MCP server \"${config.name}\": lazyConnect requires cachedTools (the host must pre-populate the tool schemas so they can be advertised without a connection).`,\n )\n }\n // OAuth + lazy is rejected — see `McpServerConfig.lazyConnect` for the\n // rationale. Surfacing this at bootstrap (rather than at first-call) is\n // load-bearing: the host needs the failure proximate to the misconfig\n // so it can render an auth affordance before the model commits to a\n // tool call that would fail mid-run.\n if (config.lazyConnect && config.auth === 'oauth') {\n return emitConfigFailure(\n config,\n hooks,\n `MCP server \"${config.name}\": lazyConnect is not compatible with auth: 'oauth' — OAuth servers must complete the handshake at bootstrap so a login affordance can surface before the model commits to a tool call.`,\n )\n }\n\n await safeCallHook(hooks, 'mcp:bootstrap:start', { name: config.name, transport: config.transport })\n\n // Build an auth provider when the config asks for OAuth and the host\n // wired a factory. Non-interactive — the SDK uses stored tokens / refresh,\n // never opens a browser during bootstrap. Missing tokens surface as\n // `UnauthorizedError` from `connect()`, which we convert to a skip below.\n const explicitAuth = config.auth === 'oauth'\n const authProvider = explicitAuth ? options?.buildAuthProvider?.(config) : undefined\n\n // Soft warnings emitted by the tolerant client (e.g. a 4xx on\n // `notifications/initialized`). Surfaced on the success arm of\n // `mcp:bootstrap:end` so hosts can render a \"connected with caveats\"\n // status instead of having to subscribe to stderr.\n const warnings: string[] = []\n const onWarning = (message: string) => { warnings.push(message) }\n\n // Lazy fast-path — defer transport + connect to `getClient()`. Schemas\n // come from `cachedTools`; the host owns invalidation. We still emit\n // `mcp:bootstrap:end ok: true, lazy: true` so timing dashboards stay\n // honest (the row appears, just with a near-zero `durationMs`).\n if (config.lazyConnect) {\n const cachedSchemas = config.cachedTools!\n const filteredTools = await applyMcpToolFilters(config, cachedSchemas, hooks)\n const handle = makeLazyConnector(config, _clientFactory, authProvider)\n const durationMs = Date.now() - start\n await safeCallHook(hooks, 'mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: true,\n toolCount: filteredTools.length,\n lazy: true,\n cached: true,\n })\n return { ok: true, name: config.name, config, lazy: true, handle, tools: filteredTools }\n }\n\n let client: Client | null = null\n let transport: ClosableTransport | null = null\n try {\n // TolerantMcpClient is a drop-in subclass that survives a 4xx on the\n // `notifications/initialized` post (some real-world servers reject it\n // without that breaking subsequent `tools/list` etc.). See\n // ./tolerant-client.ts for the exact semantics.\n client = _clientFactory\n ? _clientFactory({ onWarning })\n : await createTolerantClient({ name: 'zidane', version: '1.0.0' }, { onWarning })\n const currentClient = client\n\n transport = await createTransport(config, authProvider) as ClosableTransport\n const bootstrapTimeout = config.bootstrapTimeout ?? DEFAULT_MCP_BOOTSTRAP_TIMEOUT_MS\n // When `cachedTools` is provided we still establish the connection\n // (the SDK needs it for `tools/call`) but skip the `tools/list`\n // round-trip — that's the cheaper of the two networking costs on\n // a fast server, but on a slow / chatty one it's the dominant one.\n const cachedSchemas = config.cachedTools\n const mcpTools = await raceWithTimeout(\n async () => {\n await currentClient.connect(transport as Parameters<Client['connect']>[0])\n return cachedSchemas ?? (await currentClient.listTools()).tools\n },\n bootstrapTimeout,\n `MCP server \"${config.name}\" bootstrap timed out after ${bootstrapTimeout}ms (configurable via \\`bootstrapTimeout\\`).`,\n )\n\n // Expose the raw, pre-filter tool list to hosts so a settings UI or\n // a tool-catalog persistence layer can capture every advertised\n // tool — including ones the config's `disabledTools` / `toolFilter`\n // is about to drop. Read-only; mutation goes through\n // `mcp:tools:filter` below. See AgentHooks['mcp:tools:list'] doc.\n await safeCallHook(hooks, 'mcp:tools:list', {\n name: config.name,\n transport: config.transport,\n tools: mcpTools as McpToolSchema[],\n })\n\n // Per-tool filtering — config-side first (static host policy), then the\n // `mcp:tools:filter` hook (runtime / dynamic decisions). Both compose AND-\n // style: a tool needs to pass every stage to land in the agent registry.\n const filteredTools = await applyMcpToolFilters(config, mcpTools, hooks)\n\n // Capture the server-issued `instructions` from the initialize handshake.\n // The SDK stored them on the client during `connect()` (see\n // `tolerant-client.ts`); the public `getInstructions()` returns the\n // string or `undefined`. We trim + nullable-coerce here so the agent's\n // system-prompt builder gets one normalized shape, and a server that\n // sends `\"\"` (empty string) is treated identically to \"no instructions\"\n // rather than emitting a section with an empty body.\n //\n // Defensive: older `_clientFactory` test mocks don't implement\n // `getInstructions` (the method was added to the SDK after the mocks\n // were written). Guard so an unknown function shape degrades to\n // \"no instructions\" instead of crashing bootstrap.\n let rawInstructions: unknown\n if (typeof (currentClient as { getInstructions?: unknown }).getInstructions === 'function') {\n try {\n rawInstructions = (currentClient as { getInstructions: () => unknown }).getInstructions()\n }\n catch {\n rawInstructions = undefined\n }\n }\n const instructions = typeof rawInstructions === 'string' && rawInstructions.trim().length > 0\n ? rawInstructions\n : undefined\n\n const durationMs = Date.now() - start\n await safeCallHook(hooks, 'mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: true,\n toolCount: filteredTools.length,\n ...(cachedSchemas ? { cached: true } : {}),\n ...(warnings.length > 0 ? { warnings } : {}),\n })\n return {\n ok: true,\n name: config.name,\n config,\n lazy: false,\n client: currentClient,\n tools: filteredTools,\n ...(instructions !== undefined ? { instructions } : {}),\n }\n }\n catch (err) {\n // Close in order: transport first (may not yet be wired into the\n // client when connect() hadn't completed), then client (close()\n // is a no-op on transports that already closed).\n await closeTransportQuietly(transport)\n await closeClientQuietly(client)\n const rawError = err instanceof Error ? err : new Error(String(err))\n const error = withTransportMismatchHint(config.transport, rawError)\n const durationMs = Date.now() - start\n\n // OAuth path — convert \"needs login\" into a skip instead of an error.\n // Two cases reach here:\n // 1. Explicit `auth: 'oauth'` with no stored tokens (provider built,\n // SDK threw UnauthorizedError when none could be refreshed).\n // 2. No auth flag, but the server returned 401 + RFC 9728 metadata\n // AND the user did not provide a static Authorization header\n // (the headers escape hatch — see McpServerConfig.auth docs).\n // The auto-promote path requires `buildAuthProvider` so the host\n // can complete the login. Without it, this falls through as a\n // regular bootstrap error.\n if (isUnauthorizedError(err)) {\n const eligibleAutoPromote = !explicitAuth\n && !hasAuthorizationHeader(config.headers)\n && !!options?.buildAuthProvider\n if (explicitAuth || eligibleAutoPromote) {\n await safeCallHook(hooks, 'mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: false,\n error,\n })\n await safeCallHook(hooks, 'mcp:auth:required', {\n name: config.name,\n transport: config.transport,\n reason: explicitAuth ? 'no-tokens' : 'auto-promoted',\n })\n return { ok: false, skipped: true, name: config.name }\n }\n }\n\n await safeCallHook(hooks, 'mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: false,\n error,\n })\n return { ok: false, name: config.name, error }\n }\n}\n\n/**\n * Emit the start/end hooks for a config-level failure and return the error\n * result. Centralised so the various validation branches (enabled/disabled\n * mutex, lazyConnect-without-cachedTools, lazyConnect+OAuth) stay readable.\n */\nasync function emitConfigFailure(\n config: McpServerConfig,\n hooks: Hookable<AgentHooks> | undefined,\n message: string,\n): Promise<BootstrapResult> {\n const error = new Error(message)\n await safeCallHook(hooks, 'mcp:bootstrap:start', { name: config.name, transport: config.transport })\n await safeCallHook(hooks, 'mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs: 0,\n ok: false,\n error,\n })\n return { ok: false, name: config.name, error }\n}\n\n/**\n * Per-server lazy bootstrap handle returned by {@link makeLazyConnector}.\n *\n * - `connect()` triggers (or reuses the in-flight) transport build +\n * `client.connect()`. Concurrent callers converge on a single promise;\n * a rejection drops the cached promise so the next call retries.\n * - `closeIfConnected()` closes the live client when one exists and\n * short-circuits when the server was never used. Always awaits a\n * pending connect first so a `destroy()` racing with a first\n * `tools/call` cannot leak the freshly-built client.\n */\ninterface LazyConnectHandle {\n connect: () => Promise<Client>\n closeIfConnected: () => Promise<void>\n}\n\n/**\n * Build a memoized lazy connector + matching close handle for a\n * `lazyConnect: true` server. State lives in the closure: the connector\n * tracks its own in-flight and resolved-client state so the close path\n * can reason about \"never connected\" vs \"in flight\" vs \"live\" without\n * forcing a connect from inside `close()`.\n *\n * Concurrency contract:\n * - First `connect()` builds + connects a fresh client. Concurrent\n * callers converge on the same in-flight promise.\n * - On rejection, the cached promise is dropped so the next caller\n * retries with a fresh client instance.\n * - `closeIfConnected()` awaits any pending connect, closes the\n * resulting client, and marks the handle destroyed. Any subsequent\n * `connect()` rejects synchronously so a tool call racing the\n * shutdown can't leak a freshly-built client past the close.\n */\nfunction makeLazyConnector(\n config: McpServerConfig,\n _clientFactory: McpClientFactory | undefined,\n authProvider: OAuthClientProvider | undefined,\n): LazyConnectHandle {\n let inFlight: Promise<Client> | null = null\n let live: Client | null = null\n let destroyed = false\n\n const connect = (): Promise<Client> => {\n if (destroyed) {\n return Promise.reject(new Error(\n `MCP server \"${config.name}\": cannot connect after close()`,\n ))\n }\n if (live)\n return Promise.resolve(live)\n if (inFlight)\n return inFlight\n const pending = (async () => {\n // Match the eager path's timeout — a lazy connect that hangs\n // would wedge a tool call indefinitely without it.\n const bootstrapTimeout = config.bootstrapTimeout ?? DEFAULT_MCP_BOOTSTRAP_TIMEOUT_MS\n const client = _clientFactory\n ? _clientFactory()\n : await createTolerantClient({ name: 'zidane', version: '1.0.0' })\n let transport: ClosableTransport | null = null\n try {\n transport = await createTransport(config, authProvider) as ClosableTransport\n await raceWithTimeout(\n () => client.connect(transport as Parameters<Client['connect']>[0]),\n bootstrapTimeout,\n `MCP server \"${config.name}\" lazy connect timed out after ${bootstrapTimeout}ms (configurable via \\`bootstrapTimeout\\`).`,\n )\n // Shutdown ran while we were connecting — close the freshly\n // built client right here so it doesn't leak past destroy().\n if (destroyed) {\n await closeTransportQuietly(transport)\n await closeClientQuietly(client)\n throw new Error(`MCP server \"${config.name}\": closed during connect`)\n }\n live = client\n return client\n }\n catch (err) {\n // Close in order: transport first (may not be wired into the\n // client yet on a connect failure), then client.\n await closeTransportQuietly(transport)\n await closeClientQuietly(client)\n throw err instanceof Error\n ? withTransportMismatchHint(config.transport, err)\n : err\n }\n })()\n inFlight = pending\n // Clear the in-flight cache on either outcome — success leaves the\n // resolved client cached on `live`; failure drops the slot so the\n // next caller retries against a fresh client instance, matching the\n // bootstrap-level retry behavior in `agent.ts`'s `mcpWarmupPromise`.\n pending.then(\n () => { inFlight = null },\n () => { inFlight = null },\n )\n return pending\n }\n\n const closeIfConnected = async (): Promise<void> => {\n destroyed = true\n // Race-safe drain: if a connect is in flight, wait for it to settle\n // before deciding whether to close. Successful resolution promotes\n // the client to `live`; failure leaves both `live` and `inFlight`\n // null. Either way, after the await the state is terminal and the\n // close decision is unambiguous.\n if (inFlight) {\n try { await inFlight }\n catch { /* connect failed; nothing to close */ }\n }\n if (live) {\n const client = live\n live = null\n await client.close()\n }\n }\n\n return { connect, closeIfConnected }\n}\n\n/**\n * Apply config-side filters (`enabledTools` / `disabledTools` / `toolFilter`)\n * and then the `mcp:tools:filter` hook to the upstream tool list.\n *\n * Composition order — narrowest-to-widest:\n * 1. Allow-list (`enabledTools`) — keep only listed tools.\n * 2. Deny-list (`disabledTools`) — drop listed tools.\n * 3. Predicate (`toolFilter`) — fine-grained metadata filtering.\n * 4. Hook (`mcp:tools:filter`) — runtime / per-host decisions.\n *\n * The mutual exclusion of `enabledTools` and `disabledTools` is checked in\n * `bootstrapServer` so this stays a pure data transform.\n */\nasync function applyMcpToolFilters(\n config: McpServerConfig,\n tools: Array<{ name: string, description?: string | null, inputSchema?: unknown }>,\n hooks: Hookable<AgentHooks> | undefined,\n): Promise<Array<{ name: string, description?: string | null, inputSchema?: unknown }>> {\n let filtered = tools\n\n if (config.enabledTools && config.enabledTools.length > 0) {\n const allow = new Set(config.enabledTools)\n filtered = filtered.filter(t => allow.has(t.name))\n }\n\n if (config.disabledTools && config.disabledTools.length > 0) {\n const deny = new Set(config.disabledTools)\n filtered = filtered.filter(t => !deny.has(t.name))\n }\n\n if (config.toolFilter) {\n const predicate = config.toolFilter\n filtered = filtered.filter(t => predicate(t))\n }\n\n if (hooks) {\n // Pass a fresh array so handlers cannot retroactively mutate the caller's\n // upstream list; mutations they make to `ctx.tools` are scoped to this turn.\n const ctx = { server: config.name, transport: config.transport, tools: [...filtered] }\n await hooks.callHook('mcp:tools:filter', ctx)\n filtered = ctx.tools\n }\n\n return filtered\n}\n\n/**\n * Build the zidane `ToolDef` that wraps a single MCP tool. Extracted so the\n * parallel bootstrap path can assemble tools from a results array without\n * inlining a 70-line closure inside the collector loop.\n *\n * `getClient` resolves to a live `Client` ready for `tools/call`. For\n * eagerly-bootstrapped servers it's a constant resolved promise; for\n * `lazyConnect: true` servers it's the memoized connector built by\n * {@link makeLazyConnector} — the first invocation pays the connect cost,\n * concurrent / subsequent calls observe the cached client. Reconnects /\n * swap-outs go through a fresh `connectMcpServers` call rather than\n * rewiring the tool in place.\n */\nfunction buildMcpToolDef(\n config: McpServerConfig,\n getClient: () => Promise<Client>,\n tool: { name: string, description?: string | null, inputSchema?: unknown },\n namespacedName: string,\n hooks: Hookable<AgentHooks> | undefined,\n): ToolDef {\n return {\n spec: {\n name: namespacedName,\n description: tool.description || '',\n inputSchema: (tool.inputSchema ?? { type: 'object', properties: {} }) as Record<string, unknown>,\n },\n execute: async (input: Record<string, unknown>, ctx: ToolContext) => {\n const { turnId, callId, signal } = ctx\n const displayName = ctx.toolAliases?.[namespacedName] ?? namespacedName\n\n // Shared identity fields for every `mcp:tool:*` hook ctx the\n // wrapper fires. Mirrors `runId / parentRunId / depth` from the\n // tool context so subagent observability stays consistent\n // between `tool:*` and `mcp:tool:*` events.\n const identity = {\n ...(ctx.runId !== undefined ? { runId: ctx.runId } : {}),\n ...(ctx.parentRunId !== undefined ? { parentRunId: ctx.parentRunId } : {}),\n ...(typeof ctx.depth === 'number' ? { depth: ctx.depth } : {}),\n }\n\n // Gate — block MCP tool execution or substitute a synthetic result.\n const gateCtx: McpToolHookContext & {\n block: boolean\n reason: string\n result?: string | ToolResultContent[]\n } = {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input,\n ...identity,\n block: false,\n reason: 'MCP tool execution was blocked',\n }\n await hooks?.callHook('mcp:tool:gate', gateCtx)\n\n // Conflict resolution mirrors the loop's `tool:gate`: when both `block`\n // and `result` are set (e.g. a policy gate refuses on top of a consumer\n // cache substitute), `block` wins.\n if (gateCtx.block)\n return `Blocked: ${gateCtx.reason}`\n\n const effectiveInput = gateCtx.input\n\n // MCP gate `result` substitute — skip the upstream callTool, fire the\n // transform + after hooks so consumers see the substitute consistently\n // with normally-executed calls.\n if (gateCtx.result !== undefined) {\n let substitute: string | ToolResultContent[] = gateCtx.result\n const transformCtx = {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n result: substitute,\n outputBytes: toolOutputByteLength(substitute),\n }\n await hooks?.callHook('mcp:tool:transform', transformCtx)\n substitute = transformCtx.result\n await hooks?.callHook('mcp:tool:after', {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n result: substitute,\n outputBytes: toolOutputByteLength(substitute),\n })\n return substitute\n }\n await hooks?.callHook('mcp:tool:before', {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n })\n const timeout = config.toolTimeout ?? 30_000\n try {\n // Resolve the live client. For eager servers this is a no-op\n // (constant resolved promise); for `lazyConnect: true` servers\n // this triggers the deferred connect on first call and reuses\n // the cached client afterward.\n const client = await getClient()\n // Race the call against the configured timeout AND the run-level\n // abort signal. Aborting the run has to propagate into MCP calls\n // — otherwise a hung stdio server keeps the tool call alive\n // until `destroy()` eventually closes the client, which can be\n // minutes if the agent is waiting on `waitForIdle()`.\n const result = await raceWithTimeoutAndSignal(\n () => client.callTool({ name: tool.name, arguments: effectiveInput }),\n timeout,\n `MCP tool \"${tool.name}\" on server \"${config.name}\" timed out after ${timeout}ms`,\n signal,\n )\n let output: string | ToolResultContent[] = packMcpResult(result.content)\n\n // Transform — mutate result before returning. `outputBytes` reflects\n // the size before any consumer mutation so a truncation hook can size-budget.\n const transformCtx = {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n result: output,\n outputBytes: toolOutputByteLength(output),\n }\n await hooks?.callHook('mcp:tool:transform', transformCtx)\n output = transformCtx.result\n\n await hooks?.callHook('mcp:tool:after', {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n result: output,\n outputBytes: toolOutputByteLength(output),\n })\n return output\n }\n catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n await hooks?.callHook('mcp:tool:error', {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n error,\n })\n await hooks?.callHook('mcp:tool:after', {\n turnId,\n callId,\n server: config.name,\n tool: tool.name,\n displayName,\n input: effectiveInput,\n ...identity,\n result: error.message,\n outputBytes: Buffer.byteLength(error.message),\n })\n throw error\n }\n },\n }\n}\n\nasync function closeClientQuietly(client: Pick<Client, 'close'> | null | undefined): Promise<void> {\n if (!client)\n return\n try {\n await client.close()\n }\n catch {\n // Best-effort cleanup — original bootstrap error is more actionable.\n }\n}\n\nasync function raceWithTimeout<T>(\n task: () => Promise<T>,\n timeoutMs: number,\n timeoutMessage: string,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await new Promise<T>((resolvePromise, rejectPromise) => {\n timer = setTimeout(() => rejectPromise(new Error(timeoutMessage)), timeoutMs)\n task().then(resolvePromise, rejectPromise)\n })\n }\n finally {\n if (timer)\n clearTimeout(timer)\n }\n}\n\n/**\n * Race a promise-returning task against (a) a timeout and (b) an optional\n * abort signal. Cleans up its timer and abort listener on every exit path.\n *\n * The task itself isn't cancellable (the MCP SDK doesn't take a signal), so\n * the rejection unblocks the tool call while the underlying RPC completes in\n * the background. When the agent subsequently calls `connection.close()` the\n * stdio transport kills the subprocess, which clears any stuck in-flight work.\n */\nasync function raceWithTimeoutAndSignal<T>(\n task: () => Promise<T>,\n timeoutMs: number,\n timeoutMessage: string,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal?.aborted)\n throw new Error('MCP tool call aborted')\n\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await new Promise<T>((resolvePromise, rejectPromise) => {\n timer = setTimeout(() => rejectPromise(new Error(timeoutMessage)), timeoutMs)\n if (signal) {\n onAbort = () => rejectPromise(new Error('MCP tool call aborted'))\n signal.addEventListener('abort', onAbort, { once: true })\n }\n task().then(resolvePromise, rejectPromise)\n })\n }\n finally {\n if (timer)\n clearTimeout(timer)\n if (signal && onAbort)\n signal.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;AAmEA,SAAgB,+BAA+B,MAA+D;CAC5G,MAAM,QAAQ,IAAI,IAAgC,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC;CAC5E,OAAO;EACL,OAAM,SAAQ,MAAM,IAAI,IAAI;EAC5B,OAAO,MAAM,UAAU;GAAE,MAAM,IAAI,MAAM,KAAK;EAAE;EAChD,SAAS,SAAS;GAAE,MAAM,OAAO,IAAI;EAAE;CACzC;AACF;AA+BA,MAAM,sBAAsB;AAE5B,IAAa,mBAAb,MAA6D;CAC3D;CACA;CACA;CACA;CACA;CACA;CAIA;CAEA,YAAY,MAA+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