zidane 5.1.7 → 5.1.9

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 (42) hide show
  1. package/dist/{agent-BEtOGMct.d.ts → agent-CzHIRBSN.d.ts} +2 -2
  2. package/dist/{agent-BEtOGMct.d.ts.map → agent-CzHIRBSN.d.ts.map} +1 -1
  3. package/dist/chat.d.ts +30 -12
  4. package/dist/chat.d.ts.map +1 -1
  5. package/dist/chat.js +1 -1
  6. package/dist/{index-CsJOjP5T.d.ts → index-C0dEcjjn.d.ts} +2 -2
  7. package/dist/{index-CsJOjP5T.d.ts.map → index-C0dEcjjn.d.ts.map} +1 -1
  8. package/dist/{index-CYnIU6Pp.d.ts → index-EqQH76lu.d.ts} +2 -2
  9. package/dist/{index-CYnIU6Pp.d.ts.map → index-EqQH76lu.d.ts.map} +1 -1
  10. package/dist/index.d.ts +3 -3
  11. package/dist/index.js +4 -4
  12. package/dist/{login-B3yZG4iI.js → login-DZzbLMDE.js} +3 -3
  13. package/dist/{login-B3yZG4iI.js.map → login-DZzbLMDE.js.map} +1 -1
  14. package/dist/{mcp-8S8mSbr2.js → mcp-BXhRMq8-.js} +2 -2
  15. package/dist/mcp-BXhRMq8-.js.map +1 -0
  16. package/dist/mcp.d.ts +1 -1
  17. package/dist/mcp.js +1 -1
  18. package/dist/{presets-B800CKGw.js → presets-CXuvAWCQ.js} +2 -2
  19. package/dist/{presets-B800CKGw.js.map → presets-CXuvAWCQ.js.map} +1 -1
  20. package/dist/presets.d.ts +2 -2
  21. package/dist/presets.js +1 -1
  22. package/dist/providers.d.ts +1 -1
  23. package/dist/session/sqlite.d.ts +1 -1
  24. package/dist/session.d.ts +1 -1
  25. package/dist/skills.d.ts +2 -2
  26. package/dist/{stdio-loader-C48v4hPt.js → stdio-loader-EVAF5KlU.js} +2 -2
  27. package/dist/stdio-loader-EVAF5KlU.js.map +1 -0
  28. package/dist/{tool-formatters-Depi9Hwr.d.ts → tool-formatters-B2radwGM.d.ts} +3 -3
  29. package/dist/{tool-formatters-Depi9Hwr.d.ts.map → tool-formatters-B2radwGM.d.ts.map} +1 -1
  30. package/dist/{tools-DngHXth6.js → tools-3vw1Ukwq.js} +2 -2
  31. package/dist/{tools-DngHXth6.js.map → tools-3vw1Ukwq.js.map} +1 -1
  32. package/dist/tools.d.ts +2 -2
  33. package/dist/tools.js +1 -1
  34. package/dist/tui.d.ts +2 -2
  35. package/dist/tui.js +4 -4
  36. package/dist/{turn-operations-BF8_mSmx.js → turn-operations-DMT48AUM.js} +42 -13
  37. package/dist/turn-operations-DMT48AUM.js.map +1 -0
  38. package/dist/types.d.ts +2 -2
  39. package/package.json +1 -1
  40. package/dist/mcp-8S8mSbr2.js.map +0 -1
  41. package/dist/stdio-loader-C48v4hPt.js.map +0 -1
  42. package/dist/turn-operations-BF8_mSmx.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-BXhRMq8-.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'\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\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 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 const msg = notifyError instanceof Error ? notifyError.message : String(notifyError)\n console.warn(`[zidane:mcp] server rejected notifications/initialized (continuing): ${msg}`)\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, ToolResultContent } from '../types'\nimport { Buffer } from 'node:buffer'\nimport { toolOutputByteLength } from '../types'\nimport { hasAuthorizationHeader } from './oauth-provider'\nimport { sseToJsonFetchIfNeeded } from './sse-to-json-fetch'\nimport { createTolerantClient } from './tolerant-client'\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 } from '../types'\n\nexport interface McpConnection {\n tools: Record<string, ToolDef>\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 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\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 (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 mediaType = typeof block.mimeType === 'string'\n ? block.mimeType\n : (typeof block.mediaType === 'string' ? block.mediaType : 'image/png')\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 out.push({ type: 'image', mediaType: res.mimeType, 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 */\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 })\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 * 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?: () => Client,\n hooks?: Hookable<AgentHooks>,\n options?: ConnectMcpServersOptions,\n): Promise<McpConnection> {\n const connections: { name: string, client: Client }[] = []\n const tools: Record<string, ToolDef> = {}\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. With `Promise.all` + per-server try/catch, wall-clock\n // collapses to the slowest server, and the existing partial-failure tolerance\n // keeps the agent alive when any subset connects.\n const bootstrapResults = await Promise.all(configs.map(config => bootstrapServer(config, _clientFactory, hooks, options)))\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 hooks?.callHook('mcp:error', { name: result.name, error: result.error })\n continue\n }\n\n connections.push({ name: result.name, client: result.client })\n const toolNames: string[] = []\n for (const tool of result.tools) {\n const namespacedName = `mcp_${result.config.name}_${tool.name}`\n toolNames.push(namespacedName)\n tools[namespacedName] = buildMcpToolDef(result.config, result.client, tool, namespacedName, hooks)\n }\n await hooks?.callHook('mcp:connect', {\n name: result.name,\n transport: result.config.transport,\n tools: toolNames,\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 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(\n connections.map(async ({ name, client }) => {\n await hooks?.callHook('mcp:close', { name })\n await client.close()\n }),\n )\n },\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 */\ntype BootstrapResult\n = | { ok: true, skipped?: false, name: string, config: McpServerConfig, client: Client, 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: (() => Client) | 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 const error = new Error(\n `MCP server \"${config.name}\": enabledTools and disabledTools are mutually exclusive — set one or the other, not both.`,\n )\n await hooks?.callHook('mcp:bootstrap:start', { name: config.name, transport: config.transport })\n await hooks?.callHook('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 await hooks?.callHook('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 let client: Client | 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()\n : await createTolerantClient({ name: 'zidane', version: '1.0.0' })\n const currentClient = client\n\n const transport = await createTransport(config, authProvider)\n const bootstrapTimeout = config.bootstrapTimeout ?? DEFAULT_MCP_BOOTSTRAP_TIMEOUT_MS\n const { tools: mcpTools } = await raceWithTimeout(\n async () => {\n await currentClient.connect(transport)\n return await currentClient.listTools()\n },\n bootstrapTimeout,\n `MCP server \"${config.name}\" bootstrap timed out after ${bootstrapTimeout}ms`,\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 const durationMs = Date.now() - start\n await hooks?.callHook('mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: true,\n toolCount: filteredTools.length,\n })\n return { ok: true, name: config.name, config, client: currentClient, tools: filteredTools }\n }\n catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n await closeClientQuietly(client)\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 hooks?.callHook('mcp:bootstrap:end', {\n name: config.name,\n transport: config.transport,\n durationMs,\n ok: false,\n error,\n })\n await hooks?.callHook('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 hooks?.callHook('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 * 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 * The returned `execute` closes over the bootstrapped `client` — reconnects /\n * swap-outs must go through a fresh `connectMcpServers` call rather than\n * rewiring the tool in place.\n */\nfunction buildMcpToolDef(\n config: McpServerConfig,\n client: 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 // Gate — block MCP tool execution or substitute a synthetic result.\n const gateCtx: {\n turnId: string\n callId: string\n server: string\n tool: string\n displayName: string\n input: Record<string, unknown>\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 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 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 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 })\n const timeout = config.toolTimeout ?? 30_000\n try {\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 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 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 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 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,EAAE,CAAC,CAAC;CAC7E,OAAO;EACL,OAAM,SAAQ,MAAM,IAAI,KAAK;EAC7B,OAAO,MAAM,UAAU;GAAE,MAAM,IAAI,MAAM,MAAM;;EAC/C,SAAS,SAAS;GAAE,MAAM,OAAO,KAAK;;EACvC;;AAgCH,MAAM,sBAAsB;AAE5B,IAAa,mBAAb,MAA6D;CAC3D;CACA;CACA;CACA;CACA;CACA;CAIA;CAEA,YAAY,MAA+B;EACzC,KAAK,OAAO,KAAK;EACjB,KAAK,QAAQ,KAAK;EAClB,KAAK,eAAe,KAAK;EACzB,KAAK,qBAAqB,KAAK;EAC/B,KAAK,aAAa,KAAK,cAAc;EACrC,KAAK,SAAS,KAAK;;CAGrB,IAAI,cAAwC;EAC1C,OAAO,KAAK;;CAGd,IAAI,iBAAsC;EACxC,OAAO;GAKL,eAAe,CAAC,KAAK,gBAAgB,8BAA8B;GACnE,aAAa,KAAK;GAElB,4BAA4B;GAC5B,aAAa,CAAC,sBAAsB,gBAAgB;GACpD,gBAAgB,CAAC,OAAO;GACxB,GAAI,KAAK,SAAS,EAAE,OAAO,KAAK,QAAQ,GAAG,EAAE;GAC9C;;CAGH,SAAkC;EAChC,OAAO,KAAK,MAAM,KAAK,KAAK,KAAK,EAAE;;CAGrC,WAAW,QAA2B;EACpC,KAAK,MAAM,EAAE,QAAQ,CAAC;;CAGxB,oBAA6D;EAC3D,OAAO,KAAK,MAAM,KAAK,KAAK,KAAK,EAAE;;CAGrC,sBAAsB,MAAyC;EAC7D,KAAK,MAAM,EAAE,mBAAmB,MAAM,CAAC;;CAGzC,iBAAkD;EAChD,OAAO,KAAK,MAAM,KAAK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AY,gBAAgB,kBAAkB;GAC7D,QAAQ,iBAAiB,cAAc,IAAI,MAAM,eAAe,CAAC,EAAE,UAAU;GAC7E,IAAI,QAAQ;IACV,gBAAgB,8BAAc,IAAI,MAAM,wBAAwB,CAAC;IACjE,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;;GAE3D,MAAM,CAAC,KAAK,gBAAgB,cAAc;IAC1C;WAEI;EACN,IAAI,OACF,aAAa,MAAM;EACrB,IAAI,UAAU,SACZ,OAAO,oBAAoB,SAAS,QAAQ"}
package/dist/mcp.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as resultToString, f as ConnectMcpServersOptions, g as normalizeMcpServers, gt as McpServerConfig, h as normalizeMcpBlocks, m as connectMcpServers, p as McpConnection } from "./agent-BEtOGMct.js";
1
+ import { _ as resultToString, f as ConnectMcpServersOptions, g as normalizeMcpServers, gt as McpServerConfig, h as normalizeMcpBlocks, m as connectMcpServers, p as McpConnection } from "./agent-CzHIRBSN.js";
2
2
  export { ConnectMcpServersOptions, McpConnection, McpServerConfig, connectMcpServers, normalizeMcpBlocks, normalizeMcpServers, resultToString };
package/dist/mcp.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as resultToString, n as normalizeMcpBlocks, r as normalizeMcpServers, t as connectMcpServers } from "./mcp-8S8mSbr2.js";
1
+ import { i as resultToString, n as normalizeMcpBlocks, r as normalizeMcpServers, t as connectMcpServers } from "./mcp-BXhRMq8-.js";
2
2
  export { connectMcpServers, normalizeMcpBlocks, normalizeMcpServers, resultToString };
@@ -1,4 +1,4 @@
1
- import { a as multiEdit, i as readFile, n as createSpawnTool, o as listFiles, r as shell, t as writeFile, u as edit } from "./tools-DngHXth6.js";
1
+ import { a as multiEdit, i as readFile, n as createSpawnTool, o as listFiles, r as shell, t as writeFile, u as edit } from "./tools-3vw1Ukwq.js";
2
2
  //#region src/presets/basic.ts
3
3
  /**
4
4
  * Core tools available in every basic preset (without spawn).
@@ -87,4 +87,4 @@ function composePresets(...presets) {
87
87
  //#endregion
88
88
  export { basic_default as i, definePreset as n, basicTools as r, composePresets as t };
89
89
 
90
- //# sourceMappingURL=presets-B800CKGw.js.map
90
+ //# sourceMappingURL=presets-CXuvAWCQ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"presets-B800CKGw.js","names":[],"sources":["../src/presets/basic.ts","../src/presets/index.ts"],"sourcesContent":["import { definePreset } from '.'\nimport { edit, listFiles, multiEdit, readFile, shell, writeFile } from '../tools'\nimport { createSpawnTool } from '../tools/spawn'\n\n/**\n * Core tools available in every basic preset (without spawn).\n *\n * `edit` and `multi_edit` ship in the basic set because surgical edits are the\n * default modality for production agents — `write_file` is for full overwrites.\n * `glob` and `grep` are exported but opt-in: not every agent needs codebase\n * search, and shipping them by default would force `tool:gate` work onto\n * consumers that prefer the model to use `shell` + classic Unix tools.\n */\nexport const basicTools = { shell, readFile, writeFile, listFiles, edit, multiEdit }\n\nexport default definePreset({\n name: 'basic',\n system: 'You are a helpful assistant with access to shell, file reading, file writing, surgical and multi-edit tools, directory listing, and sub-agent spawning. Prefer `edit` / `multi_edit` for in-place changes and `write_file` for full file overwrites. Use them to accomplish tasks in the project directory.',\n // `persist: true` shares the parent's session with every child agent — child\n // turns land in `session.turns` tagged with their own `runId`, and the run\n // itself is recorded in `session.runs` with `parentRunId` + `depth`. That's\n // what lets a reloaded TUI session reconstruct the full subagent tree (see\n // `eventsFromTurns` in `tui/store.ts`). Hosts that want children in-memory\n // only can construct their own preset with `createSpawnTool()`.\n tools: { ...basicTools, spawn: createSpawnTool({ persist: true }) },\n})\n","import type { AgentHooks, AgentOptions } from '../agent'\n\nexport type { AgentHookMap } from '../agent'\n\n/**\n * A preset is a reusable slice of `AgentOptions` — spread it into `createAgent()`\n * to configure tools, a default system prompt, aliases, behavior defaults, and\n * agent-lifetime hooks.\n *\n * `provider`, `execution`, `session`, and internal fields are excluded so presets\n * remain shareable and composable.\n *\n * ```ts\n * import { basic } from 'zidane/presets'\n * createAgent({ ...basic, provider })\n * ```\n *\n * ### Composing multiple presets\n *\n * Bare `...spread` is shallow — `{ ...a, ...b }` overwrites every key `b`\n * defines, including `hooks`. Use {@link composePresets} when you want\n * field-aware merging (per-event hook concat, tools shallow-merge, etc.):\n *\n * ```ts\n * createAgent({ ...composePresets(basic, telemetry, mine), provider })\n * ```\n */\nexport type Preset = Omit<Partial<AgentOptions>, 'provider' | 'execution' | 'session' | 'mcpConnector'>\n\n/**\n * Identity helper for type inference when defining a preset.\n */\nexport function definePreset(config: Preset): Preset {\n return config\n}\n\n/**\n * Field-aware composition of presets. Right-most preset wins for scalar fields;\n * objects shallow-merge; arrays and hook handler lists concatenate. Designed so\n * stacking presets does the obvious thing without the spread-collision footgun:\n *\n * - `name`, `system`, `eager`, `skills` → last-defined wins\n * - `tools`, `toolAliases`, `behavior` → shallow-merge (later keys override)\n * - `mcpServers` → concat with last-wins on `name` collision\n * - `hooks` → per-event concat; every handler fires\n *\n * `hooks` always emerges as `event → handler[]` so downstream registration\n * (in `createAgent`) sees a uniform shape. Order of handlers within an event\n * follows preset order: earlier presets register first.\n *\n * `mcpServers` is deduped by `name` because shipping two servers with the same\n * name would trip the connector at runtime — a later preset overriding an\n * earlier preset's `github` server is the practical intent.\n */\nexport function composePresets(...presets: Preset[]): Preset {\n const out: Preset = {}\n const hooksByEvent: { [K in keyof AgentHooks]?: AgentHooks[K][] } = {}\n // Keep mcpServers in source-order on first sight, but allow later\n // declarations to override earlier ones with the same `name`. A `Map`\n // keyed by name gives O(1) override + stable iteration.\n const mcpByName = new Map<string, NonNullable<Preset['mcpServers']>[number]>()\n\n for (const p of presets) {\n if (p.name !== undefined)\n out.name = p.name\n if (p.system !== undefined)\n out.system = p.system\n if (p.eager !== undefined)\n out.eager = p.eager\n if (p.skills !== undefined)\n out.skills = p.skills\n if (p.tools)\n out.tools = { ...out.tools, ...p.tools }\n if (p.toolAliases)\n out.toolAliases = { ...out.toolAliases, ...p.toolAliases }\n if (p.behavior)\n out.behavior = { ...out.behavior, ...p.behavior }\n if (p.mcpServers) {\n for (const server of p.mcpServers)\n mcpByName.set(server.name, server)\n }\n if (p.hooks) {\n for (const [event, handler] of Object.entries(p.hooks)) {\n if (handler === undefined)\n continue\n const list = Array.isArray(handler) ? handler : [handler]\n const key = event as keyof AgentHooks\n // Safe cast: we read the loose `AgentHookMap` shape (handler-or-array)\n // and re-emit only as arrays. Each `list` element matches the event's\n // handler signature by construction (the input was typed `AgentHookMap`).\n const bucket = (hooksByEvent[key] ??= []) as unknown[]\n bucket.push(...(list as unknown[]))\n }\n }\n }\n\n if (mcpByName.size > 0)\n out.mcpServers = [...mcpByName.values()]\n\n if (Object.keys(hooksByEvent).length > 0)\n out.hooks = hooksByEvent\n\n return out\n}\n\nexport { default as basic, basicTools } from './basic'\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,aAAa;CAAE;CAAO;CAAU;CAAW;CAAW;CAAM;CAAW;AAEpF,IAAA,gBAAe,aAAa;CAC1B,MAAM;CACN,QAAQ;CAOR,OAAO;EAAE,GAAG;EAAY,OAAO,gBAAgB,EAAE,SAAS,MAAM,CAAC;EAAE;CACpE,CAAC;;;;;;ACOF,SAAgB,aAAa,QAAwB;CACnD,OAAO;;;;;;;;;;;;;;;;;;;;AAqBT,SAAgB,eAAe,GAAG,SAA2B;CAC3D,MAAM,MAAc,EAAE;CACtB,MAAM,eAA8D,EAAE;CAItE,MAAM,4BAAY,IAAI,KAAwD;CAE9E,KAAK,MAAM,KAAK,SAAS;EACvB,IAAI,EAAE,SAAS,KAAA,GACb,IAAI,OAAO,EAAE;EACf,IAAI,EAAE,WAAW,KAAA,GACf,IAAI,SAAS,EAAE;EACjB,IAAI,EAAE,UAAU,KAAA,GACd,IAAI,QAAQ,EAAE;EAChB,IAAI,EAAE,WAAW,KAAA,GACf,IAAI,SAAS,EAAE;EACjB,IAAI,EAAE,OACJ,IAAI,QAAQ;GAAE,GAAG,IAAI;GAAO,GAAG,EAAE;GAAO;EAC1C,IAAI,EAAE,aACJ,IAAI,cAAc;GAAE,GAAG,IAAI;GAAa,GAAG,EAAE;GAAa;EAC5D,IAAI,EAAE,UACJ,IAAI,WAAW;GAAE,GAAG,IAAI;GAAU,GAAG,EAAE;GAAU;EACnD,IAAI,EAAE,YACJ,KAAK,MAAM,UAAU,EAAE,YACrB,UAAU,IAAI,OAAO,MAAM,OAAO;EAEtC,IAAI,EAAE,OACJ,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,EAAE,MAAM,EAAE;GACtD,IAAI,YAAY,KAAA,GACd;GACF,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,UAAU,CAAC,QAAQ;GACzD,MAAM,MAAM;GAKZ,CADgB,aAAa,SAAS,EAAE,EACjC,KAAK,GAAI,KAAmB;;;CAKzC,IAAI,UAAU,OAAO,GACnB,IAAI,aAAa,CAAC,GAAG,UAAU,QAAQ,CAAC;CAE1C,IAAI,OAAO,KAAK,aAAa,CAAC,SAAS,GACrC,IAAI,QAAQ;CAEd,OAAO"}
1
+ {"version":3,"file":"presets-CXuvAWCQ.js","names":[],"sources":["../src/presets/basic.ts","../src/presets/index.ts"],"sourcesContent":["import { definePreset } from '.'\nimport { edit, listFiles, multiEdit, readFile, shell, writeFile } from '../tools'\nimport { createSpawnTool } from '../tools/spawn'\n\n/**\n * Core tools available in every basic preset (without spawn).\n *\n * `edit` and `multi_edit` ship in the basic set because surgical edits are the\n * default modality for production agents — `write_file` is for full overwrites.\n * `glob` and `grep` are exported but opt-in: not every agent needs codebase\n * search, and shipping them by default would force `tool:gate` work onto\n * consumers that prefer the model to use `shell` + classic Unix tools.\n */\nexport const basicTools = { shell, readFile, writeFile, listFiles, edit, multiEdit }\n\nexport default definePreset({\n name: 'basic',\n system: 'You are a helpful assistant with access to shell, file reading, file writing, surgical and multi-edit tools, directory listing, and sub-agent spawning. Prefer `edit` / `multi_edit` for in-place changes and `write_file` for full file overwrites. Use them to accomplish tasks in the project directory.',\n // `persist: true` shares the parent's session with every child agent — child\n // turns land in `session.turns` tagged with their own `runId`, and the run\n // itself is recorded in `session.runs` with `parentRunId` + `depth`. That's\n // what lets a reloaded TUI session reconstruct the full subagent tree (see\n // `eventsFromTurns` in `tui/store.ts`). Hosts that want children in-memory\n // only can construct their own preset with `createSpawnTool()`.\n tools: { ...basicTools, spawn: createSpawnTool({ persist: true }) },\n})\n","import type { AgentHooks, AgentOptions } from '../agent'\n\nexport type { AgentHookMap } from '../agent'\n\n/**\n * A preset is a reusable slice of `AgentOptions` — spread it into `createAgent()`\n * to configure tools, a default system prompt, aliases, behavior defaults, and\n * agent-lifetime hooks.\n *\n * `provider`, `execution`, `session`, and internal fields are excluded so presets\n * remain shareable and composable.\n *\n * ```ts\n * import { basic } from 'zidane/presets'\n * createAgent({ ...basic, provider })\n * ```\n *\n * ### Composing multiple presets\n *\n * Bare `...spread` is shallow — `{ ...a, ...b }` overwrites every key `b`\n * defines, including `hooks`. Use {@link composePresets} when you want\n * field-aware merging (per-event hook concat, tools shallow-merge, etc.):\n *\n * ```ts\n * createAgent({ ...composePresets(basic, telemetry, mine), provider })\n * ```\n */\nexport type Preset = Omit<Partial<AgentOptions>, 'provider' | 'execution' | 'session' | 'mcpConnector'>\n\n/**\n * Identity helper for type inference when defining a preset.\n */\nexport function definePreset(config: Preset): Preset {\n return config\n}\n\n/**\n * Field-aware composition of presets. Right-most preset wins for scalar fields;\n * objects shallow-merge; arrays and hook handler lists concatenate. Designed so\n * stacking presets does the obvious thing without the spread-collision footgun:\n *\n * - `name`, `system`, `eager`, `skills` → last-defined wins\n * - `tools`, `toolAliases`, `behavior` → shallow-merge (later keys override)\n * - `mcpServers` → concat with last-wins on `name` collision\n * - `hooks` → per-event concat; every handler fires\n *\n * `hooks` always emerges as `event → handler[]` so downstream registration\n * (in `createAgent`) sees a uniform shape. Order of handlers within an event\n * follows preset order: earlier presets register first.\n *\n * `mcpServers` is deduped by `name` because shipping two servers with the same\n * name would trip the connector at runtime — a later preset overriding an\n * earlier preset's `github` server is the practical intent.\n */\nexport function composePresets(...presets: Preset[]): Preset {\n const out: Preset = {}\n const hooksByEvent: { [K in keyof AgentHooks]?: AgentHooks[K][] } = {}\n // Keep mcpServers in source-order on first sight, but allow later\n // declarations to override earlier ones with the same `name`. A `Map`\n // keyed by name gives O(1) override + stable iteration.\n const mcpByName = new Map<string, NonNullable<Preset['mcpServers']>[number]>()\n\n for (const p of presets) {\n if (p.name !== undefined)\n out.name = p.name\n if (p.system !== undefined)\n out.system = p.system\n if (p.eager !== undefined)\n out.eager = p.eager\n if (p.skills !== undefined)\n out.skills = p.skills\n if (p.tools)\n out.tools = { ...out.tools, ...p.tools }\n if (p.toolAliases)\n out.toolAliases = { ...out.toolAliases, ...p.toolAliases }\n if (p.behavior)\n out.behavior = { ...out.behavior, ...p.behavior }\n if (p.mcpServers) {\n for (const server of p.mcpServers)\n mcpByName.set(server.name, server)\n }\n if (p.hooks) {\n for (const [event, handler] of Object.entries(p.hooks)) {\n if (handler === undefined)\n continue\n const list = Array.isArray(handler) ? handler : [handler]\n const key = event as keyof AgentHooks\n // Safe cast: we read the loose `AgentHookMap` shape (handler-or-array)\n // and re-emit only as arrays. Each `list` element matches the event's\n // handler signature by construction (the input was typed `AgentHookMap`).\n const bucket = (hooksByEvent[key] ??= []) as unknown[]\n bucket.push(...(list as unknown[]))\n }\n }\n }\n\n if (mcpByName.size > 0)\n out.mcpServers = [...mcpByName.values()]\n\n if (Object.keys(hooksByEvent).length > 0)\n out.hooks = hooksByEvent\n\n return out\n}\n\nexport { default as basic, basicTools } from './basic'\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,aAAa;CAAE;CAAO;CAAU;CAAW;CAAW;CAAM;CAAW;AAEpF,IAAA,gBAAe,aAAa;CAC1B,MAAM;CACN,QAAQ;CAOR,OAAO;EAAE,GAAG;EAAY,OAAO,gBAAgB,EAAE,SAAS,MAAM,CAAC;EAAE;CACpE,CAAC;;;;;;ACOF,SAAgB,aAAa,QAAwB;CACnD,OAAO;;;;;;;;;;;;;;;;;;;;AAqBT,SAAgB,eAAe,GAAG,SAA2B;CAC3D,MAAM,MAAc,EAAE;CACtB,MAAM,eAA8D,EAAE;CAItE,MAAM,4BAAY,IAAI,KAAwD;CAE9E,KAAK,MAAM,KAAK,SAAS;EACvB,IAAI,EAAE,SAAS,KAAA,GACb,IAAI,OAAO,EAAE;EACf,IAAI,EAAE,WAAW,KAAA,GACf,IAAI,SAAS,EAAE;EACjB,IAAI,EAAE,UAAU,KAAA,GACd,IAAI,QAAQ,EAAE;EAChB,IAAI,EAAE,WAAW,KAAA,GACf,IAAI,SAAS,EAAE;EACjB,IAAI,EAAE,OACJ,IAAI,QAAQ;GAAE,GAAG,IAAI;GAAO,GAAG,EAAE;GAAO;EAC1C,IAAI,EAAE,aACJ,IAAI,cAAc;GAAE,GAAG,IAAI;GAAa,GAAG,EAAE;GAAa;EAC5D,IAAI,EAAE,UACJ,IAAI,WAAW;GAAE,GAAG,IAAI;GAAU,GAAG,EAAE;GAAU;EACnD,IAAI,EAAE,YACJ,KAAK,MAAM,UAAU,EAAE,YACrB,UAAU,IAAI,OAAO,MAAM,OAAO;EAEtC,IAAI,EAAE,OACJ,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,EAAE,MAAM,EAAE;GACtD,IAAI,YAAY,KAAA,GACd;GACF,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,UAAU,CAAC,QAAQ;GACzD,MAAM,MAAM;GAKZ,CADgB,aAAa,SAAS,EAAE,EACjC,KAAK,GAAI,KAAmB;;;CAKzC,IAAI,UAAU,OAAO,GACnB,IAAI,aAAa,CAAC,GAAG,UAAU,QAAQ,CAAC;CAE1C,IAAI,OAAO,KAAK,aAAa,CAAC,SAAS,GACrC,IAAI,QAAQ;CAEd,OAAO"}
package/dist/presets.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as AgentHookMap } from "./agent-BEtOGMct.js";
2
- import { a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-CYnIU6Pp.js";
1
+ import { n as AgentHookMap } from "./agent-CzHIRBSN.js";
2
+ import { a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-EqQH76lu.js";
3
3
  export { AgentHookMap, Preset, _default as basic, basicTools, composePresets, definePreset };
package/dist/presets.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as basic_default, n as definePreset, r as basicTools, t as composePresets } from "./presets-B800CKGw.js";
1
+ import { i as basic_default, n as definePreset, r as basicTools, t as composePresets } from "./presets-CXuvAWCQ.js";
2
2
  export { basic_default as basic, basicTools, composePresets, definePreset };
@@ -1,2 +1,2 @@
1
- import { $ as openrouter, G as ProviderCapabilities, J as ToolCall, K as StreamCallbacks, Q as OpenRouterParams, W as Provider, X as ToolSpec, Y as ToolResult, Z as TurnResult, at as openaiCompat, ct as CerebrasParams, dt as anthropic, et as OpenAICompatAuthHeader, it as mapOAIFinishReason, lt as cerebras, nt as OpenAICompatParams, ot as OpenAIParams, q as StreamOptions, rt as classifyOpenAICompatError, st as openai, tt as OpenAICompatHttpError, ut as AnthropicParams } from "./agent-BEtOGMct.js";
1
+ import { $ as openrouter, G as ProviderCapabilities, J as ToolCall, K as StreamCallbacks, Q as OpenRouterParams, W as Provider, X as ToolSpec, Y as ToolResult, Z as TurnResult, at as openaiCompat, ct as CerebrasParams, dt as anthropic, et as OpenAICompatAuthHeader, it as mapOAIFinishReason, lt as cerebras, nt as OpenAICompatParams, ot as OpenAIParams, q as StreamOptions, rt as classifyOpenAICompatError, st as openai, tt as OpenAICompatHttpError, ut as AnthropicParams } from "./agent-CzHIRBSN.js";
2
2
  export { AnthropicParams, CerebrasParams, OpenAICompatAuthHeader, OpenAICompatHttpError, OpenAICompatParams, OpenAIParams, OpenRouterParams, Provider, ProviderCapabilities, StreamCallbacks, StreamOptions, ToolCall, ToolResult, ToolSpec, TurnResult, anthropic, cerebras, classifyOpenAICompatError, mapOAIFinishReason, openai, openaiCompat, openrouter };
@@ -1,4 +1,4 @@
1
- import { A as SessionStore } from "../agent-BEtOGMct.js";
1
+ import { A as SessionStore } from "../agent-CzHIRBSN.js";
2
2
 
3
3
  //#region src/session/sqlite.d.ts
4
4
  interface SqliteStoreOptions {
package/dist/session.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as SessionStore, B as createMemoryStore, D as Session, Dt as SessionMessage, E as CreateSessionOptions, F as autoDetectAndConvert, H as FileMapStoreOptions, I as fromAnthropic, L as fromOpenAI, M as loadSession, N as RemoteStoreOptions, O as SessionData, Ot as SessionTurn, P as createRemoteStore, R as toAnthropic, U as createFileMapStore, V as FileMapAdapter, j as createSession, k as SessionRun, wt as SessionContentBlock, z as toOpenAI } from "./agent-BEtOGMct.js";
1
+ import { A as SessionStore, B as createMemoryStore, D as Session, Dt as SessionMessage, E as CreateSessionOptions, F as autoDetectAndConvert, H as FileMapStoreOptions, I as fromAnthropic, L as fromOpenAI, M as loadSession, N as RemoteStoreOptions, O as SessionData, Ot as SessionTurn, P as createRemoteStore, R as toAnthropic, U as createFileMapStore, V as FileMapAdapter, j as createSession, k as SessionRun, wt as SessionContentBlock, z as toOpenAI } from "./agent-CzHIRBSN.js";
2
2
  export { CreateSessionOptions, FileMapAdapter, FileMapStoreOptions, RemoteStoreOptions, Session, SessionContentBlock, SessionData, SessionMessage, SessionRun, SessionStore, SessionTurn, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, fromAnthropic, fromOpenAI, loadSession, toAnthropic, toOpenAI };
package/dist/skills.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { C as SkillResource, S as SkillDiagnostic, T as SkillsConfig, c as DeactivationReason, d as createSkillActivationState, l as SkillActivationState, o as ActivationVia, s as ActiveSkill, u as SkillActivationStateOptions, w as SkillSource, x as SkillConfig } from "./agent-BEtOGMct.js";
2
- import { S as installAllowedToolsGate, _ as inferSource, a as SkillValidationResult, b as buildCatalog, c as parseAllowedToolPattern, d as validateSkillName, f as resolveSkills, g as getDefaultScanPaths, h as discoverSkills, i as SkillValidationIssue, l as validateResourcePath, m as SourcedScanPath, n as writeSkillToDisk, o as isToolAllowedByUnion, p as interpolateShellCommands, r as writeSkillsToDisk, s as matchesAllowedTool, t as defineSkill, u as validateSkillForWrite, v as parseFrontmatter, x as IMPLICITLY_ALLOWED_SKILL_TOOLS, y as parseSkillFile } from "./index-CsJOjP5T.js";
1
+ import { C as SkillResource, S as SkillDiagnostic, T as SkillsConfig, c as DeactivationReason, d as createSkillActivationState, l as SkillActivationState, o as ActivationVia, s as ActiveSkill, u as SkillActivationStateOptions, w as SkillSource, x as SkillConfig } from "./agent-CzHIRBSN.js";
2
+ import { S as installAllowedToolsGate, _ as inferSource, a as SkillValidationResult, b as buildCatalog, c as parseAllowedToolPattern, d as validateSkillName, f as resolveSkills, g as getDefaultScanPaths, h as discoverSkills, i as SkillValidationIssue, l as validateResourcePath, m as SourcedScanPath, n as writeSkillToDisk, o as isToolAllowedByUnion, p as interpolateShellCommands, r as writeSkillsToDisk, s as matchesAllowedTool, t as defineSkill, u as validateSkillForWrite, v as parseFrontmatter, x as IMPLICITLY_ALLOWED_SKILL_TOOLS, y as parseSkillFile } from "./index-C0dEcjjn.js";
3
3
  export { ActivationVia, ActiveSkill, DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, SkillActivationState, SkillActivationStateOptions, SkillConfig, SkillDiagnostic, SkillResource, SkillSource, SkillValidationIssue, SkillValidationResult, SkillsConfig, SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, interpolateShellCommands, isToolAllowedByUnion, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, resolveSkills, validateResourcePath, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
@@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import process from "node:process";
3
3
  import { PassThrough } from "node:stream";
4
4
  import * as z from "zod/v4";
5
- //#region build/cross-spawn-shim.mjs
5
+ //#region scripts/cross-spawn-shim.mjs
6
6
  /**
7
7
  * Build-time replacement for the userland process-spawn helper that the
8
8
  * MCP SDK's stdio transport depends on. Injected by tsdown via the
@@ -2117,4 +2117,4 @@ var StdioClientTransport = class {
2117
2117
  //#endregion
2118
2118
  export { StdioClientTransport, getDefaultEnvironment };
2119
2119
 
2120
- //# sourceMappingURL=stdio-loader-C48v4hPt.js.map
2120
+ //# sourceMappingURL=stdio-loader-EVAF5KlU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stdio-loader-EVAF5KlU.js","names":["spawn","nodeSpawn","spawnSync","nodeSpawnSync","spawn"],"sources":["../scripts/cross-spawn-shim.mjs","../node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"],"sourcesContent":["/**\n * Build-time replacement for the userland process-spawn helper that the\n * MCP SDK's stdio transport depends on. Injected by tsdown via the\n * rolldown alias plugin in `tsdown.config.ts`.\n *\n * Why this exists\n *\n * The upstream spawn helper is CJS and its first line dynamically resolves\n * Node's process-spawn built-in via a bare specifier. When a downstream\n * consumer re-bundles zidane as ESM (esbuild / Vite / tsup with\n * `format: 'esm'` and Node built-ins not externalized), that bare\n * resolution gets wrapped in esbuild's `__require` shim and throws at\n * runtime — every stdio MCP server fails to launch.\n *\n * Aliasing the helper to this file at zidane's own build step replaces\n * the offending bare resolution with explicit `node:`-prefixed imports.\n * Downstream bundlers recognize the `node:` prefix as a Node built-in\n * and externalize it automatically. The upstream MCP SDK is unmodified.\n *\n * Tradeoff\n *\n * The replaced helper does two extra things vs. raw spawn:\n * 1. Windows `.cmd` / `.bat` / `.ps1` resolution via PATHEXT + cmd.exe\n * shelling. Compensated below with `shell: true` on Win32, which\n * routes through cmd.exe and handles the common `npx` / `pnpm` /\n * `yarn` shims.\n * 2. Synthesizes a clean ENOENT error event for missing commands.\n * `node:child_process.spawn` already emits a perfectly usable\n * `error` event with `code === 'ENOENT'`, which the MCP SDK's stdio\n * transport forwards to `onerror`. Functionally equivalent.\n *\n * Net: zero behavioural change on POSIX, near-identical on Windows for\n * MCP-style stdio invocations.\n */\n\nimport { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst IS_WIN32 = process.platform === 'win32'\n\nfunction withWin32Shell(options) {\n // Only opt into shell mode on Windows, and only when the caller hasn't\n // explicitly disabled it. POSIX never needs the shell wrapper — args\n // would have to be re-quoted (changes argv semantics) and trap/`set -e`\n // behaviour shifts in subtle ways.\n if (!IS_WIN32)\n return options\n if (options && options.shell !== undefined)\n return options\n return { ...(options ?? {}), shell: true }\n}\n\nexport function spawn(command, args, options) {\n return nodeSpawn(command, args, withWin32Shell(options))\n}\n\nexport function spawnSync(command, args, options) {\n return nodeSpawnSync(command, args, withWin32Shell(options))\n}\n\n// Match cross-spawn's CommonJS interop shape so existing imports keep\n// working byte-for-byte:\n// - default import: `import spawn from 'cross-spawn'` (SDK uses this)\n// - named import: `import { spawn, sync } from 'cross-spawn'`\n// - require pattern: `const cs = require('cross-spawn'); cs.sync(...)`\nspawn.spawn = spawn\nspawn.sync = spawnSync\n\nexport const sync = spawnSync\nexport default spawn\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","import { JSONRPCMessageSchema } from '../types.js';\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n append(chunk) {\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n readMessage() {\n if (!this._buffer) {\n return null;\n }\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n return deserializeMessage(line);\n }\n clear() {\n this._buffer = undefined;\n }\n}\nexport function deserializeMessage(line) {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\nexport function serializeMessage(message) {\n return JSON.stringify(message) + '\\n';\n}\n//# sourceMappingURL=stdio.js.map","import spawn from 'cross-spawn';\nimport process from 'node:process';\nimport { PassThrough } from 'node:stream';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Environment variables to inherit by default, if an environment is not explicitly given.\n */\nexport const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32'\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n 'PROGRAMFILES'\n ]\n : /* list inspired by the default env inheritance of sudo */\n ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n/**\n * Returns a default environment object including only environment variables deemed safe to inherit.\n */\nexport function getDefaultEnvironment() {\n const env = {};\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n const value = process.env[key];\n if (value === undefined) {\n continue;\n }\n if (value.startsWith('()')) {\n // Skip functions, which are a security risk.\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n/**\n * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioClientTransport {\n constructor(server) {\n this._readBuffer = new ReadBuffer();\n this._stderrStream = null;\n this._serverParams = server;\n if (server.stderr === 'pipe' || server.stderr === 'overlapped') {\n this._stderrStream = new PassThrough();\n }\n }\n /**\n * Starts the server process and prepares to communicate with it.\n */\n async start() {\n if (this._process) {\n throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return new Promise((resolve, reject) => {\n this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {\n // merge default env with server env because mcp server needs some env vars\n env: {\n ...getDefaultEnvironment(),\n ...this._serverParams.env\n },\n stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],\n shell: false,\n windowsHide: process.platform === 'win32',\n cwd: this._serverParams.cwd\n });\n this._process.on('error', error => {\n reject(error);\n this.onerror?.(error);\n });\n this._process.on('spawn', () => {\n resolve();\n });\n this._process.on('close', _code => {\n this._process = undefined;\n this.onclose?.();\n });\n this._process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n this._process.stdout?.on('data', chunk => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n });\n this._process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n if (this._stderrStream && this._process.stderr) {\n this._process.stderr.pipe(this._stderrStream);\n }\n });\n }\n /**\n * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to \"pipe\" or \"overlapped\".\n *\n * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to\n * attach listeners before the start method is invoked. This prevents loss of any early\n * error output emitted by the child process.\n */\n get stderr() {\n if (this._stderrStream) {\n return this._stderrStream;\n }\n return this._process?.stderr ?? null;\n }\n /**\n * The child process pid spawned by this transport.\n *\n * This is only available after the transport has been started.\n */\n get pid() {\n return this._process?.pid ?? null;\n }\n processReadBuffer() {\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n async close() {\n if (this._process) {\n const processToClose = this._process;\n this._process = undefined;\n const closePromise = new Promise(resolve => {\n processToClose.once('close', () => {\n resolve();\n });\n });\n try {\n processToClose.stdin?.end();\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGTERM');\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n }\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGKILL');\n }\n catch {\n // ignore\n }\n }\n }\n this._readBuffer.clear();\n }\n send(message) {\n return new Promise(resolve => {\n if (!this._process?.stdin) {\n throw new Error('Not connected');\n }\n const json = serializeMessage(message);\n if (this._process.stdin.write(json)) {\n resolve();\n }\n else {\n this._process.stdin.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map"],"x_google_ignoreList":[1,2,3],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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