codeden 0.6.1 → 0.6.3

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 (39) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +187 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/drizzle/20261112095507_inbox_notify/migration.sql +1 -0
  4. package/dist/drizzle/20261112095507_inbox_notify/snapshot.json +3514 -0
  5. package/dist/drizzle/20261112140714_turn_fork_point/migration.sql +1 -0
  6. package/dist/drizzle/20261112140714_turn_fork_point/snapshot.json +3524 -0
  7. package/dist/{main-BTA6NERX.js → main-Bx58CdV4.js} +6343 -14677
  8. package/dist/main-Bx58CdV4.js.map +1 -0
  9. package/dist/{main-DgIYOEGD.js → main-CMt4z1Z9.js} +2 -2
  10. package/dist/{main-DgIYOEGD.js.map → main-CMt4z1Z9.js.map} +1 -1
  11. package/dist/mediaType-BCz-hbZl.js +9731 -0
  12. package/dist/mediaType-BCz-hbZl.js.map +1 -0
  13. package/dist/{runner-C59QJvYP.js → runner-CiaiUWOE.js} +1367 -13438
  14. package/dist/runner-CiaiUWOE.js.map +1 -0
  15. package/dist/runner.js +1 -1
  16. package/dist/server-test-b0hHPqXb.js +3766 -0
  17. package/dist/server-test-b0hHPqXb.js.map +1 -0
  18. package/dist/tree-31WAOm5k.js +13481 -0
  19. package/dist/tree-31WAOm5k.js.map +1 -0
  20. package/dist/web/assets/{core-BE80EdZx.js → core-FqX7NQzW.js} +1 -1
  21. package/dist/web/assets/engine-oniguruma-C5UP18m1.js +1 -0
  22. package/dist/web/assets/{highlighted-body-JLMTFACH-DKf-ZukU.js → highlighted-body-JLMTFACH-BMKFJRL-.js} +1 -1
  23. package/dist/web/assets/{highlights-CXgTTgn7.js → highlights-9yuGk1pg.js} +1 -1
  24. package/dist/web/assets/index-C3QkKvUn.js +942 -0
  25. package/dist/web/assets/index-CmllrYFx.css +1 -0
  26. package/dist/web/assets/langs-DfCgj44a.js +1 -0
  27. package/dist/web/assets/mermaid-WFAXDIZX-zTA5f8lD.js +1 -0
  28. package/dist/web/assets/{shiki-BoVdalr2.js → shiki-Qa-y3xHo.js} +2 -2
  29. package/dist/web/assets/{stream-tokenizer-Ccxf5ToF.js → stream-tokenizer-VL43-ily.js} +1 -1
  30. package/dist/web/assets/{themes-C9K67wea.js → themes-Di4DO5zr.js} +2 -2
  31. package/dist/web/index.html +2 -2
  32. package/package.json +1 -1
  33. package/dist/main-BTA6NERX.js.map +0 -1
  34. package/dist/runner-C59QJvYP.js.map +0 -1
  35. package/dist/web/assets/engine-oniguruma-CYbHTBkj.js +0 -1
  36. package/dist/web/assets/index-Bq-TWYoS.css +0 -1
  37. package/dist/web/assets/index-Cr_5sx1k.js +0 -937
  38. package/dist/web/assets/langs-2fbnR5VK.js +0 -1
  39. package/dist/web/assets/mermaid-WFAXDIZX-VZd02gKu.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-test-b0hHPqXb.js","names":["z\n .url","z.NEVER","z.looseObject","z.string","z.array","z.boolean","z.object","z\n .object","z.coerce.number","z.literal","z.any","z.number","crossSpawn"],"sources":["../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js","../../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js","../../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/stream.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../../runner/src/mcp/resolve-spec.ts","../../runner/src/mcp/stdio-env.ts","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js","../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js","../../runner/src/mcp/stdio-transport.ts","../../runner/src/mcp/server-test.ts"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n constructor(_client) {\n this._client = _client;\n }\n /**\n * Calls a tool and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to tool execution, allowing you to\n * observe intermediate task status updates for long-running tool calls.\n * Automatically validates structured output if the tool has an outputSchema.\n *\n * @example\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Tool execution started:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Tool status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Tool result:', message.result);\n * break;\n * case 'error':\n * console.error('Tool error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - Tool call parameters (name and arguments)\n * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n // Access Client's internal methods\n const clientInternal = this._client;\n // Add task creation parameters if server supports it and not explicitly provided\n const optionsWithTask = {\n ...options,\n // We check if the tool is known to be a task during auto-configuration, but assume\n // the caller knows what they're doing if they pass this explicitly\n task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n };\n const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n // Get the validator for this tool (if it has an output schema)\n const validator = clientInternal.getToolOutputValidator(params.name);\n // Iterate through the stream and validate the final result if needed\n for await (const message of stream) {\n // If this is a result message and the tool has an output schema, validate it\n if (message.type === 'result' && validator) {\n const result = message.result;\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n };\n return;\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n };\n return;\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n yield { type: 'error', error };\n return;\n }\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n };\n return;\n }\n }\n }\n // Yield the message (either validated result or any other message type)\n yield message;\n }\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._client.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.cancelTask({ taskId }, options);\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._client.requestStream(request, resultSchema, options);\n }\n}\n//# sourceMappingURL=client.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getLiteralValue, getObjectShape, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n if (!schema || data === null || typeof data !== 'object')\n return;\n // Handle object properties\n if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n const obj = data;\n const props = schema.properties;\n for (const key of Object.keys(props)) {\n const propSchema = props[key];\n // If missing or explicitly undefined, apply default if present\n if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n obj[key] = propSchema.default;\n }\n // Recurse into existing nested objects/arrays\n if (obj[key] !== undefined) {\n applyElicitationDefaults(propSchema, obj[key]);\n }\n }\n }\n if (Array.isArray(schema.anyOf)) {\n for (const sub of schema.anyOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n // Combine schemas\n if (Array.isArray(schema.oneOf)) {\n for (const sub of schema.oneOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n if (!capabilities) {\n return { supportsFormMode: false, supportsUrlMode: false };\n }\n const hasFormCapability = capabilities.form !== undefined;\n const hasUrlCapability = capabilities.url !== undefined;\n // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n const supportsUrlMode = hasUrlCapability;\n return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomClient\",\n * version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n /**\n * Initializes this client with the given name and version information.\n */\n constructor(_clientInfo, options) {\n super(options);\n this._clientInfo = _clientInfo;\n this._cachedToolOutputValidators = new Map();\n this._cachedKnownTaskTools = new Set();\n this._cachedRequiredTaskTools = new Set();\n this._listChangedDebounceTimers = new Map();\n this._capabilities = options?.capabilities ?? {};\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n // Store list changed config for setup after connection (when we know server capabilities)\n if (options?.listChanged) {\n this._pendingListChangedConfig = options.listChanged;\n }\n }\n /**\n * Set up handlers for list changed notifications based on config and server capabilities.\n * This should only be called after initialization when server capabilities are known.\n * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n * @internal\n */\n _setupListChangedHandlers(config) {\n if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n const result = await this.listTools();\n return result.tools;\n });\n }\n if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n const result = await this.listPrompts();\n return result.prompts;\n });\n }\n if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n const result = await this.listResources();\n return result.resources;\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalClientTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce client-side validation for elicitation.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const methodValue = getLiteralValue(methodSchema);\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'elicitation/create') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(ElicitRequestSchema, request);\n if (!validatedRequest.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n params.mode = params.mode ?? 'form';\n const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n if (params.mode === 'form' && !supportsFormMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n }\n if (params.mode === 'url' && !supportsUrlMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n }\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against ElicitResultSchema\n const validationResult = safeParse(ElicitResultSchema, result);\n if (!validationResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n }\n const validatedResult = validationResult.data;\n const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n if (this._capabilities.elicitation?.form?.applyDefaults) {\n try {\n applyElicitationDefaults(requestedSchema, validatedResult.content);\n }\n catch {\n // gracefully ignore errors in default application\n }\n }\n }\n return validatedResult;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n if (method === 'sampling/createMessage') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against appropriate schema based on tools presence\n const hasTools = params.tools || params.toolChoice;\n const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;\n const validationResult = safeParse(resultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapability(capability, method) {\n if (!this._serverCapabilities?.[capability]) {\n throw new Error(`Server does not support ${capability} (required for ${method})`);\n }\n }\n async connect(transport, options) {\n await super.connect(transport);\n // When transport sessionId is already set this means we are trying to reconnect.\n // In this case we don't need to initialize again.\n if (transport.sessionId !== undefined) {\n return;\n }\n try {\n const result = await this.request({\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: this._capabilities,\n clientInfo: this._clientInfo\n }\n }, InitializeResultSchema, options);\n if (result === undefined) {\n throw new Error(`Server sent invalid initialize result: ${result}`);\n }\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n }\n this._serverCapabilities = result.capabilities;\n this._serverVersion = result.serverInfo;\n // HTTP transports must set the protocol version in each header after initialization.\n if (transport.setProtocolVersion) {\n transport.setProtocolVersion(result.protocolVersion);\n }\n this._instructions = result.instructions;\n await this.notification({\n method: 'notifications/initialized'\n });\n // Set up list changed handlers now that we know server capabilities\n if (this._pendingListChangedConfig) {\n this._setupListChangedHandlers(this._pendingListChangedConfig);\n this._pendingListChangedConfig = undefined;\n }\n }\n catch (error) {\n // Disconnect if initialization fails.\n void this.close();\n throw error;\n }\n }\n /**\n * After initialization has completed, this will be populated with the server's reported capabilities.\n */\n getServerCapabilities() {\n return this._serverCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the server's name and version.\n */\n getServerVersion() {\n return this._serverVersion;\n }\n /**\n * After initialization has completed, this may be populated with information about the server's instructions.\n */\n getInstructions() {\n return this._instructions;\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'logging/setLevel':\n if (!this._serverCapabilities?.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._serverCapabilities?.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!this._serverCapabilities?.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._serverCapabilities?.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'completion/complete':\n if (!this._serverCapabilities?.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'initialize':\n // No specific capability required for initialize\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/roots/list_changed':\n if (!this._capabilities.roots?.listChanged) {\n throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n }\n break;\n case 'notifications/initialized':\n // No specific capability required for initialized\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!this._capabilities.sampling) {\n throw new Error(`Client does not support sampling capability (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._capabilities.elicitation) {\n throw new Error(`Client does not support elicitation capability (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._capabilities.roots) {\n throw new Error(`Client does not support roots capability (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Client does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertTaskCapability(method) {\n assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n }\n async ping(options) {\n return this.request({ method: 'ping' }, EmptyResultSchema, options);\n }\n async complete(params, options) {\n return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n }\n async setLoggingLevel(level, options) {\n return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n }\n async getPrompt(params, options) {\n return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n }\n async listPrompts(params, options) {\n return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n }\n async listResources(params, options) {\n return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n }\n async listResourceTemplates(params, options) {\n return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n }\n async readResource(params, options) {\n return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n }\n async subscribeResource(params, options) {\n return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n }\n async unsubscribeResource(params, options) {\n return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n }\n /**\n * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n *\n * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n */\n async callTool(params, resultSchema = CallToolResultSchema, options) {\n // Guard: required-task tools need experimental API\n if (this.isToolTaskRequired(params.name)) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n }\n const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n // Check if the tool has an outputSchema\n const validator = this.getToolOutputValidator(params.name);\n if (validator) {\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n return result;\n }\n isToolTask(toolName) {\n if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n return false;\n }\n return this._cachedKnownTaskTools.has(toolName);\n }\n /**\n * Check if a tool requires task-based execution.\n * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n */\n isToolTaskRequired(toolName) {\n return this._cachedRequiredTaskTools.has(toolName);\n }\n /**\n * Cache validators for tool output schemas.\n * Called after listTools() to pre-compile validators for better performance.\n */\n cacheToolMetadata(tools) {\n this._cachedToolOutputValidators.clear();\n this._cachedKnownTaskTools.clear();\n this._cachedRequiredTaskTools.clear();\n for (const tool of tools) {\n // If the tool has an outputSchema, create and cache the validator\n if (tool.outputSchema) {\n const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n this._cachedToolOutputValidators.set(tool.name, toolValidator);\n }\n // If the tool supports task-based execution, cache that information\n const taskSupport = tool.execution?.taskSupport;\n if (taskSupport === 'required' || taskSupport === 'optional') {\n this._cachedKnownTaskTools.add(tool.name);\n }\n if (taskSupport === 'required') {\n this._cachedRequiredTaskTools.add(tool.name);\n }\n }\n }\n /**\n * Get cached validator for a tool\n */\n getToolOutputValidator(toolName) {\n return this._cachedToolOutputValidators.get(toolName);\n }\n async listTools(params, options) {\n const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n // Cache the tools and their output schemas for future validation\n this.cacheToolMetadata(result.tools);\n return result;\n }\n /**\n * Set up a single list changed handler.\n * @internal\n */\n _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n // Validate options using Zod schema (validates autoRefresh and debounceMs)\n const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n if (!parseResult.success) {\n throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n }\n // Validate callback\n if (typeof options.onChanged !== 'function') {\n throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n }\n const { autoRefresh, debounceMs } = parseResult.data;\n const { onChanged } = options;\n const refresh = async () => {\n if (!autoRefresh) {\n onChanged(null, null);\n return;\n }\n try {\n const items = await fetcher();\n onChanged(null, items);\n }\n catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onChanged(error, null);\n }\n };\n const handler = () => {\n if (debounceMs) {\n // Clear any pending debounce timer for this list type\n const existingTimer = this._listChangedDebounceTimers.get(listType);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n // Set up debounced refresh\n const timer = setTimeout(refresh, debounceMs);\n this._listChangedDebounceTimers.set(listType, timer);\n }\n else {\n // No debounce, refresh immediately\n refresh();\n }\n };\n // Register notification handler\n this.setNotificationHandler(notificationSchema, handler);\n }\n async sendRootsListChanged() {\n return this.notification({ method: 'notifications/roots/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(config) {\n if (typeof config == \"function\")\n throw new TypeError(\n \"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];\n let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType, terminated = !1;\n function feed(chunk) {\n if (terminated)\n throw new Error(\n \"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.\"\n );\n if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n const trailing2 = processLines(chunk);\n trailing2 !== \"\" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();\n return;\n }\n if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();\n return;\n }\n pendingFragments.push(chunk);\n const input = pendingFragments.join(\"\");\n pendingFragments.length = 0, pendingFragmentsLength = 0;\n const trailing = processLines(input);\n trailing !== \"\" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();\n }\n function checkBufferSize() {\n maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: \"max-buffer-size-exceeded\"\n })\n )));\n }\n function processLines(chunk) {\n let searchIndex = 0;\n if (chunk.indexOf(\"\\r\") === -1) {\n let lfIndex = chunk.indexOf(`\n`, searchIndex);\n for (; lfIndex !== -1; ) {\n if (searchIndex === lfIndex) {\n dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex\n ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n break;\n parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n return;\n }\n if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n value2.includes(\"\\0\") || (id = value2);\n return;\n }\n if (firstCharCode === 58) {\n if (onComment) {\n const line2 = chunk.slice(start, end);\n onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex === -1) {\n processField(line, \"\", line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value || void 0;\n break;\n case \"data\":\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n break;\n case \"id\":\n value.includes(\"\\0\") || (id = value);\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n dataLines > 0 && onEvent({\n id,\n event: eventType,\n data\n }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join(\"\");\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;\n }\n return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"eventsource-parser\";\nclass ErrorEvent extends Event {\n /**\n * Constructs a new `ErrorEvent` instance. This is typically not called directly,\n * but rather emitted by the `EventSource` object when an error occurs.\n *\n * @param type - The type of the event (should be \"error\")\n * @param errorEventInitDict - Optional properties to include in the error event\n */\n constructor(type, errorEventInitDict) {\n var _a, _b;\n super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;\n }\n /**\n * Node.js \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n * we explicitly include the properties in the `inspect` method.\n *\n * This is automatically called by Node.js when you `console.log` an instance of this class.\n *\n * @param _depth - The current depth\n * @param options - The options passed to `util.inspect`\n * @param inspect - The inspect function to use (prevents having to import it from `util`)\n * @returns A string representation of the error\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](_depth, options, inspect) {\n return inspect(inspectableError(this), options);\n }\n /**\n * Deno \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n * we explicitly include the properties in the `inspect` method.\n *\n * This is automatically called by Deno when you `console.log` an instance of this class.\n *\n * @param inspect - The inspect function to use (prevents having to import it from `util`)\n * @param options - The options passed to `Deno.inspect`\n * @returns A string representation of the error\n */\n [Symbol.for(\"Deno.customInspect\")](inspect, options) {\n return inspect(inspectableError(this), options);\n }\n}\nfunction syntaxError(message) {\n const DomException = globalThis.DOMException;\n return typeof DomException == \"function\" ? new DomException(message, \"SyntaxError\") : new SyntaxError(message);\n}\nfunction flattenError(err) {\n return err instanceof Error ? \"errors\" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(\", \") : \"cause\" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;\n}\nfunction inspectableError(err) {\n return {\n type: err.type,\n message: err.message,\n code: err.code,\n defaultPrevented: err.defaultPrevented,\n cancelable: err.cancelable,\n timeStamp: err.timeStamp\n };\n}\nvar __typeError = (msg) => {\n throw TypeError(msg);\n}, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError(\"Cannot \" + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, \"read from private field\"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError(\"Cannot add the same private member more than once\") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, \"write to private field\"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, \"access private method\"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect;\nclass EventSource extends EventTarget {\n constructor(url, eventSourceInitDict) {\n var _a, _b;\n super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {\n var _a2;\n __privateGet(this, _parser).reset();\n const { body, redirected, status, headers } = response;\n if (status === 204) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, \"Server sent HTTP 204, not reconnecting\", 204), this.close();\n return;\n }\n if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);\n return;\n }\n if (!(headers.get(\"content-type\") || \"\").startsWith(\"text/event-stream\")) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected \"text/event-stream\"', status);\n return;\n }\n if (__privateGet(this, _readyState) === this.CLOSED)\n return;\n __privateSet(this, _readyState, this.OPEN);\n const openEvent = new Event(\"open\");\n if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != \"object\" || !body || !(\"getReader\" in body)) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, \"Invalid response body, expected a web ReadableStream\", status), this.close();\n return;\n }\n const decoder = new TextDecoder(), reader = body.getReader();\n let open = !0;\n do {\n const { done, value } = await reader.read();\n value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));\n } while (open);\n }), __privateAdd(this, _onFetchError, (err) => {\n __privateSet(this, _controller, void 0), !(err.name === \"AbortError\" || err.type === \"aborted\") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));\n }), __privateAdd(this, _onEvent, (event) => {\n typeof event.id == \"string\" && __privateSet(this, _lastEventId, event.id);\n const messageEvent = new MessageEvent(event.event || \"message\", {\n data: event.data,\n origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,\n lastEventId: event.id || \"\"\n });\n __privateGet(this, _onMessage) && (!event.event || event.event === \"message\") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);\n }), __privateAdd(this, _onRetryChange, (value) => {\n __privateSet(this, _reconnectInterval, value);\n }), __privateAdd(this, _reconnect, () => {\n __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);\n });\n try {\n if (url instanceof URL)\n __privateSet(this, _url, url);\n else if (typeof url == \"string\")\n __privateSet(this, _url, new URL(url, getBaseURL()));\n else\n throw new Error(\"Invalid URL\");\n } catch {\n throw syntaxError(\"An invalid or illegal string was specified\");\n }\n __privateSet(this, _parser, createParser({\n onEvent: __privateGet(this, _onEvent),\n onRetry: __privateGet(this, _onRetryChange)\n })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);\n }\n /**\n * Returns the state of this EventSource object's connection. It can have the values described below.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)\n *\n * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,\n * defined in the TypeScript `dom` library.\n *\n * @public\n */\n get readyState() {\n return __privateGet(this, _readyState);\n }\n /**\n * Returns the URL providing the event stream.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)\n *\n * @public\n */\n get url() {\n return __privateGet(this, _url).href;\n }\n /**\n * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \"include\", and false otherwise.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)\n */\n get withCredentials() {\n return __privateGet(this, _withCredentials);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n get onerror() {\n return __privateGet(this, _onError);\n }\n set onerror(value) {\n __privateSet(this, _onError, value);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n get onmessage() {\n return __privateGet(this, _onMessage);\n }\n set onmessage(value) {\n __privateSet(this, _onMessage, value);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n get onopen() {\n return __privateGet(this, _onOpen);\n }\n set onopen(value) {\n __privateSet(this, _onOpen, value);\n }\n addEventListener(type, listener, options) {\n const listen = listener;\n super.addEventListener(type, listen, options);\n }\n removeEventListener(type, listener, options) {\n const listen = listener;\n super.removeEventListener(type, listen, options);\n }\n /**\n * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)\n *\n * @public\n */\n close() {\n __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));\n }\n}\n_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**\n* Connect to the given URL and start receiving events\n*\n* @internal\n*/\nconnect_fn = function() {\n __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));\n}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**\n* Get request options for the `fetch()` request\n*\n* @returns The request options\n* @internal\n*/\ngetRequestOptions_fn = function() {\n var _a;\n const init = {\n // [spec] Let `corsAttributeState` be `Anonymous`…\n // [spec] …will have their mode set to \"cors\"…\n mode: \"cors\",\n redirect: \"follow\",\n headers: { Accept: \"text/event-stream\", ...__privateGet(this, _lastEventId) ? { \"Last-Event-ID\": __privateGet(this, _lastEventId) } : void 0 },\n cache: \"no-store\",\n signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal\n };\n return \"window\" in globalThis && (init.credentials = this.withCredentials ? \"include\" : \"same-origin\"), init;\n}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**\n* Handles the process referred to in the EventSource specification as \"failing a connection\".\n*\n* @param error - The error causing the connection to fail\n* @param code - The HTTP status code, if available\n* @internal\n*/\nfailConnection_fn = function(message, code) {\n var _a;\n __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);\n const errorEvent = new ErrorEvent(\"error\", { code, message });\n (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);\n}, /**\n* Schedules a reconnection attempt against the EventSource endpoint.\n*\n* @param message - The error causing the connection to fail\n* @param code - The HTTP status code, if available\n* @internal\n*/\nscheduleReconnect_fn = function(message, code) {\n var _a;\n if (__privateGet(this, _readyState) === this.CLOSED)\n return;\n __privateSet(this, _readyState, this.CONNECTING);\n const errorEvent = new ErrorEvent(\"error\", { code, message });\n (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));\n}, _reconnect = /* @__PURE__ */ new WeakMap(), /**\n* ReadyState representing an EventSource currently trying to connect\n*\n* @public\n*/\nEventSource.CONNECTING = 0, /**\n* ReadyState representing an EventSource connection that is open (eg connected)\n*\n* @public\n*/\nEventSource.OPEN = 1, /**\n* ReadyState representing an EventSource connection that is closed (eg disconnected)\n*\n* @public\n*/\nEventSource.CLOSED = 2;\nfunction getBaseURL() {\n const doc = \"document\" in globalThis ? globalThis.document : void 0;\n return doc && typeof doc == \"object\" && \"baseURI\" in doc && typeof doc.baseURI == \"string\" ? doc.baseURI : void 0;\n}\nexport {\n ErrorEvent,\n EventSource\n};\n//# sourceMappingURL=index.js.map\n","/**\n * Normalizes HeadersInit to a plain Record<string, string> for manipulation.\n * Handles Headers objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers) {\n if (!headers)\n return {};\n if (headers instanceof Headers) {\n return Object.fromEntries(headers.entries());\n }\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n return { ...headers };\n}\n/**\n * Creates a fetch function that includes base RequestInit options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global fetch)\n * @param baseInit - The base RequestInit to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch = fetch, baseInit) {\n if (!baseInit) {\n return baseFetch;\n }\n // Return a wrapped fetch that merges base RequestInit with call-specific init\n return async (url, init) => {\n const mergedInit = {\n ...baseInit,\n ...init,\n // Headers need special handling - merge instead of replace\n headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n };\n return baseFetch(url, mergedInit);\n };\n}\nconst MAX_REDIRECTS = 5;\nconst REDIRECT_STATUSES = [301, 302, 303, 307, 308];\n/** @internal Whether `to` has the scheme, host and port of `from`, or is its https form with both on default ports. */\nexport function isWithinOrigin(from, to) {\n if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) {\n return true;\n }\n return from.hostname === to.hostname && from.protocol === 'http:' && from.port === '' && to.protocol === 'https:' && to.port === '';\n}\nfunction redirectTarget(response, requestUrl) {\n const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get('location') : null;\n try {\n return location ? new URL(location, requestUrl) : undefined;\n }\n catch {\n return undefined;\n }\n}\n/** @internal Follows the redirect in `response` while it stays within the origin of `url`; undefined when `response` is to be used as is. */\nexport function followWithinOrigin(baseFetch, url, init, response, followed = 0) {\n const target = redirectTarget(response, url);\n // 301, 302 and 303 turn a request with a body into a GET, so only 307 and 308 are followed for those.\n const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? 'GET').toUpperCase() === 'GET';\n if (!target || followed === MAX_REDIRECTS || !keepsMethod) {\n return undefined;\n }\n const from = new URL(url);\n const addsUserinfo = (target.username || target.password) && (target.username !== from.username || target.password !== from.password);\n if (addsUserinfo || !isWithinOrigin(from, target)) {\n return undefined;\n }\n return Promise.resolve(response.body?.cancel())\n .then(() => baseFetch(target, { ...init, redirect: 'manual' }))\n .then(next => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);\n}\nconst followingFetches = new WeakSet();\n/** @internal Wraps a fetch for `redirectPolicy: 'follow'`: `fetchWithinOrigin` returns the result as it is, so redirects are left to the fetch. */\nexport function fetchLeavingRedirects(baseFetch) {\n const following = (url, init) => (baseFetch ?? fetch)(url, init);\n followingFetches.add(following);\n return following;\n}\n/** @internal Wraps a fetch so it follows a redirect only within the request's origin; any other redirect response is returned as is. */\nexport function fetchWithinOrigin(baseFetch = fetch) {\n if (followingFetches.has(baseFetch)) {\n return baseFetch;\n }\n return (url, init) => {\n if (init?.redirect === 'error' || init?.redirect === 'manual') {\n return baseFetch(url, init);\n }\n // Browsers answer a manual redirect with an opaque response: it is returned and nothing is followed.\n return Promise.resolve(baseFetch(url, { ...init, redirect: 'manual' })).then(response => followWithinOrigin(baseFetch, url, init, response) ?? response);\n };\n}\n/** @internal Describes a redirect that `fetchWithinOrigin` returned unfollowed, naming its target without userinfo, query or fragment. */\nexport function unfollowedRedirect(response, requestUrl) {\n if (response.type === 'opaqueredirect') {\n return 'Redirect not followed: this runtime does not expose the redirect target';\n }\n const from = response.url || requestUrl;\n const target = redirectTarget(response, from);\n if (!target) {\n return undefined;\n }\n target.username = target.password = target.search = target.hash = '';\n if (target.protocol === 'http:' && new URL(from).protocol === 'https:') {\n target.protocol = 'https:';\n return `Redirect to plain http not followed; try ${target.href} instead`;\n }\n return `Redirect to ${target.href} not followed`;\n}\n//# sourceMappingURL=transport.js.map","let crypto;\ncrypto =\n globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n globalThis.crypto ?? // Node.js >18\n import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n let result = \"\";\n while (result.length < size) {\n const randomBytes = await getRandomValues(size - result.length);\n for (const randomByte of randomBytes) {\n if (randomByte < evenDistCutoff) {\n result += mask[randomByte % mask.length];\n }\n }\n }\n return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n // Generate base64url string\n // btoa is deprecated in Node.js but is used here for web browser compatibility\n // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n if (!length)\n length = 43;\n if (length < 43 || length > 128) {\n throw `Expected a length between 43 and 128. Received ${length}.`;\n }\n const verifier = await generateVerifier(length);\n const challenge = await generateChallenge(verifier);\n return {\n code_verifier: verifier,\n code_challenge: challenge,\n };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n const actualChallenge = await generateChallenge(code_verifier);\n return actualChallenge === expectedChallenge;\n}\n","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n return z.NEVER;\n }\n})\n .refine(url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional(),\n /**\n * Not part of the wire format: the authorization server this value was obtained from, added by\n * the client's `auth()` before it is stored and compared when it is read back.\n */\n issuer: z.string().optional().catch(undefined)\n})\n .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional(),\n /**\n * Not part of the wire format: the authorization server this value was obtained from, added by\n * the client's `auth()` before it is stored and compared when it is read back.\n */\n issuer: z.string().optional().catch(undefined)\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n})\n .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n})\n .strip();\n//# sourceMappingURL=auth.js.map","/**\n * Utilities for handling OAuth resource URIs.\n */\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url) {\n const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n resourceURL.hash = ''; // Remove fragment\n return resourceURL;\n}\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param requestedResource The resource URL being requested\n * @param configuredResource The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({ requestedResource, configuredResource }) {\n const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n // Compare the origin (scheme, domain, and port)\n if (requested.origin !== configured.origin) {\n return false;\n }\n // Handle cases like requested=/foo and configured=/foo/\n if (requested.pathname.length < configured.pathname.length) {\n return false;\n }\n // Check if the requested path starts with the configured path\n // Ensure both paths end with / for proper comparison\n // This ensures that if we have paths like \"/api\" and \"/api/users\",\n // we properly detect that \"/api/users\" is a subpath of \"/api\"\n // By adding a trailing slash if missing, we avoid false positives\n // where paths like \"/api123\" would incorrectly match \"/api\"\n const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n return requestedPath.startsWith(configuredPath);\n}\n//# sourceMappingURL=auth-utils.js.map","/**\n * Base class for all OAuth errors\n */\nexport class OAuthError extends Error {\n constructor(message, errorUri) {\n super(message);\n this.errorUri = errorUri;\n this.name = this.constructor.name;\n }\n /**\n * Converts the error to a standard OAuth error response object\n */\n toResponseObject() {\n const response = {\n error: this.errorCode,\n error_description: this.message\n };\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n return response;\n }\n get errorCode() {\n return this.constructor.errorCode;\n }\n}\n/**\n * Invalid request error - The request is missing a required parameter,\n * includes an invalid parameter value, includes a parameter more than once,\n * or is otherwise malformed.\n */\nexport class InvalidRequestError extends OAuthError {\n}\nInvalidRequestError.errorCode = 'invalid_request';\n/**\n * Invalid client error - Client authentication failed (e.g., unknown client, no client\n * authentication included, or unsupported authentication method).\n */\nexport class InvalidClientError extends OAuthError {\n}\nInvalidClientError.errorCode = 'invalid_client';\n/**\n * Invalid grant error - The provided authorization grant or refresh token is\n * invalid, expired, revoked, does not match the redirection URI used in the\n * authorization request, or was issued to another client.\n */\nexport class InvalidGrantError extends OAuthError {\n}\nInvalidGrantError.errorCode = 'invalid_grant';\n/**\n * Unauthorized client error - The authenticated client is not authorized to use\n * this authorization grant type.\n */\nexport class UnauthorizedClientError extends OAuthError {\n}\nUnauthorizedClientError.errorCode = 'unauthorized_client';\n/**\n * Unsupported grant type error - The authorization grant type is not supported\n * by the authorization server.\n */\nexport class UnsupportedGrantTypeError extends OAuthError {\n}\nUnsupportedGrantTypeError.errorCode = 'unsupported_grant_type';\n/**\n * Invalid scope error - The requested scope is invalid, unknown, malformed, or\n * exceeds the scope granted by the resource owner.\n */\nexport class InvalidScopeError extends OAuthError {\n}\nInvalidScopeError.errorCode = 'invalid_scope';\n/**\n * Access denied error - The resource owner or authorization server denied the request.\n */\nexport class AccessDeniedError extends OAuthError {\n}\nAccessDeniedError.errorCode = 'access_denied';\n/**\n * Server error - The authorization server encountered an unexpected condition\n * that prevented it from fulfilling the request.\n */\nexport class ServerError extends OAuthError {\n}\nServerError.errorCode = 'server_error';\n/**\n * Temporarily unavailable error - The authorization server is currently unable to\n * handle the request due to a temporary overloading or maintenance of the server.\n */\nexport class TemporarilyUnavailableError extends OAuthError {\n}\nTemporarilyUnavailableError.errorCode = 'temporarily_unavailable';\n/**\n * Unsupported response type error - The authorization server does not support\n * obtaining an authorization code using this method.\n */\nexport class UnsupportedResponseTypeError extends OAuthError {\n}\nUnsupportedResponseTypeError.errorCode = 'unsupported_response_type';\n/**\n * Unsupported token type error - The authorization server does not support\n * the requested token type.\n */\nexport class UnsupportedTokenTypeError extends OAuthError {\n}\nUnsupportedTokenTypeError.errorCode = 'unsupported_token_type';\n/**\n * Invalid token error - The access token provided is expired, revoked, malformed,\n * or invalid for other reasons.\n */\nexport class InvalidTokenError extends OAuthError {\n}\nInvalidTokenError.errorCode = 'invalid_token';\n/**\n * Method not allowed error - The HTTP method used is not allowed for this endpoint.\n * (Custom, non-standard error)\n */\nexport class MethodNotAllowedError extends OAuthError {\n}\nMethodNotAllowedError.errorCode = 'method_not_allowed';\n/**\n * Too many requests error - Rate limit exceeded.\n * (Custom, non-standard error based on RFC 6585)\n */\nexport class TooManyRequestsError extends OAuthError {\n}\nTooManyRequestsError.errorCode = 'too_many_requests';\n/**\n * Invalid client metadata error - The client metadata is invalid.\n * (Custom error for dynamic client registration - RFC 7591)\n */\nexport class InvalidClientMetadataError extends OAuthError {\n}\nInvalidClientMetadataError.errorCode = 'invalid_client_metadata';\n/**\n * Insufficient scope error - The request requires higher privileges than provided by the access token.\n */\nexport class InsufficientScopeError extends OAuthError {\n}\nInsufficientScopeError.errorCode = 'insufficient_scope';\n/**\n * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.\n * (Custom error for resource indicators - RFC 8707)\n */\nexport class InvalidTargetError extends OAuthError {\n}\nInvalidTargetError.errorCode = 'invalid_target';\n/**\n * A utility class for defining one-off error codes\n */\nexport class CustomOAuthError extends OAuthError {\n constructor(customErrorCode, message, errorUri) {\n super(message, errorUri);\n this.customErrorCode = customErrorCode;\n }\n get errorCode() {\n return this.customErrorCode;\n }\n}\n/**\n * A full list of all OAuthErrors, enabling parsing from error responses\n */\nexport const OAUTH_ERRORS = {\n [InvalidRequestError.errorCode]: InvalidRequestError,\n [InvalidClientError.errorCode]: InvalidClientError,\n [InvalidGrantError.errorCode]: InvalidGrantError,\n [UnauthorizedClientError.errorCode]: UnauthorizedClientError,\n [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,\n [InvalidScopeError.errorCode]: InvalidScopeError,\n [AccessDeniedError.errorCode]: AccessDeniedError,\n [ServerError.errorCode]: ServerError,\n [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,\n [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,\n [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,\n [InvalidTokenError.errorCode]: InvalidTokenError,\n [MethodNotAllowedError.errorCode]: MethodNotAllowedError,\n [TooManyRequestsError.errorCode]: TooManyRequestsError,\n [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,\n [InsufficientScopeError.errorCode]: InsufficientScopeError,\n [InvalidTargetError.errorCode]: InvalidTargetError\n};\n//# sourceMappingURL=errors.js.map","import pkceChallenge from 'pkce-challenge';\nimport { LATEST_PROTOCOL_VERSION } from '../types.js';\nimport { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js';\nimport { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js';\nimport { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js';\nimport { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js';\nimport { fetchWithinOrigin, unfollowedRedirect } from '../shared/transport.js';\nexport class UnauthorizedError extends Error {\n constructor(message) {\n super(message ?? 'Unauthorized');\n }\n}\nfunction isClientAuthMethod(method) {\n return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);\n}\nconst AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';\nconst AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';\n/**\n * Determines the best client authentication method to use based on server support and client configuration.\n *\n * Priority order (highest to lowest):\n * 1. client_secret_basic (if client secret is available)\n * 2. client_secret_post (if client secret is available)\n * 3. none (for public clients)\n *\n * @param clientInformation - OAuth client information containing credentials\n * @param supportedMethods - Authentication methods supported by the authorization server\n * @returns The selected authentication method\n */\nexport function selectClientAuthMethod(clientInformation, supportedMethods) {\n const hasClientSecret = clientInformation.client_secret !== undefined;\n // Prefer the method returned by the server during client registration, if valid.\n // When server metadata is present we also require the method to be listed as supported;\n // when supportedMethods is empty (metadata omitted the field) the DCR hint stands alone.\n if ('token_endpoint_auth_method' in clientInformation &&\n clientInformation.token_endpoint_auth_method &&\n isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&\n (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {\n return clientInformation.token_endpoint_auth_method;\n }\n // If server metadata omits token_endpoint_auth_methods_supported, RFC 8414 §2 says the\n // default is client_secret_basic. RFC 6749 §2.3.1 also requires servers to support HTTP\n // Basic authentication for clients with a secret, making it the safest default.\n if (supportedMethods.length === 0) {\n return hasClientSecret ? 'client_secret_basic' : 'none';\n }\n // Try methods in priority order (most secure first)\n if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {\n return 'client_secret_basic';\n }\n if (hasClientSecret && supportedMethods.includes('client_secret_post')) {\n return 'client_secret_post';\n }\n if (supportedMethods.includes('none')) {\n return 'none';\n }\n // Fallback: use what we have\n return hasClientSecret ? 'client_secret_post' : 'none';\n}\n/**\n * Applies client authentication to the request based on the specified method.\n *\n * Implements OAuth 2.1 client authentication methods:\n * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)\n * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)\n * - none: Public client authentication (RFC 6749 Section 2.1)\n *\n * @param method - The authentication method to use\n * @param clientInformation - OAuth client information containing credentials\n * @param headers - HTTP headers object to modify\n * @param params - URL search parameters to modify\n * @throws {Error} When required credentials are missing\n */\nfunction applyClientAuthentication(method, clientInformation, headers, params) {\n const { client_id, client_secret } = clientInformation;\n switch (method) {\n case 'client_secret_basic':\n applyBasicAuth(client_id, client_secret, headers);\n return;\n case 'client_secret_post':\n applyPostAuth(client_id, client_secret, params);\n return;\n case 'none':\n applyPublicAuth(client_id, params);\n return;\n default:\n throw new Error(`Unsupported client authentication method: ${method}`);\n }\n}\n/**\n * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyBasicAuth(clientId, clientSecret, headers) {\n if (!clientSecret) {\n throw new Error('client_secret_basic authentication requires a client_secret');\n }\n const credentials = btoa(`${clientId}:${clientSecret}`);\n headers.set('Authorization', `Basic ${credentials}`);\n}\n/**\n * Applies POST body authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyPostAuth(clientId, clientSecret, params) {\n params.set('client_id', clientId);\n if (clientSecret) {\n params.set('client_secret', clientSecret);\n }\n}\n/**\n * Applies public client authentication (RFC 6749 Section 2.1)\n */\nfunction applyPublicAuth(clientId, params) {\n params.set('client_id', clientId);\n}\n/**\n * Parses an OAuth error response from a string or Response object.\n *\n * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec\n * and an instance of the appropriate OAuthError subclass will be returned.\n * If parsing fails, it falls back to a generic ServerError that includes\n * the response status (if available) and original content.\n *\n * @param input - A Response object or string containing the error response\n * @returns A Promise that resolves to an OAuthError instance\n */\nexport async function parseErrorResponse(input) {\n const statusCode = input instanceof Response ? input.status : undefined;\n const body = input instanceof Response ? await input.text() : input;\n try {\n const result = OAuthErrorResponseSchema.parse(JSON.parse(body));\n const { error, error_description, error_uri } = result;\n const errorClass = OAUTH_ERRORS[error] || ServerError;\n return new errorClass(error_description || '', error_uri);\n }\n catch (error) {\n // Not a valid OAuth error response, but try to inform the user of the raw data anyway\n const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : undefined;\n const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`;\n return new ServerError(errorMessage);\n }\n}\n/**\n * Compares two authorization server identifiers, tolerating a single trailing `/`\n * difference (`String(new URL(...))` is slash-suffixed, advertised values often are not).\n */\nfunction issuersMatch(a, b) {\n let [x, y] = [a, b];\n try {\n // Two URLs are compared as parsed, so the spelling of scheme, host or default port does not matter.\n [x, y] = [new URL(a).href, new URL(b).href];\n }\n catch {\n // Not two URLs: compared as written.\n }\n return x === y || (x.endsWith('/') && x.slice(0, -1) === y) || (y.endsWith('/') && y.slice(0, -1) === x);\n}\n/**\n * {@linkcode auth} stamps everything it passes to `saveClientInformation` / `saveTokens` with\n * `issuer`, the authorization server URL used for discovery. This returns `stored` unless its\n * stamp names a different authorization server, in which case the caller behaves as if nothing\n * were stored. A value without a stamp (saved by an earlier version) is returned as-is, and\n * is stamped once this authorization server has accepted it.\n */\nfunction discardIfIssuerMismatch(stored, issuer) {\n // `null`: a `JSON.parse(storage.getItem(...))`-style getter with nothing stored.\n if (!stored)\n return undefined;\n // A stamp that is not a string (raw storage) counts as no stamp.\n if (typeof stored.issuer !== 'string')\n return stored.issuer == null ? stored : { ...stored, issuer: undefined };\n return issuersMatch(stored.issuer, issuer) ? stored : undefined;\n}\n// `issuer` is added by the client when it stores a value; authorization server responses are parsed without it.\nconst TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });\nconst RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });\nfunction boundElsewhereError(stored, issuer) {\n return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. ` +\n 'Clear the stored client information, or correct `expectedIssuer`, if the authorization server has moved.');\n}\n/**\n * Orchestrates the full auth flow with a server.\n *\n * This can be used as a single entry point for all authorization functionality,\n * instead of linking together the other lower-level functions in this module.\n */\nexport async function auth(provider, options) {\n try {\n return await authInternal(provider, options);\n }\n catch (error) {\n // Handle recoverable error types by invalidating credentials and retrying\n if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {\n await provider.invalidateCredentials?.('all');\n return await authInternal(provider, options);\n }\n else if (error instanceof InvalidGrantError) {\n await provider.invalidateCredentials?.('tokens');\n return await authInternal(provider, options);\n }\n // Throw otherwise\n throw error;\n }\n}\nasync function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {\n // Check if the provider has cached discovery state to skip discovery\n const cachedState = await provider.discoveryState?.();\n let resourceMetadata;\n let authorizationServerUrl;\n let metadata;\n // If resourceMetadataUrl is not provided, try to load it from cached state\n // This handles browser redirects where the URL was saved before navigation\n let effectiveResourceMetadataUrl = resourceMetadataUrl;\n if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {\n effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);\n }\n if (cachedState?.authorizationServerUrl) {\n // Restore discovery state from cache\n authorizationServerUrl = cachedState.authorizationServerUrl;\n resourceMetadata = cachedState.resourceMetadata;\n metadata =\n cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }));\n // If resource metadata wasn't cached, try to fetch it for selectResourceURL\n if (!resourceMetadata) {\n try {\n resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);\n }\n catch {\n // RFC 9728 not available — selectResourceURL will handle undefined\n }\n }\n // Re-save if we enriched the cached state with missing metadata\n if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {\n await provider.saveDiscoveryState?.({\n authorizationServerUrl: String(authorizationServerUrl),\n resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n resourceMetadata,\n authorizationServerMetadata: metadata\n });\n }\n }\n else {\n // Full discovery via RFC 9728\n const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });\n authorizationServerUrl = serverInfo.authorizationServerUrl;\n metadata = serverInfo.authorizationServerMetadata;\n resourceMetadata = serverInfo.resourceMetadata;\n // Persist discovery state for future use\n // TODO: resourceMetadataUrl is only populated when explicitly provided via options\n // or loaded from cached state. The URL derived internally by\n // discoverOAuthProtectedResourceMetadata() is not captured back here.\n await provider.saveDiscoveryState?.({\n authorizationServerUrl: String(authorizationServerUrl),\n resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n resourceMetadata,\n authorizationServerMetadata: metadata\n });\n }\n // Binding key for stored credentials: the authorization server URL that discovery used\n // (advertised by the resource server, restored from discoveryState(), or the legacy\n // resource-origin fallback). `metadata.issuer` is deliberately not used: this version does\n // not check that the metadata document echoes the URL it was fetched from.\n const issuer = String(authorizationServerUrl);\n // Send the metadata's resource indicator verbatim: `selectResourceURL` returns a parsed\n // `URL`, and `URL.href` appends \"/\" to a pathless indicator such as `https://example.com`,\n // which exact-match authorization servers reject (#1968). A URL returned by the\n // provider's own `validateResourceURL` is used as returned.\n const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);\n const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;\n // Apply scope selection strategy (SEP-835):\n // 1. WWW-Authenticate scope (passed via `scope` param)\n // 2. PRM scopes_supported\n // 3. Client metadata scope (user-configured fallback)\n // The resolved scope is used consistently for both DCR and the authorization request.\n const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope;\n // Handle client registration if needed. Client information stamped for a different\n // authorization server reads back as `undefined`, so the flow re-registers exactly as if\n // nothing were stored.\n const storedClientInformation = await Promise.resolve(provider.clientInformation());\n let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);\n const canRegisterAgain = provider.saveClientInformation !== undefined && !!provider.redirectUrl;\n if (storedClientInformation && !clientInformation && !canRegisterAgain) {\n // Pre-registered credentials, or a non-interactive client running on configured\n // credentials: neither can be re-created by registering with this authorization server.\n throw boundElsewhereError(storedClientInformation, issuer);\n }\n // Saved by an earlier version: bound to the first authorization server that accepts it.\n const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : undefined;\n const bindClientInformation = async () => {\n try {\n if (unstampedClientInformation)\n await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });\n }\n catch {\n // A provider that only expects this call after a registration keeps working, unbound.\n }\n };\n if (!clientInformation) {\n if (authorizationCode !== undefined) {\n throw new Error('Existing OAuth client information is required when exchanging an authorization code');\n }\n const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;\n const clientMetadataUrl = provider.clientMetadataUrl;\n if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {\n throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);\n }\n const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;\n if (shouldUseUrlBasedClientId) {\n // SEP-991: URL-based Client IDs\n clientInformation = { client_id: clientMetadataUrl, issuer };\n await provider.saveClientInformation?.(clientInformation);\n }\n else {\n // Fallback to dynamic registration\n if (!provider.saveClientInformation) {\n throw new Error('OAuth client information must be saveable for dynamic registration');\n }\n const fullInformation = await registerClient(authorizationServerUrl, {\n metadata,\n clientMetadata: provider.clientMetadata,\n scope: resolvedScope,\n fetchFn\n });\n clientInformation = { ...fullInformation, issuer };\n await provider.saveClientInformation(clientInformation);\n }\n }\n // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL\n const nonInteractiveFlow = !provider.redirectUrl;\n // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows\n if (authorizationCode !== undefined || nonInteractiveFlow) {\n const tokens = await fetchToken(provider, authorizationServerUrl, {\n metadata,\n resource,\n authorizationCode,\n fetchFn\n });\n await bindClientInformation();\n await provider.saveTokens({ ...tokens, issuer });\n return 'AUTHORIZED';\n }\n // A refresh token stamped for a different authorization server reads back as `undefined`,\n // so it is never posted to this one's token endpoint.\n const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);\n if (tokens?.refresh_token && tokens.issuer == null) {\n // eslint-disable-next-line no-console\n console.warn(\"[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that \" +\n 'does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and ' +\n 'saveClientInformation() receive unchanged.');\n }\n // Handle token refresh or new authorization\n if (tokens?.refresh_token) {\n try {\n // Attempt to refresh the token\n const newTokens = await refreshAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n refreshToken: tokens.refresh_token,\n resource,\n addClientAuthentication: provider.addClientAuthentication,\n fetchFn\n });\n await bindClientInformation();\n await provider.saveTokens({ ...newTokens, issuer });\n return 'AUTHORIZED';\n }\n catch (error) {\n // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n if (!(error instanceof OAuthError) || error instanceof ServerError) {\n // Could not refresh OAuth tokens\n }\n else {\n // Refresh failed for another reason, re-throw\n throw error;\n }\n }\n }\n const state = provider.state ? await provider.state() : undefined;\n // Start new authorization flow\n const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n state,\n redirectUrl: provider.redirectUrl,\n scope: resolvedScope,\n resource\n });\n await provider.saveCodeVerifier(codeVerifier);\n await provider.redirectToAuthorization(authorizationUrl);\n return 'REDIRECT';\n}\n/**\n * SEP-991: URL-based Client IDs\n * Validate that the client_id is a valid URL with https scheme\n */\nexport function isHttpsUrl(value) {\n if (!value)\n return false;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && url.pathname !== '/';\n }\n catch {\n return false;\n }\n}\n/**\n * Selects the RFC 8707 resource indicator for an MCP server: the provider's\n * {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when\n * implemented, otherwise the protected resource metadata's `resource` (checked against the\n * server URL with `checkResourceAllowed`), or `undefined` when there is no metadata.\n *\n * The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has\n * the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string\n * verbatim instead of this URL's `href` (#1968); callers that emit the `resource`\n * parameter themselves should do the same.\n */\nexport async function selectResourceURL(serverUrl, provider, resourceMetadata) {\n const defaultResource = resourceUrlFromServerUrl(serverUrl);\n // If provider has custom validation, delegate to it\n if (provider.validateResourceURL) {\n return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);\n }\n // Only include resource parameter when Protected Resource Metadata is present\n if (!resourceMetadata) {\n return undefined;\n }\n // Validate that the metadata's resource is compatible with our request\n if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {\n throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);\n }\n // Prefer the resource from metadata since it's what the server is telling us to request\n return new URL(resourceMetadata.resource);\n}\n/**\n * Extract resource_metadata, scope, and error from WWW-Authenticate header.\n */\nexport function extractWWWAuthenticateParams(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return {};\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return {};\n }\n const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;\n let resourceMetadataUrl;\n if (resourceMetadataMatch) {\n try {\n resourceMetadataUrl = new URL(resourceMetadataMatch);\n }\n catch {\n // Ignore invalid URL\n }\n }\n const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;\n const error = extractFieldFromWwwAuth(res, 'error') || undefined;\n return {\n resourceMetadataUrl,\n scope,\n error\n };\n}\n/**\n * Extracts a specific field's value from the WWW-Authenticate header string.\n *\n * @param response The HTTP response object containing the headers.\n * @param fieldName The name of the field to extract (e.g., \"realm\", \"nonce\").\n * @returns The field value\n */\nfunction extractFieldFromWwwAuth(response, fieldName) {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n if (!wwwAuthHeader) {\n return null;\n }\n const pattern = new RegExp(`${fieldName}=(?:\"([^\"]+)\"|([^\\\\s,]+))`);\n const match = wwwAuthHeader.match(pattern);\n if (match) {\n // Pattern matches: field_name=\"value\" or field_name=value (unquoted)\n return match[1] || match[2];\n }\n return null;\n}\n/**\n * Extract resource_metadata from response header.\n * @deprecated Use `extractWWWAuthenticateParams` instead.\n */\nexport function extractResourceMetadataUrl(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return undefined;\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return undefined;\n }\n const regex = /resource_metadata=\"([^\"]*)\"/;\n const match = regex.exec(authenticateHeader);\n if (!match) {\n return undefined;\n }\n try {\n return new URL(match[1]);\n }\n catch {\n return undefined;\n }\n}\n/**\n * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n */\nexport async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {\n const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {\n protocolVersion: opts?.protocolVersion,\n metadataUrl: opts?.resourceMetadataUrl\n });\n if (!response || response.status === 404) {\n await response?.body?.cancel();\n throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);\n }\n return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\n/**\n * Helper function to handle fetch with CORS retry logic\n */\nasync function fetchWithCorsRetry(url, headers, fetchFn = fetch) {\n try {\n return await fetchWithinOrigin(fetchFn)(url, { headers });\n }\n catch (error) {\n if (error instanceof TypeError) {\n if (headers) {\n // CORS errors come back as TypeError, retry without headers\n return fetchWithCorsRetry(url, undefined, fetchFn);\n }\n else {\n // We're getting CORS errors on retry too, return undefined\n return undefined;\n }\n }\n throw error;\n }\n}\n/**\n * Constructs the well-known path for auth-related metadata discovery\n */\nfunction buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {\n // Strip trailing slash from pathname to avoid double slashes\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\n/**\n * Tries to discover OAuth metadata at a specific URL\n */\nasync function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {\n const headers = {\n 'MCP-Protocol-Version': protocolVersion\n };\n return await fetchWithCorsRetry(url, headers, fetchFn);\n}\n/**\n * Determines if fallback to root discovery should be attempted\n */\nfunction shouldAttemptFallback(response, pathname) {\n return !response || (!response.ok && response.status < 500 && pathname !== '/');\n}\n/**\n * Generic function for discovering OAuth metadata with fallback support\n */\nasync function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {\n const issuer = new URL(serverUrl);\n const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;\n let url;\n if (opts?.metadataUrl) {\n url = new URL(opts.metadataUrl);\n }\n else {\n // Try path-aware discovery first\n const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);\n url.search = issuer.search;\n }\n let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery\n if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {\n const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n }\n return response;\n}\n/**\n * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n *\n * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.\n */\nexport async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {\n if (typeof issuer === 'string') {\n issuer = new URL(issuer);\n }\n if (!authorizationServerUrl) {\n authorizationServerUrl = issuer;\n }\n if (typeof authorizationServerUrl === 'string') {\n authorizationServerUrl = new URL(authorizationServerUrl);\n }\n protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION);\n const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {\n protocolVersion,\n metadataServerUrl: authorizationServerUrl\n });\n if (!response || response.status === 404) {\n await response?.body?.cancel();\n return undefined;\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);\n }\n return OAuthMetadataSchema.parse(await response.json());\n}\n/**\n * Builds a list of discovery URLs to try for authorization server metadata.\n * URLs are returned in priority order:\n * 1. OAuth metadata at the given URL\n * 2. OIDC metadata endpoints at the given URL\n */\nexport function buildDiscoveryUrls(authorizationServerUrl) {\n const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;\n const hasPath = url.pathname !== '/';\n const urlsToTry = [];\n if (!hasPath) {\n // Root path: https://example.com/.well-known/oauth-authorization-server\n urlsToTry.push({\n url: new URL('/.well-known/oauth-authorization-server', url.origin),\n type: 'oauth'\n });\n // OIDC: https://example.com/.well-known/openid-configuration\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n }\n // Strip trailing slash from pathname to avoid double slashes\n let pathname = url.pathname;\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n // 1. OAuth metadata at the given URL\n // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1\n urlsToTry.push({\n url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),\n type: 'oauth'\n });\n // 2. OIDC metadata endpoints\n // RFC 8414 style: Insert /.well-known/openid-configuration before the path\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n type: 'oidc'\n });\n // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path\n urlsToTry.push({\n url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n}\n/**\n * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata\n * and OpenID Connect Discovery 1.0 specifications.\n *\n * This function implements a fallback strategy for authorization server discovery:\n * 1. Attempts RFC 8414 OAuth metadata discovery first\n * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery\n *\n * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's\n * protected resource metadata, or the MCP server's URL if the\n * metadata was not found.\n * @param options - Configuration options\n * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch\n * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION\n * @returns Promise resolving to authorization server metadata, or undefined if discovery fails\n */\nexport async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {\n const headers = {\n 'MCP-Protocol-Version': protocolVersion,\n Accept: 'application/json'\n };\n // Get the list of URLs to try\n const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n // Try each URL in order\n for (const { url: endpointUrl, type } of urlsToTry) {\n const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n if (!response) {\n /**\n * CORS error occurred - don't throw as the endpoint may not allow CORS,\n * continue trying other possible endpoints\n */\n continue;\n }\n if (!response.ok) {\n await response.body?.cancel();\n // Continue looking for any 4xx response code, or a redirect that was not followed.\n if (response.status < 500) {\n continue; // Try next URL\n }\n throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);\n }\n // Parse and validate based on type\n if (type === 'oauth') {\n return OAuthMetadataSchema.parse(await response.json());\n }\n else {\n return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n }\n }\n return undefined;\n}\n/**\n * Discovers the authorization server for an MCP server following\n * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected\n * Resource Metadata), with fallback to treating the server URL as the\n * authorization server.\n *\n * This function combines two discovery steps into one call:\n * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the\n * authorization server URL (RFC 9728).\n * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).\n *\n * Use this when you need the authorization server metadata for operations outside the\n * {@linkcode auth} orchestrator, such as token refresh or token revocation.\n *\n * @param serverUrl - The MCP resource server URL\n * @param opts - Optional configuration\n * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint\n * @param opts.fetchFn - Custom fetch function for HTTP requests\n * @returns Authorization server URL, metadata, and resource metadata (if available)\n */\nexport async function discoverOAuthServerInfo(serverUrl, opts) {\n let resourceMetadata;\n let authorizationServerUrl;\n try {\n resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);\n if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n authorizationServerUrl = resourceMetadata.authorization_servers[0];\n }\n }\n catch {\n // RFC 9728 not supported -- fall back to treating the server URL as the authorization server\n }\n // If we don't get a valid authorization server from protected resource metadata,\n // fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server\n if (!authorizationServerUrl) {\n authorizationServerUrl = String(new URL('/', serverUrl));\n }\n const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });\n return {\n authorizationServerUrl,\n authorizationServerMetadata,\n resourceMetadata\n };\n}\nfunction resourceIndicatorToString(resource) {\n return typeof resource === 'string' ? resource : resource.href;\n}\n/**\n * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.\n */\nexport async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {\n let authorizationUrl;\n if (metadata) {\n authorizationUrl = new URL(metadata.authorization_endpoint);\n if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {\n throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);\n }\n if (metadata.code_challenge_methods_supported &&\n !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {\n throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);\n }\n }\n else {\n authorizationUrl = new URL('/authorize', authorizationServerUrl);\n }\n // Generate PKCE challenge\n const challenge = await pkceChallenge();\n const codeVerifier = challenge.code_verifier;\n const codeChallenge = challenge.code_challenge;\n authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);\n authorizationUrl.searchParams.set('client_id', clientInformation.client_id);\n authorizationUrl.searchParams.set('code_challenge', codeChallenge);\n authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);\n authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));\n if (state) {\n authorizationUrl.searchParams.set('state', state);\n }\n if (scope) {\n authorizationUrl.searchParams.set('scope', scope);\n }\n if (scope?.includes('offline_access')) {\n // if the request includes the OIDC-only \"offline_access\" scope,\n // we need to set the prompt to \"consent\" to ensure the user is prompted to grant offline access\n // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess\n authorizationUrl.searchParams.append('prompt', 'consent');\n }\n if (resource) {\n authorizationUrl.searchParams.set('resource', resourceIndicatorToString(resource));\n }\n return { authorizationUrl, codeVerifier };\n}\n/**\n * Prepares token request parameters for an authorization code exchange.\n *\n * This is the default implementation used by fetchToken when the provider\n * doesn't implement prepareTokenRequest.\n *\n * @param authorizationCode - The authorization code received from the authorization endpoint\n * @param codeVerifier - The PKCE code verifier\n * @param redirectUri - The redirect URI used in the authorization request\n * @returns URLSearchParams for the authorization_code grant\n */\nexport function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {\n return new URLSearchParams({\n grant_type: 'authorization_code',\n code: authorizationCode,\n code_verifier: codeVerifier,\n redirect_uri: String(redirectUri)\n });\n}\n/**\n * Internal helper to execute a token request with the given parameters.\n * Used by exchangeAuthorization, refreshAuthorization, and fetchToken.\n */\nasync function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {\n const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json'\n });\n if (resource) {\n tokenRequestParams.set('resource', resourceIndicatorToString(resource));\n }\n if (addClientAuthentication) {\n await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);\n }\n else if (clientInformation) {\n const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];\n const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);\n applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);\n }\n const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {\n method: 'POST',\n headers,\n body: tokenRequestParams\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return TokenResponseSchema.parse(await response.json());\n}\n/**\n * Exchanges an authorization code for an access token with the given server.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Falls back to appropriate defaults when server metadata is unavailable\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, auth code, etc.\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When token exchange fails or authentication is invalid\n */\nexport async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Exchange a refresh token for an updated access token.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Preserves the original refresh token if a new one is not returned\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, refresh token, etc.\n * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)\n * @throws {Error} When token refresh fails or authentication is invalid\n */\nexport async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken\n });\n const tokens = await executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n // Preserve original refresh token if server didn't return a new one\n return { refresh_token: refreshToken, ...tokens };\n}\n/**\n * Unified token fetching that works with any grant type via provider.prepareTokenRequest().\n *\n * This function provides a single entry point for obtaining tokens regardless of the\n * OAuth grant type. The provider's prepareTokenRequest() method determines which grant\n * to use and supplies the grant-specific parameters.\n *\n * @param provider - OAuth client provider that implements prepareTokenRequest()\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration for the token request\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails\n *\n * @example\n * // Provider for client_credentials:\n * class MyProvider implements OAuthClientProvider {\n * prepareTokenRequest(scope) {\n * const params = new URLSearchParams({ grant_type: 'client_credentials' });\n * if (scope) params.set('scope', scope);\n * return params;\n * }\n * // ... other methods\n * }\n *\n * const tokens = await fetchToken(provider, authServerUrl, { metadata });\n */\nexport async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {\n // Nothing is sent to an authorization server other than the one the client information is stamped for.\n const readClientInformation = async () => {\n const storedClientInformation = await provider.clientInformation();\n const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));\n if (storedClientInformation && !checked) {\n throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));\n }\n return checked;\n };\n let clientInformation = await readClientInformation();\n const scope = provider.clientMetadata.scope;\n // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code\n let tokenRequestParams;\n if (provider.prepareTokenRequest) {\n tokenRequestParams = await provider.prepareTokenRequest(scope);\n }\n // Default to authorization_code grant if no custom prepareTokenRequest\n if (!tokenRequestParams) {\n if (!authorizationCode) {\n throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');\n }\n if (!provider.redirectUrl) {\n throw new Error('redirectUrl is required for authorization_code flow');\n }\n const codeVerifier = await provider.codeVerifier();\n tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);\n }\n // A provider may fill in its client information while the request is prepared.\n clientInformation ?? (clientInformation = await readClientInformation());\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication: provider.addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.\n *\n * If `scope` is provided, it overrides `clientMetadata.scope` in the registration\n * request body. This allows callers to apply the Scope Selection Strategy (SEP-835)\n * consistently across both DCR and the subsequent authorization request.\n */\nexport async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {\n let registrationUrl;\n if (metadata) {\n if (!metadata.registration_endpoint) {\n throw new Error('Incompatible auth server: does not support dynamic client registration');\n }\n registrationUrl = new URL(metadata.registration_endpoint);\n }\n else {\n registrationUrl = new URL('/register', authorizationServerUrl);\n }\n const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n ...clientMetadata,\n ...(scope !== undefined ? { scope } : {})\n })\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return RegistrationResponseSchema.parse(await response.json());\n}\n//# sourceMappingURL=auth.js.map","import { EventSource } from 'eventsource';\nimport { createFetchWithInit, fetchLeavingRedirects, fetchWithinOrigin, normalizeHeaders, unfollowedRedirect } from '../shared/transport.js';\nimport { JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nexport class SseError extends Error {\n constructor(code, message, event) {\n super(`SSE error: ${message}`);\n this.code = code;\n this.event = event;\n }\n}\n/**\n * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving\n * messages and make separate POST requests for sending messages.\n * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.\n */\nexport class SSEClientTransport {\n constructor(url, opts) {\n this._url = url;\n this._resourceMetadataUrl = undefined;\n this._scope = undefined;\n this._eventSourceInit = opts?.eventSourceInit;\n this._requestInit = opts?.requestInit;\n this._authProvider = opts?.authProvider;\n this._fetch = opts?.fetch;\n this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n this._followRedirects = opts?.redirectPolicy === 'follow';\n if (this._followRedirects) {\n this._fetch = fetchLeavingRedirects(this._fetch);\n this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);\n }\n }\n /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */\n _unfollowedRedirect(response, url) {\n const text = unfollowedRedirect(response, url);\n return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;\n }\n async _authThenStart() {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n let result;\n try {\n result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return await this._startOrAuth();\n }\n async _commonHeaders() {\n const headers = {};\n if (this._authProvider) {\n const tokens = await this._authProvider.tokens();\n if (tokens) {\n headers['Authorization'] = `Bearer ${tokens.access_token}`;\n }\n }\n if (this._protocolVersion) {\n headers['mcp-protocol-version'] = this._protocolVersion;\n }\n const extraHeaders = normalizeHeaders(this._requestInit?.headers);\n return new Headers({\n ...headers,\n ...extraHeaders\n });\n }\n _startOrAuth() {\n const baseFetch = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch);\n const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);\n let redirect;\n return new Promise((resolve, reject) => {\n this._eventSource = new EventSource(this._url.href, {\n ...this._eventSourceInit,\n fetch: async (url, init) => {\n const headers = await this._commonHeaders();\n headers.set('Accept', 'text/event-stream');\n const response = await fetchImpl(url, {\n ...init,\n headers\n });\n redirect = this._unfollowedRedirect(response, url);\n if (response.status === 401 && response.headers.has('www-authenticate')) {\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n }\n return response;\n }\n });\n this._abortController = new AbortController();\n this._eventSource.onerror = event => {\n if (event.code === 401 && this._authProvider) {\n this._authThenStart().then(resolve, reject);\n return;\n }\n const error = new SseError(event.code, redirect ?? event.message, event);\n reject(error);\n this.onerror?.(error);\n };\n this._eventSource.onopen = () => {\n // The connection is open, but we need to wait for the endpoint to be received.\n };\n this._eventSource.addEventListener('endpoint', (event) => {\n const messageEvent = event;\n try {\n this._endpoint = new URL(messageEvent.data, this._url);\n if (this._endpoint.origin !== this._url.origin) {\n throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);\n }\n }\n catch (error) {\n reject(error);\n this.onerror?.(error);\n void this.close();\n return;\n }\n resolve();\n });\n this._eventSource.onmessage = (event) => {\n const messageEvent = event;\n let message;\n try {\n message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));\n }\n catch (error) {\n this.onerror?.(error);\n return;\n }\n this.onmessage?.(message);\n };\n });\n }\n async start() {\n if (this._eventSource) {\n throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return await this._startOrAuth();\n }\n /**\n * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n */\n async finishAuth(authorizationCode) {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n authorizationCode,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError('Failed to authorize');\n }\n }\n async close() {\n this._abortController?.abort();\n this._eventSource?.close();\n this.onclose?.();\n }\n async send(message) {\n if (!this._endpoint) {\n throw new Error('Not connected');\n }\n try {\n const headers = await this._commonHeaders();\n headers.set('content-type', 'application/json');\n const init = {\n ...this._requestInit,\n method: 'POST',\n headers,\n body: JSON.stringify(message),\n signal: this._abortController?.signal\n };\n const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);\n if (!response.ok) {\n const text = await response.text().catch(() => null);\n if (response.status === 401 && this._authProvider) {\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n // Purposely _not_ awaited, so we don't call onerror twice\n return this.send(message);\n }\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);\n }\n // Release connection - POST responses don't have content we need\n await response.body?.cancel();\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n setProtocolVersion(version) {\n this._protocolVersion = version;\n }\n}\n//# sourceMappingURL=sse.js.map","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n typeof onError == \"function\" && onError(error), (onError === \"terminate\" || error.type === \"max-buffer-size-exceeded\") && controller.error(error);\n },\n onRetry,\n onComment,\n maxBufferSize\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","import { mediaTypeEssence } from '../shared/mediaType.js';\nimport { createFetchWithInit, fetchLeavingRedirects, fetchWithinOrigin, followWithinOrigin, normalizeHeaders, unfollowedRedirect } from '../shared/transport.js';\nimport { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nimport { EventSourceParserStream } from 'eventsource-parser/stream';\n// Default reconnection options for StreamableHTTP connections\nconst DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {\n initialReconnectionDelay: 1000,\n maxReconnectionDelay: 30000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 2\n};\nexport class StreamableHTTPError extends Error {\n constructor(code, message) {\n super(`Streamable HTTP error: ${message}`);\n this.code = code;\n }\n}\n/**\n * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events\n * for receiving messages.\n */\nexport class StreamableHTTPClientTransport {\n constructor(url, opts) {\n this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401\n this._url = url;\n this._resourceMetadataUrl = undefined;\n this._scope = undefined;\n this._requestInit = opts?.requestInit;\n this._authProvider = opts?.authProvider;\n this._fetch = opts?.fetch;\n this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n this._followRedirects = opts?.redirectPolicy === 'follow';\n if (this._followRedirects) {\n this._fetch = fetchLeavingRedirects(this._fetch);\n this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);\n }\n this._sessionId = opts?.sessionId;\n this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;\n }\n /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */\n _unfollowedRedirect(response, url) {\n const text = unfollowedRedirect(response, url);\n return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;\n }\n async _authThenStart() {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n let result;\n try {\n result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return await this._startOrAuthSse({ resumptionToken: undefined });\n }\n async _commonHeaders() {\n const headers = {};\n if (this._authProvider) {\n const tokens = await this._authProvider.tokens();\n if (tokens) {\n headers['Authorization'] = `Bearer ${tokens.access_token}`;\n }\n }\n if (this._sessionId) {\n headers['mcp-session-id'] = this._sessionId;\n }\n if (this._protocolVersion) {\n headers['mcp-protocol-version'] = this._protocolVersion;\n }\n const extraHeaders = normalizeHeaders(this._requestInit?.headers);\n return new Headers({\n ...headers,\n ...extraHeaders\n });\n }\n async _startOrAuthSse(options) {\n const { resumptionToken } = options;\n try {\n // Try to open an initial SSE stream with GET to listen for server messages\n // This is optional according to the spec - server may not support it\n const headers = await this._commonHeaders();\n headers.set('Accept', 'text/event-stream');\n // Include Last-Event-ID header for resumable streams if provided\n if (resumptionToken) {\n headers.set('last-event-id', resumptionToken);\n }\n const fetchFn = this._fetch ?? fetch;\n const init = { method: 'GET', headers, signal: this._abortController?.signal };\n // A response that is not a redirect is used as it arrives, so reading the stream starts as early as before.\n let response = await fetchFn(this._url, this._followRedirects ? init : { ...init, redirect: 'manual' });\n const followed = this._followRedirects ? undefined : followWithinOrigin(fetchFn, this._url, init, response);\n if (followed) {\n response = await followed;\n }\n if (!response.ok) {\n await response.body?.cancel();\n if (response.status === 401 && this._authProvider) {\n // Need to authenticate\n return await this._authThenStart();\n }\n // 405 indicates that the server does not offer an SSE stream at GET endpoint\n // This is an expected case that should not trigger an error\n if (response.status === 405) {\n return;\n }\n throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);\n }\n this._handleSseStream(response.body, options, true);\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n /**\n * Calculates the next reconnection delay using backoff algorithm\n *\n * @param attempt Current reconnection attempt count for the specific stream\n * @returns Time to wait in milliseconds before next reconnection attempt\n */\n _getNextReconnectionDelay(attempt) {\n // Use server-provided retry value if available\n if (this._serverRetryMs !== undefined) {\n return this._serverRetryMs;\n }\n // Fall back to exponential backoff\n const initialDelay = this._reconnectionOptions.initialReconnectionDelay;\n const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;\n const maxDelay = this._reconnectionOptions.maxReconnectionDelay;\n // Cap at maximum delay\n return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);\n }\n /**\n * Schedule a reconnection attempt using server-provided retry interval or backoff\n *\n * @param lastEventId The ID of the last received event for resumability\n * @param attemptCount Current reconnection attempt count for this specific stream\n */\n _scheduleReconnection(options, attemptCount = 0) {\n // Use provided options or default options\n const maxRetries = this._reconnectionOptions.maxRetries;\n // Check if we've exceeded maximum retry attempts\n if (attemptCount >= maxRetries) {\n this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));\n return;\n }\n // Calculate next delay based on current attempt count\n const delay = this._getNextReconnectionDelay(attemptCount);\n // Schedule the reconnection\n this._reconnectionTimeout = setTimeout(() => {\n // Use the last event ID to resume where we left off\n this._startOrAuthSse(options).catch(error => {\n this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));\n // Schedule another attempt if this one failed, incrementing the attempt counter\n this._scheduleReconnection(options, attemptCount + 1);\n });\n }, delay);\n }\n _handleSseStream(stream, options, isReconnectable) {\n if (!stream) {\n return;\n }\n const { onresumptiontoken, replayMessageId } = options;\n let lastEventId;\n // Track whether we've received a priming event (event with ID)\n // Per spec, server SHOULD send a priming event with ID before closing\n let hasPrimingEvent = false;\n // Track whether we've received a response - if so, no need to reconnect\n // Reconnection is for when server disconnects BEFORE sending response\n let receivedResponse = false;\n const processStream = async () => {\n // this is the closest we can get to trying to catch network errors\n // if something happens reader will throw\n try {\n // Create a pipeline: binary stream -> text decoder -> SSE parser\n const reader = stream\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream({\n onRetry: (retryMs) => {\n // Capture server-provided retry value for reconnection timing\n this._serverRetryMs = retryMs;\n }\n }))\n .getReader();\n while (true) {\n const { value: event, done } = await reader.read();\n if (done) {\n break;\n }\n // Update last event ID if provided\n if (event.id) {\n lastEventId = event.id;\n // Mark that we've received a priming event - stream is now resumable\n hasPrimingEvent = true;\n onresumptiontoken?.(event.id);\n }\n // Skip events with no data (priming events, keep-alives)\n if (!event.data) {\n continue;\n }\n if (!event.event || event.event === 'message') {\n try {\n const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n if (isJSONRPCResultResponse(message)) {\n // Mark that we received a response - no need to reconnect for this request\n receivedResponse = true;\n if (replayMessageId !== undefined) {\n message.id = replayMessageId;\n }\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n // Handle graceful server-side disconnect\n // Server may close connection after sending event ID and retry field\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n }\n catch (error) {\n // Handle stream errors - likely a network disconnect\n this.onerror?.(new Error(`SSE stream disconnected: ${error}`));\n // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n // Use the exponential backoff reconnection strategy\n try {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n catch (error) {\n this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));\n }\n }\n }\n };\n processStream();\n }\n async start() {\n if (this._abortController) {\n throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n this._abortController = new AbortController();\n }\n /**\n * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n */\n async finishAuth(authorizationCode) {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n authorizationCode,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError('Failed to authorize');\n }\n }\n async close() {\n if (this._reconnectionTimeout) {\n clearTimeout(this._reconnectionTimeout);\n this._reconnectionTimeout = undefined;\n }\n this._abortController?.abort();\n this.onclose?.();\n }\n async send(message, options) {\n try {\n const { resumptionToken, onresumptiontoken } = options || {};\n if (resumptionToken) {\n // If we have at last event ID, we need to reconnect the SSE stream\n this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err));\n return;\n }\n const headers = await this._commonHeaders();\n headers.set('content-type', 'application/json');\n headers.set('accept', 'application/json, text/event-stream');\n const init = {\n ...this._requestInit,\n method: 'POST',\n headers,\n body: JSON.stringify(message),\n signal: this._abortController?.signal\n };\n const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);\n // Handle session ID received during initialization\n const sessionId = response.headers.get('mcp-session-id');\n if (sessionId) {\n this._sessionId = sessionId;\n }\n if (!response.ok) {\n const text = await response.text().catch(() => null);\n if (response.status === 401 && this._authProvider) {\n // Prevent infinite recursion when server returns 401 after successful auth\n if (this._hasCompletedAuthFlow) {\n throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');\n }\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n // Mark that we completed auth flow\n this._hasCompletedAuthFlow = true;\n // Purposely _not_ awaited, so we don't call onerror twice\n return this.send(message);\n }\n if (response.status === 403 && this._authProvider) {\n const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);\n if (error === 'insufficient_scope') {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n // Check if we've already tried upscoping with this header to prevent infinite loops.\n if (this._lastUpscopingHeader === wwwAuthHeader) {\n throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');\n }\n if (scope) {\n this._scope = scope;\n }\n if (resourceMetadataUrl) {\n this._resourceMetadataUrl = resourceMetadataUrl;\n }\n // Mark that upscoping was tried.\n this._lastUpscopingHeader = wwwAuthHeader ?? undefined;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetch\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return this.send(message);\n }\n }\n throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text}`);\n }\n // Reset auth loop flag on successful response\n this._hasCompletedAuthFlow = false;\n this._lastUpscopingHeader = undefined;\n // If the response is 202 Accepted, there's no body to process\n if (response.status === 202) {\n await response.body?.cancel();\n // if the accepted notification is initialized, we start the SSE stream\n // if it's supported by the server\n if (isInitializedNotification(message)) {\n // Start without a lastEventId since this is a fresh connection\n this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));\n }\n return;\n }\n // Get original message(s) for detecting request IDs\n const messages = Array.isArray(message) ? message : [message];\n const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;\n // Check the response type (parsed media type — see mediaTypeEssence)\n const contentType = response.headers.get('content-type');\n const responseMediaType = mediaTypeEssence(contentType);\n if (hasRequests) {\n if (responseMediaType === 'text/event-stream') {\n // Handle SSE stream responses for requests\n // We use the same handler as standalone streams, which now supports\n // reconnection with the last event ID\n this._handleSseStream(response.body, { onresumptiontoken }, false);\n }\n else if (responseMediaType === 'application/json') {\n // For non-streaming servers, we might get direct JSON responses\n const data = await response.json();\n const responseMessages = Array.isArray(data)\n ? data.map(msg => JSONRPCMessageSchema.parse(msg))\n : [JSONRPCMessageSchema.parse(data)];\n for (const msg of responseMessages) {\n this.onmessage?.(msg);\n }\n }\n else {\n await response.body?.cancel();\n throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n }\n }\n else {\n // No requests in message but got 200 OK - still need to release connection\n await response.body?.cancel();\n }\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n get sessionId() {\n return this._sessionId;\n }\n /**\n * Terminates the current session by sending a DELETE request to the server.\n *\n * Clients that no longer need a particular session\n * (e.g., because the user is leaving the client application) SHOULD send an\n * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly\n * terminate the session.\n *\n * The server MAY respond with HTTP 405 Method Not Allowed, indicating that\n * the server does not allow clients to terminate sessions.\n */\n async terminateSession() {\n if (!this._sessionId) {\n return; // No session to terminate\n }\n try {\n const headers = await this._commonHeaders();\n const init = {\n ...this._requestInit,\n method: 'DELETE',\n headers,\n signal: this._abortController?.signal\n };\n const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);\n await response.body?.cancel();\n // We specifically handle 405 as a valid response according to the spec,\n // meaning the server does not support explicit session termination\n if (!response.ok && response.status !== 405) {\n throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);\n }\n this._sessionId = undefined;\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n setProtocolVersion(version) {\n this._protocolVersion = version;\n }\n get protocolVersion() {\n return this._protocolVersion;\n }\n /**\n * Resume an SSE stream from a previous event ID.\n * Opens a GET SSE connection with Last-Event-ID header to replay missed events.\n *\n * @param lastEventId The event ID to resume from\n * @param options Optional callback to receive new resumption tokens\n */\n async resumeStream(lastEventId, options) {\n await this._startOrAuthSse({\n resumptionToken: lastEventId,\n onresumptiontoken: options?.onresumptiontoken\n });\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","import type { McpServerSpec } from \"@codeden/contracts\";\n\n/** What a connection test starts or reaches, after environment variables are applied. */\nexport type ResolvedMcpServer =\n | {\n type: \"stdio\";\n command: string;\n args: string[];\n /** The server's own variables (on top of the runner's environment). */\n env: Record<string, string>;\n cwd: string | undefined;\n }\n | { type: \"http\" | \"sse\"; url: string; headers: Record<string, string> };\n\n/** A `${VAR}` without a default named a variable that is not set. */\nexport class MissingEnvError extends Error {\n constructor(readonly names: string[]) {\n super(\n names.length === 1\n ? `Environment variable ${names[0]} is not set`\n : `Environment variables ${names.join(\", \")} are not set`,\n );\n this.name = \"MissingEnvError\";\n }\n}\n\nconst PLACEHOLDER = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g;\n\n/**\n * Expand `${VAR}` and `${VAR:-default}` the way Claude Code does in its MCP config: an unset\n * variable takes the default, and one without a default is collected into `missing`.\n */\nexport function expandEnvVars(\n value: string,\n env: Record<string, string | undefined>,\n missing: Set<string>,\n): string {\n return value.replace(PLACEHOLDER, (match, name: string, fallback: string | undefined) => {\n const set = env[name];\n if (set !== undefined) return set;\n if (fallback !== undefined) return fallback;\n missing.add(name);\n return match;\n });\n}\n\nconst mapValues = (o: Record<string, string> | undefined, f: (v: string) => string) =>\n Object.fromEntries(Object.entries(o ?? {}).map(([k, v]) => [k, f(v)]));\n\n/**\n * Set a header, replacing every copy of it under any casing. HTTP header names are\n * case-insensitive, and two spellings (`authorization` and `Authorization`) would otherwise\n * be sent as one header with both values joined, such as an invalid `Bearer a, Bearer b`.\n */\nfunction setHeader(headers: Record<string, string>, name: string, value: string): void {\n const lower = name.toLowerCase();\n for (const existing of Object.keys(headers)) {\n if (existing.toLowerCase() === lower) delete headers[existing];\n }\n headers[name] = value;\n}\n\n/**\n * Apply the environment to a spec as the provider would before starting it.\n * - `expandEnv` (Claude): `${VAR}` placeholders in the command, args, env, URL and headers.\n * - Codex: `bearerTokenEnvVar` becomes an `Authorization: Bearer` header, and the native\n * `env_http_headers` table (header name -> variable name) adds headers from set variables.\n * Header names are matched case-insensitively and one value wins, in this order: the\n * bearer-token variable, then `env_http_headers`, then the headers themselves (the last\n * spelling in the file when the same header appears twice there).\n * Throws `MissingEnvError` naming every variable that is required but not set.\n */\nexport function resolveMcpSpec(\n spec: McpServerSpec,\n opts: { expandEnv: boolean; env: Record<string, string | undefined> },\n): ResolvedMcpServer {\n const missing = new Set<string>();\n const x = (v: string) => (opts.expandEnv ? expandEnvVars(v, opts.env, missing) : v);\n let resolved: ResolvedMcpServer;\n if (spec.type === \"stdio\") {\n resolved = {\n type: \"stdio\",\n command: x(spec.command),\n args: (spec.args ?? []).map(x),\n env: mapValues(spec.env, x),\n cwd: spec.cwd ? x(spec.cwd) : undefined,\n };\n } else {\n const url = x(spec.url);\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(spec.headers ?? {})) {\n setHeader(headers, name, x(value));\n }\n const envHeaders = spec.extra?.env_http_headers;\n if (envHeaders && typeof envHeaders === \"object\" && !Array.isArray(envHeaders)) {\n for (const [header, variable] of Object.entries(envHeaders)) {\n const value = typeof variable === \"string\" ? opts.env[variable] : undefined;\n if (value !== undefined) setHeader(headers, header, value);\n }\n }\n if (spec.bearerTokenEnvVar) {\n const token = opts.env[spec.bearerTokenEnvVar];\n if (token === undefined) missing.add(spec.bearerTokenEnvVar);\n else setHeader(headers, \"Authorization\", `Bearer ${token}`);\n }\n resolved = { type: spec.type, url, headers };\n }\n if (missing.size > 0) throw new MissingEnvError([...missing]);\n return resolved;\n}\n","import type { McpStdioEnv } from \"@codeden/contracts\";\n\n/** Variables Codex passes from its own environment to every local stdio server, on POSIX. */\nconst CODEX_POSIX_DEFAULTS = [\n \"HOME\",\n \"LOGNAME\",\n \"PATH\",\n \"SHELL\",\n \"USER\",\n \"__CF_USER_TEXT_ENCODING\",\n \"LANG\",\n \"LC_ALL\",\n \"TERM\",\n \"TMPDIR\",\n \"TZ\",\n];\n\n/** The same on Windows. */\nconst CODEX_WINDOWS_DEFAULTS = [\n \"PATH\",\n \"PATHEXT\",\n \"SHELL\",\n \"COMSPEC\",\n \"SYSTEMROOT\",\n \"WINDIR\",\n \"SYSTEMDRIVE\",\n \"USERNAME\",\n \"USERDOMAIN\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"PROGRAMFILES\",\n \"PROGRAMFILES(X86)\",\n \"PROGRAMW6432\",\n \"PROGRAMDATA\",\n \"LOCALAPPDATA\",\n \"APPDATA\",\n \"TEMP\",\n \"TMP\",\n \"TMPDIR\",\n \"POWERSHELL\",\n \"PWSH\",\n];\n\n/** CA bundle variables Codex also passes on when they are set and not empty. */\nconst CODEX_CA_VARS = [\n \"CODEX_CA_CERTIFICATE\",\n \"SSL_CERT_FILE\",\n \"REQUESTS_CA_BUNDLE\",\n \"CURL_CA_BUNDLE\",\n \"NODE_EXTRA_CA_CERTS\",\n \"GIT_SSL_CAINFO\",\n \"CARGO_HTTP_CAINFO\",\n \"PIP_CERT\",\n \"BUNDLE_SSL_CA_CERT\",\n \"npm_config_cafile\",\n \"NPM_CONFIG_CAFILE\",\n];\n\n/** Added to a failed `allowlist` test of a stdio server that started. */\nexport const ALLOWLIST_NOTE =\n \"Codex starts a stdio server with only a few variables from your environment (PATH, HOME or \" +\n \"USERPROFILE, the temp folder and the like), the names listed in its env_vars and its env \" +\n \"table. If the server needs another variable, such as a token, add its name to the \" +\n \"server's env_vars in ~/.codex/config.toml.\";\n\n/**\n * Names in Codex's native `env_vars` list (kept in a spec's `extra`): plain names, or\n * `{ name, source }` tables. A `source = \"remote\"` entry is read on a remote machine, never\n * from the local environment, so it is left out.\n */\nexport function codexEnvVarNames(extra: Record<string, unknown> | undefined): string[] {\n const list = extra?.env_vars;\n if (!Array.isArray(list)) return [];\n return list.flatMap((entry: unknown) => {\n if (typeof entry === \"string\") return [entry];\n if (typeof entry !== \"object\" || entry === null) return [];\n const { name, source } = entry as { name?: unknown; source?: unknown };\n return typeof name === \"string\" && source !== \"remote\" ? [name] : [];\n });\n}\n\n/**\n * The environment a stdio server starts with in a connection test (`McpStdioEnv`). `base` is\n * the runner's environment (minus CodeDen's secrets); the server's own `env` always wins.\n * Variable names are matched ignoring case on Windows, as the OS does.\n */\nexport function stdioServerEnv(opts: {\n policy: McpStdioEnv;\n base: Record<string, string>;\n serverEnv: Record<string, string>;\n /** Names to pass from `base` besides the defaults (`allowlist`). */\n envVars: string[];\n platform?: NodeJS.Platform;\n}): Record<string, string> {\n const windows = (opts.platform ?? process.platform) === \"win32\";\n const fold = (name: string) => (windows ? name.toUpperCase() : name);\n const out: Record<string, string> = {};\n const set = (name: string, value: string) => {\n if (windows) {\n for (const key of Object.keys(out)) if (fold(key) === fold(name)) delete out[key];\n }\n out[name] = value;\n };\n\n if (opts.policy === \"inherit\") {\n Object.assign(out, opts.base);\n } else {\n const byName = new Map(Object.entries(opts.base).map(([k, v]) => [fold(k), v]));\n const defaults = windows ? CODEX_WINDOWS_DEFAULTS : CODEX_POSIX_DEFAULTS;\n for (const name of [...defaults, ...opts.envVars]) {\n const value = byName.get(fold(name));\n if (value !== undefined) set(name, value);\n }\n for (const name of CODEX_CA_VARS) {\n const value = byName.get(fold(name));\n if (value) set(name, value);\n }\n }\n for (const [name, value] of Object.entries(opts.serverEnv)) set(name, value);\n return out;\n}\n","import { JSONRPCMessageSchema } from '../types.js';\nexport const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n constructor(options) {\n this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;\n }\n append(chunk) {\n const newSize = (this._buffer?.length ?? 0) + chunk.length;\n if (newSize > this._maxBufferSize) {\n this.clear();\n throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);\n }\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","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed);\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","/// <reference path=\"../types/cross-spawn.d.ts\" />\nimport type { ChildProcess, spawn as nodeSpawn } from \"node:child_process\";\nimport { ReadBuffer, serializeMessage } from \"@modelcontextprotocol/sdk/shared/stdio.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport crossSpawn from \"cross-spawn\";\n\n/** Starts the server process: `cross-spawn` by default, a fake child in tests. */\nexport type SpawnServer = (\n command: string,\n args: string[],\n options: Parameters<typeof nodeSpawn>[2],\n) => ChildProcess;\n\nexport interface McpStdioParams {\n command: string;\n args: string[];\n env: Record<string, string>;\n cwd: string;\n onStderr: (chunk: string) => void;\n spawn?: SpawnServer;\n}\n\n/**\n * MCP over a child process's stdin and stdout, for connection tests (§12.4).\n *\n * It only talks to the process and never stops it: the test stops the whole tree it started,\n * on every path. So the pid is kept from spawn to the end, even after the process has exited\n * or the client has closed the transport, and on POSIX the process leads its own process\n * group, which still reaches what it started after it is gone. `cross-spawn` runs `.cmd`\n * shims such as `npx` on Windows.\n */\nexport class McpStdioTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n /** The server process, from spawn on; null when it could not be started. */\n pid: number | null = null;\n private child: ChildProcess | null = null;\n private readonly buffer = new ReadBuffer();\n\n constructor(private readonly params: McpStdioParams) {}\n\n start(): Promise<void> {\n if (this.child) throw new Error(\"Already started\");\n const spawn = this.params.spawn ?? crossSpawn;\n return new Promise((resolve, reject) => {\n const child = spawn(this.params.command, this.params.args, {\n cwd: this.params.cwd,\n env: this.params.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n detached: process.platform !== \"win32\",\n });\n this.child = child;\n child.once(\"error\", (error) => {\n reject(error);\n this.onerror?.(error);\n });\n child.once(\"spawn\", () => {\n this.pid = child.pid ?? null;\n resolve();\n });\n child.once(\"close\", () => {\n this.child = null;\n this.onclose?.();\n });\n child.stdout?.on(\"data\", (chunk: Buffer) => this.read(chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => this.params.onStderr(chunk.toString(\"utf8\")));\n for (const stream of [child.stdin, child.stdout, child.stderr]) {\n stream?.on(\"error\", (error) => this.onerror?.(error));\n }\n });\n }\n\n send(message: JSONRPCMessage): Promise<void> {\n const stdin = this.child?.stdin;\n if (!stdin?.writable) return Promise.reject(new Error(\"Not connected\"));\n return new Promise((resolve, reject) => {\n stdin.write(serializeMessage(message), (error) => (error ? reject(error) : resolve()));\n });\n }\n\n /** Detach from the process; stopping it is the caller's job (see the class comment). */\n async close(): Promise<void> {\n this.child = null;\n this.buffer.clear();\n }\n\n private read(chunk: Buffer): void {\n try {\n this.buffer.append(chunk);\n } catch (error) {\n this.onerror?.(error as Error);\n return;\n }\n for (;;) {\n let message: JSONRPCMessage | null;\n try {\n message = this.buffer.readMessage();\n } catch (error) {\n // A line that isn't JSON-RPC (a log line on stdout) is reported and skipped.\n this.onerror?.(error as Error);\n continue;\n }\n if (message === null) return;\n this.onmessage?.(message);\n }\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport {\n MCP_TEST_DEFAULT_TIMEOUT_MS,\n MCP_TEST_DESCRIPTION_LIMIT,\n MCP_TEST_ERROR_LIMIT,\n MCP_TEST_MAX_PAGES,\n MCP_TEST_MAX_TOOLS,\n MCP_TEST_STDERR_LIMIT,\n type McpServerSpec,\n type McpServerTestResult,\n type McpStdioEnv,\n type McpTestStage,\n type McpTestTool,\n} from \"@codeden/contracts\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport { childEnv } from \"../process/env\";\nimport type { ProcessSupervisor } from \"../process/supervisor\";\nimport { killTreeAndOrphans } from \"../process/tree\";\nimport { type ResolvedMcpServer, resolveMcpSpec } from \"./resolve-spec\";\nimport { ALLOWLIST_NOTE, codexEnvVarNames, stdioServerEnv } from \"./stdio-env\";\nimport { McpStdioTransport, type SpawnServer } from \"./stdio-transport\";\n\nexport interface McpServerTestOptions {\n spec: McpServerSpec;\n /** Working directory of a stdio server without its own `cwd`; the home folder when omitted. */\n cwd?: string;\n /** Expand `${VAR}` placeholders (Claude Code's config). */\n expandEnv: boolean;\n timeoutMs?: number;\n /** Reported to the server as the client version. */\n clientVersion: string;\n /** Environment for placeholders and stdio servers; the runner's (minus secrets) by default. */\n env?: Record<string, string>;\n /** How much of `env` a stdio server gets (`McpStdioEnv`); `inherit` when omitted. */\n stdioEnv?: McpStdioEnv;\n /** The platform whose rules `allowlist` follows; this one by default. */\n platform?: NodeJS.Platform;\n /** Tracks a stdio server while it runs, so a runner shutdown stops it too. */\n supervisor?: Pick<ProcessSupervisor, \"adopt\" | \"release\">;\n /** Starts a stdio server (`cross-spawn` by default; tests pass a fake child process). */\n spawn?: SpawnServer;\n /** Stops a stdio server's whole process tree (`killTreeAndOrphans` by default). */\n stopTree?: (pid: number) => Promise<void>;\n}\n\n/** Keeps the last `limit` characters written to it. */\nclass TailBuffer {\n private text = \"\";\n constructor(private readonly limit: number) {}\n append(chunk: string): void {\n this.text = (this.text + chunk).slice(-this.limit * 2);\n }\n value(): string | undefined {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: strips terminal colour codes\n const clean = this.text.replace(/\\u001b\\[[0-9;?]*[A-Za-z]/g, \"\").trim();\n return clean ? clean.slice(-this.limit) : undefined;\n }\n}\n\n/**\n * Connect to an MCP server as an agent would (§12.4): start it (stdio) or reach its URL\n * (http/sse), run the `initialize` handshake and `tools/list`, then stop it. Never throws:\n * a server that fails is an `ok: false` result with the stage, the error and (stdio) the end\n * of its stderr.\n */\nexport async function testMcpServer(opts: McpServerTestOptions): Promise<McpServerTestResult> {\n const started = performance.now();\n const elapsed = () => Math.round(performance.now() - started);\n const timeoutMs = opts.timeoutMs ?? MCP_TEST_DEFAULT_TIMEOUT_MS;\n const env = opts.env ?? childEnv();\n const stderr = new TailBuffer(MCP_TEST_STDERR_LIMIT);\n let stage: McpTestStage = \"start\";\n let timedOut = false;\n let protocolVersion: string | null = null;\n let stdio: McpStdioTransport | null = null;\n\n const stdioEnv = opts.stdioEnv ?? \"inherit\";\n const fail = (error: unknown): McpServerTestResult => {\n const tail = stderr.value();\n // A server that started and then failed may have missed a variable the policy left out.\n const note =\n stdioEnv === \"allowlist\" && opts.spec.type === \"stdio\" && stage !== \"start\"\n ? ALLOWLIST_NOTE\n : undefined;\n return {\n ok: false,\n durationMs: elapsed(),\n stage,\n error: describeError(error, { timedOut, timeoutMs, type: opts.spec.type }),\n timedOut,\n ...(tail ? { stderrTail: tail } : {}),\n ...(note ? { note } : {}),\n };\n };\n\n const client = new Client({ name: \"codeden-mcp-test\", version: opts.clientVersion });\n try {\n const server = resolveMcpSpec(opts.spec, { expandEnv: opts.expandEnv, env });\n const cwd = (server.type === \"stdio\" ? server.cwd : undefined) ?? opts.cwd ?? homedir();\n const transport: Transport = createTransport(server, {\n cwd,\n env,\n stdioEnv,\n envVars: opts.spec.type === \"stdio\" ? codexEnvVarNames(opts.spec.extra) : [],\n platform: opts.platform,\n stderr,\n spawn: opts.spawn,\n });\n // The client starts the transport, then negotiates the protocol version; both are\n // observed here so a failure names its stage and a success reports the version.\n const start = transport.start.bind(transport);\n transport.start = async () => {\n await start();\n stage = \"connect\";\n if (stdio?.pid) {\n opts.supervisor?.adopt({ pid: stdio.pid, label: \"MCP server test\", cwd });\n }\n };\n const setVersion = transport.setProtocolVersion?.bind(transport);\n transport.setProtocolVersion = (version: string) => {\n protocolVersion = version;\n setVersion?.(version);\n };\n if (transport instanceof McpStdioTransport) stdio = transport;\n\n const work = (async () => {\n await client.connect(transport, { timeout: timeoutMs });\n stage = \"list_tools\";\n return listTools(client, timeoutMs);\n })();\n const { toolCount, morePages, tools } = await withTimeout(work, timeoutMs, () => {\n timedOut = true;\n });\n const info = client.getServerVersion();\n return {\n ok: true,\n durationMs: elapsed(),\n server: {\n name: info?.name ?? \"\",\n version: info?.version ?? \"\",\n ...(info?.title ? { title: info.title } : {}),\n },\n protocolVersion,\n toolCount,\n morePages,\n tools,\n };\n } catch (error) {\n return fail(error);\n } finally {\n const stopTree = opts.stopTree ?? ((pid: number) => killTreeAndOrphans(pid, 1_000));\n await stop(client, stdio?.pid ?? null, stopTree);\n if (stdio?.pid) opts.supervisor?.release(stdio.pid);\n }\n}\n\nfunction createTransport(\n server: ResolvedMcpServer,\n ctx: {\n cwd: string;\n env: Record<string, string>;\n stdioEnv: McpStdioEnv;\n envVars: string[];\n platform?: NodeJS.Platform;\n stderr: TailBuffer;\n spawn?: SpawnServer;\n },\n): Transport {\n if (server.type === \"stdio\") {\n if (!existsSync(ctx.cwd) || !statSync(ctx.cwd).isDirectory()) {\n throw new Error(`Working folder not found: ${ctx.cwd}`);\n }\n return new McpStdioTransport({\n command: server.command,\n args: server.args,\n env: stdioServerEnv({\n policy: ctx.stdioEnv,\n base: ctx.env,\n serverEnv: server.env,\n envVars: ctx.envVars,\n platform: ctx.platform,\n }),\n cwd: ctx.cwd,\n onStderr: (chunk) => ctx.stderr.append(chunk),\n spawn: ctx.spawn,\n });\n }\n let url: URL;\n try {\n url = new URL(server.url);\n } catch {\n throw new Error(`Not a valid URL: ${server.url}`);\n }\n const requestInit = { headers: server.headers };\n return server.type === \"sse\"\n ? new SSEClientTransport(url, { requestInit })\n : new StreamableHTTPClientTransport(url, { requestInit });\n}\n\n/** Every page of `tools/list`, up to `MCP_TEST_MAX_PAGES`; `morePages` when it stopped early. */\nasync function listTools(\n client: Client,\n timeoutMs: number,\n): Promise<{ toolCount: number; morePages: boolean; tools: McpTestTool[] }> {\n if (!client.getServerCapabilities()?.tools) return { toolCount: 0, morePages: false, tools: [] };\n const tools: McpTestTool[] = [];\n let toolCount = 0;\n let cursor: string | undefined;\n for (let page = 0; page < MCP_TEST_MAX_PAGES; page++) {\n const result = await client.listTools(cursor ? { cursor } : undefined, { timeout: timeoutMs });\n toolCount += result.tools.length;\n for (const tool of result.tools) {\n if (tools.length >= MCP_TEST_MAX_TOOLS) break;\n tools.push({\n name: tool.name,\n ...(tool.title ? { title: tool.title } : {}),\n ...(tool.description\n ? { description: tool.description.slice(0, MCP_TEST_DESCRIPTION_LIMIT) }\n : {}),\n });\n }\n cursor = result.nextCursor;\n if (!cursor) break;\n }\n return { toolCount, morePages: cursor !== undefined, tools };\n}\n\nfunction withTimeout<T>(work: Promise<T>, ms: number, onTimeout: () => void): Promise<T> {\n // The work is abandoned (and the transport closed) on timeout; its rejection is expected.\n work.catch(() => undefined);\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n onTimeout();\n reject(new Error(\"timed out\"));\n }, ms);\n });\n return Promise.race([work, timeout]).finally(() => clearTimeout(timer));\n}\n\n/**\n * Stop the server on every path (success, failed handshake, timeout): the whole process tree\n * of the pid kept from spawn, including what it started and left behind (wrappers such as\n * `npx`, detached helpers), then the client.\n */\nasync function stop(\n client: Client,\n pid: number | null,\n stopTree: (pid: number) => Promise<void>,\n): Promise<void> {\n if (pid !== null) await stopTree(pid).catch(() => undefined);\n await client.close().catch(() => undefined);\n}\n\nfunction describeError(\n error: unknown,\n ctx: { timedOut: boolean; timeoutMs: number; type: McpServerSpec[\"type\"] },\n): string {\n let message: string;\n if (ctx.timedOut) {\n message = `No answer within ${Math.round(ctx.timeoutMs / 1000)} s; the server was stopped`;\n } else if (error instanceof Error) {\n message = error.message;\n const code = (error as { code?: unknown }).code;\n if (ctx.type !== \"stdio\" && (code === 401 || /\\b401\\b/.test(message))) {\n message = `Unauthorized (401): the server needs a sign-in, which the agent's CLI does and this test can't. ${message}`;\n }\n // `fetch failed` hides the reason (refused, DNS, TLS) in its cause.\n const cause = (error as { cause?: unknown }).cause;\n if (cause instanceof Error && !message.includes(cause.message)) {\n message = `${message}: ${cause.message}`;\n }\n if (/connection closed/i.test(message) && ctx.type === \"stdio\") {\n message = `${message}. The server stopped before it answered`;\n }\n } else {\n message = String(error);\n }\n return message.slice(0, MCP_TEST_ERROR_LIMIT);\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"mappings":";;;;;;;AAGA,MAAa,eAAe;CACxB,cAAc;CACd,SAAS;CACT,WAAW;CACX,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,eAAe;CACf,aAAa;CACb,iBAAiB;CACjB,eAAe;CACf,QAAQ;AACZ;;AAaA,IAAW;AAER,0BAA0B,wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;ACZtD,IAAa,0BAAb,MAAqC;CACjC,YAAY,SAAS;EACjB,KAAK,UAAU;CACnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,OA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