@nest-mcp/nestjs 0.0.0-stage → 2.0.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["fromJsonSchema","isPlainRecord","#mutationObservers","#append","#serverNames","#registerDynamic","#handlers","#effectiveTargets","#gatewayNames","#catalogRuntimeNames","#assertKnownTargets","#assertOpen","#closed","#assertCatalogToolCompatibility","#resolveVisibility","#assertNoEntryCollision","#notify","#scanned","#gateways","#httpComposers","#oauthProxies","#providerTokenList","#resolveProvider","#createGatewayFeature","#unsubscribeCapabilityMutations","#ready","#assertReady","#shutdownError","#closeTask","#performClose","#bindGatewayPolicy","#resolveOptionalProvider","#resolveProviderMethods","#getNodeHandler","#nodeHandler","#proxy","#readForm","#metadata"],"sources":["../src/mcp-catalog-exposure.ts","../src/decorators/mcp-handler.decorators.ts","../src/http/node-bridge.ts","../src/mcp-catalog.runtime.ts","../src/discovery/mcp-handler.registry.ts","../src/mcp-capabilities.service.ts","../src/discovery/mcp-handler.explorer.ts","../src/server/provider-resolution.ts","../src/server/mcp-server-options.ts","../src/oauth/mcp-oauth-options.ts","../src/mcp-runtime.service.ts","../src/mcp-http.controller.ts","../src/mcp-cors.ts","../src/oauth/mcp-oauth.controller.ts","../src/oauth/mcp-oauth.service.ts","../src/http/mcp-http-routes.ts","../src/mcp.module-definition.ts","../src/mcp.module.ts","../src/mcp-handler.middleware.ts"],"sourcesContent":["import type { MaybePromise } from \"@nest-mcp/core\";\nimport type { McpServerBuildContext, McpServerPrincipal } from \"@nest-mcp/server\";\nimport type { Tool } from \"@modelcontextprotocol/server\";\n\nexport const MCP_CATALOG_SEARCH_TOOL_NAME = \"nest-mcp.catalog.search\";\nexport const MCP_CATALOG_SCHEMAS_TOOL_NAME = \"nest-mcp.catalog.schemas\";\n\nexport type McpCatalogExposureKind = \"eager\" | \"search\" | \"lazy\";\n\n/** Recursive readonly view used for detached catalog values. */\nexport type McpCatalogReadonly<Value> = Value extends readonly unknown[]\n\t? { readonly [Index in keyof Value]: McpCatalogReadonly<Value[Index]> }\n\t: Value extends object\n\t\t? { readonly [Key in keyof Value]: McpCatalogReadonly<Value[Key]> }\n\t\t: Value;\n\n/** A detached, deeply frozen public projection of one visible SDK tool. */\nexport interface McpCatalogTool {\n\treadonly tool: McpCatalogReadonly<Tool>;\n\treadonly tags: readonly string[];\n}\n\nexport interface McpCatalogNameSelector {\n\treadonly kind: \"name\";\n\treadonly name: string;\n}\n\nexport interface McpCatalogTagSelector {\n\treadonly kind: \"tag\";\n\treadonly tag: string;\n}\n\nexport interface McpCatalogPredicateSelector {\n\treadonly kind: \"predicate\";\n\treadonly predicate: (tool: McpCatalogTool) => boolean;\n}\n\nexport type McpCatalogToolSelector =\n\tMcpCatalogNameSelector | McpCatalogTagSelector | McpCatalogPredicateSelector;\n\nexport interface McpCatalogEagerExposure {\n\treadonly kind: \"eager\";\n}\n\nexport interface McpCatalogSearchExposure {\n\treadonly kind: \"search\";\n\t/** Selectors for tools advertised eagerly. Every other visible tool receives deferredMetadata. */\n\treadonly eager?: readonly McpCatalogToolSelector[];\n\t/** Explicit vendor-specific marker merged into deferred tools' existing `_meta`. */\n\treadonly deferredMetadata: Readonly<Record<string, unknown>>;\n}\n\nexport interface McpCatalogLazyExposure {\n\treadonly kind: \"lazy\";\n\t/** Selectors for ordinary tools included in `tools/list` beside the bounded meta-tools. */\n\treadonly eager?: readonly McpCatalogToolSelector[];\n}\n\nexport type McpCatalogExposureStrategy<\n\tKind extends McpCatalogExposureKind = McpCatalogExposureKind,\n> = Extract<\n\tMcpCatalogEagerExposure | McpCatalogSearchExposure | McpCatalogLazyExposure,\n\t{ readonly kind: Kind }\n>;\n\n/** Deliberately omits raw auth info, requests, callbacks, policies and registry definitions. */\nexport interface McpCatalogExposureResolverInput {\n\treadonly runtimeName: string;\n\treadonly era: McpServerBuildContext[\"era\"];\n\treadonly principal?: Readonly<McpServerPrincipal>;\n\treadonly signal?: AbortSignal;\n\treadonly tools: readonly McpCatalogTool[];\n}\n\nexport type McpCatalogExposureResolver<\n\tStrategy extends McpCatalogExposureStrategy = McpCatalogExposureStrategy,\n> = (input: McpCatalogExposureResolverInput) => MaybePromise<Strategy>;\n\n/** Injectable Nest policy that selects the catalog projection for one serving unit. */\nexport interface McpCatalogExposurePolicy<\n\tStrategy extends McpCatalogExposureStrategy = McpCatalogExposureStrategy,\n> {\n\tresolve(input: McpCatalogExposureResolverInput): MaybePromise<Strategy>;\n}\n\n/** Framework-internal callback adapter. Nest applications configure a policy provider token. */\nexport interface McpCatalogExposureOptions {\n\treadonly resolver: McpCatalogExposureResolver;\n}\n\nexport interface McpCatalogSearchResultTool {\n\treadonly name: string;\n\treadonly title?: string;\n\treadonly description?: string;\n\treadonly tags: readonly string[];\n}\n\nexport interface McpCatalogSearchResult {\n\treadonly tools: readonly McpCatalogSearchResultTool[];\n\treadonly nextCursor?: string;\n}\n\nexport interface McpCatalogSchemasResult {\n\treadonly tools: readonly McpCatalogReadonly<Tool>[];\n}\n","import { SetMetadata } from \"@nestjs/common\";\nimport type {\n\tCacheHint,\n\tIcon,\n\tPromptCallback,\n\tReadResourceCallback,\n\tReadResourceTemplateCallback,\n\tResourceMetadata,\n\tResourceTemplate,\n\tStandardSchemaWithJSON,\n\tToolAnnotations,\n\tToolCallback,\n} from \"@nest-mcp/server\";\nimport type { McpCapabilityVisibility } from \"../mcp-capability.types.ts\";\nimport { MCP_HANDLER_METADATA, MCP_TARGETS_METADATA } from \"../mcp.tokens.ts\";\n\ninterface HandlerTarget {\n\t/** Runtime names receiving this handler. Omit for every configured server. */\n\treadonly servers?: string | readonly string[];\n\t/** Discovery visibility. Invocation authorization remains independently mandatory. */\n\treadonly visibility?: McpCapabilityVisibility;\n}\n\nexport interface ToolOptions<\n\tInputSchema extends StandardSchemaWithJSON | undefined = StandardSchemaWithJSON | undefined,\n> extends HandlerTarget {\n\treadonly name: string;\n\treadonly title?: string;\n\treadonly description?: string;\n\treadonly inputSchema?: InputSchema;\n\treadonly outputSchema?: StandardSchemaWithJSON;\n\treadonly annotations?: ToolAnnotations;\n\treadonly icons?: Icon[];\n\treadonly _meta?: Record<string, unknown>;\n\t/** Searchable application labels used only by Nest MCP catalog selectors. */\n\treadonly tags?: readonly string[];\n}\n\nexport interface ResourceOptions<\n\tUri extends string | ResourceTemplate = string | ResourceTemplate,\n> extends HandlerTarget {\n\treadonly name: string;\n\treadonly uri: Uri;\n\treadonly title?: string;\n\treadonly description?: string;\n\treadonly mimeType?: string;\n\treadonly size?: number;\n\treadonly icons?: Icon[];\n\treadonly annotations?: ResourceMetadata[\"annotations\"];\n\treadonly _meta?: Record<string, unknown>;\n\treadonly cacheHint?: CacheHint;\n}\n\nexport interface PromptOptions<\n\tArgsSchema extends StandardSchemaWithJSON | undefined = StandardSchemaWithJSON | undefined,\n> extends HandlerTarget {\n\treadonly name: string;\n\treadonly title?: string;\n\treadonly description?: string;\n\treadonly argsSchema?: ArgsSchema;\n\treadonly icons?: Icon[];\n\treadonly _meta?: Record<string, unknown>;\n}\n\nexport interface ToolHandlerDefinition {\n\treadonly kind: \"tool\";\n\treadonly options: ToolOptions;\n}\n\nexport interface ResourceHandlerDefinition {\n\treadonly kind: \"resource\";\n\treadonly options: ResourceOptions;\n}\n\nexport interface PromptHandlerDefinition {\n\treadonly kind: \"prompt\";\n\treadonly options: PromptOptions;\n}\n\nexport type HandlerDefinition =\n\tToolHandlerDefinition | ResourceHandlerDefinition | PromptHandlerDefinition;\n\n/** Legacy-decorator signature that checks the decorated method without replacing it. */\nexport type TypedMethodDecorator<ExpectedHandler> = <Handler extends ExpectedHandler>(\n\ttarget: object,\n\tpropertyKey: string | symbol,\n\tdescriptor: TypedPropertyDescriptor<Handler>,\n) => void;\n\nexport type ToolMethodDecorator<InputSchema extends StandardSchemaWithJSON | undefined> =\n\tTypedMethodDecorator<ToolCallback<InputSchema>>;\n\nexport type PromptMethodDecorator<ArgsSchema extends StandardSchemaWithJSON | undefined> =\n\tTypedMethodDecorator<PromptCallback<ArgsSchema>>;\n\nexport type ResourceMethodDecorator<Uri extends string | ResourceTemplate> = TypedMethodDecorator<\n\tUri extends string ? ReadResourceCallback : ReadResourceTemplateCallback\n>;\n\nexport function Tool<const InputSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\toptions: ToolOptions<InputSchema>,\n): ToolMethodDecorator<InputSchema> {\n\treturn typedMetadataDecorator(freezeToolDefinition(options));\n}\n\nexport function Resource<const Uri extends string | ResourceTemplate>(\n\toptions: ResourceOptions<Uri>,\n): ResourceMethodDecorator<Uri> {\n\treturn typedMetadataDecorator(freezeResourceDefinition(options));\n}\n\nexport function Prompt<const ArgsSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\toptions: PromptOptions<ArgsSchema>,\n): PromptMethodDecorator<ArgsSchema> {\n\treturn typedMetadataDecorator(freezePromptDefinition(options));\n}\n\n/** Supplies a default server target for every MCP handler declared by a provider class. */\nexport function Targets(...serverNames: readonly [string, ...string[]]): ClassDecorator {\n\tconst normalized = normalizeTargets(serverNames);\n\treturn SetMetadata(MCP_TARGETS_METADATA, normalized);\n}\n\nfunction typedMetadataDecorator<Handler>(\n\tdefinition: HandlerDefinition,\n): TypedMethodDecorator<Handler> {\n\tconst decorator = SetMetadata(MCP_HANDLER_METADATA, definition);\n\treturn (target, propertyKey, descriptor) => {\n\t\tdecorator(target, propertyKey, descriptor);\n\t};\n}\n\nfunction freezeToolDefinition(options: ToolOptions): ToolHandlerDefinition {\n\tconst { tags, ...sdkOptions } = options;\n\tconst normalizedTags = normalizeTags(tags);\n\treturn Object.freeze({\n\t\tkind: \"tool\",\n\t\toptions: freezeOptions({\n\t\t\t...sdkOptions,\n\t\t\t...(normalizedTags === undefined ? {} : { tags: normalizedTags }),\n\t\t}),\n\t});\n}\n\nfunction freezeResourceDefinition(options: ResourceOptions): ResourceHandlerDefinition {\n\treturn Object.freeze({ kind: \"resource\", options: freezeOptions(options) });\n}\n\nfunction freezePromptDefinition(options: PromptOptions): PromptHandlerDefinition {\n\treturn Object.freeze({ kind: \"prompt\", options: freezeOptions(options) });\n}\n\nfunction freezeOptions<Options extends HandlerTarget>(options: Options): Options {\n\tconst servers = options.servers;\n\tconst normalizedServers =\n\t\tservers === undefined\n\t\t\t? undefined\n\t\t\t: typeof servers === \"string\"\n\t\t\t\t? normalizeTargets([servers])[0]\n\t\t\t\t: normalizeTargets(servers);\n\treturn Object.freeze({\n\t\t...options,\n\t\t...(normalizedServers === undefined ? {} : { servers: normalizedServers }),\n\t});\n}\n\nfunction normalizeTargets(serverNames: readonly string[]): readonly string[] {\n\tif (serverNames.length === 0) {\n\t\tthrow new TypeError(\"At least one MCP server target is required.\");\n\t}\n\tconst normalized = serverNames.map((serverName, index) => {\n\t\tif (typeof serverName !== \"string\" || serverName.trim().length === 0) {\n\t\t\tthrow new TypeError(`MCP target at index ${String(index)} must be a non-empty string.`);\n\t\t}\n\t\treturn serverName.trim();\n\t});\n\tif (new Set(normalized).size !== normalized.length) {\n\t\tthrow new TypeError(\"MCP class-level targets must not contain duplicates.\");\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction normalizeTags(tags: readonly string[] | undefined): readonly string[] | undefined {\n\tif (tags === undefined) return undefined;\n\tif (!Array.isArray(tags) || tags.length > 32) {\n\t\tthrow new TypeError(\"MCP tool tags must be an array containing at most 32 entries.\");\n\t}\n\tconst normalized = tags.map((tag, index) => {\n\t\tif (typeof tag !== \"string\" || tag.trim().length === 0 || tag.trim().length > 64) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`MCP tool tag at index ${String(index)} must contain between 1 and 64 characters.`,\n\t\t\t);\n\t\t}\n\t\treturn tag.trim();\n\t});\n\tif (new Set(normalized).size !== normalized.length) {\n\t\tthrow new TypeError(\"MCP tool tags must not contain duplicates.\");\n\t}\n\treturn Object.freeze(normalized);\n}\n","import type { NodeIncomingMessageLike, NodeServerResponseLike } from \"@modelcontextprotocol/node\";\nimport type { AuthInfo } from \"@modelcontextprotocol/server\";\n\n/**\n * Platform-neutral bridge between Nest's Express/Fastify request objects and\n * the official Node MCP adapter. Shared by every Nest controller that hands a\n * raw exchange to a fetch-shaped MCP facade.\n */\n\ninterface RawCarrier {\n\treadonly raw: unknown;\n}\n\ninterface BodyCarrier {\n\treadonly body: unknown;\n}\n\ninterface FastifyReplyLike extends RawCarrier {\n\thijack(): unknown;\n}\n\nexport function toNodeRequest(request: unknown): NodeIncomingMessageLike {\n\tconst candidate = hasRaw(request) ? request.raw : request;\n\tif (!isNodeRequest(candidate)) {\n\t\tthrow new TypeError(\"Nest MCP HTTP controller requires a Node-compatible HTTP request.\");\n\t}\n\treturn candidate;\n}\n\nexport function toNodeResponse(response: unknown): NodeServerResponseLike {\n\tconst candidate = hasRaw(response) ? response.raw : response;\n\tif (!isNodeResponse(candidate)) {\n\t\tthrow new TypeError(\"Nest MCP HTTP controller requires a Node-compatible HTTP response.\");\n\t}\n\treturn candidate;\n}\n\nexport function parsedBodyOf(request: unknown): unknown {\n\treturn hasBody(request) ? request.body : undefined;\n}\n\nexport function hijackFastifyReply(response: unknown, rawResponse: NodeServerResponseLike): void {\n\tif (!isFastifyReply(response) || response.raw !== rawResponse) return;\n\tresponse.hijack();\n}\n\nexport function forwardValidatedAuth(request: unknown, rawRequest: NodeIncomingMessageLike): void {\n\tif (request === rawRequest || !isObject(request) || rawRequest.auth !== undefined) return;\n\tconst auth = Reflect.get(request, \"auth\");\n\tif (isAuthInfo(auth)) rawRequest.auth = auth;\n}\n\nfunction isAuthInfo(value: unknown): value is AuthInfo {\n\tif (!isObject(value)) return false;\n\tconst token = Reflect.get(value, \"token\");\n\tconst clientId = Reflect.get(value, \"clientId\");\n\tconst scopes = Reflect.get(value, \"scopes\");\n\tconst expiresAt = Reflect.get(value, \"expiresAt\");\n\tconst resource = Reflect.get(value, \"resource\");\n\tconst extra = Reflect.get(value, \"extra\");\n\treturn (\n\t\ttypeof token === \"string\" &&\n\t\ttypeof clientId === \"string\" &&\n\t\tArray.isArray(scopes) &&\n\t\tscopes.every((scope) => typeof scope === \"string\") &&\n\t\t(expiresAt === undefined || typeof expiresAt === \"number\") &&\n\t\t(resource === undefined || resource instanceof URL) &&\n\t\t(extra === undefined || isObject(extra))\n\t);\n}\n\nfunction hasRaw(value: unknown): value is RawCarrier {\n\treturn isObject(value) && \"raw\" in value;\n}\n\nfunction hasBody(value: unknown): value is BodyCarrier {\n\treturn isObject(value) && \"body\" in value;\n}\n\nfunction isFastifyReply(value: unknown): value is FastifyReplyLike {\n\treturn hasRaw(value) && typeof Reflect.get(value, \"hijack\") === \"function\";\n}\n\nfunction isNodeRequest(value: unknown): value is NodeIncomingMessageLike {\n\treturn (\n\t\tisObject(value) &&\n\t\tisObject(Reflect.get(value, \"headers\")) &&\n\t\ttypeof Reflect.get(value, Symbol.asyncIterator) === \"function\"\n\t);\n}\n\nfunction isNodeResponse(value: unknown): value is NodeServerResponseLike {\n\treturn (\n\t\tisObject(value) &&\n\t\ttypeof Reflect.get(value, \"writeHead\") === \"function\" &&\n\t\ttypeof Reflect.get(value, \"write\") === \"function\" &&\n\t\ttypeof Reflect.get(value, \"end\") === \"function\" &&\n\t\ttypeof Reflect.get(value, \"on\") === \"function\"\n\t);\n}\n\nfunction isObject(value: unknown): value is object {\n\treturn typeof value === \"object\" && value !== null;\n}\n\n/** Reconstructs the request origin, honoring a terminating proxy's forwarded headers. */\nexport function nodeRequestUrl(request: unknown): URL {\n\tconst raw = toNodeRequest(request);\n\tconst headers = raw.headers;\n\tconst forwardedProto = headerValue(headers[\"x-forwarded-proto\"]);\n\tconst encrypted = Reflect.get(Reflect.get(raw, \"socket\") ?? {}, \"encrypted\") === true;\n\tconst scheme = forwardedProto ?? (encrypted ? \"https\" : \"http\");\n\tconst host = headerValue(headers[\"x-forwarded-host\"]) ?? headerValue(headers.host) ?? \"localhost\";\n\treturn new URL(raw.url ?? \"/\", `${scheme}://${host}`);\n}\n\n/** Builds a web `Request` from a Nest request with an explicit body, for hand dispatch. */\nexport function toWebRequestWithBody(request: unknown, body: string | undefined): Request {\n\tconst raw = toNodeRequest(request);\n\tconst url = nodeRequestUrl(request);\n\tconst headers = new Headers();\n\tfor (const [name, value] of Object.entries(raw.headers)) {\n\t\tif (typeof value === \"string\") headers.set(name, value);\n\t\telse if (Array.isArray(value)) headers.set(name, value.join(\", \"));\n\t}\n\tconst method = (raw.method ?? \"GET\").toUpperCase();\n\tconst carriesBody = method !== \"GET\" && method !== \"HEAD\" && body !== undefined;\n\treturn new Request(url.href, {\n\t\tmethod,\n\t\theaders,\n\t\t...(carriesBody ? { body } : {}),\n\t});\n}\n\n/** Reads a Node request body as text, capped; returns \"\" when the stream is empty or over cap. */\nexport async function readNodeBodyText(request: unknown, maxBytes: number): Promise<string> {\n\tconst raw = toNodeRequest(request);\n\tconst chunks: Buffer[] = [];\n\tlet total = 0;\n\tfor await (const chunk of raw as AsyncIterable<unknown>) {\n\t\tconst buffer =\n\t\t\ttypeof chunk === \"string\"\n\t\t\t\t? Buffer.from(chunk)\n\t\t\t\t: chunk instanceof Uint8Array\n\t\t\t\t\t? Buffer.from(chunk)\n\t\t\t\t\t: undefined;\n\t\tif (buffer === undefined) continue;\n\t\ttotal += buffer.byteLength;\n\t\tif (total > maxBytes) return \"\";\n\t\tchunks.push(buffer);\n\t}\n\treturn Buffer.concat(chunks).toString(\"utf8\");\n}\n\n/** Writes a web `Response` (status, headers, multiple set-cookie, buffered body) to a Node response. */\nexport async function writeWebResponse(response: Response, nestResponse: unknown): Promise<void> {\n\tconst raw = toNodeResponse(nestResponse);\n\thijackFastifyReply(nestResponse, raw);\n\tconst headers: Record<string, string | string[]> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tif (key.toLowerCase() !== \"set-cookie\") headers[key] = value;\n\t});\n\tconst cookies =\n\t\ttypeof response.headers.getSetCookie === \"function\" ? response.headers.getSetCookie() : [];\n\tif (cookies.length > 0) headers[\"set-cookie\"] = cookies;\n\t// Node's writeHead accepts array header values (e.g. multiple Set-Cookie),\n\t// which the structural NodeServerResponseLike type narrows to string.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\traw.writeHead(response.status, headers as Record<string, string>);\n\tconst body = response.body === null ? undefined : Buffer.from(await response.arrayBuffer());\n\traw.end(body);\n}\n\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n\treturn Array.isArray(value) ? value[0] : value;\n}\n","import {\n\tfromJsonSchema,\n\tProtocolError,\n\tProtocolErrorCode,\n\tspecTypeSchemas,\n} from \"@modelcontextprotocol/server\";\nimport type {\n\tCallToolResult,\n\tListToolsResult,\n\tMcpServer,\n\tRegisteredTool,\n\tStandardSchemaWithJSON,\n\tTool,\n} from \"@modelcontextprotocol/server\";\nimport type { McpServerBuildContext } from \"@nest-mcp/server\";\nimport { McpModuleError } from \"./mcp.errors.ts\";\nimport {\n\tMCP_CATALOG_SCHEMAS_TOOL_NAME,\n\tMCP_CATALOG_SEARCH_TOOL_NAME,\n} from \"./mcp-catalog-exposure.ts\";\nimport type {\n\tMcpCatalogExposureOptions,\n\tMcpCatalogExposureResolverInput,\n\tMcpCatalogExposureStrategy,\n\tMcpCatalogSearchResultTool,\n\tMcpCatalogTool,\n\tMcpCatalogToolSelector,\n} from \"./mcp-catalog-exposure.ts\";\n\nexport const MCP_CATALOG_MAX_TOOLS = 10_000;\nexport const MCP_CATALOG_LIST_PAGE_SIZE = 50;\nexport const MCP_CATALOG_SEARCH_DEFAULT_LIMIT = 20;\nexport const MCP_CATALOG_SEARCH_MAX_LIMIT = 50;\nexport const MCP_CATALOG_SCHEMA_BATCH_LIMIT = 20;\nexport const MCP_CATALOG_INPUT_BYTE_LIMIT = 16 * 1024;\nexport const MCP_CATALOG_QUERY_LENGTH_LIMIT = 256;\nexport const MCP_CATALOG_CURSOR_LENGTH_LIMIT = 512;\nexport const MCP_CATALOG_TOOL_NAME_LENGTH_LIMIT = 128;\n\nconst CATALOG_SELECTOR_LIMIT = 64;\nconst CATALOG_METADATA_BYTE_LIMIT = 8 * 1024;\nconst CATALOG_JSON_DEPTH_LIMIT = 16;\nconst EMPTY_INPUT_SCHEMA = Object.freeze({\n\ttype: \"object\",\n\tproperties: Object.freeze({}),\n}) satisfies Tool[\"inputSchema\"];\n\nexport interface McpCatalogRegisteredTool {\n\treadonly name: string;\n\treadonly registration: RegisteredTool;\n\treadonly tags: readonly string[];\n}\n\nexport interface McpCatalogMetaToolDefinition {\n\treadonly name: string;\n\treadonly title: string;\n\treadonly description: string;\n\treadonly inputSchema: StandardSchemaWithJSON;\n\treadonly outputSchema: StandardSchemaWithJSON;\n\treadonly handler: unknown;\n}\n\nexport type McpCatalogMetaToolRegistrar = (\n\tdefinition: McpCatalogMetaToolDefinition,\n) => RegisteredTool;\n\ninterface CatalogEntry {\n\treadonly tool: Tool;\n\treadonly publicTool: McpCatalogTool;\n\treadonly registration: RegisteredTool;\n}\n\ninterface NormalizedSearchExposure {\n\treadonly kind: \"search\";\n\treadonly eager: readonly McpCatalogToolSelector[];\n\treadonly deferredMetadata: Readonly<Record<string, unknown>>;\n}\n\ninterface NormalizedLazyExposure {\n\treadonly kind: \"lazy\";\n\treadonly eager: readonly McpCatalogToolSelector[];\n}\n\ntype NormalizedExposure =\n\t{ readonly kind: \"eager\" } | NormalizedSearchExposure | NormalizedLazyExposure;\n\ninterface SearchInput {\n\treadonly query?: string;\n\treadonly cursor?: string;\n\treadonly limit?: number;\n}\n\ninterface SearchOutput {\n\treadonly tools: readonly McpCatalogSearchResultTool[];\n\treadonly nextCursor?: string;\n}\n\ninterface SchemasInput {\n\treadonly names: readonly string[];\n}\n\ninterface CursorEnvelope {\n\treadonly v: 1;\n\treadonly kind: \"list\" | \"search\";\n\treadonly offset: number;\n\treadonly binding?: string;\n}\n\nconst SEARCH_INPUT_SCHEMA = fromJsonSchema<SearchInput>({\n\ttype: \"object\",\n\tproperties: {\n\t\tquery: { type: \"string\", maxLength: MCP_CATALOG_QUERY_LENGTH_LIMIT },\n\t\tcursor: { type: \"string\", maxLength: MCP_CATALOG_CURSOR_LENGTH_LIMIT },\n\t\tlimit: {\n\t\t\ttype: \"integer\",\n\t\t\tminimum: 1,\n\t\t\tmaximum: MCP_CATALOG_SEARCH_MAX_LIMIT,\n\t\t},\n\t},\n\tadditionalProperties: false,\n});\n\nconst SCHEMAS_INPUT_SCHEMA = fromJsonSchema<SchemasInput>({\n\ttype: \"object\",\n\tproperties: {\n\t\tnames: {\n\t\t\ttype: \"array\",\n\t\t\titems: { type: \"string\", minLength: 1, maxLength: MCP_CATALOG_TOOL_NAME_LENGTH_LIMIT },\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MCP_CATALOG_SCHEMA_BATCH_LIMIT,\n\t\t\tuniqueItems: true,\n\t\t},\n\t},\n\trequired: [\"names\"],\n\tadditionalProperties: false,\n});\n\nconst SEARCH_OUTPUT_SCHEMA = fromJsonSchema<SearchOutput>({\n\ttype: \"object\",\n\tproperties: {\n\t\ttools: {\n\t\t\ttype: \"array\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\ttitle: { type: \"string\" },\n\t\t\t\t\tdescription: { type: \"string\" },\n\t\t\t\t\ttags: { type: \"array\", items: { type: \"string\" } },\n\t\t\t\t},\n\t\t\t\trequired: [\"name\", \"tags\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t},\n\t\t\tmaxItems: MCP_CATALOG_SEARCH_MAX_LIMIT,\n\t\t},\n\t\tnextCursor: { type: \"string\", maxLength: MCP_CATALOG_CURSOR_LENGTH_LIMIT },\n\t},\n\trequired: [\"tools\"],\n\tadditionalProperties: false,\n});\n\nconst SCHEMAS_OUTPUT_SCHEMA = standardSchemaWithJson(specTypeSchemas.ListToolsResult);\n\nexport function assertMcpCatalogExposureOptions(\n\toptions: McpCatalogExposureOptions,\n\truntimeName: string,\n): void {\n\tif (typeof options !== \"object\" || options === null || typeof options.resolver !== \"function\") {\n\t\tthrow catalogError(\n\t\t\t`MCP catalog exposure for server \"${runtimeName}\" requires a resolver function.`,\n\t\t);\n\t}\n}\n\n/** Applies one strategy to only the exact post-visibility registrations owned by this build. */\nexport async function applyMcpCatalogExposure(\n\tserver: McpServer,\n\tcontext: McpServerBuildContext,\n\tregistrations: readonly McpCatalogRegisteredTool[],\n\toptions: McpCatalogExposureOptions,\n\ttimeoutMs: number,\n\tregisterMetaTool: McpCatalogMetaToolRegistrar,\n): Promise<void> {\n\ttry {\n\t\tif (registrations.length > MCP_CATALOG_MAX_TOOLS) {\n\t\t\tthrow catalogError(\n\t\t\t\t`MCP catalog for server \"${context.runtimeName}\" exceeds ${String(MCP_CATALOG_MAX_TOOLS)} visible tools.`,\n\t\t\t);\n\t\t}\n\t\tconst entries = Object.freeze(\n\t\t\tregistrations\n\t\t\t\t.filter(({ registration }) => registration.enabled)\n\t\t\t\t.map((registration) => snapshotEntry(registration)),\n\t\t);\n\t\tconst resolverInput = snapshotResolverInput(context, entries);\n\t\tconst resolved = await resolveWithinDeadline(\n\t\t\toptions.resolver,\n\t\t\tresolverInput,\n\t\t\ttimeoutMs,\n\t\t\tcontext.requestInfo?.signal,\n\t\t);\n\t\tconst strategy = normalizeStrategy(resolved, context.runtimeName);\n\t\tif (strategy.kind === \"eager\") return;\n\n\t\tconst eager = selectEagerEntries(entries, strategy.eager, context.runtimeName);\n\t\tif (strategy.kind === \"search\") {\n\t\t\tapplyDeferredMetadata(entries, eager, strategy.deferredMetadata, context.runtimeName);\n\t\t\treturn;\n\t\t}\n\t\tawait installLazyCatalog(server, entries, eager, registerMetaTool);\n\t} catch (cause) {\n\t\tif (cause instanceof McpModuleError && cause.code === \"INVALID_CATALOG_EXPOSURE\") {\n\t\t\tthrow cause;\n\t\t}\n\t\tthrow catalogError(\n\t\t\t`MCP catalog exposure failed closed for server \"${context.runtimeName}\".`,\n\t\t\tcause,\n\t\t);\n\t}\n}\n\nfunction snapshotEntry(registration: McpCatalogRegisteredTool): CatalogEntry {\n\tconst tool = projectRegisteredTool(registration.name, registration.registration);\n\tconst tags = detachJson(registration.tags, \"MCP catalog tags\");\n\tconst publicTool = Object.freeze({ tool, tags }) as McpCatalogTool;\n\treturn Object.freeze({\n\t\ttool,\n\t\tpublicTool,\n\t\tregistration: registration.registration,\n\t});\n}\n\nfunction projectRegisteredTool(name: string, registration: RegisteredTool): Tool {\n\tconst projected = {\n\t\tname,\n\t\t...(registration.title === undefined ? {} : { title: registration.title }),\n\t\t...(registration.description === undefined ? {} : { description: registration.description }),\n\t\tinputSchema:\n\t\t\tregistration.inputSchema === undefined\n\t\t\t\t? EMPTY_INPUT_SCHEMA\n\t\t\t\t: toInputJsonSchema(registration.inputSchema),\n\t\t...(registration.outputSchema === undefined\n\t\t\t? {}\n\t\t\t: { outputSchema: toOutputJsonSchema(registration.outputSchema) }),\n\t\t...(registration.annotations === undefined ? {} : { annotations: registration.annotations }),\n\t\t...(registration.icons === undefined ? {} : { icons: registration.icons }),\n\t\t...(registration.execution === undefined ? {} : { execution: registration.execution }),\n\t\t...(registration[\"_meta\"] === undefined ? {} : { _meta: registration[\"_meta\"] }),\n\t} satisfies Tool;\n\treturn detachJson(projected, `MCP tool \"${name}\"`);\n}\n\nfunction toInputJsonSchema(schema: StandardSchemaWithJSON): Tool[\"inputSchema\"] {\n\tconst converted = schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" });\n\tif (!isPlainRecord(converted)) {\n\t\tthrow catalogError(\"MCP tool input schema must convert to a JSON Schema object.\");\n\t}\n\tif (converted.type !== undefined && converted.type !== \"object\") {\n\t\tthrow catalogError(\"MCP tool input schema must describe an object at its root.\");\n\t}\n\treturn { type: \"object\", ...converted };\n}\n\nfunction toOutputJsonSchema(schema: StandardSchemaWithJSON): NonNullable<Tool[\"outputSchema\"]> {\n\tconst converted = schema[\"~standard\"].jsonSchema.output({ target: \"draft-2020-12\" });\n\tif (!isPlainRecord(converted)) {\n\t\tthrow catalogError(\"MCP tool output schema must convert to a JSON Schema object.\");\n\t}\n\treturn {\n\t\t...(converted.type === undefined && isObjectShapedSchema(converted) ? { type: \"object\" } : {}),\n\t\t...converted,\n\t};\n}\n\nfunction isObjectShapedSchema(schema: Record<string, unknown>): boolean {\n\tif (\n\t\t\"properties\" in schema ||\n\t\t\"patternProperties\" in schema ||\n\t\t\"additionalProperties\" in schema ||\n\t\t\"required\" in schema\n\t) {\n\t\treturn true;\n\t}\n\tfor (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n\t\tconst members = schema[keyword];\n\t\tif (\n\t\t\tArray.isArray(members) &&\n\t\t\tmembers.length > 0 &&\n\t\t\tmembers.every(\n\t\t\t\t(member) =>\n\t\t\t\t\tisPlainRecord(member) && (member.type === \"object\" || isObjectShapedSchema(member)),\n\t\t\t)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction snapshotResolverInput(\n\tcontext: McpServerBuildContext,\n\tentries: readonly CatalogEntry[],\n): McpCatalogExposureResolverInput {\n\tconst principal =\n\t\tcontext.principal === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze({\n\t\t\t\t\t...context.principal,\n\t\t\t\t\tscopes: Object.freeze([...context.principal.scopes]),\n\t\t\t\t});\n\treturn Object.freeze({\n\t\truntimeName: context.runtimeName,\n\t\tera: context.era,\n\t\t...(principal === undefined ? {} : { principal }),\n\t\t...(context.requestInfo?.signal === undefined ? {} : { signal: context.requestInfo.signal }),\n\t\ttools: Object.freeze(entries.map(({ publicTool }) => publicTool)),\n\t});\n}\n\nasync function resolveWithinDeadline(\n\tresolver: McpCatalogExposureOptions[\"resolver\"],\n\tinput: McpCatalogExposureResolverInput,\n\ttimeoutMs: number,\n\tsignal: AbortSignal | undefined,\n): Promise<McpCatalogExposureStrategy> {\n\tconst task = Promise.resolve().then(() => resolver(input));\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (callback: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tcallback();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tfinish(() =>\n\t\t\t\treject(\n\t\t\t\t\tcatalogError(\n\t\t\t\t\t\t\"MCP catalog exposure resolver was aborted before the build completed.\",\n\t\t\t\t\t\tsignal?.reason,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tfinish(() =>\n\t\t\t\treject(\n\t\t\t\t\tcatalogError(\n\t\t\t\t\t\t`MCP catalog exposure resolver exceeded its ${String(timeoutMs)}ms deadline.`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t}, timeoutMs);\n\t\ttask.then(\n\t\t\t(value) => finish(() => resolve(value)),\n\t\t\t(cause: unknown) =>\n\t\t\t\tfinish(() =>\n\t\t\t\t\treject(catalogError(\"MCP catalog exposure resolver threw or rejected.\", cause)),\n\t\t\t\t),\n\t\t);\n\t\tif (signal?.aborted === true) onAbort();\n\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nfunction normalizeStrategy(\n\tvalue: McpCatalogExposureStrategy,\n\truntimeName: string,\n): NormalizedExposure {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow catalogError(\n\t\t\t`MCP catalog resolver for server \"${runtimeName}\" must return a strategy object.`,\n\t\t);\n\t}\n\tif (value.kind === \"eager\") return Object.freeze({ kind: \"eager\" });\n\tif (value.kind === \"search\") {\n\t\treturn Object.freeze({\n\t\t\tkind: \"search\",\n\t\t\teager: normalizeSelectors(value.eager),\n\t\t\tdeferredMetadata: normalizeDeferredMetadata(value.deferredMetadata),\n\t\t});\n\t}\n\tif (value.kind === \"lazy\") {\n\t\treturn Object.freeze({ kind: \"lazy\", eager: normalizeSelectors(value.eager) });\n\t}\n\tthrow catalogError(\n\t\t`MCP catalog resolver for server \"${runtimeName}\" returned an undeclared strategy kind.`,\n\t);\n}\n\nfunction normalizeSelectors(\n\tselectors: readonly McpCatalogToolSelector[] | undefined,\n): readonly McpCatalogToolSelector[] {\n\tif (selectors === undefined) return Object.freeze([]);\n\tif (!Array.isArray(selectors) || selectors.length > CATALOG_SELECTOR_LIMIT) {\n\t\tthrow catalogError(\n\t\t\t`MCP catalog eager selectors must contain at most ${String(CATALOG_SELECTOR_LIMIT)} entries.`,\n\t\t);\n\t}\n\treturn Object.freeze(\n\t\tselectors.map((selector, index) => {\n\t\t\tif (typeof selector !== \"object\" || selector === null) {\n\t\t\t\tthrow catalogError(`MCP catalog selector at index ${String(index)} must be an object.`);\n\t\t\t}\n\t\t\tif (selector.kind === \"name\") {\n\t\t\t\tconst name = normalizeBoundedString(\n\t\t\t\t\tselector.name,\n\t\t\t\t\tMCP_CATALOG_TOOL_NAME_LENGTH_LIMIT,\n\t\t\t\t\t`MCP catalog name selector at index ${String(index)}`,\n\t\t\t\t);\n\t\t\t\treturn Object.freeze({ kind: \"name\", name });\n\t\t\t}\n\t\t\tif (selector.kind === \"tag\") {\n\t\t\t\tconst tag = normalizeBoundedString(\n\t\t\t\t\tselector.tag,\n\t\t\t\t\t64,\n\t\t\t\t\t`MCP catalog tag selector at index ${String(index)}`,\n\t\t\t\t);\n\t\t\t\treturn Object.freeze({ kind: \"tag\", tag });\n\t\t\t}\n\t\t\tif (selector.kind === \"predicate\" && typeof selector.predicate === \"function\") {\n\t\t\t\treturn Object.freeze({ kind: \"predicate\", predicate: selector.predicate });\n\t\t\t}\n\t\t\tthrow catalogError(`MCP catalog selector at index ${String(index)} is invalid.`);\n\t\t}),\n\t);\n}\n\nfunction normalizeDeferredMetadata(value: unknown): Readonly<Record<string, unknown>> {\n\tconst detached = detachJson(\n\t\tvalue,\n\t\t\"MCP search exposure deferredMetadata\",\n\t\tCATALOG_METADATA_BYTE_LIMIT,\n\t);\n\tif (!isPlainRecord(detached) || Object.keys(detached).length === 0) {\n\t\tthrow catalogError(\"MCP search exposure deferredMetadata must be a non-empty JSON object.\");\n\t}\n\treturn detached;\n}\n\nfunction selectEagerEntries(\n\tentries: readonly CatalogEntry[],\n\tselectors: readonly McpCatalogToolSelector[],\n\truntimeName: string,\n): ReadonlySet<CatalogEntry> {\n\tconst selected = new Set<CatalogEntry>();\n\tfor (const entry of entries) {\n\t\tfor (const selector of selectors) {\n\t\t\tlet matches: boolean;\n\t\t\tif (selector.kind === \"name\") matches = entry.tool.name === selector.name;\n\t\t\telse if (selector.kind === \"tag\") matches = entry.publicTool.tags.includes(selector.tag);\n\t\t\telse {\n\t\t\t\tlet decision: unknown;\n\t\t\t\ttry {\n\t\t\t\t\tdecision = selector.predicate(entry.publicTool);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow catalogError(\n\t\t\t\t\t\t`MCP catalog predicate selector threw for tool \"${entry.tool.name}\" on server \"${runtimeName}\".`,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (typeof decision !== \"boolean\") {\n\t\t\t\t\tthrow catalogError(\n\t\t\t\t\t\t`MCP catalog predicate selector returned ${typeof decision} instead of boolean for tool \"${entry.tool.name}\" on server \"${runtimeName}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tmatches = decision;\n\t\t\t}\n\t\t\tif (matches) {\n\t\t\t\tselected.add(entry);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn selected;\n}\n\nfunction applyDeferredMetadata(\n\tentries: readonly CatalogEntry[],\n\teager: ReadonlySet<CatalogEntry>,\n\tmetadata: Readonly<Record<string, unknown>>,\n\truntimeName: string,\n): void {\n\tfor (const entry of entries) {\n\t\tif (eager.has(entry)) continue;\n\t\t// Merge from the detached pre-resolver snapshot, never a mutable SDK handle reread.\n\t\tconst existing = entry.tool[\"_meta\"] ?? {};\n\t\tfor (const key of Object.keys(metadata)) {\n\t\t\tif (Object.hasOwn(existing, key)) {\n\t\t\t\tthrow catalogError(\n\t\t\t\t\t`MCP deferred metadata key \"${key}\" collides with existing _meta on tool \"${entry.tool.name}\" for server \"${runtimeName}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst merged = detachJson(\n\t\t\t{ ...existing, ...metadata },\n\t\t\t`MCP deferred metadata for tool \"${entry.tool.name}\"`,\n\t\t);\n\t\tentry.registration.update({ _meta: merged });\n\t}\n}\n\nasync function installLazyCatalog(\n\tserver: McpServer,\n\tentries: readonly CatalogEntry[],\n\teager: ReadonlySet<CatalogEntry>,\n\tregisterMetaTool: McpCatalogMetaToolRegistrar,\n): Promise<void> {\n\tconst searchRegistration = registerMetaTool({\n\t\tname: MCP_CATALOG_SEARCH_TOOL_NAME,\n\t\ttitle: \"Search tool catalog\",\n\t\tdescription: \"Search the authorized tool catalog using bounded, paginated summaries.\",\n\t\tinputSchema: SEARCH_INPUT_SCHEMA,\n\t\toutputSchema: SEARCH_OUTPUT_SCHEMA,\n\t\thandler: async (input: SearchInput): Promise<CallToolResult> =>\n\t\t\tcreateSearchResult(entries, input),\n\t});\n\tconst schemasRegistration = registerMetaTool({\n\t\tname: MCP_CATALOG_SCHEMAS_TOOL_NAME,\n\t\ttitle: \"Fetch tool schemas\",\n\t\tdescription: \"Fetch complete definitions for a bounded batch of authorized tools.\",\n\t\tinputSchema: SCHEMAS_INPUT_SCHEMA,\n\t\toutputSchema: SCHEMAS_OUTPUT_SCHEMA,\n\t\thandler: async (input: SchemasInput): Promise<CallToolResult> =>\n\t\t\tcreateSchemasResult(entries, input),\n\t});\n\tconst listed = [\n\t\t...entries.filter((entry) => eager.has(entry)).map(({ tool }) => tool),\n\t\tprojectRegisteredTool(MCP_CATALOG_SEARCH_TOOL_NAME, searchRegistration),\n\t\tprojectRegisteredTool(MCP_CATALOG_SCHEMAS_TOOL_NAME, schemasRegistration),\n\t];\n\tconst binding = await cursorBinding(\n\t\t\"list\",\n\t\tlisted.map(({ name }) => name),\n\t);\n\tserver.server.setRequestHandler(\"tools/list\", (request): ListToolsResult => {\n\t\tconst offset = decodeCursor(request.params?.cursor, \"list\", binding).offset;\n\t\tconst tools = listed.slice(offset, offset + MCP_CATALOG_LIST_PAGE_SIZE);\n\t\tconst nextOffset = offset + tools.length;\n\t\treturn {\n\t\t\ttools,\n\t\t\t...(nextOffset < listed.length\n\t\t\t\t? {\n\t\t\t\t\t\tnextCursor: encodeCursor({\n\t\t\t\t\t\t\tv: 1,\n\t\t\t\t\t\t\tkind: \"list\",\n\t\t\t\t\t\t\toffset: nextOffset,\n\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t});\n}\n\nasync function createSearchResult(\n\tentries: readonly CatalogEntry[],\n\tinput: SearchInput,\n): Promise<CallToolResult> {\n\tassertInputSize(input, MCP_CATALOG_SEARCH_TOOL_NAME);\n\tconst query = normalizeSearchQuery(input.query);\n\tconst matches = entries.filter((entry) => matchesSearch(entry.publicTool, query));\n\tconst binding = await cursorBinding(\"search\", [query, ...matches.map(({ tool }) => tool.name)]);\n\tconst cursor = decodeCursor(input.cursor, \"search\", binding);\n\tconst limit = normalizeSearchLimit(input.limit);\n\tconst tools = matches\n\t\t.slice(cursor.offset, cursor.offset + limit)\n\t\t.map(({ publicTool }) => summarizeTool(publicTool));\n\tconst nextOffset = cursor.offset + tools.length;\n\tconst structuredContent: Record<string, unknown> = {\n\t\ttools,\n\t\t...(nextOffset < matches.length\n\t\t\t? {\n\t\t\t\t\tnextCursor: encodeCursor({\n\t\t\t\t\t\tv: 1,\n\t\t\t\t\t\tkind: \"search\",\n\t\t\t\t\t\toffset: nextOffset,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\treturn {\n\t\tcontent: [{ type: \"text\", text: JSON.stringify(structuredContent) }],\n\t\tstructuredContent,\n\t};\n}\n\nfunction createSchemasResult(\n\tentries: readonly CatalogEntry[],\n\tinput: SchemasInput,\n): CallToolResult {\n\tassertInputSize(input, MCP_CATALOG_SCHEMAS_TOOL_NAME);\n\tif (!Array.isArray(input.names) || input.names.length > MCP_CATALOG_SCHEMA_BATCH_LIMIT) {\n\t\tthrow invalidParams(\n\t\t\t`names must contain between 1 and ${String(MCP_CATALOG_SCHEMA_BATCH_LIMIT)} unique tool names.`,\n\t\t);\n\t}\n\tconst byName = new Map(entries.map((entry) => [entry.tool.name, entry.tool]));\n\tconst tools = input.names.flatMap((name) => {\n\t\tconst tool = byName.get(name);\n\t\treturn tool === undefined ? [] : [tool];\n\t});\n\tconst structuredContent: Record<string, unknown> = { tools };\n\treturn {\n\t\tcontent: [{ type: \"text\", text: JSON.stringify(structuredContent) }],\n\t\tstructuredContent,\n\t};\n}\n\nfunction summarizeTool(tool: McpCatalogTool): McpCatalogSearchResultTool {\n\treturn Object.freeze({\n\t\tname: tool.tool.name,\n\t\t...(tool.tool.title === undefined ? {} : { title: tool.tool.title }),\n\t\t...(tool.tool.description === undefined ? {} : { description: tool.tool.description }),\n\t\ttags: tool.tags,\n\t});\n}\n\nfunction matchesSearch(tool: McpCatalogTool, query: string): boolean {\n\tif (query.length === 0) return true;\n\treturn [tool.tool.name, tool.tool.title, tool.tool.description, ...tool.tags]\n\t\t.filter((value): value is string => typeof value === \"string\")\n\t\t.some((value) => value.toLowerCase().includes(query));\n}\n\nfunction normalizeSearchQuery(value: string | undefined): string {\n\tif (value === undefined) return \"\";\n\tif (typeof value !== \"string\" || value.length > MCP_CATALOG_QUERY_LENGTH_LIMIT) {\n\t\tthrow invalidParams(\n\t\t\t`query must contain at most ${String(MCP_CATALOG_QUERY_LENGTH_LIMIT)} characters.`,\n\t\t);\n\t}\n\treturn value.trim().toLowerCase();\n}\n\nfunction normalizeSearchLimit(value: number | undefined): number {\n\tconst limit = value ?? MCP_CATALOG_SEARCH_DEFAULT_LIMIT;\n\tif (!Number.isSafeInteger(limit) || limit <= 0 || limit > MCP_CATALOG_SEARCH_MAX_LIMIT) {\n\t\tthrow invalidParams(\n\t\t\t`limit must be an integer between 1 and ${String(MCP_CATALOG_SEARCH_MAX_LIMIT)}.`,\n\t\t);\n\t}\n\treturn limit;\n}\n\nfunction encodeCursor(cursor: CursorEnvelope): string {\n\tconst bytes = new TextEncoder().encode(JSON.stringify(cursor));\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn `v1.${btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/u, \"\")}`;\n}\n\nfunction decodeCursor(\n\tvalue: string | undefined,\n\tkind: CursorEnvelope[\"kind\"],\n\tbinding?: string,\n): CursorEnvelope {\n\tif (value === undefined) {\n\t\treturn { v: 1, kind, offset: 0, ...(binding === undefined ? {} : { binding }) };\n\t}\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length > MCP_CATALOG_CURSOR_LENGTH_LIMIT ||\n\t\t!value.startsWith(\"v1.\")\n\t) {\n\t\tthrow invalidParams(\"Invalid MCP catalog cursor.\");\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tconst encoded = value.slice(3).replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n\t\tconst padding = \"=\".repeat((4 - (encoded.length % 4)) % 4);\n\t\tconst binary = atob(encoded + padding);\n\t\tconst bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n\t\tparsed = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\t} catch {\n\t\tthrow invalidParams(\"Invalid MCP catalog cursor.\");\n\t}\n\tif (\n\t\t!isPlainRecord(parsed) ||\n\t\t!hasExactCursorKeys(parsed, binding !== undefined) ||\n\t\tparsed.v !== 1 ||\n\t\tparsed.kind !== kind ||\n\t\t!Number.isSafeInteger(parsed.offset) ||\n\t\ttypeof parsed.offset !== \"number\" ||\n\t\tparsed.offset < 0 ||\n\t\tparsed.offset > MCP_CATALOG_MAX_TOOLS ||\n\t\t(binding === undefined ? parsed.binding !== undefined : parsed.binding !== binding)\n\t) {\n\t\tthrow invalidParams(\"Invalid MCP catalog cursor.\");\n\t}\n\treturn {\n\t\tv: 1,\n\t\tkind,\n\t\toffset: parsed.offset,\n\t\t...(binding === undefined ? {} : { binding }),\n\t};\n}\n\nfunction hasExactCursorKeys(cursor: Record<string, unknown>, hasBinding: boolean): boolean {\n\tconst expected = hasBinding ? [\"binding\", \"kind\", \"offset\", \"v\"] : [\"kind\", \"offset\", \"v\"];\n\tconst actual = Object.keys(cursor).toSorted();\n\treturn actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\n\nasync function cursorBinding(\n\tkind: CursorEnvelope[\"kind\"],\n\tvalues: readonly string[],\n): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(JSON.stringify({ kind, values })),\n\t\t),\n\t);\n\treturn [...digest].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction assertInputSize(input: unknown, toolName: string): void {\n\tlet serialized: string;\n\ttry {\n\t\tserialized = JSON.stringify(input);\n\t} catch {\n\t\tthrow invalidParams(`Input for ${toolName} must be JSON serializable.`);\n\t}\n\tif (new TextEncoder().encode(serialized).byteLength > MCP_CATALOG_INPUT_BYTE_LIMIT) {\n\t\tthrow invalidParams(\n\t\t\t`Input for ${toolName} exceeds ${String(MCP_CATALOG_INPUT_BYTE_LIMIT)} bytes.`,\n\t\t);\n\t}\n}\n\nfunction normalizeBoundedString(value: unknown, maximum: number, label: string): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0 || value.trim().length > maximum) {\n\t\tthrow catalogError(`${label} must contain between 1 and ${String(maximum)} characters.`);\n\t}\n\treturn value.trim();\n}\n\nfunction detachJson<Value>(value: Value, label: string, maximumBytes?: number): Value {\n\tlet clone: Value;\n\ttry {\n\t\tclone = structuredClone(value);\n\t} catch (cause) {\n\t\tthrow catalogError(`${label} must be safely detachable.`, cause);\n\t}\n\tassertJsonSafe(clone, label, 0, new Set());\n\tif (maximumBytes !== undefined) {\n\t\tconst bytes = new TextEncoder().encode(JSON.stringify(clone)).byteLength;\n\t\tif (bytes > maximumBytes) {\n\t\t\tthrow catalogError(`${label} exceeds ${String(maximumBytes)} serialized bytes.`);\n\t\t}\n\t}\n\treturn deepFreeze(clone);\n}\n\nfunction assertJsonSafe(\n\tvalue: unknown,\n\tlabel: string,\n\tdepth: number,\n\tancestors: Set<object>,\n): void {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow catalogError(`${label} contains a non-finite number.`);\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow catalogError(`${label} contains a non-JSON value.`);\n\t}\n\tif (depth >= CATALOG_JSON_DEPTH_LIMIT) {\n\t\tthrow catalogError(`${label} exceeds the maximum JSON nesting depth.`);\n\t}\n\tif (ancestors.has(value)) throw catalogError(`${label} must not contain cycles.`);\n\tif (!Array.isArray(value) && !isPlainRecord(value)) {\n\t\tthrow catalogError(`${label} must contain only JSON arrays and objects.`);\n\t}\n\tancestors.add(value);\n\tfor (const entry of Array.isArray(value) ? value : Object.values(value)) {\n\t\tassertJsonSafe(entry, label, depth + 1, ancestors);\n\t}\n\tancestors.delete(value);\n}\n\nfunction deepFreeze<Value>(value: Value): Value {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tfor (const entry of Array.isArray(value) ? value : Object.values(value)) deepFreeze(entry);\n\treturn Object.freeze(value);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value) as unknown;\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction standardSchemaWithJson(schema: unknown): StandardSchemaWithJSON {\n\tif (!isStandardSchemaWithJson(schema)) {\n\t\tthrow new TypeError(\"Official MCP schema does not expose Standard JSON Schema conversion.\");\n\t}\n\treturn schema;\n}\n\nfunction isStandardSchemaWithJson(value: unknown): value is StandardSchemaWithJSON {\n\tif ((typeof value !== \"object\" || value === null) && typeof value !== \"function\") return false;\n\tconst standard: unknown = Reflect.get(value, \"~standard\");\n\tif (!isPlainRecord(standard)) return false;\n\tconst jsonSchema = standard.jsonSchema;\n\treturn (\n\t\tisPlainRecord(jsonSchema) &&\n\t\ttypeof jsonSchema.input === \"function\" &&\n\t\ttypeof jsonSchema.output === \"function\" &&\n\t\ttypeof standard.validate === \"function\"\n\t);\n}\n\nfunction invalidParams(message: string): ProtocolError {\n\treturn new ProtocolError(ProtocolErrorCode.InvalidParams, message);\n}\n\nfunction catalogError(message: string, cause?: unknown): McpModuleError {\n\treturn new McpModuleError(\n\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\tmessage,\n\t\tcause === undefined ? undefined : { cause },\n\t);\n}\n","import { Injectable } from \"@nestjs/common\";\nimport {\n\tcomposeMcpMiddleware,\n\tcreateMcpAuthorizationMiddleware,\n\tcreateMcpLifecycleMiddleware,\n\tcreateMcpOperation,\n\tcreateMcpOperationContext,\n} from \"@nest-mcp/core\";\nimport type { MaybePromise, McpOperationHandler } from \"@nest-mcp/core\";\nimport type {\n\tMcpServer,\n\tMcpServerBuildContext,\n\tMcpServerFeature,\n\tMcpServerPrincipal,\n\tPromptCallback,\n\tReadResourceCallback,\n\tReadResourceTemplateCallback,\n\tRegisteredTool,\n\tResourceTemplate,\n\tServerContext,\n\tStandardSchemaWithJSON,\n\tToolCallback,\n} from \"@nest-mcp/server\";\nimport type {\n\tMcpCapabilityDescriptor,\n\tMcpCapabilityMutation,\n\tMcpCapabilityMutationObserver,\n\tMcpCapabilityVisibilityPolicy,\n\tMcpDynamicHandlerRegistration,\n} from \"../mcp-capability.types.ts\";\nimport { McpModuleError } from \"../mcp.errors.ts\";\nimport {\n\tMCP_CATALOG_SCHEMAS_TOOL_NAME,\n\tMCP_CATALOG_SEARCH_TOOL_NAME,\n} from \"../mcp-catalog-exposure.ts\";\nimport type { McpCatalogExposureOptions } from \"../mcp-catalog-exposure.ts\";\nimport {\n\tapplyMcpCatalogExposure,\n\tMCP_CATALOG_TOOL_NAME_LENGTH_LIMIT,\n\ttype McpCatalogMetaToolDefinition,\n\ttype McpCatalogRegisteredTool,\n} from \"../mcp-catalog.runtime.ts\";\nimport type {\n\tMcpHandlerAuthorizationPolicy,\n\tMcpHandlerInvocationInput,\n\tMcpHandlerInvocationOutput,\n\tMcpHandlerLifecycleObserver,\n\tMcpHandlerMiddleware,\n\tMcpHandlerOperationContext,\n} from \"../mcp.types.ts\";\nimport {\n\tMcpProviderRegistry,\n\tisMcpRuntimeProviderToken,\n\tmcpProviderTokenName,\n} from \"../mcp-provider.registry.ts\";\nimport type {\n\tHandlerDefinition,\n\tPromptOptions,\n\tResourceOptions,\n\tToolOptions,\n} from \"../decorators/mcp-handler.decorators.ts\";\n\nconst DEFAULT_VISIBILITY_TIMEOUT_MS = 30_000;\n\nexport type McpDiscoveredHandler = (\n\t...arguments_: unknown[]\n) => MaybePromise<McpHandlerInvocationOutput>;\n\ninterface RegisteredHandler {\n\treadonly id: symbol;\n\treadonly definition: HandlerDefinition;\n\treadonly handler: McpDiscoveredHandler;\n\treadonly source: string;\n\treadonly visibility: boolean | McpCapabilityVisibilityPolicy | undefined;\n}\n\ninterface McpHandlerPipelineOptions {\n\treadonly serverName: string;\n\treadonly authorization?: McpHandlerAuthorizationPolicy;\n\treadonly middleware?: readonly McpHandlerMiddleware[];\n\treadonly lifecycleObserver?: McpHandlerLifecycleObserver;\n\treadonly visibilityTimeoutMs?: number;\n\treadonly catalogExposure?: McpCatalogExposureOptions;\n}\n\n@Injectable()\nexport class McpHandlerRegistry {\n\t#handlers: readonly RegisteredHandler[] = Object.freeze([]);\n\t#closed = false;\n\t#serverNames: readonly string[] | undefined;\n\t#gatewayNames = new Set<string>();\n\t#catalogRuntimeNames = new Set<string>();\n\treadonly #mutationObservers = new Set<McpCapabilityMutationObserver>();\n\n\tconstructor(private readonly providers: McpProviderRegistry) {}\n\n\t/** Adds one discovered handler. Prefer the typed capability methods for live registration. */\n\tregister(definition: HandlerDefinition, handler: McpDiscoveredHandler, source: string): void {\n\t\tthis.#append(definition, handler, source, this.#serverNames !== undefined);\n\t}\n\n\t/** Atomically installs a live tool for future per-request server builds. */\n\tregisterTool<const InputSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\t\toptions: ToolOptions<InputSchema>,\n\t\thandler: ToolCallback<InputSchema>,\n\t\tsource = `dynamic tool \"${options.name}\"`,\n\t): McpDynamicHandlerRegistration<ToolCallback<InputSchema>> {\n\t\treturn this.#registerDynamic({ kind: \"tool\", options }, eraseHandler(handler), source, (next) =>\n\t\t\teraseHandler(next),\n\t\t);\n\t}\n\n\t/** Atomically installs a live prompt for future per-request server builds. */\n\tregisterPrompt<const ArgsSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\t\toptions: PromptOptions<ArgsSchema>,\n\t\thandler: PromptCallback<ArgsSchema>,\n\t\tsource = `dynamic prompt \"${options.name}\"`,\n\t): McpDynamicHandlerRegistration<PromptCallback<ArgsSchema>> {\n\t\treturn this.#registerDynamic(\n\t\t\t{ kind: \"prompt\", options },\n\t\t\teraseHandler(handler),\n\t\t\tsource,\n\t\t\t(next) => eraseHandler(next),\n\t\t);\n\t}\n\n\t/** Atomically installs a fixed or templated resource for future server builds. */\n\tregisterResource<const Uri extends string | ResourceTemplate>(\n\t\toptions: ResourceOptions<Uri>,\n\t\thandler: Uri extends string ? ReadResourceCallback : ReadResourceTemplateCallback,\n\t\tsource = `dynamic resource \"${options.name}\"`,\n\t): McpDynamicHandlerRegistration<\n\t\tUri extends string ? ReadResourceCallback : ReadResourceTemplateCallback\n\t> {\n\t\ttype Handler = Uri extends string ? ReadResourceCallback : ReadResourceTemplateCallback;\n\t\treturn this.#registerDynamic(\n\t\t\t{ kind: \"resource\", options },\n\t\t\teraseHandler(handler),\n\t\t\tsource,\n\t\t\t(next: Handler) => eraseHandler(next),\n\t\t);\n\t}\n\n\tlist(): readonly McpCapabilityDescriptor[] {\n\t\treturn this.#handlers.map((entry) =>\n\t\t\tObject.freeze({\n\t\t\t\tkind: entry.definition.kind,\n\t\t\t\tname: entry.definition.options.name,\n\t\t\t\tsource: entry.source,\n\t\t\t\tserverNames: Object.freeze([...this.#effectiveTargets(entry.definition)]),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Locks target validation to the runtimes declared by the root module. */\n\tconfigureRuntimes(\n\t\tserverNames: readonly string[],\n\t\tgatewayNames: readonly string[] = [],\n\t\tcatalogRuntimeNames: readonly string[] = [],\n\t): void {\n\t\tif (this.#serverNames !== undefined) {\n\t\t\tthrow new McpModuleError(\"INVALID_OPTIONS\", \"MCP handler runtimes are already configured.\");\n\t\t}\n\t\tthis.#serverNames = normalizeRuntimeNames(serverNames);\n\t\tthis.#gatewayNames = new Set(normalizeRuntimeNames(gatewayNames));\n\t\tthis.#catalogRuntimeNames = new Set(normalizeRuntimeNames(catalogRuntimeNames));\n\t\tfor (const runtimeName of new Set([...this.#gatewayNames, ...this.#catalogRuntimeNames])) {\n\t\t\tif (!this.#serverNames.includes(runtimeName)) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t`MCP specialized runtime \"${runtimeName}\" is not a configured server.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const entry of this.#handlers) this.#assertKnownTargets(entry.definition, entry.source);\n\t\tfor (const runtimeName of this.#serverNames) this.assertNoCollisions(runtimeName);\n\t}\n\n\t/** Observes committed live mutations. The returned unsubscriber is idempotent. */\n\tonMutation(observer: McpCapabilityMutationObserver): () => void {\n\t\tthis.#assertOpen();\n\t\tif (typeof observer !== \"function\") {\n\t\t\tthrow new TypeError(\"MCP capability mutation observer must be a function.\");\n\t\t}\n\t\tthis.#mutationObservers.add(observer);\n\t\treturn () => {\n\t\t\tthis.#mutationObservers.delete(observer);\n\t\t};\n\t}\n\n\t/** Seals live mutation APIs and releases handler callbacks during application shutdown. */\n\tclose(): void {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tthis.#handlers = Object.freeze([]);\n\t\tthis.#mutationObservers.clear();\n\t}\n\n\tassertNoCollisions(runtimeName: string): void {\n\t\tconst seen = new Map<string, string>();\n\t\tfor (const entry of this.#handlers) {\n\t\t\tif (!targetsRuntime(entry.definition.options.servers, runtimeName)) continue;\n\t\t\tthis.#assertCatalogToolCompatibility(entry.definition, entry.source, runtimeName);\n\t\t\tconst key = registrationKey(entry.definition);\n\t\t\tconst previous = seen.get(key);\n\t\t\tif (previous !== undefined) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"DUPLICATE_HANDLER\",\n\t\t\t\t\t`Duplicate MCP ${entry.definition.kind} registration \"${key}\" for server \"${runtimeName}\" from ${previous} and ${entry.source}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tseen.set(key, entry.source);\n\t\t}\n\t}\n\n\t/** Whether discovery found any decorated handler targeting one runtime. */\n\thasHandlersFor(runtimeName: string): boolean {\n\t\treturn this.#handlers.some((entry) =>\n\t\t\ttargetsRuntime(entry.definition.options.servers, runtimeName),\n\t\t);\n\t}\n\n\tasServerFeature(options: McpHandlerPipelineOptions): McpServerFeature {\n\t\tconst visibilityTimeoutMs = normalizeVisibilityTimeout(options.visibilityTimeoutMs);\n\t\treturn async (server, context) => {\n\t\t\t// A build owns one immutable snapshot. Concurrent live mutations affect only later builds.\n\t\t\tconst snapshot = this.#handlers.filter((entry) =>\n\t\t\t\ttargetsRuntime(entry.definition.options.servers, context.runtimeName),\n\t\t\t);\n\t\t\tconst visible = await selectVisibleHandlers(snapshot, context, visibilityTimeoutMs);\n\t\t\tconst catalogRegistrations: McpCatalogRegisteredTool[] = [];\n\t\t\tfor (const entry of visible) {\n\t\t\t\tconst registration = registerHandler(server, entry, options, context.principal);\n\t\t\t\tif (registration !== undefined && entry.definition.kind === \"tool\") {\n\t\t\t\t\tcatalogRegistrations.push(\n\t\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t\tname: entry.definition.options.name,\n\t\t\t\t\t\t\tregistration,\n\t\t\t\t\t\t\ttags: entry.definition.options.tags ?? Object.freeze([]),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options.catalogExposure !== undefined) {\n\t\t\t\tawait applyMcpCatalogExposure(\n\t\t\t\t\tserver,\n\t\t\t\t\tcontext,\n\t\t\t\t\tObject.freeze(catalogRegistrations),\n\t\t\t\t\toptions.catalogExposure,\n\t\t\t\t\tvisibilityTimeoutMs,\n\t\t\t\t\t(definition) => registerCatalogMetaTool(server, definition, options, context.principal),\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t#append(\n\t\tdefinition: HandlerDefinition,\n\t\thandler: McpDiscoveredHandler,\n\t\tsource: string,\n\t\tnotify: boolean,\n\t): RegisteredHandler {\n\t\tthis.#assertOpen();\n\t\tconst normalizedSource = normalizeSource(source);\n\t\tconst normalizedDefinition = freezeDefinition(definition);\n\t\tthis.#assertKnownTargets(normalizedDefinition, normalizedSource);\n\t\tconst entry = Object.freeze({\n\t\t\tid: Symbol(normalizedSource),\n\t\t\tdefinition: normalizedDefinition,\n\t\t\thandler,\n\t\t\tsource: normalizedSource,\n\t\t\tvisibility: this.#resolveVisibility(normalizedDefinition, normalizedSource),\n\t\t}) satisfies RegisteredHandler;\n\t\tthis.#assertNoEntryCollision(entry);\n\t\tthis.#handlers = Object.freeze([...this.#handlers, entry]);\n\t\tif (notify) this.#notify(entry, \"registered\");\n\t\treturn entry;\n\t}\n\n\t#registerDynamic<Handler>(\n\t\tdefinition: HandlerDefinition,\n\t\thandler: McpDiscoveredHandler,\n\t\tsource: string,\n\t\teraseReplacement: (handler: Handler) => McpDiscoveredHandler,\n\t): McpDynamicHandlerRegistration<Handler> {\n\t\tthis.#assertOpen();\n\t\tif (this.#serverNames === undefined) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"RUNTIME_NOT_READY\",\n\t\t\t\t\"Dynamic MCP capabilities can be registered after application bootstrap configures runtimes.\",\n\t\t\t);\n\t\t}\n\t\tlet current = this.#append(definition, handler, source, true);\n\t\tlet active = true;\n\t\treturn Object.freeze({\n\t\t\tsource: current.source,\n\t\t\treplace: (nextHandler: Handler): boolean => {\n\t\t\t\tthis.#assertOpen();\n\t\t\t\tif (!active) return false;\n\t\t\t\tconst index = this.#handlers.findIndex((entry) => entry.id === current.id);\n\t\t\t\tif (index === -1) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconst replacement = Object.freeze({\n\t\t\t\t\t...current,\n\t\t\t\t\tid: Symbol(current.source),\n\t\t\t\t\thandler: eraseReplacement(nextHandler),\n\t\t\t\t}) satisfies RegisteredHandler;\n\t\t\t\tthis.#handlers = Object.freeze([\n\t\t\t\t\t...this.#handlers.slice(0, index),\n\t\t\t\t\treplacement,\n\t\t\t\t\t...this.#handlers.slice(index + 1),\n\t\t\t\t]);\n\t\t\t\tcurrent = replacement;\n\t\t\t\tthis.#notify(replacement, \"replaced\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tunregister: (): boolean => {\n\t\t\t\tthis.#assertOpen();\n\t\t\t\tif (!active) return false;\n\t\t\t\tconst next = this.#handlers.filter((entry) => entry.id !== current.id);\n\t\t\t\tif (next.length === this.#handlers.length) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tthis.#handlers = Object.freeze(next);\n\t\t\t\tactive = false;\n\t\t\t\tthis.#notify(current, \"unregistered\");\n\t\t\t\treturn true;\n\t\t\t},\n\t\t});\n\t}\n\n\t#assertOpen(): void {\n\t\tif (!this.#closed) return;\n\t\tthrow new McpModuleError(\n\t\t\t\"RUNTIME_CLOSED\",\n\t\t\t\"MCP capabilities cannot be mutated after the Nest runtime begins shutdown.\",\n\t\t);\n\t}\n\n\t#resolveVisibility(\n\t\tdefinition: HandlerDefinition,\n\t\tsource: string,\n\t): boolean | McpCapabilityVisibilityPolicy | undefined {\n\t\tconst visibility = definition.options.visibility;\n\t\tif (visibility === undefined || typeof visibility === \"boolean\") return visibility;\n\t\tif (!isMcpRuntimeProviderToken(visibility)) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_VISIBILITY_POLICY\",\n\t\t\t\t`MCP handler ${source} visibility must be a boolean or collaborator provider token.`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tconst policy = this.providers.get(visibility);\n\t\t\tif (!isCapabilityVisibilityPolicy(policy)) {\n\t\t\t\tthrow new TypeError(\"resolved provider does not implement isVisible(context)\");\n\t\t\t}\n\t\t\treturn policy;\n\t\t} catch (cause) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_VISIBILITY_POLICY\",\n\t\t\t\t`MCP handler ${source} visibility policy ${mcpProviderTokenName(visibility)} must be a registered singleton collaborator provider.`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t}\n\n\t#assertKnownTargets(definition: HandlerDefinition, source: string): void {\n\t\tif (this.#serverNames === undefined) return;\n\t\tfor (const target of explicitTargets(definition.options.servers)) {\n\t\t\tif (!this.#serverNames.includes(target)) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"UNKNOWN_SERVER_TARGET\",\n\t\t\t\t\t`MCP handler ${source} targets unknown server \"${target}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t#assertNoEntryCollision(candidate: RegisteredHandler): void {\n\t\tif (this.#serverNames === undefined) return;\n\t\tconst candidateTargets = this.#effectiveTargets(candidate.definition);\n\t\tfor (const gatewayName of candidateTargets) {\n\t\t\tif (this.#gatewayNames.has(gatewayName)) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t`MCP gateway server \"${gatewayName}\" must be dedicated and cannot also host decorated or dynamic tools, prompts, or resources.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const runtimeName of candidateTargets) {\n\t\t\tthis.#assertCatalogToolCompatibility(candidate.definition, candidate.source, runtimeName);\n\t\t}\n\t\tconst key = registrationKey(candidate.definition);\n\t\tfor (const entry of this.#handlers) {\n\t\t\tif (registrationKey(entry.definition) !== key) continue;\n\t\t\tconst existingTargets = this.#effectiveTargets(entry.definition);\n\t\t\tconst collision = candidateTargets.find((target) => existingTargets.includes(target));\n\t\t\tif (collision !== undefined) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"DUPLICATE_HANDLER\",\n\t\t\t\t\t`Duplicate MCP ${candidate.definition.kind} registration \"${key}\" for server \"${collision}\" from ${entry.source} and ${candidate.source}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t#effectiveTargets(definition: HandlerDefinition): readonly string[] {\n\t\treturn definition.options.servers === undefined\n\t\t\t? (this.#serverNames ?? [])\n\t\t\t: explicitTargets(definition.options.servers);\n\t}\n\n\t#notify(entry: RegisteredHandler, type: McpCapabilityMutation[\"type\"]): void {\n\t\tconst mutation = Object.freeze({\n\t\t\tkind: entry.definition.kind,\n\t\t\ttype,\n\t\t\tsource: entry.source,\n\t\t\tserverNames: Object.freeze([...this.#effectiveTargets(entry.definition)]),\n\t\t}) satisfies McpCapabilityMutation;\n\t\tfor (const observer of this.#mutationObservers) {\n\t\t\ttry {\n\t\t\t\tconst result = observer(mutation);\n\t\t\t\tvoid Promise.resolve(result).catch(() => undefined);\n\t\t\t} catch {\n\t\t\t\t// Observation must not make an already-committed mutation appear to fail.\n\t\t\t}\n\t\t}\n\t}\n\n\t#assertCatalogToolCompatibility(\n\t\tdefinition: HandlerDefinition,\n\t\tsource: string,\n\t\truntimeName: string,\n\t): void {\n\t\tif (definition.kind !== \"tool\" || !this.#catalogRuntimeNames.has(runtimeName)) return;\n\t\tif (definition.options.name.length > MCP_CATALOG_TOOL_NAME_LENGTH_LIMIT) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\t\t\t`MCP tool \"${definition.options.name}\" from ${source} exceeds the ${String(MCP_CATALOG_TOOL_NAME_LENGTH_LIMIT)} character catalog name limit on server \"${runtimeName}\".`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tdefinition.options.name !== MCP_CATALOG_SEARCH_TOOL_NAME &&\n\t\t\tdefinition.options.name !== MCP_CATALOG_SCHEMAS_TOOL_NAME\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new McpModuleError(\n\t\t\t\"DUPLICATE_HANDLER\",\n\t\t\t`MCP tool \"${definition.options.name}\" from ${source} collides with a reserved catalog meta-tool on server \"${runtimeName}\".`,\n\t\t);\n\t}\n}\n\nfunction isCapabilityVisibilityPolicy(value: unknown): value is McpCapabilityVisibilityPolicy {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\ttypeof Reflect.get(value, \"isVisible\") === \"function\"\n\t);\n}\n\nasync function selectVisibleHandlers(\n\thandlers: readonly RegisteredHandler[],\n\tcontext: McpServerBuildContext,\n\ttimeoutMs: number,\n): Promise<readonly RegisteredHandler[]> {\n\tconst policies = new Set<McpCapabilityVisibilityPolicy>();\n\tfor (const entry of handlers) {\n\t\tif (typeof entry.visibility === \"object\") policies.add(entry.visibility);\n\t}\n\tconst visibilityTask = Promise.all(\n\t\t[...policies].map(async (policy) => {\n\t\t\tlet visible: unknown;\n\t\t\ttry {\n\t\t\t\tvisible = await policy.isVisible(context);\n\t\t\t} catch (cause) {\n\t\t\t\tthrow visibilityError(policy, context.runtimeName, \"threw or rejected\", cause);\n\t\t\t}\n\t\t\tif (typeof visible !== \"boolean\") {\n\t\t\t\tthrow visibilityError(\n\t\t\t\t\tpolicy,\n\t\t\t\t\tcontext.runtimeName,\n\t\t\t\t\t`returned ${typeof visible} instead of boolean`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [policy, visible] as const;\n\t\t}),\n\t).then((entries) => new Map(entries));\n\tconst byPolicy = await withDeadline(\n\t\tvisibilityTask,\n\t\ttimeoutMs,\n\t\tcontext.requestInfo?.signal,\n\t\t`MCP visibility evaluation for server \"${context.runtimeName}\"`,\n\t);\n\treturn handlers.filter((entry) => {\n\t\tif (entry.visibility === false) return false;\n\t\tif (entry.visibility === true || entry.visibility === undefined) return true;\n\t\treturn byPolicy.get(entry.visibility) === true;\n\t});\n}\n\nfunction visibilityError(\n\tpolicy: McpCapabilityVisibilityPolicy,\n\truntimeName: string,\n\tdetail: string,\n\tcause?: unknown,\n): McpModuleError {\n\treturn new McpModuleError(\n\t\t\"INVALID_VISIBILITY_POLICY\",\n\t\t`MCP visibility policy ${policy.constructor.name || \"<anonymous>\"} ${detail} for server \"${runtimeName}\".`,\n\t\tcause === undefined ? undefined : { cause },\n\t);\n}\n\nfunction withDeadline<T>(\n\ttask: Promise<T>,\n\ttimeoutMs: number,\n\tsignal: AbortSignal | undefined,\n\tlabel: string,\n): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (callback: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tcallback();\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\tfinish(() => reject(signal?.reason ?? new DOMException(`${label} aborted.`, \"AbortError\")));\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tfinish(() =>\n\t\t\t\treject(\n\t\t\t\t\tnew McpModuleError(\n\t\t\t\t\t\t\"INVALID_VISIBILITY_POLICY\",\n\t\t\t\t\t\t`${label} exceeded its ${String(timeoutMs)}ms deadline.`,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t}, timeoutMs);\n\t\ttask.then(\n\t\t\t(value) => finish(() => resolve(value)),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal?.aborted === true) onAbort();\n\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nfunction normalizeVisibilityTimeout(value: number | undefined): number {\n\tconst timeout = value ?? DEFAULT_VISIBILITY_TIMEOUT_MS;\n\tif (!Number.isSafeInteger(timeout) || timeout <= 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"MCP handlerVisibilityTimeoutMs must be a positive safe integer.\",\n\t\t);\n\t}\n\treturn timeout;\n}\n\nfunction normalizeRuntimeNames(names: readonly string[]): readonly string[] {\n\tconst normalized = names.map((name, index) => {\n\t\tif (typeof name !== \"string\" || name.trim().length === 0) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP runtime name at index ${String(index)} must be a non-empty string.`,\n\t\t\t);\n\t\t}\n\t\treturn name.trim();\n\t});\n\tif (new Set(normalized).size !== normalized.length) {\n\t\tthrow new McpModuleError(\"INVALID_OPTIONS\", \"MCP runtime names must be unique.\");\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction normalizeSource(source: string): string {\n\tif (typeof source !== \"string\" || source.trim().length === 0) {\n\t\tthrow new McpModuleError(\"INVALID_HANDLER\", \"MCP handler source must be a non-empty string.\");\n\t}\n\treturn source.trim();\n}\n\nfunction explicitTargets(targets: string | readonly string[] | undefined): readonly string[] {\n\tif (targets === undefined) return [];\n\treturn typeof targets === \"string\" ? [targets] : targets;\n}\n\nfunction targetsRuntime(\n\ttargets: string | readonly string[] | undefined,\n\truntimeName: string,\n): boolean {\n\treturn (\n\t\ttargets === undefined ||\n\t\t(typeof targets === \"string\" ? targets === runtimeName : targets.includes(runtimeName))\n\t);\n}\n\nfunction registrationKey(definition: HandlerDefinition): string {\n\tif (definition.kind === \"resource\" && typeof definition.options.uri === \"string\") {\n\t\treturn `${definition.kind}:${definition.options.uri}`;\n\t}\n\treturn `${definition.kind}:${definition.options.name}`;\n}\n\nfunction freezeDefinition(definition: HandlerDefinition): HandlerDefinition {\n\tif (typeof definition.options.name !== \"string\" || definition.options.name.trim().length === 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_HANDLER\",\n\t\t\t`MCP ${definition.kind} name must be a non-empty string.`,\n\t\t);\n\t}\n\tconst targets = definition.options.servers;\n\tconst frozenTargets = targets === undefined ? {} : { servers: normalizeHandlerTargets(targets) };\n\tif (definition.kind === \"tool\") {\n\t\tconst { tags, annotations, icons, _meta: meta, ...sdkOptions } = definition.options;\n\t\tconst normalizedTags = normalizeToolTags(tags);\n\t\treturn Object.freeze({\n\t\t\tkind: \"tool\",\n\t\t\toptions: Object.freeze({\n\t\t\t\t...sdkOptions,\n\t\t\t\t...frozenTargets,\n\t\t\t\t...(annotations === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tannotations: snapshotDefinitionMetadata(\n\t\t\t\t\t\t\t\tannotations,\n\t\t\t\t\t\t\t\t`MCP tool \"${definition.options.name}\" annotations`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t...(icons === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ticons: snapshotDefinitionMetadata(\n\t\t\t\t\t\t\t\ticons,\n\t\t\t\t\t\t\t\t`MCP tool \"${definition.options.name}\" icons`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t...(meta === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t_meta: snapshotDefinitionMetadata(\n\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t`MCP tool \"${definition.options.name}\" metadata`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t...(normalizedTags === undefined ? {} : { tags: normalizedTags }),\n\t\t\t}),\n\t\t});\n\t}\n\tif (definition.kind === \"prompt\") {\n\t\treturn Object.freeze({\n\t\t\tkind: \"prompt\",\n\t\t\toptions: Object.freeze({ ...definition.options, ...frozenTargets }),\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tkind: \"resource\",\n\t\toptions: Object.freeze({ ...definition.options, ...frozenTargets }),\n\t});\n}\n\nfunction normalizeToolTags(tags: readonly string[] | undefined): readonly string[] | undefined {\n\tif (tags === undefined) return undefined;\n\tif (!Array.isArray(tags) || tags.length > 32) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"MCP tool tags must be an array containing at most 32 entries.\",\n\t\t);\n\t}\n\tconst normalized = tags.map((tag, index) => {\n\t\tif (typeof tag !== \"string\" || tag.trim().length === 0 || tag.trim().length > 64) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP tool tag at index ${String(index)} must contain between 1 and 64 characters.`,\n\t\t\t);\n\t\t}\n\t\treturn tag.trim();\n\t});\n\tif (new Set(normalized).size !== normalized.length) {\n\t\tthrow new McpModuleError(\"INVALID_OPTIONS\", \"MCP tool tags must not contain duplicates.\");\n\t}\n\treturn Object.freeze(normalized);\n}\n\nfunction snapshotDefinitionMetadata<Value>(value: Value, label: string): Value {\n\tlet snapshot: Value;\n\ttry {\n\t\tsnapshot = structuredClone(value);\n\t} catch (cause) {\n\t\tthrow new McpModuleError(\"INVALID_OPTIONS\", `${label} must be safely detachable.`, {\n\t\t\tcause,\n\t\t});\n\t}\n\tfreezePolicyValue(snapshot);\n\treturn snapshot;\n}\n\nfunction normalizeHandlerTargets(targets: string | readonly string[]): string | readonly string[] {\n\tconst values = typeof targets === \"string\" ? [targets] : targets;\n\tif (!Array.isArray(values) || values.length === 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"MCP handler targets must contain at least one server name.\",\n\t\t);\n\t}\n\tconst normalized = values.map((target, index) => {\n\t\tif (typeof target !== \"string\" || target.trim().length === 0) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP handler target at index ${String(index)} must be a non-empty string.`,\n\t\t\t);\n\t\t}\n\t\treturn target.trim();\n\t});\n\tif (new Set(normalized).size !== normalized.length) {\n\t\tthrow new McpModuleError(\"INVALID_OPTIONS\", \"MCP handler targets must not contain duplicates.\");\n\t}\n\treturn typeof targets === \"string\" ? normalized[0]! : Object.freeze(normalized);\n}\n\nfunction eraseHandler(handler: unknown): McpDiscoveredHandler {\n\tif (typeof handler !== \"function\") {\n\t\tthrow new McpModuleError(\"INVALID_HANDLER\", \"Dynamic MCP handler must be callable.\");\n\t}\n\treturn (...arguments_: unknown[]) => Reflect.apply(handler, undefined, arguments_);\n}\n\nfunction registerHandler(\n\tserver: McpServer,\n\tentry: RegisteredHandler,\n\toptions: McpHandlerPipelineOptions,\n\tprincipal: McpServerPrincipal | undefined,\n): RegisteredTool | undefined {\n\tconst callback = (...arguments_: unknown[]): Promise<McpHandlerInvocationOutput> =>\n\t\tinvokeHandler(entry, arguments_, options, principal);\n\tif (entry.definition.kind === \"tool\") {\n\t\tconst {\n\t\t\tname,\n\t\t\tservers: _servers,\n\t\t\tvisibility: _visibility,\n\t\t\ttags: _tags,\n\t\t\t...config\n\t\t} = entry.definition.options;\n\t\tconst registerTool = server.registerTool.bind(server);\n\t\tconst registration: unknown = Reflect.apply(registerTool, undefined, [name, config, callback]);\n\t\tif (!isRegisteredTool(registration)) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_HANDLER\",\n\t\t\t\t`MCP tool ${entry.source} did not produce an official registration handle.`,\n\t\t\t);\n\t\t}\n\t\treturn registration;\n\t}\n\tif (entry.definition.kind === \"prompt\") {\n\t\tconst {\n\t\t\tname,\n\t\t\tservers: _servers,\n\t\t\tvisibility: _visibility,\n\t\t\t...config\n\t\t} = entry.definition.options;\n\t\tconst registerPrompt = server.registerPrompt.bind(server);\n\t\tReflect.apply(registerPrompt, undefined, [name, config, callback]);\n\t\treturn undefined;\n\t}\n\tconst {\n\t\tname,\n\t\turi,\n\t\tservers: _servers,\n\t\tvisibility: _visibility,\n\t\t...config\n\t} = entry.definition.options;\n\tconst registerResource = server.registerResource.bind(server);\n\tReflect.apply(registerResource, undefined, [name, uri, config, callback]);\n\treturn undefined;\n}\n\nfunction isRegisteredTool(value: unknown): value is RegisteredTool {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"enabled\" in value &&\n\t\ttypeof value.enabled === \"boolean\" &&\n\t\t\"update\" in value &&\n\t\ttypeof value.update === \"function\" &&\n\t\t\"enable\" in value &&\n\t\ttypeof value.enable === \"function\" &&\n\t\t\"disable\" in value &&\n\t\ttypeof value.disable === \"function\"\n\t);\n}\n\nfunction registerCatalogMetaTool(\n\tserver: McpServer,\n\tdefinition: McpCatalogMetaToolDefinition,\n\toptions: McpHandlerPipelineOptions,\n\tprincipal: McpServerPrincipal | undefined,\n): RegisteredTool {\n\tconst source = `catalog meta-tool \"${definition.name}\"`;\n\tconst entry = Object.freeze({\n\t\tid: Symbol(source),\n\t\tdefinition: freezeDefinition({\n\t\t\tkind: \"tool\",\n\t\t\toptions: {\n\t\t\t\tname: definition.name,\n\t\t\t\ttitle: definition.title,\n\t\t\t\tdescription: definition.description,\n\t\t\t\tinputSchema: definition.inputSchema,\n\t\t\t\toutputSchema: definition.outputSchema,\n\t\t\t},\n\t\t}),\n\t\thandler: eraseHandler(definition.handler),\n\t\tsource,\n\t\tvisibility: true,\n\t}) satisfies RegisteredHandler;\n\tconst registration = registerHandler(server, entry, options, principal);\n\tif (registration === undefined) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\t\t`MCP catalog meta-tool \"${definition.name}\" did not produce a tool registration.`,\n\t\t);\n\t}\n\treturn registration;\n}\n\nasync function invokeHandler(\n\tentry: RegisteredHandler,\n\tcallbackArguments: readonly unknown[],\n\toptions: McpHandlerPipelineOptions,\n\tprincipal: McpServerPrincipal | undefined,\n): Promise<McpHandlerInvocationOutput> {\n\tconst sdkContext = callbackArguments.at(-1);\n\tif (!isServerContext(sdkContext)) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_HANDLER\",\n\t\t\t`MCP ${entry.definition.kind} handler ${entry.source} received no official server context.`,\n\t\t);\n\t}\n\n\tconst input = Object.freeze({\n\t\tkind: entry.definition.kind,\n\t\tname: entry.definition.options.name,\n\t\tserverName: options.serverName,\n\t\tsource: entry.source,\n\t\targuments: snapshotHandlerArguments(callbackArguments.slice(0, -1)),\n\t}) satisfies McpHandlerInvocationInput;\n\tconst requestId = String(sdkContext.mcpReq.id);\n\tconst context = createMcpOperationContext({\n\t\toperationId: crypto.randomUUID(),\n\t\trole: \"server\",\n\t\toperation: {\n\t\t\tname: sdkContext.mcpReq.method,\n\t\t\tkind: \"request\",\n\t\t\tcapability: capability(entry.definition.kind),\n\t\t\ttarget: options.serverName,\n\t\t\tattributes: {\n\t\t\t\t\"mcp.handler.kind\": entry.definition.kind,\n\t\t\t\t\"mcp.handler.name\": entry.definition.options.name,\n\t\t\t\t\"mcp.transport\": sdkContext.http?.req === undefined ? \"stdio\" : \"http\",\n\t\t\t},\n\t\t},\n\t\tsignal: sdkContext.mcpReq.signal,\n\t\trequestId,\n\t\t...(sdkContext.sessionId === undefined ? {} : { sessionId: sdkContext.sessionId }),\n\t\t...(principal === undefined ? {} : { principal }),\n\t}) satisfies McpHandlerOperationContext;\n\tconst operation = createMcpOperation(input, context);\n\tconst terminal: McpOperationHandler<\n\t\tMcpHandlerInvocationInput,\n\t\tMcpHandlerInvocationOutput,\n\t\tMcpHandlerOperationContext\n\t> = () => entry.handler(...callbackArguments);\n\tconst middleware: McpHandlerMiddleware[] = [];\n\tif (options.lifecycleObserver !== undefined) {\n\t\tmiddleware.push(createMcpLifecycleMiddleware(options.lifecycleObserver));\n\t}\n\tif (options.authorization !== undefined) {\n\t\tmiddleware.push(createMcpAuthorizationMiddleware(options.authorization));\n\t}\n\tmiddleware.push(...(options.middleware ?? []));\n\treturn composeMcpMiddleware(middleware, terminal)(operation);\n}\n\nfunction snapshotHandlerArguments(values: readonly unknown[]): readonly unknown[] {\n\treturn Object.freeze(\n\t\tvalues.map((value) => {\n\t\t\tlet clone: unknown;\n\t\t\ttry {\n\t\t\t\tclone = value instanceof URL ? new URL(value.href) : structuredClone(value);\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"INVALID_HANDLER\",\n\t\t\t\t\t\"Validated MCP handler arguments must be snapshot-safe before authorization.\",\n\t\t\t\t\t{ cause },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn freezePolicyValue(clone);\n\t\t}),\n\t);\n}\n\nfunction freezePolicyValue(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tfor (const entry of value) freezePolicyValue(entry);\n\t\treturn Object.freeze(value);\n\t}\n\tif (isPlainRecord(value)) {\n\t\tfor (const entry of Object.values(value)) freezePolicyValue(entry);\n\t\treturn Object.freeze(value);\n\t}\n\treturn value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value) as unknown;\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction isServerContext(value: unknown): value is ServerContext {\n\tif (typeof value !== \"object\" || value === null || !(\"mcpReq\" in value)) return false;\n\tconst request = value.mcpReq;\n\treturn (\n\t\ttypeof request === \"object\" &&\n\t\trequest !== null &&\n\t\t\"id\" in request &&\n\t\t\"method\" in request &&\n\t\ttypeof request.method === \"string\" &&\n\t\t\"signal\" in request &&\n\t\trequest.signal instanceof AbortSignal\n\t);\n}\n\nfunction capability(kind: McpHandlerInvocationInput[\"kind\"]): string {\n\tif (kind === \"tool\") return \"tools\";\n\tif (kind === \"resource\") return \"resources\";\n\treturn \"prompts\";\n}\n","import { Injectable } from \"@nestjs/common\";\nimport type {\n\tPromptCallback,\n\tReadResourceCallback,\n\tReadResourceTemplateCallback,\n\tResourceTemplate,\n\tStandardSchemaWithJSON,\n\tToolCallback,\n} from \"@nest-mcp/server\";\nimport type {\n\tMcpCapabilityDescriptor,\n\tMcpCapabilityMutationObserver,\n\tMcpDynamicHandlerRegistration,\n} from \"./mcp-capability.types.ts\";\nimport type {\n\tPromptOptions,\n\tResourceOptions,\n\tToolOptions,\n} from \"./decorators/mcp-handler.decorators.ts\";\nimport { McpHandlerRegistry } from \"./discovery/mcp-handler.registry.ts\";\n\n/** Public Nest service for live capability registration after application bootstrap. */\n@Injectable()\nexport class McpCapabilitiesService {\n\tconstructor(private readonly registry: McpHandlerRegistry) {}\n\n\tlist(): readonly McpCapabilityDescriptor[] {\n\t\treturn this.registry.list();\n\t}\n\n\tregisterTool<const InputSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\t\toptions: ToolOptions<InputSchema>,\n\t\thandler: ToolCallback<InputSchema>,\n\t\tsource?: string,\n\t): McpDynamicHandlerRegistration<ToolCallback<InputSchema>> {\n\t\treturn this.registry.registerTool(options, handler, source);\n\t}\n\n\tregisterPrompt<const ArgsSchema extends StandardSchemaWithJSON | undefined = undefined>(\n\t\toptions: PromptOptions<ArgsSchema>,\n\t\thandler: PromptCallback<ArgsSchema>,\n\t\tsource?: string,\n\t): McpDynamicHandlerRegistration<PromptCallback<ArgsSchema>> {\n\t\treturn this.registry.registerPrompt(options, handler, source);\n\t}\n\n\tregisterResource<const Uri extends string | ResourceTemplate>(\n\t\toptions: ResourceOptions<Uri>,\n\t\thandler: Uri extends string ? ReadResourceCallback : ReadResourceTemplateCallback,\n\t\tsource?: string,\n\t): McpDynamicHandlerRegistration<\n\t\tUri extends string ? ReadResourceCallback : ReadResourceTemplateCallback\n\t> {\n\t\treturn this.registry.registerResource(options, handler, source);\n\t}\n\n\tonMutation(observer: McpCapabilityMutationObserver): () => void {\n\t\treturn this.registry.onMutation(observer);\n\t}\n}\n","import { Injectable, Scope } from \"@nestjs/common\";\nimport { DiscoveryService, MetadataScanner, Reflector } from \"@nestjs/core\";\nimport { McpModuleError } from \"../mcp.errors.ts\";\nimport { MCP_HANDLER_METADATA, MCP_TARGETS_METADATA } from \"../mcp.tokens.ts\";\nimport type { HandlerDefinition } from \"../decorators/mcp-handler.decorators.ts\";\nimport { McpHandlerRegistry } from \"./mcp-handler.registry.ts\";\n\n@Injectable()\nexport class McpHandlerExplorer {\n\t#scanned = false;\n\n\tconstructor(\n\t\tprivate readonly discovery: DiscoveryService,\n\t\tprivate readonly metadataScanner: MetadataScanner,\n\t\tprivate readonly reflector: Reflector,\n\t\tprivate readonly registry: McpHandlerRegistry,\n\t) {}\n\n\tassertSingleRoot(): void {\n\t\tconst rootCount = this.discovery\n\t\t\t.getProviders()\n\t\t\t.filter(({ token }) => token === McpHandlerRegistry).length;\n\t\tif (rootCount === 1) return;\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"McpModule.forRoot() or forRootAsync() must be imported exactly once per Nest application. Configure every inbound MCP server in that shared root and import one McpClientModule when named upstreams are needed.\",\n\t\t);\n\t}\n\n\tscan(): void {\n\t\tif (this.#scanned) return;\n\t\tthis.#scanned = true;\n\n\t\tfor (const wrapper of this.discovery.getProviders()) {\n\t\t\tconst metatype = wrapper.metatype;\n\t\t\tif (metatype?.prototype === undefined) continue;\n\t\t\tconst classTargets = this.reflector.get<readonly string[]>(MCP_TARGETS_METADATA, metatype);\n\t\t\tfor (const methodName of this.metadataScanner.getAllMethodNames(metatype.prototype)) {\n\t\t\t\tconst prototypeMethod: unknown = metatype.prototype[methodName];\n\t\t\t\tif (typeof prototypeMethod !== \"function\") continue;\n\t\t\t\tconst definition = this.reflector.get<HandlerDefinition>(\n\t\t\t\t\tMCP_HANDLER_METADATA,\n\t\t\t\t\tprototypeMethod,\n\t\t\t\t);\n\t\t\t\tif (definition === undefined) continue;\n\n\t\t\t\tif (\n\t\t\t\t\t(wrapper.scope !== undefined && wrapper.scope !== Scope.DEFAULT) ||\n\t\t\t\t\t!wrapper.isDependencyTreeStatic()\n\t\t\t\t) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_SCOPE\",\n\t\t\t\t\t\t`Decorated MCP handler ${metatype.name}.${methodName} must belong to a singleton provider with a static dependency tree.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst instance: unknown = wrapper.instance;\n\t\t\t\tif (typeof instance !== \"object\" || instance === null) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_SCOPE\",\n\t\t\t\t\t\t`Decorated MCP handler ${metatype.name}.${methodName} must belong to a singleton provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst method: unknown = Reflect.get(instance, methodName);\n\t\t\t\tif (typeof method !== \"function\") {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_HANDLER\",\n\t\t\t\t\t\t`Decorated MCP handler ${metatype.name}.${methodName} is not callable.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis.registry.register(\n\t\t\t\t\twithDefaultTargets(definition, classTargets),\n\t\t\t\t\t(...arguments_: unknown[]) => Reflect.apply(method, instance, arguments_),\n\t\t\t\t\t`${metatype.name}.${methodName}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction withDefaultTargets(\n\tdefinition: HandlerDefinition,\n\tclassTargets: readonly string[] | undefined,\n): HandlerDefinition {\n\tif (definition.options.servers !== undefined || classTargets === undefined) return definition;\n\tif (definition.kind === \"tool\") {\n\t\treturn Object.freeze({\n\t\t\tkind: \"tool\",\n\t\t\toptions: Object.freeze({ ...definition.options, servers: classTargets }),\n\t\t});\n\t}\n\tif (definition.kind === \"prompt\") {\n\t\treturn Object.freeze({\n\t\t\tkind: \"prompt\",\n\t\t\toptions: Object.freeze({ ...definition.options, servers: classTargets }),\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tkind: \"resource\",\n\t\toptions: Object.freeze({ ...definition.options, servers: classTargets }),\n\t});\n}\n","import { McpModuleError } from \"../mcp.errors.ts\";\nimport { mcpProviderTokenName } from \"../mcp-provider.registry.ts\";\nimport type { McpProviderRegistry } from \"../mcp-provider.registry.ts\";\nimport type { McpProviderToken } from \"../mcp-provider.types.ts\";\n\nexport function requireProvider<Value>(\n\tproviders: McpProviderRegistry,\n\ttoken: McpProviderToken<Value>,\n): Value {\n\tconst provider = providers.get(token);\n\tif ((typeof provider !== \"object\" && typeof provider !== \"function\") || provider === null) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server collaborator ${mcpProviderTokenName(token)} must be listed in McpModule collaborators.providers.`,\n\t\t);\n\t}\n\t// Token typing and Nest's provider registration establish the public contract.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\treturn provider as Value;\n}\n\nexport function requireMethodProvider<Value extends object, Method extends keyof Value>(\n\tproviders: McpProviderRegistry,\n\ttoken: McpProviderToken<Value>,\n\tmethods: Method | readonly Method[],\n): Value & Record<Method, Extract<Value[Method], (...arguments_: never[]) => unknown>> {\n\tconst provider = requireProvider(providers, token);\n\tconst requiredMethods = Array.isArray(methods) ? methods : [methods];\n\tif (requiredMethods.some((method) => typeof Reflect.get(provider, method) !== \"function\")) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server collaborator ${mcpProviderTokenName(token)} must implement ${requiredMethods\n\t\t\t\t.map((method) => `${String(method)}()`)\n\t\t\t\t.join(\", \")}.`,\n\t\t);\n\t}\n\t// Runtime validation above narrows the configured method to a callable.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\treturn provider as Value &\n\t\tRecord<Method, Extract<Value[Method], (...arguments_: never[]) => unknown>>;\n}\n\nexport function bindProviderMethod<Value extends object, Method extends keyof Value>(\n\tproviders: McpProviderRegistry,\n\ttoken: McpProviderToken<Value>,\n\tmethod: Method,\n): Extract<Value[Method], (...arguments_: never[]) => unknown> {\n\tconst provider = requireMethodProvider(providers, token, method);\n\t// Function.bind() loses the indexed-access relationship; the validated method keeps it.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\treturn provider[method].bind(provider) as Extract<\n\t\tValue[Method],\n\t\t(...arguments_: never[]) => unknown\n\t>;\n}\n\nexport function discardProperties(value: object, properties: readonly PropertyKey[]): void {\n\tfor (const property of properties) Reflect.deleteProperty(value, property);\n}\n","import type { CreateMcpHandlerOptions, ServerOptions } from \"@modelcontextprotocol/server\";\nimport { McpProviderRegistry } from \"../mcp-provider.registry.ts\";\nimport {\n\tbindProviderMethod,\n\tdiscardProperties,\n\trequireMethodProvider,\n} from \"./provider-resolution.ts\";\nimport type { McpNestServerHttpOptions, McpNestServerOptions } from \"./mcp-server.types.ts\";\n\nexport function resolveMcpNestServerOptions(\n\toptions: McpNestServerOptions | undefined,\n\tproviders: McpProviderRegistry,\n): ServerOptions | undefined {\n\tif (options === undefined) return undefined;\n\tconst { jsonSchemaValidator, requestState, ...data } = options;\n\treturn {\n\t\t...data,\n\t\t...(jsonSchemaValidator === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tjsonSchemaValidator: requireMethodProvider(\n\t\t\t\t\t\tproviders,\n\t\t\t\t\t\tjsonSchemaValidator,\n\t\t\t\t\t\t\"getValidator\",\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t...(requestState === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\trequestState:\n\t\t\t\t\t\trequestState.verifier === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tverify: bindProviderMethod(providers, requestState.verifier, \"verify\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t}),\n\t};\n}\n\nexport function resolveMcpNestServerHttpOptions(\n\toptions: McpNestServerHttpOptions | undefined,\n\tproviders: McpProviderRegistry,\n): Omit<CreateMcpHandlerOptions, \"onerror\"> | undefined {\n\tif (options === undefined) return undefined;\n\tconst { eventBus, ...data } = options;\n\tdiscardProperties(data, [\"bus\", \"onerror\"]);\n\treturn {\n\t\t...data,\n\t\t...(eventBus === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tbus: requireMethodProvider(providers, eventBus, [\"publish\", \"subscribe\"]),\n\t\t\t\t}),\n\t};\n}\n","import {\n\tcreateMcpClientIdMetadataResolver,\n\tMcpOAuthProxy,\n\tMcpOAuthSecretKeyring,\n\tMcpOAuthServer,\n\tMcpUpstreamAdapter,\n} from \"@nest-mcp/auth\";\nimport type {\n\tMcpClientIdMetadataResolver,\n\tMcpOAuthClientResolver,\n\tMcpOAuthProxyOptions,\n\tMcpUpstreamSubjectResolver,\n} from \"@nest-mcp/auth\";\nimport type { McpFetchHandler, McpResourceServerOptions } from \"@nest-mcp/server/auth\";\nimport { McpResourceServer } from \"@nest-mcp/server/auth\";\nimport { McpModuleError } from \"../mcp.errors.ts\";\nimport type { McpProviderRegistry } from \"../mcp-provider.registry.ts\";\nimport { requireMethodProvider } from \"../server/provider-resolution.ts\";\nimport type { McpNestServerOAuthOptions } from \"./mcp-oauth.types.ts\";\n\nexport interface McpResolvedServerOAuth {\n\t/** Composes the configured OAuth protection around a runtime's fetch handler. */\n\treadonly compose: (handler: McpFetchHandler) => McpFetchHandler;\n\t/** The authorization-server proxy, when `oauth.proxy` is configured. */\n\treadonly proxy?: McpOAuthProxy;\n}\n\n/**\n * Resolves the `oauth` group into a composition function (and, for the proxy,\n * the `McpOAuthProxy` instance). Returns `undefined` when nothing is configured.\n */\nexport function resolveMcpNestServerOAuth(\n\toptions: McpNestServerOAuthOptions | undefined,\n\tproviders: McpProviderRegistry,\n\tserverName: string,\n): McpResolvedServerOAuth | undefined {\n\tif (options === undefined) return undefined;\n\tif (options.proxy !== undefined && options.resource !== undefined) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" configures both oauth.proxy and oauth.resource; the proxy already protects the resource. Configure exactly one.`,\n\t\t);\n\t}\n\tif (options.proxy !== undefined) {\n\t\treturn resolveProxy(options, providers, serverName);\n\t}\n\tif (options.resource !== undefined) {\n\t\tconst compose = resolveResource(options, providers, serverName);\n\t\treturn compose === undefined ? undefined : { compose };\n\t}\n\treturn undefined;\n}\n\nfunction resolveProxy(\n\toptions: McpNestServerOAuthOptions,\n\tproviders: McpProviderRegistry,\n\tserverName: string,\n): McpResolvedServerOAuth {\n\tconst proxyOptions = options.proxy;\n\tif (proxyOptions === undefined) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" is missing oauth.proxy.`,\n\t\t);\n\t}\n\tif (typeof proxyOptions.issuer !== \"string\" || proxyOptions.issuer.length === 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" oauth.proxy.issuer must be a non-empty string.`,\n\t\t);\n\t}\n\tconst primaryResource = proxyOptions.resources?.[0];\n\tif (\n\t\t!Array.isArray(proxyOptions.resources) ||\n\t\tproxyOptions.resources.length === 0 ||\n\t\ttypeof primaryResource !== \"string\"\n\t) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" oauth.proxy.resources must list at least one resource URL.`,\n\t\t);\n\t}\n\n\tconst signingKeys = requireMethodProvider(\n\t\tproviders,\n\t\tproxyOptions.signingKeys,\n\t\t\"getSigningKeys\",\n\t).getSigningKeys();\n\tconst masterSecret = requireMethodProvider(\n\t\tproviders,\n\t\tproxyOptions.secret,\n\t\t\"getMasterSecret\",\n\t).getMasterSecret();\n\tconst upstreamConfig = requireMethodProvider(\n\t\tproviders,\n\t\tproxyOptions.upstream,\n\t\t\"getUpstream\",\n\t).getUpstream();\n\tconst stateStore = requireMethodProvider(providers, proxyOptions.stateStore, \"take\");\n\tconst tokenStore =\n\t\tproxyOptions.tokenStore === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.tokenStore, \"take\");\n\tconst clientResolver: McpOAuthClientResolver | undefined =\n\t\tproxyOptions.clientResolver === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.clientResolver, \"resolveClient\");\n\tconst consentRenderer =\n\t\tproxyOptions.consent === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.consent, \"render\").render;\n\tconst subjectResolver: McpUpstreamSubjectResolver | undefined =\n\t\tproxyOptions.subjectResolver === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.subjectResolver, \"resolveSubject\")\n\t\t\t\t\t.resolveSubject;\n\tconst anonymousProvider =\n\t\tproxyOptions.anonymous === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.anonymous, \"permit\");\n\tconst guardedFetch =\n\t\tproxyOptions.fetch === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, proxyOptions.fetch, \"fetch\").fetch;\n\n\tconst cimd: McpClientIdMetadataResolver | undefined =\n\t\tproxyOptions.cimd?.enabled === true\n\t\t\t? createMcpClientIdMetadataResolver({\n\t\t\t\t\t...(proxyOptions.cimd.allowedHosts === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { allowedHosts: proxyOptions.cimd.allowedHosts }),\n\t\t\t\t\t...(proxyOptions.cimd.maxDocumentBytes === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { maxDocumentBytes: proxyOptions.cimd.maxDocumentBytes }),\n\t\t\t\t\t...(proxyOptions.cimd.fetchTimeoutMs === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { fetchTimeoutMs: proxyOptions.cimd.fetchTimeoutMs }),\n\t\t\t\t})\n\t\t\t: undefined;\n\n\tconst upstream = new McpUpstreamAdapter({\n\t\tupstream: upstreamConfig,\n\t\t...(guardedFetch === undefined ? {} : { fetch: guardedFetch }),\n\t});\n\tconst proxyConstructorOptions: McpOAuthProxyOptions = {\n\t\tissuer: proxyOptions.issuer,\n\t\tresources: proxyOptions.resources,\n\t\tsigningKeys,\n\t\tsecrets: new McpOAuthSecretKeyring(masterSecret),\n\t\tupstream,\n\t\tstateStore,\n\t\t...(proxyOptions.basePath === undefined ? {} : { basePath: proxyOptions.basePath }),\n\t\t...(proxyOptions.scopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { scopesSupported: proxyOptions.scopesSupported }),\n\t\t...(tokenStore === undefined ? {} : { tokenStore }),\n\t\t...(cimd === undefined ? {} : { cimd }),\n\t\t...(clientResolver === undefined ? {} : { clientResolver }),\n\t\t...(consentRenderer === undefined ? {} : { consentRenderer }),\n\t\t...(subjectResolver === undefined ? {} : { resolveUpstreamSubject: subjectResolver }),\n\t\t...(proxyOptions.ttl === undefined ? {} : { ttl: proxyOptions.ttl }),\n\t};\n\tconst proxy = new McpOAuthProxy(proxyConstructorOptions);\n\n\t// Advertise the exact (non-suffixed) protected-resource metadata URL the OAuth\n\t// controller serves at origin root, so the 401 challenge resolves.\n\tconst resourceMetadataUrl = new URL(\"/.well-known/oauth-protected-resource\", proxyOptions.issuer)\n\t\t.href;\n\tconst resourceServerOptions: McpResourceServerOptions = {\n\t\tbearerAuth: {\n\t\t\tverifier: proxy.verifier,\n\t\t\tresourceMetadataUrl,\n\t\t\t...(proxyOptions.requiredScopes === undefined\n\t\t\t\t? {}\n\t\t\t\t: { requiredScopes: [...proxyOptions.requiredScopes] }),\n\t\t},\n\t\tmetadata: {\n\t\t\toauthMetadata: proxy.authorizationServerMetadata,\n\t\t\tresourceServerUrl: new URL(primaryResource),\n\t\t},\n\t\t...(anonymousProvider === undefined\n\t\t\t? {}\n\t\t\t: { anonymous: async (request: Request) => anonymousProvider.permit(request) }),\n\t};\n\n\tconst compose = (handler: McpFetchHandler): McpFetchHandler =>\n\t\tnew McpOAuthServer(new McpResourceServer(handler, resourceServerOptions), {\n\t\t\tproxy,\n\t\t\t...(proxyOptions.basePath === undefined ? {} : { basePath: proxyOptions.basePath }),\n\t\t});\n\n\treturn { compose, proxy };\n}\n\nfunction resolveResource(\n\toptions: McpNestServerOAuthOptions,\n\tproviders: McpProviderRegistry,\n\tserverName: string,\n): ((handler: McpFetchHandler) => McpFetchHandler) | undefined {\n\tconst resource = options.resource;\n\tif (resource === undefined) return undefined;\n\n\tif (typeof resource.resourceServerUrl !== \"string\" || resource.resourceServerUrl.length === 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" oauth.resource.resourceServerUrl must be a non-empty URL string.`,\n\t\t);\n\t}\n\tlet resourceServerUrl: URL;\n\ttry {\n\t\tresourceServerUrl = new URL(resource.resourceServerUrl);\n\t} catch {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" oauth.resource.resourceServerUrl must be a valid URL.`,\n\t\t);\n\t}\n\n\tconst verifier = requireMethodProvider(providers, resource.verifier, \"verifyAccessToken\");\n\tconst anonymousProvider =\n\t\tresource.anonymous === undefined\n\t\t\t? undefined\n\t\t\t: requireMethodProvider(providers, resource.anonymous, \"permit\");\n\n\tconst resourceServerOptions: McpResourceServerOptions = {\n\t\tbearerAuth: {\n\t\t\tverifier,\n\t\t\t...(resource.requiredScopes === undefined\n\t\t\t\t? {}\n\t\t\t\t: { requiredScopes: [...resource.requiredScopes] }),\n\t\t},\n\t\t...(resource.metadata === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\toauthMetadata: resource.metadata.oauthMetadata,\n\t\t\t\t\t\tresourceServerUrl,\n\t\t\t\t\t\t...(resource.metadata.serviceDocumentationUrl === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { serviceDocumentationUrl: new URL(resource.metadata.serviceDocumentationUrl) }),\n\t\t\t\t\t\t...(resource.metadata.scopesSupported === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { scopesSupported: [...resource.metadata.scopesSupported] }),\n\t\t\t\t\t\t...(resource.metadata.resourceName === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { resourceName: resource.metadata.resourceName }),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t...(anonymousProvider === undefined\n\t\t\t? {}\n\t\t\t: { anonymous: async (request: Request) => anonymousProvider.permit(request) }),\n\t};\n\n\treturn (handler) => new McpResourceServer(handler, resourceServerOptions);\n}\n","import {\n\tInject,\n\tInjectable,\n\tOptional,\n\ttype OnApplicationBootstrap,\n\ttype OnModuleDestroy,\n} from \"@nestjs/common\";\nimport { McpClientRuntime } from \"@nest-mcp/client\";\nimport {\n\tMcpGateway,\n\tbindMcpGatewayMiddleware,\n\tcreateMcpClientRuntimeUpstream,\n} from \"@nest-mcp/gateway\";\nimport type { McpGatewayPolicy } from \"@nest-mcp/gateway\";\nimport { McpServerRegistry, type McpServerFeature, type McpServerRuntime } from \"@nest-mcp/server\";\nimport { McpCapabilitiesService } from \"./mcp-capabilities.service.ts\";\nimport type { McpCatalogExposurePolicy } from \"./mcp-catalog-exposure.ts\";\nimport { McpModuleError } from \"./mcp.errors.ts\";\nimport { McpProviderRegistry, mcpProviderTokenName } from \"./mcp-provider.registry.ts\";\nimport type { McpProviderToken } from \"./mcp-provider.types.ts\";\nimport { assertMcpCatalogExposureOptions } from \"./mcp-catalog.runtime.ts\";\nimport { MCP_MODULE_OPTIONS } from \"./mcp.tokens.ts\";\nimport type {\n\tMcpHandlerAuthorizationPolicy,\n\tMcpHandlerLifecycleObserver,\n\tMcpHandlerMiddlewareProvider,\n\tMcpGatewayAuthorizationContextProvider,\n\tMcpGatewayClientProvider,\n\tMcpGatewayLifecycleObserverProvider,\n\tMcpGatewayMiddlewareProvider,\n\tMcpGatewayObserverErrorReporter,\n\tMcpModuleOptions,\n\tMcpNestGatewayOptions,\n\tMcpNestGatewayUpstreamDefinition,\n\tMcpServerContributor,\n\tMcpServerErrorReporter,\n\tMcpServerLifecycleObserver,\n\tMcpServerMiddlewareProvider,\n\tMcpServerPrincipalClaimsProvider,\n\tMcpServerRuntimeObserverProvider,\n} from \"./mcp.types.ts\";\nimport { McpHandlerExplorer } from \"./discovery/mcp-handler.explorer.ts\";\nimport { McpHandlerRegistry } from \"./discovery/mcp-handler.registry.ts\";\nimport { McpClientService } from \"./client/mcp-client.service.ts\";\nimport {\n\tresolveMcpNestServerHttpOptions,\n\tresolveMcpNestServerOptions,\n} from \"./server/mcp-server-options.ts\";\nimport { resolveMcpNestServerOAuth } from \"./oauth/mcp-oauth-options.ts\";\nimport type { McpFetchHandler } from \"@nest-mcp/server/auth\";\nimport type { McpOAuthProxy } from \"@nest-mcp/auth\";\n\n@Injectable()\nexport class McpRuntimeService implements OnApplicationBootstrap, OnModuleDestroy {\n\t#ready = false;\n\treadonly #gateways = new Map<string, McpGateway>();\n\treadonly #httpComposers = new Map<string, (handler: McpFetchHandler) => McpFetchHandler>();\n\treadonly #oauthProxies = new Map<string, McpOAuthProxy>();\n\t#closeTask: Promise<void> | undefined;\n\t#shutdownError: AggregateError | undefined;\n\t#unsubscribeCapabilityMutations: (() => void) | undefined;\n\n\tconstructor(\n\t\t@Inject(MCP_MODULE_OPTIONS) private readonly options: McpModuleOptions,\n\t\t@Inject(McpClientService)\n\t\t@Optional()\n\t\tprivate readonly clientService: McpClientService | undefined,\n\t\tprivate readonly servers: McpServerRegistry,\n\t\tprivate readonly explorer: McpHandlerExplorer,\n\t\tprivate readonly handlerRegistry: McpHandlerRegistry,\n\t\t/** Public live-capability service used by future request server builds. */\n\t\treadonly capabilities: McpCapabilitiesService,\n\t\tprivate readonly providers: McpProviderRegistry,\n\t) {}\n\n\tasync onApplicationBootstrap(): Promise<void> {\n\t\ttry {\n\t\t\tthis.explorer.assertSingleRoot();\n\t\t\tif (this.options.autoDiscover !== false) this.explorer.scan();\n\t\t\tconst definitions = this.options.servers ?? [];\n\t\t\tfor (const definition of definitions) {\n\t\t\t\tif (definition.catalogExposure === undefined) continue;\n\t\t\t\tif (\n\t\t\t\t\ttypeof definition.catalogExposure !== \"object\" ||\n\t\t\t\t\tdefinition.catalogExposure === null ||\n\t\t\t\t\tdefinition.catalogExposure.policy === undefined\n\t\t\t\t) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\t\t\t\t\t`MCP catalog exposure for server \"${definition.name}\" requires a policy provider token.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (definition.gateway !== undefined) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\t\t\t\t\t`MCP catalog exposure cannot be combined with gateway server \"${definition.name}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif ((definition.contributors?.length ?? 0) > 0) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_CATALOG_EXPOSURE\",\n\t\t\t\t\t\t`MCP catalog exposure for server \"${definition.name}\" cannot safely project tools from custom contributors. Register cataloged tools through decorators or McpCapabilitiesService.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.handlerRegistry.configureRuntimes(\n\t\t\t\tdefinitions.map(({ name }) => name),\n\t\t\t\tdefinitions.flatMap(({ name, gateway }) =>\n\t\t\t\t\tgateway === undefined || gateway.composition === \"tools\" ? [] : [name],\n\t\t\t\t),\n\t\t\t\tdefinitions.flatMap(({ name, catalogExposure }) =>\n\t\t\t\t\tcatalogExposure === undefined ? [] : [name],\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst oauthRouteOwners = new Map<string, string>();\n\t\t\tfor (const definition of definitions) {\n\t\t\t\tconst {\n\t\t\t\t\tcatalogExposure,\n\t\t\t\t\tcontributors: contributorTokens,\n\t\t\t\t\tgateway,\n\t\t\t\t\thandlerAuthorization: handlerAuthorizationToken,\n\t\t\t\t\thandlerLifecycleObserver: handlerLifecycleObserverToken,\n\t\t\t\t\thandlerMiddleware: handlerMiddlewareTokens,\n\t\t\t\t\thandlerVisibilityTimeoutMs,\n\t\t\t\t\thttp: httpOptions,\n\t\t\t\t\tlifecycleObserver: lifecycleObserverToken,\n\t\t\t\t\tmiddleware: middlewareTokens,\n\t\t\t\t\toauth: oauthOptions,\n\t\t\t\t\tobserver: observerToken,\n\t\t\t\t\tonError: errorReporterToken,\n\t\t\t\t\tprincipalClaims: principalClaimsToken,\n\t\t\t\t\tserverOptions,\n\t\t\t\t\t...serverDefinition\n\t\t\t\t} = definition;\n\t\t\t\tReflect.deleteProperty(serverDefinition, \"features\");\n\t\t\t\tconst resolvedOAuth = resolveMcpNestServerOAuth(\n\t\t\t\t\toauthOptions,\n\t\t\t\t\tthis.providers,\n\t\t\t\t\tdefinition.name,\n\t\t\t\t);\n\t\t\t\tif (resolvedOAuth !== undefined) {\n\t\t\t\t\tthis.#httpComposers.set(definition.name, resolvedOAuth.compose);\n\t\t\t\t\tif (resolvedOAuth.proxy !== undefined) {\n\t\t\t\t\t\tconst proxy = resolvedOAuth.proxy;\n\t\t\t\t\t\t// Two proxies sharing an issuer+basePath would silently shadow each\n\t\t\t\t\t\t// other's identical routes; refuse the ambiguous configuration.\n\t\t\t\t\t\tconst route = `${proxy.authorizationServerMetadata.issuer}${proxy.basePath}`;\n\t\t\t\t\t\tconst owner = oauthRouteOwners.get(route);\n\t\t\t\t\t\tif (owner !== undefined) {\n\t\t\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t\t\t\t`MCP servers \"${owner}\" and \"${definition.name}\" both expose an OAuth proxy at \"${route}\". Give each a distinct issuer or oauth.proxy.basePath.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\toauthRouteOwners.set(route, definition.name);\n\t\t\t\t\t\tthis.#oauthProxies.set(definition.name, proxy);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst resolvedServerOptions = resolveMcpNestServerOptions(serverOptions, this.providers);\n\t\t\t\tconst resolvedHttpOptions = resolveMcpNestServerHttpOptions(httpOptions, this.providers);\n\t\t\t\tconst contributors = this.#providerTokenList(\n\t\t\t\t\tcontributorTokens,\n\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\"contributors\",\n\t\t\t\t).map((token) =>\n\t\t\t\t\tthis.#resolveProvider<McpServerContributor>(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\"contributor\",\n\t\t\t\t\t\t\"contribute\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst catalogPolicy =\n\t\t\t\t\tcatalogExposure === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpCatalogExposurePolicy>(\n\t\t\t\t\t\t\t\tcatalogExposure.policy,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"catalog exposure policy\",\n\t\t\t\t\t\t\t\t\"resolve\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst resolvedCatalogExposure =\n\t\t\t\t\tcatalogPolicy === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: Object.freeze({\n\t\t\t\t\t\t\t\tresolver: (input: Parameters<McpCatalogExposurePolicy[\"resolve\"]>[0]) =>\n\t\t\t\t\t\t\t\t\tcatalogPolicy.resolve(input),\n\t\t\t\t\t\t\t});\n\t\t\t\tif (resolvedCatalogExposure !== undefined) {\n\t\t\t\t\tassertMcpCatalogExposureOptions(resolvedCatalogExposure, definition.name);\n\t\t\t\t}\n\t\t\t\tconst handlerAuthorization =\n\t\t\t\t\thandlerAuthorizationToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpHandlerAuthorizationPolicy>(\n\t\t\t\t\t\t\t\thandlerAuthorizationToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"handler authorization policy\",\n\t\t\t\t\t\t\t\t\"authorize\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst handlerMiddleware = this.#providerTokenList(\n\t\t\t\t\thandlerMiddlewareTokens,\n\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\"handlerMiddleware\",\n\t\t\t\t).map((token) => {\n\t\t\t\t\tconst provider = this.#resolveProvider<McpHandlerMiddlewareProvider>(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\"handler middleware\",\n\t\t\t\t\t\t\"handle\",\n\t\t\t\t\t);\n\t\t\t\t\treturn provider.handle.bind(provider);\n\t\t\t\t});\n\t\t\t\tconst handlerLifecycleObserver =\n\t\t\t\t\thandlerLifecycleObserverToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpHandlerLifecycleObserver>(\n\t\t\t\t\t\t\t\thandlerLifecycleObserverToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"handler lifecycle observer\",\n\t\t\t\t\t\t\t\t\"onEvent\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst principalClaimsProvider =\n\t\t\t\t\tprincipalClaimsToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpServerPrincipalClaimsProvider>(\n\t\t\t\t\t\t\t\tprincipalClaimsToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"principal claims provider\",\n\t\t\t\t\t\t\t\t\"resolvePrincipalClaims\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst middleware = this.#providerTokenList(\n\t\t\t\t\tmiddlewareTokens,\n\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\"middleware\",\n\t\t\t\t).map((token) => {\n\t\t\t\t\tconst provider = this.#resolveProvider<McpServerMiddlewareProvider>(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\"server middleware\",\n\t\t\t\t\t\t\"handle\",\n\t\t\t\t\t);\n\t\t\t\t\treturn provider.handle.bind(provider);\n\t\t\t\t});\n\t\t\t\tconst lifecycleObserver =\n\t\t\t\t\tlifecycleObserverToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpServerLifecycleObserver>(\n\t\t\t\t\t\t\t\tlifecycleObserverToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"server lifecycle observer\",\n\t\t\t\t\t\t\t\t\"onEvent\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst runtimeObserver =\n\t\t\t\t\tobserverToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpServerRuntimeObserverProvider>(\n\t\t\t\t\t\t\t\tobserverToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"server runtime observer\",\n\t\t\t\t\t\t\t\t\"observe\",\n\t\t\t\t\t\t\t);\n\t\t\t\tconst errorReporter =\n\t\t\t\t\terrorReporterToken === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: this.#resolveProvider<McpServerErrorReporter>(\n\t\t\t\t\t\t\t\terrorReporterToken,\n\t\t\t\t\t\t\t\tdefinition.name,\n\t\t\t\t\t\t\t\t\"server error reporter\",\n\t\t\t\t\t\t\t\t\"report\",\n\t\t\t\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tgateway !== undefined &&\n\t\t\t\t\tgateway.composition !== \"tools\" &&\n\t\t\t\t\t(this.handlerRegistry.hasHandlersFor(definition.name) || contributors.length > 0)\n\t\t\t\t) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t\t`MCP gateway server \"${definition.name}\" must be dedicated and cannot also host decorated or contributed capabilities.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst discovered = this.handlerRegistry.asServerFeature({\n\t\t\t\t\tserverName: definition.name,\n\t\t\t\t\t...(resolvedCatalogExposure === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { catalogExposure: resolvedCatalogExposure }),\n\t\t\t\t\t...(handlerAuthorization === undefined ? {} : { authorization: handlerAuthorization }),\n\t\t\t\t\t...(handlerMiddleware.length === 0 ? {} : { middleware: handlerMiddleware }),\n\t\t\t\t\t...(handlerLifecycleObserver === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { lifecycleObserver: handlerLifecycleObserver }),\n\t\t\t\t\t...(handlerVisibilityTimeoutMs === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { visibilityTimeoutMs: handlerVisibilityTimeoutMs }),\n\t\t\t\t});\n\t\t\t\tconst features: McpServerFeature[] = [];\n\t\t\t\t// Discovery may be disabled while live registry APIs remain enabled.\n\t\t\t\t// Install projected tools first so the SDK owns the shared tools handlers.\n\t\t\t\tif (gateway?.composition === \"tools\") {\n\t\t\t\t\tfeatures.push(this.#createGatewayFeature(definition.name, gateway));\n\t\t\t\t}\n\t\t\t\tif (gateway === undefined || gateway.composition === \"tools\") features.push(discovered);\n\t\t\t\tif (contributors.length > 0) {\n\t\t\t\t\tfeatures.push(async (server, context) => {\n\t\t\t\t\t\tfor (const contributor of contributors) await contributor.contribute(server, context);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (gateway !== undefined && gateway.composition !== \"tools\") {\n\t\t\t\t\tfeatures.push(this.#createGatewayFeature(definition.name, gateway));\n\t\t\t\t}\n\t\t\t\tthis.servers.register({\n\t\t\t\t\t...serverDefinition,\n\t\t\t\t\t...(resolvedServerOptions === undefined ? {} : { serverOptions: resolvedServerOptions }),\n\t\t\t\t\t...(resolvedHttpOptions === undefined ? {} : { http: resolvedHttpOptions }),\n\t\t\t\t\t...(principalClaimsProvider === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tprincipalClaims: (authInfo) =>\n\t\t\t\t\t\t\t\t\tprincipalClaimsProvider.resolvePrincipalClaims(authInfo),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t...(middleware.length === 0 ? {} : { middleware }),\n\t\t\t\t\t...(lifecycleObserver === undefined ? {} : { lifecycleObserver }),\n\t\t\t\t\t...(runtimeObserver === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { observer: (event) => runtimeObserver.observe(event) }),\n\t\t\t\t\t...(errorReporter === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { onError: (error) => errorReporter.report(error) }),\n\t\t\t\t\t...(features.length === 0 ? {} : { features }),\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.#unsubscribeCapabilityMutations = this.handlerRegistry.onMutation(\n\t\t\t\t({ kind, serverNames }) => {\n\t\t\t\t\tfor (const serverName of serverNames) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst notifier = this.servers.get(serverName).notify;\n\t\t\t\t\t\t\tif (kind === \"tool\") notifier.toolsChanged();\n\t\t\t\t\t\t\telse if (kind === \"prompt\") notifier.promptsChanged();\n\t\t\t\t\t\t\telse notifier.resourcesChanged();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// A committed registry mutation remains valid if publication races shutdown.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.#ready = true;\n\t\t} catch (bootstrapError) {\n\t\t\ttry {\n\t\t\t\tawait this.close();\n\t\t\t} catch (cleanupError) {\n\t\t\t\t// Both caught failures are retained explicitly in AggregateError.errors.\n\t\t\t\t// oxlint-disable-next-line eslint/preserve-caught-error\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[bootstrapError, cleanupError],\n\t\t\t\t\t\"MCP bootstrap failed and its partially initialized runtimes could not close cleanly.\",\n\t\t\t\t\t{ cause: bootstrapError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow bootstrapError;\n\t\t}\n\t}\n\n\t/**\n\t * Composes the configured OAuth resource-server protection around a runtime's\n\t * fetch handler. Returns the runtime untouched when the server has no `oauth`\n\t * group, so the HTTP controller's default composition seam is a no-op unless\n\t * OAuth is configured.\n\t */\n\tcomposeHttpHandler(serverName: string, runtime: McpServerRuntime): McpFetchHandler {\n\t\tconst composer = this.#httpComposers.get(serverName);\n\t\treturn composer === undefined ? runtime : composer(runtime);\n\t}\n\n\t/** The OAuth authorization-server proxy for a server, when `oauth.proxy` is configured. */\n\toauthProxy(serverName: string): McpOAuthProxy | undefined {\n\t\treturn this.#oauthProxies.get(serverName);\n\t}\n\n\tserver(name: string): McpServerRuntime {\n\t\tthis.#assertReady();\n\t\treturn this.servers.get(name);\n\t}\n\n\tclient(name: string): ReturnType<McpClientRuntime[\"requireClient\"]> {\n\t\tthis.#assertReady();\n\t\treturn this.clients.requireClient(name);\n\t}\n\n\t/** Named client runtime imported through `McpClientModule`. */\n\tget clients(): McpClientRuntime {\n\t\tif (this.clientService === undefined) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"UNKNOWN_CLIENT\",\n\t\t\t\t\"No McpClientModule is imported by this MCP root.\",\n\t\t\t);\n\t\t}\n\t\treturn this.clientService;\n\t}\n\n\t/** Returns the aggregate gateway owned by one configured inbound server. */\n\tgateway(serverName: string): McpGateway {\n\t\tthis.#assertReady();\n\t\tconst gateway = this.#gateways.get(serverName);\n\t\tif (gateway === undefined) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"UNKNOWN_GATEWAY\",\n\t\t\t\t`No MCP gateway is configured for server \"${serverName}\".`,\n\t\t\t);\n\t\t}\n\t\treturn gateway;\n\t}\n\n\tlistGateways(): readonly McpGateway[] {\n\t\tthis.#assertReady();\n\t\treturn Object.freeze([...this.#gateways.values()]);\n\t}\n\n\tisReady(): boolean {\n\t\treturn this.#ready;\n\t}\n\n\t/** Last cleanup failure contained by the Nest lifecycle hook, if any. */\n\tget shutdownError(): AggregateError | undefined {\n\t\treturn this.#shutdownError;\n\t}\n\n\t/** Explicit shutdown API. Unlike the Nest hook, this rejects on cleanup failure. */\n\tclose(): Promise<void> {\n\t\tif (this.#closeTask !== undefined) return this.#closeTask;\n\t\tthis.#ready = false;\n\t\tthis.#closeTask = Promise.resolve().then(() => this.#performClose());\n\t\treturn this.#closeTask;\n\t}\n\n\tasync onModuleDestroy(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.close();\n\t\t} catch {\n\t\t\t// Nest aborts adapter disposal when a destroy hook rejects. The error remains\n\t\t\t// available through shutdownError and the explicit close() promise.\n\t\t}\n\t}\n\n\tasync #performClose(): Promise<void> {\n\t\tconst errors: unknown[] = [];\n\t\tthis.#unsubscribeCapabilityMutations?.();\n\t\tthis.#unsubscribeCapabilityMutations = undefined;\n\t\tthis.handlerRegistry.close();\n\t\t// Stop accepting inbound gateway work before closing its upstream clients.\n\t\ttry {\n\t\t\tawait this.servers.close();\n\t\t} catch (error) {\n\t\t\terrors.push(error);\n\t\t}\n\t\tconst gatewayResults = await Promise.allSettled(\n\t\t\t[...this.#gateways.values()].map(async (gateway) => gateway.close()),\n\t\t);\n\t\tfor (const result of gatewayResults) {\n\t\t\tif (result.status === \"rejected\") errors.push(result.reason);\n\t\t}\n\t\tif (this.clientService !== undefined) {\n\t\t\ttry {\n\t\t\t\tawait this.clientService.closeFromAggregate();\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(error);\n\t\t\t}\n\t\t}\n\t\tthis.#gateways.clear();\n\t\tthis.#httpComposers.clear();\n\t\tthis.#oauthProxies.clear();\n\t\tif (errors.length > 0) {\n\t\t\tthis.#shutdownError = new AggregateError(errors, \"One or more MCP runtimes failed to close.\");\n\t\t\tthrow this.#shutdownError;\n\t\t}\n\t}\n\n\t#assertReady(): void {\n\t\tif (!this.#ready) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"RUNTIME_NOT_READY\",\n\t\t\t\t\"The MCP runtime is not ready until Nest application bootstrap completes.\",\n\t\t\t);\n\t\t}\n\t}\n\n\t#createGatewayFeature(serverName: string, options: McpNestGatewayOptions) {\n\t\tconst {\n\t\t\tauthorizationContextResolver: authorizationContextResolverToken,\n\t\t\tcomposition,\n\t\t\tdiscoveryCache: discoveryCacheToken,\n\t\t\tlifecycleObserver: lifecycleObserverToken,\n\t\t\tmiddleware: middlewareTokens,\n\t\t\tnameCodec: nameCodecToken,\n\t\t\tonObserverError: observerErrorReporterToken,\n\t\t\tpolicy: policyToken,\n\t\t\tpromptNameCodec: promptNameCodecToken,\n\t\t\tresourceTemplateNameCodec: resourceTemplateNameCodecToken,\n\t\t\tresourceTemplateUriCodec: resourceTemplateUriCodecToken,\n\t\t\tresourceUriCodec: resourceUriCodecToken,\n\t\t\tupstreams: upstreamDefinitions,\n\t\t\t...gatewayOptions\n\t\t} = options;\n\t\tconst policy = this.#bindGatewayPolicy(\n\t\t\tthis.#resolveProvider<McpGatewayPolicy>(\n\t\t\t\tpolicyToken,\n\t\t\t\tserverName,\n\t\t\t\t\"gateway policy\",\n\t\t\t\t\"authorize\",\n\t\t\t),\n\t\t\tserverName,\n\t\t);\n\t\tconst nameCodec = this.#resolveOptionalProvider(\n\t\t\tnameCodecToken,\n\t\t\tserverName,\n\t\t\t\"gateway name codec\",\n\t\t\t[\"encode\", \"decode\", \"tryDecode\"],\n\t\t);\n\t\tconst promptNameCodec = this.#resolveOptionalProvider(\n\t\t\tpromptNameCodecToken,\n\t\t\tserverName,\n\t\t\t\"gateway prompt name codec\",\n\t\t\t[\"encode\", \"decode\", \"tryDecode\"],\n\t\t);\n\t\tconst resourceUriCodec = this.#resolveOptionalProvider(\n\t\t\tresourceUriCodecToken,\n\t\t\tserverName,\n\t\t\t\"gateway resource URI codec\",\n\t\t\t[\"encode\", \"decode\", \"tryDecode\"],\n\t\t);\n\t\tconst resourceTemplateUriCodec = this.#resolveOptionalProvider(\n\t\t\tresourceTemplateUriCodecToken,\n\t\t\tserverName,\n\t\t\t\"gateway resource-template URI codec\",\n\t\t\t[\"encode\", \"decode\", \"tryDecode\"],\n\t\t);\n\t\tconst resourceTemplateNameCodec = this.#resolveOptionalProvider(\n\t\t\tresourceTemplateNameCodecToken,\n\t\t\tserverName,\n\t\t\t\"gateway resource-template name codec\",\n\t\t\t[\"encode\", \"decode\", \"tryDecode\"],\n\t\t);\n\t\tconst discoveryCache = this.#resolveOptionalProvider(\n\t\t\tdiscoveryCacheToken,\n\t\t\tserverName,\n\t\t\t\"gateway discovery cache\",\n\t\t\t[\"get\", \"set\", \"delete\", \"clear\"],\n\t\t);\n\t\tconst authorizationContextProvider =\n\t\t\tauthorizationContextResolverToken === undefined\n\t\t\t\t? undefined\n\t\t\t\t: this.#resolveProvider<McpGatewayAuthorizationContextProvider>(\n\t\t\t\t\t\tauthorizationContextResolverToken,\n\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\"gateway authorization context resolver\",\n\t\t\t\t\t\t\"resolveAuthorizationContext\",\n\t\t\t\t\t);\n\t\tconst middleware = this.#providerTokenList(\n\t\t\tmiddlewareTokens,\n\t\t\tserverName,\n\t\t\t\"gateway middleware\",\n\t\t).map((token) => {\n\t\t\tconst provider = this.#resolveProvider<McpGatewayMiddlewareProvider>(\n\t\t\t\ttoken,\n\t\t\t\tserverName,\n\t\t\t\t\"gateway middleware\",\n\t\t\t\t\"handle\",\n\t\t\t);\n\t\t\treturn bindMcpGatewayMiddleware(provider.handle, provider);\n\t\t});\n\t\tconst lifecycleObserver =\n\t\t\tlifecycleObserverToken === undefined\n\t\t\t\t? undefined\n\t\t\t\t: this.#resolveProvider<McpGatewayLifecycleObserverProvider>(\n\t\t\t\t\t\tlifecycleObserverToken,\n\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\"gateway lifecycle observer\",\n\t\t\t\t\t\t\"onEvent\",\n\t\t\t\t\t);\n\t\tconst observerErrorReporter =\n\t\t\tobserverErrorReporterToken === undefined\n\t\t\t\t? undefined\n\t\t\t\t: this.#resolveProvider<McpGatewayObserverErrorReporter>(\n\t\t\t\t\t\tobserverErrorReporterToken,\n\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\"gateway observer error reporter\",\n\t\t\t\t\t\t\"report\",\n\t\t\t\t\t);\n\t\tif (!Array.isArray(upstreamDefinitions)) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP gateway upstreams for server \"${serverName}\" must be an array.`,\n\t\t\t);\n\t\t}\n\t\tconst upstreams = upstreamDefinitions.map((definition) => {\n\t\t\tif (isProviderGatewayUpstream(definition)) {\n\t\t\t\tif (typeof definition.name !== \"string\" || definition.name.trim().length === 0) {\n\t\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t\t\"Nest gateway provider-backed upstream names must be non-empty strings.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst clientProvider = this.#resolveProvider<McpGatewayClientProvider>(\n\t\t\t\t\tdefinition.clientProvider,\n\t\t\t\t\tserverName,\n\t\t\t\t\t`gateway client provider for upstream \"${definition.name}\"`,\n\t\t\t\t\t\"resolveClient\",\n\t\t\t\t);\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tclient: clientProvider.resolveClient.bind(clientProvider),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst normalized = normalizeGatewayUpstream(definition);\n\t\t\tif (!this.clients.has(normalized.clientName)) {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"UNKNOWN_CLIENT\",\n\t\t\t\t\t`Gateway upstream references unknown MCP client \"${normalized.clientName}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn createMcpClientRuntimeUpstream(\n\t\t\t\tthis.clients,\n\t\t\t\tnormalized.clientName,\n\t\t\t\tnormalized.gatewayName,\n\t\t\t);\n\t\t});\n\t\tconst gateway = new McpGateway({\n\t\t\t...gatewayOptions,\n\t\t\tpolicy,\n\t\t\tupstreams,\n\t\t\t...(nameCodec === undefined ? {} : { nameCodec }),\n\t\t\t...(promptNameCodec === undefined ? {} : { promptNameCodec }),\n\t\t\t...(resourceUriCodec === undefined ? {} : { resourceUriCodec }),\n\t\t\t...(resourceTemplateUriCodec === undefined ? {} : { resourceTemplateUriCodec }),\n\t\t\t...(resourceTemplateNameCodec === undefined ? {} : { resourceTemplateNameCodec }),\n\t\t\t...(discoveryCache === undefined ? {} : { discoveryCache }),\n\t\t\t...(authorizationContextProvider === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tauthorizationContextResolver:\n\t\t\t\t\t\t\tauthorizationContextProvider.resolveAuthorizationContext.bind(\n\t\t\t\t\t\t\t\tauthorizationContextProvider,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t...(middleware.length === 0 ? {} : { middleware }),\n\t\t\t...(lifecycleObserver === undefined ? {} : { lifecycleObserver }),\n\t\t\t...(observerErrorReporter === undefined\n\t\t\t\t? {}\n\t\t\t\t: { onObserverError: observerErrorReporter.report.bind(observerErrorReporter) }),\n\t\t});\n\t\tthis.#gateways.set(serverName, gateway);\n\t\treturn gateway.asServerFeature({ toolsOnly: composition === \"tools\" });\n\t}\n\n\t#resolveOptionalProvider<Value>(\n\t\ttoken: McpProviderToken<Value> | undefined,\n\t\tserverName: string,\n\t\trole: string,\n\t\tmethods: readonly string[],\n\t): Value | undefined {\n\t\treturn token === undefined\n\t\t\t? undefined\n\t\t\t: this.#resolveProviderMethods(token, serverName, role, methods);\n\t}\n\n\t#resolveProvider<Value>(\n\t\ttoken: McpProviderToken<Value>,\n\t\tserverName: string,\n\t\trole: string,\n\t\tmethod: string,\n\t): Value {\n\t\treturn this.#resolveProviderMethods(token, serverName, role, [method]);\n\t}\n\n\t#resolveProviderMethods<Value>(\n\t\ttoken: McpProviderToken<Value>,\n\t\tserverName: string,\n\t\trole: string,\n\t\tmethods: readonly string[],\n\t): Value {\n\t\ttry {\n\t\t\tconst provider = this.providers.get(token);\n\t\t\tif (\n\t\t\t\t(typeof provider !== \"object\" && typeof provider !== \"function\") ||\n\t\t\t\tprovider === null ||\n\t\t\t\tmethods.some((method) => typeof Reflect.get(provider, method) !== \"function\")\n\t\t\t) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`resolved provider does not implement ${methods.map((method) => `${method}()`).join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The configured contract for every collaborator is structural and method-based.\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\t\treturn provider as Value;\n\t\t} catch (cause) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP ${role} ${mcpProviderTokenName(token)} for server \"${serverName}\" must be listed in McpModule collaborators.providers and implement ${methods.map((method) => `${method}()`).join(\", \")}.`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t}\n\n\t#providerTokenList<Value>(\n\t\tvalue: readonly McpProviderToken<Value>[] | undefined,\n\t\tserverName: string,\n\t\tfield: string,\n\t): readonly McpProviderToken<Value>[] {\n\t\tif (value === undefined) return [];\n\t\tif (Array.isArray(value)) return value;\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t`MCP server \"${serverName}\" ${field} must be an array of collaborator provider tokens.`,\n\t\t);\n\t}\n\n\t#bindGatewayPolicy(policy: McpGatewayPolicy, serverName: string): McpGatewayPolicy {\n\t\tconst { authorizePrompt, authorizeResource, authorizeResourceTemplate } = policy;\n\t\tfor (const [name, hook] of [\n\t\t\t[\"authorizePrompt\", authorizePrompt],\n\t\t\t[\"authorizeResource\", authorizeResource],\n\t\t\t[\"authorizeResourceTemplate\", authorizeResourceTemplate],\n\t\t] as const) {\n\t\t\tif (hook !== undefined && typeof hook !== \"function\") {\n\t\t\t\tthrow new McpModuleError(\n\t\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t\t`MCP gateway policy for server \"${serverName}\" has a non-callable ${name} hook.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tauthorize: (operation: Parameters<McpGatewayPolicy[\"authorize\"]>[0]) =>\n\t\t\t\tpolicy.authorize(operation),\n\t\t\t...(authorizePrompt === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tauthorizePrompt: (\n\t\t\t\t\t\t\toperation: Parameters<NonNullable<McpGatewayPolicy[\"authorizePrompt\"]>>[0],\n\t\t\t\t\t\t) => authorizePrompt.call(policy, operation),\n\t\t\t\t\t}),\n\t\t\t...(authorizeResource === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tauthorizeResource: (\n\t\t\t\t\t\t\toperation: Parameters<NonNullable<McpGatewayPolicy[\"authorizeResource\"]>>[0],\n\t\t\t\t\t\t) => authorizeResource.call(policy, operation),\n\t\t\t\t\t}),\n\t\t\t...(authorizeResourceTemplate === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tauthorizeResourceTemplate: (\n\t\t\t\t\t\t\toperation: Parameters<NonNullable<McpGatewayPolicy[\"authorizeResourceTemplate\"]>>[0],\n\t\t\t\t\t\t) => authorizeResourceTemplate.call(policy, operation),\n\t\t\t\t\t}),\n\t\t});\n\t}\n}\n\nfunction isProviderGatewayUpstream(\n\tdefinition: McpNestGatewayUpstreamDefinition,\n): definition is Extract<McpNestGatewayUpstreamDefinition, { readonly clientProvider: unknown }> {\n\treturn typeof definition === \"object\" && definition !== null && \"clientProvider\" in definition;\n}\n\nfunction normalizeGatewayUpstream(definition: McpNestGatewayUpstreamDefinition): {\n\treadonly clientName: string;\n\treadonly gatewayName: string;\n} {\n\tif (isProviderGatewayUpstream(definition)) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"A provider-backed gateway upstream cannot be normalized as a named client alias.\",\n\t\t);\n\t}\n\tif (typeof definition !== \"string\" && (typeof definition !== \"object\" || definition === null)) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"Nest gateway upstreams must be named client aliases or provider-backed descriptors.\",\n\t\t);\n\t}\n\tconst clientName =\n\t\ttypeof definition === \"string\"\n\t\t\t? definition\n\t\t\t: typeof definition.clientName === \"string\"\n\t\t\t\t? definition.clientName\n\t\t\t\t: \"\";\n\tconst gatewayName =\n\t\ttypeof definition === \"string\"\n\t\t\t? definition\n\t\t\t: definition.gatewayName === undefined\n\t\t\t\t? clientName\n\t\t\t\t: typeof definition.gatewayName === \"string\"\n\t\t\t\t\t? definition.gatewayName\n\t\t\t\t\t: \"\";\n\tif (clientName.trim().length === 0 || gatewayName.trim().length === 0) {\n\t\tthrow new McpModuleError(\n\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\"Nest gateway client and public namespace names must be non-empty strings.\",\n\t\t);\n\t}\n\treturn Object.freeze({ clientName, gatewayName });\n}\n","import { All, Inject, Req, Res } from \"@nestjs/common\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport type {\n\tFetchLikeMcpHandler,\n\tNodeMcpRequestHandler,\n\tToNodeHandlerOptions,\n} from \"@modelcontextprotocol/node\";\nimport type { McpServerRuntime } from \"@nest-mcp/server\";\nimport {\n\thardenMcpFetch,\n\tresolveMcpHttpSecurity,\n\twithMcpNodeBodyLimit,\n} from \"@nest-mcp/server/security\";\nimport type { McpHttpSecurityOptions } from \"@nest-mcp/server/security\";\nimport {\n\tforwardValidatedAuth,\n\thijackFastifyReply,\n\tparsedBodyOf,\n\ttoNodeRequest,\n\ttoNodeResponse,\n} from \"./http/node-bridge.ts\";\nimport { McpRuntimeService } from \"./mcp-runtime.service.ts\";\n\n/** Constructor returned by {@link McpHttpControllerFor}. */\nexport type McpHttpControllerClass = abstract new (\n\truntimeService: McpRuntimeService,\n) => McpHttpController;\n\n/**\n * Nest-native HTTP entry point for a named MCP server runtime.\n *\n * Extend this class through {@link McpHttpControllerFor}, then put `@Controller`\n * and any guards, interceptors, or version metadata on the concrete subclass.\n * The inherited catch-all route deliberately leaves HTTP method semantics to\n * the MCP handler.\n */\nexport abstract class McpHttpController {\n\tconstructor(@Inject(McpRuntimeService) private readonly runtimeService: McpRuntimeService) {}\n\n\tprotected get mcpServerName(): string {\n\t\tthrow new TypeError(\n\t\t\t\"MCP HTTP controller must bind a named server through McpHttpControllerFor().\",\n\t\t);\n\t}\n\n\t#nodeHandler: NodeMcpRequestHandler | undefined;\n\n\t@All()\n\tasync handleMcpRequest(\n\t\t@Req() request: unknown,\n\t\t@Res({ passthrough: true }) response: unknown,\n\t): Promise<unknown> {\n\t\tconst intercepted = this.interceptMcpRequest(request, response);\n\t\tif (intercepted !== undefined) return intercepted;\n\t\tconst nodeRequest = toNodeRequest(request);\n\t\tconst nodeResponse = toNodeResponse(response);\n\t\tforwardValidatedAuth(request, nodeRequest);\n\t\thijackFastifyReply(response, nodeResponse);\n\t\tawait this.#getNodeHandler()(nodeRequest, nodeResponse, parsedBodyOf(request));\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Optional Nest-native interception seam before the Node/Web adapter takes ownership.\n\t * Returning a value short-circuits MCP dispatch and lets Nest serialize that value;\n\t * returning `undefined` delegates to the named MCP runtime.\n\t */\n\tprotected interceptMcpRequest(_request: unknown, _response: unknown): unknown {\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Override to compose another fetch-shaped facade around the named runtime.\n\t * The default applies any configured `oauth` resource-server protection and\n\t * otherwise returns the runtime untouched.\n\t */\n\tprotected createMcpHttpHandler(runtime: McpServerRuntime): FetchLikeMcpHandler {\n\t\treturn this.runtimeService.composeHttpHandler(this.mcpServerName, runtime);\n\t}\n\n\t/** Override to observe conversion-layer failures handled as HTTP 500 responses. */\n\tprotected getNodeAdapterOptions(): Readonly<ToNodeHandlerOptions> | undefined {\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Override to replace the runtime's configured HTTP security posture for\n\t * this route. The posture is enforced outside `createMcpHttpHandler()`\n\t * composition, so a rejected request never reaches a composed facade.\n\t */\n\tprotected getHttpSecurityOptions(): McpHttpSecurityOptions | undefined {\n\t\treturn undefined;\n\t}\n\n\t#getNodeHandler(): NodeMcpRequestHandler {\n\t\tif (this.#nodeHandler === undefined) {\n\t\t\tconst runtime = this.runtimeService.server(this.mcpServerName);\n\t\t\tconst override = this.getHttpSecurityOptions();\n\t\t\tconst policy =\n\t\t\t\toverride === undefined ? runtime.httpSecurity : resolveMcpHttpSecurity(override);\n\t\t\t// Rejections detected outside the runtime still surface as observer events.\n\t\t\tconst hooks = { onRejected: (status: number) => runtime.reportRequestRejected(status) };\n\t\t\tthis.#nodeHandler = withMcpNodeBodyLimit(\n\t\t\t\ttoNodeHandler(\n\t\t\t\t\thardenMcpFetch(this.createMcpHttpHandler(runtime), policy, hooks),\n\t\t\t\t\tthis.getNodeAdapterOptions(),\n\t\t\t\t),\n\t\t\t\tpolicy,\n\t\t\t\thooks,\n\t\t\t);\n\t\t}\n\t\treturn this.#nodeHandler;\n\t}\n}\n\n/**\n * Creates a controller base bound to one named `McpRuntimeService` server.\n *\n * @example\n * ```ts\n * const ArtifactMcpControllerBase = McpHttpControllerFor(\"artifact\");\n *\n * @Controller({ path: \"mcp\", version: \"1\" })\n * @UseGuards(ArtifactGuard)\n * export class ArtifactMcpController extends ArtifactMcpControllerBase {}\n * ```\n *\n * Override `createMcpHttpHandler()` or `getNodeAdapterOptions()` on the concrete\n * controller when composition requires additional Nest-injected providers.\n */\nexport function McpHttpControllerFor(serverName: string): McpHttpControllerClass {\n\tif (typeof serverName !== \"string\" || serverName.trim().length === 0) {\n\t\tthrow new TypeError(\"MCP HTTP controller server name must be a non-empty string.\");\n\t}\n\n\tabstract class NamedMcpHttpController extends McpHttpController {\n\t\tprotected override get mcpServerName(): string {\n\t\t\treturn serverName;\n\t\t}\n\t}\n\n\treturn NamedMcpHttpController;\n}\n","import {\n\tMCP_CORS_ALLOWED_HEADERS,\n\tMCP_CORS_EXPOSED_HEADERS,\n\tMCP_CORS_METHODS,\n} from \"@nest-mcp/server/security\";\n\nconst DEFAULT_MAX_AGE_SECONDS = 600;\n\nexport interface McpCorsInput {\n\t/** Full browser origins (`https://app.example.com`), not bare hostnames. */\n\treadonly origins: readonly string[];\n\t/** Allows cookies/credentialed requests. Cookie-authenticated MCP endpoints are CSRF-able; leave off unless required. */\n\treadonly credentials?: boolean;\n\treadonly maxAgeSeconds?: number;\n\treadonly additionalAllowedHeaders?: readonly string[];\n\treadonly additionalExposedHeaders?: readonly string[];\n}\n\n/**\n * Structurally compatible with Nest's `CorsOptions` for `app.enableCors()`.\n * Arrays are mutable because Nest's own option types require `string[]`.\n */\nexport interface McpNestCorsOptions {\n\torigin: string[];\n\tmethods: string[];\n\tallowedHeaders: string[];\n\texposedHeaders: string[];\n\tcredentials: boolean;\n\tmaxAge: number;\n}\n\n/**\n * CORS options preconfigured for the 2026-07-28 MCP revision, whose\n * `Mcp-Method`/`Mcp-Name` request headers make every browser MCP POST\n * CORS-preflighted. Pass the result to `app.enableCors()` when Nest owns CORS\n * for the whole app; keep exactly one CORS owner per route — with\n * `app.enableCors()` active, the runtime's built-in `httpSecurity.cors`\n * preflight handling never runs, so disable one of the two.\n */\nexport function mcpCorsOptions(input: McpCorsInput): McpNestCorsOptions {\n\tif (typeof input !== \"object\" || input === null || !Array.isArray(input.origins)) {\n\t\tthrow new TypeError(\"mcpCorsOptions requires an origins array of full browser origins.\");\n\t}\n\tconst origins = input.origins.map((value, index) => {\n\t\tconst failure = `mcpCorsOptions origins[${String(index)}] must be a full origin like \"https://app.example.com\".`;\n\t\tif (typeof value !== \"string\" || value.trim().length === 0) throw new TypeError(failure);\n\t\tlet parsed: URL;\n\t\ttry {\n\t\t\tparsed = new URL(value);\n\t\t} catch {\n\t\t\tthrow new TypeError(failure);\n\t\t}\n\t\tif (parsed.origin === \"null\" || parsed.origin !== value.replace(/\\/$/, \"\")) {\n\t\t\tthrow new TypeError(failure);\n\t\t}\n\t\treturn parsed.origin;\n\t});\n\tconst maxAge = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;\n\tif (!Number.isInteger(maxAge) || maxAge < 0) {\n\t\tthrow new TypeError(\"mcpCorsOptions maxAgeSeconds must be a non-negative integer.\");\n\t}\n\treturn {\n\t\torigin: origins,\n\t\tmethods: [...MCP_CORS_METHODS],\n\t\tallowedHeaders: mergeHeaders(MCP_CORS_ALLOWED_HEADERS, input.additionalAllowedHeaders),\n\t\texposedHeaders: mergeHeaders(MCP_CORS_EXPOSED_HEADERS, input.additionalExposedHeaders),\n\t\tcredentials: input.credentials === true,\n\t\tmaxAge,\n\t};\n}\n\nfunction mergeHeaders(base: readonly string[], additional?: readonly string[]): string[] {\n\tconst merged = new Set(base);\n\tfor (const header of additional ?? []) {\n\t\tif (typeof header !== \"string\" || header.trim().length === 0) {\n\t\t\tthrow new TypeError(\"mcpCorsOptions header names must be non-empty strings.\");\n\t\t}\n\t\tmerged.add(header.trim().toLowerCase());\n\t}\n\treturn [...merged];\n}\n","import { Get, Inject, Post, Req, Res } from \"@nestjs/common\";\nimport type { McpOAuthProxy } from \"@nest-mcp/auth\";\nimport {\n\tparsedBodyOf,\n\treadNodeBodyText,\n\ttoWebRequestWithBody,\n\twriteWebResponse,\n} from \"../http/node-bridge.ts\";\nimport { McpModuleError } from \"../mcp.errors.ts\";\nimport { McpRuntimeService } from \"../mcp-runtime.service.ts\";\n\n/** Constructor returned by {@link McpOAuthControllerFor}. */\nexport type McpOAuthControllerClass = abstract new (\n\truntimeService: McpRuntimeService,\n) => McpOAuthController;\n\nconst MAX_FORM_BODY_BYTES = 65_536;\n\n/**\n * Nest-native host for a server's OAuth authorization-server proxy endpoints.\n * Each route is an explicit method that calls its proxy operation directly —\n * there is no path matching against a base path, so a Nest global prefix,\n * versioning, or a controller path never desynchronizes from the router. The\n * well-known documents must resolve at the origin root, so mount the concrete\n * controller at `@Controller()` and exclude those paths from any global prefix.\n * Requires the server to configure `oauth.proxy`.\n */\nexport abstract class McpOAuthController {\n\tconstructor(@Inject(McpRuntimeService) private readonly runtimeService: McpRuntimeService) {}\n\n\tprotected get mcpServerName(): string {\n\t\tthrow new TypeError(\n\t\t\t\"MCP OAuth controller must bind a named server through McpOAuthControllerFor().\",\n\t\t);\n\t}\n\n\t@Get(\".well-known/oauth-authorization-server\")\n\tasync authorizationServerMetadata(@Res({ passthrough: true }) response: unknown): Promise<void> {\n\t\tawait writeWebResponse(jsonResponse(this.#proxy().authorizationServerMetadata), response);\n\t}\n\n\t@Get(\".well-known/jwks.json\")\n\tasync jwks(@Res({ passthrough: true }) response: unknown): Promise<void> {\n\t\tawait writeWebResponse(jsonResponse(this.#proxy().jwks()), response);\n\t}\n\n\t@Get(\".well-known/oauth-protected-resource\")\n\tasync protectedResourceMetadata(@Res({ passthrough: true }) response: unknown): Promise<void> {\n\t\tawait writeWebResponse(jsonResponse(this.#proxy().protectedResourceMetadata()), response);\n\t}\n\n\t@Get(\"oauth/authorize\")\n\tasync authorize(\n\t\t@Req() request: unknown,\n\t\t@Res({ passthrough: true }) response: unknown,\n\t): Promise<void> {\n\t\tconst webRequest = toWebRequestWithBody(request, undefined);\n\t\tawait writeWebResponse(await this.#proxy().authorize(webRequest), response);\n\t}\n\n\t@Post(\"oauth/authorize/consent\")\n\tasync consent(\n\t\t@Req() request: unknown,\n\t\t@Res({ passthrough: true }) response: unknown,\n\t): Promise<void> {\n\t\tconst { webRequest, form } = await this.#readForm(request);\n\t\tawait writeWebResponse(await this.#proxy().handleConsent(webRequest, form), response);\n\t}\n\n\t@Get(\"oauth/callback\")\n\tasync callback(\n\t\t@Req() request: unknown,\n\t\t@Res({ passthrough: true }) response: unknown,\n\t): Promise<void> {\n\t\tconst webRequest = toWebRequestWithBody(request, undefined);\n\t\tawait writeWebResponse(await this.#proxy().handleCallback(webRequest), response);\n\t}\n\n\t@Post(\"oauth/token\")\n\tasync token(\n\t\t@Req() request: unknown,\n\t\t@Res({ passthrough: true }) response: unknown,\n\t): Promise<void> {\n\t\tconst { webRequest, form } = await this.#readForm(request);\n\t\tawait writeWebResponse(await this.#proxy().token(webRequest, form), response);\n\t}\n\n\tasync #readForm(\n\t\trequest: unknown,\n\t): Promise<{ readonly webRequest: Request; readonly form: URLSearchParams }> {\n\t\t// The token/consent bodies are form-encoded; read the raw stream (the SDK\n\t\t// adapter would otherwise JSON-serialize a platform-parsed body).\n\t\tconst parsed = parsedBodyOf(request);\n\t\tconst bodyText =\n\t\t\tparsed === undefined ? await readNodeBodyText(request, MAX_FORM_BODY_BYTES) : undefined;\n\t\tconst webRequest = toWebRequestWithBody(request, bodyText);\n\t\treturn { webRequest, form: toSearchParams(parsed, bodyText) };\n\t}\n\n\t#proxy(): McpOAuthProxy {\n\t\tconst proxy = this.runtimeService.oauthProxy(this.mcpServerName);\n\t\tif (proxy === undefined) {\n\t\t\tthrow new McpModuleError(\n\t\t\t\t\"INVALID_OPTIONS\",\n\t\t\t\t`MCP server \"${this.mcpServerName}\" has no oauth.proxy configured for an OAuth controller.`,\n\t\t\t);\n\t\t}\n\t\treturn proxy;\n\t}\n}\n\n/**\n * Creates an OAuth controller base bound to one named `McpRuntimeService`\n * server whose definition configures `oauth.proxy`.\n *\n * @example\n * ```ts\n * const AuthControllerBase = McpOAuthControllerFor(\"artifact\");\n *\n * @Controller()\n * export class ArtifactOAuthController extends AuthControllerBase {}\n * ```\n */\nexport function McpOAuthControllerFor(serverName: string): McpOAuthControllerClass {\n\tif (typeof serverName !== \"string\" || serverName.trim().length === 0) {\n\t\tthrow new TypeError(\"MCP OAuth controller server name must be a non-empty string.\");\n\t}\n\tabstract class NamedMcpOAuthController extends McpOAuthController {\n\t\tprotected override get mcpServerName(): string {\n\t\t\treturn serverName;\n\t\t}\n\t}\n\treturn NamedMcpOAuthController;\n}\n\nfunction jsonResponse(body: unknown): Response {\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 200,\n\t\theaders: { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n\t});\n}\n\nfunction toSearchParams(parsed: unknown, bodyText: string | undefined): URLSearchParams {\n\tif (parsed instanceof URLSearchParams) return parsed;\n\tif (typeof parsed === \"string\") return new URLSearchParams(parsed);\n\tif (typeof parsed === \"object\" && parsed !== null) {\n\t\tconst params = new URLSearchParams();\n\t\tfor (const [key, value] of Object.entries(parsed)) {\n\t\t\tif (typeof value === \"string\") params.set(key, value);\n\t\t\telse if (Array.isArray(value)) {\n\t\t\t\tfor (const entry of value) if (typeof entry === \"string\") params.append(key, entry);\n\t\t\t}\n\t\t}\n\t\treturn params;\n\t}\n\treturn new URLSearchParams(bodyText ?? \"\");\n}\n","import { Injectable } from \"@nestjs/common\";\nimport type { AuthInfo } from \"@modelcontextprotocol/server\";\nimport { McpRuntimeService } from \"../mcp-runtime.service.ts\";\n\n/**\n * Read access to a server's OAuth authorization-server proxy. Its primary use\n * is retrieving the upstream tokens behind a verified access token — the\n * credential source a gateway needs for user-delegated upstream calls.\n */\n@Injectable()\nexport class McpOAuthService {\n\tconstructor(private readonly runtimeService: McpRuntimeService) {}\n\n\t/**\n\t * Loads the upstream tokens for the grant referenced by a verified\n\t * `AuthInfo` (via its `gid` claim). Returns `undefined` when the server has\n\t * no proxy, the token carries no grant id, or the grant has been revoked.\n\t */\n\tasync upstreamTokens(\n\t\tserverName: string,\n\t\tauthInfo: Readonly<AuthInfo>,\n\t): Promise<\n\t\t| { readonly accessToken: string; readonly refreshToken?: string; readonly expiresAt?: number }\n\t\t| undefined\n\t> {\n\t\tconst proxy = this.runtimeService.oauthProxy(serverName);\n\t\tif (proxy === undefined) return undefined;\n\t\tconst grantId = grantIdOf(authInfo);\n\t\tif (grantId === undefined) return undefined;\n\t\tconst upstream = await proxy.loadUpstreamTokens(grantId);\n\t\tif (upstream === undefined) return undefined;\n\t\treturn {\n\t\t\taccessToken: upstream.accessToken,\n\t\t\t...(upstream.refreshToken === undefined ? {} : { refreshToken: upstream.refreshToken }),\n\t\t\t...(upstream.expiresAt === undefined ? {} : { expiresAt: upstream.expiresAt }),\n\t\t};\n\t}\n}\n\nfunction grantIdOf(authInfo: Readonly<AuthInfo>): string | undefined {\n\tconst claims = authInfo.extra?.[\"claims\"];\n\tif (typeof claims !== \"object\" || claims === null) return undefined;\n\tconst gid = Reflect.get(claims, \"gid\");\n\treturn typeof gid === \"string\" && gid.length > 0 ? gid : undefined;\n}\n","import {\n\tAll,\n\tController,\n\tInject,\n\tReq,\n\tRes,\n\tVERSION_NEUTRAL,\n\tapplyDecorators,\n\ttype DynamicModule,\n\ttype Type,\n} from \"@nestjs/common\";\nimport {\n\tbuildOAuthProtectedResourceMetadata,\n\tgetOAuthProtectedResourceMetadataUrl,\n\toauthMetadataResponse,\n\ttype AuthMetadataOptions,\n} from \"@nest-mcp/server/auth\";\nimport { McpHttpControllerFor } from \"../mcp-http.controller.ts\";\nimport { McpRuntimeService } from \"../mcp-runtime.service.ts\";\nimport { McpModuleError } from \"../mcp.errors.ts\";\nimport { MCP_MODULE_OPTIONS } from \"../mcp.tokens.ts\";\nimport type { McpModuleOptions, McpNestServerDefinition } from \"../mcp.types.ts\";\nimport type { McpHttpRoute } from \"./mcp-http-route.types.ts\";\nimport { toWebRequestWithBody, writeWebResponse } from \"./node-bridge.ts\";\n\n/** Generates ordinary Nest controllers while retaining the existing protocol/security pipeline. */\nexport function withMcpHttpRoutes(\n\tdefinition: DynamicModule,\n\troutes: readonly McpHttpRoute[] | undefined,\n): DynamicModule {\n\tif (routes === undefined) return definition;\n\tif (!Array.isArray(routes)) throw invalid(\"httpRoutes must be an array.\");\n\tconst paths = new Set<string>();\n\tconst controllers: Type<unknown>[] = [];\n\tfor (const input of routes) {\n\t\tif (!input || typeof input.serverName !== \"string\" || input.serverName.trim().length === 0) {\n\t\t\tthrow invalid(\"Every httpRoutes entry requires a non-empty serverName.\");\n\t\t}\n\t\tif (\n\t\t\tinput.discovery !== undefined &&\n\t\t\t(!input.discovery || typeof input.discovery !== \"object\")\n\t\t) {\n\t\t\tthrow invalid(\"HTTP discovery must be an object.\");\n\t\t}\n\t\tconst route: McpHttpRoute = {\n\t\t\tserverName: input.serverName,\n\t\t\tpath: claimPath(input.path, paths),\n\t\t\t...(input.version === undefined\n\t\t\t\t? {}\n\t\t\t\t: { version: Array.isArray(input.version) ? [...input.version] : input.version }),\n\t\t\tdecorators: decorators(input.decorators),\n\t\t\t...(input.discovery === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tdiscovery: {\n\t\t\t\t\t\t\tprotectedResourcePaths: claimPaths(input.discovery.protectedResourcePaths, paths),\n\t\t\t\t\t\t\tauthorizationServerPaths: claimPaths(input.discovery.authorizationServerPaths, paths),\n\t\t\t\t\t\t\tdecorators: decorators(input.discovery.decorators),\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t};\n\t\tif (\n\t\t\troute.discovery !== undefined &&\n\t\t\t!route.discovery.protectedResourcePaths?.length &&\n\t\t\t!route.discovery.authorizationServerPaths?.length\n\t\t) {\n\t\t\tthrow invalid(\"HTTP discovery requires at least one document path.\");\n\t\t}\n\t\tcontrollers.push(httpController(route));\n\t\tfor (const kind of [\"protectedResource\", \"authorizationServer\"] as const) {\n\t\t\tconst documentPaths = route.discovery?.[`${kind}Paths`];\n\t\t\tif (documentPaths?.length) controllers.push(discoveryController(route, kind, documentPaths));\n\t\t}\n\t}\n\treturn { ...definition, controllers: [...(definition.controllers ?? []), ...controllers] };\n}\n\nfunction httpController(route: McpHttpRoute) {\n\tconst Base = McpHttpControllerFor(route.serverName);\n\t@Controller({\n\t\tpath: route.path,\n\t\t...(route.version === undefined ? {} : { version: route.version }),\n\t})\n\tclass GeneratedMcpHttpController extends Base {\n\t\tconstructor(\n\t\t\t@Inject(McpRuntimeService) runtime: McpRuntimeService,\n\t\t\t@Inject(MCP_MODULE_OPTIONS) options: McpModuleOptions,\n\t\t) {\n\t\t\tsuper(runtime);\n\t\t\tconst server = requireServer(options, route.serverName);\n\t\t\tif (route.discovery !== undefined) discoveryMetadata(server, route);\n\t\t}\n\t}\n\tapplyDecorators(...(route.decorators ?? []))(GeneratedMcpHttpController);\n\treturn GeneratedMcpHttpController;\n}\n\nfunction discoveryController(\n\troute: McpHttpRoute,\n\tkind: \"protectedResource\" | \"authorizationServer\",\n\tpaths: readonly string[],\n) {\n\t@Controller({ version: VERSION_NEUTRAL })\n\tclass GeneratedMcpDiscoveryController {\n\t\treadonly #metadata: AuthMetadataOptions;\n\t\tconstructor(@Inject(MCP_MODULE_OPTIONS) options: McpModuleOptions) {\n\t\t\tthis.#metadata = discoveryMetadata(requireServer(options, route.serverName), route);\n\t\t}\n\n\t\t@All([...paths])\n\t\tasync document(\n\t\t\t@Req() request: unknown,\n\t\t\t@Res({ passthrough: true }) response: unknown,\n\t\t): Promise<void> {\n\t\t\tconst incoming = toWebRequestWithBody(request, undefined);\n\t\t\t// Nest selected the route. Project aliases onto the SDK's canonical metadata paths.\n\t\t\tconst url =\n\t\t\t\tkind === \"protectedResource\"\n\t\t\t\t\t? getOAuthProtectedResourceMetadataUrl(this.#metadata.resourceServerUrl)\n\t\t\t\t\t: new URL(\"/.well-known/oauth-authorization-server\", this.#metadata.resourceServerUrl)\n\t\t\t\t\t\t\t.href;\n\t\t\tconst result = oauthMetadataResponse(\n\t\t\t\tnew Request(url, { method: incoming.method, headers: incoming.headers }),\n\t\t\t\tthis.#metadata,\n\t\t\t);\n\t\t\tif (result === undefined) throw invalid(\"The SDK did not resolve the discovery document.\");\n\t\t\tawait writeWebResponse(result, response);\n\t\t}\n\t}\n\tapplyDecorators(...(route.discovery?.decorators ?? []))(GeneratedMcpDiscoveryController);\n\treturn GeneratedMcpDiscoveryController;\n}\n\nfunction requireServer(options: McpModuleOptions, name: string): McpNestServerDefinition {\n\tconst server = options.servers?.find((candidate) => candidate.name === name);\n\tif (server === undefined) throw invalid(`HTTP route references unknown MCP server \"${name}\".`);\n\treturn server;\n}\n\nfunction discoveryMetadata(\n\tserver: McpNestServerDefinition,\n\troute: McpHttpRoute,\n): AuthMetadataOptions {\n\tconst resource = server.oauth?.resource;\n\tconst metadata = resource?.metadata;\n\tif (resource === undefined || metadata === undefined) {\n\t\tthrow invalid(`HTTP discovery for \"${server.name}\" requires oauth.resource.metadata.`);\n\t}\n\tconst options: AuthMetadataOptions = {\n\t\tresourceServerUrl: new URL(resource.resourceServerUrl),\n\t\toauthMetadata: structuredClone(metadata.oauthMetadata),\n\t\t...(metadata.resourceName === undefined ? {} : { resourceName: metadata.resourceName }),\n\t\t...(metadata.scopesSupported === undefined\n\t\t\t? {}\n\t\t\t: { scopesSupported: [...metadata.scopesSupported] }),\n\t\t...(metadata.serviceDocumentationUrl === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tserviceDocumentationUrl: new URL(metadata.serviceDocumentationUrl),\n\t\t\t\t}),\n\t};\n\tbuildOAuthProtectedResourceMetadata(options);\n\tconst expectedPath = new URL(\n\t\tgetOAuthProtectedResourceMetadataUrl(options.resourceServerUrl),\n\t).pathname.slice(1);\n\tconst resourcePaths = route.discovery?.protectedResourcePaths;\n\tif (resourcePaths?.length && !resourcePaths.includes(expectedPath)) {\n\t\tthrow invalid(\n\t\t\t`HTTP discovery for \"${server.name}\" must include its bearer challenge path \"${expectedPath}\".`,\n\t\t);\n\t}\n\treturn options;\n}\n\nfunction claimPaths(input: readonly string[] | undefined, paths: Set<string>): readonly string[] {\n\tif (input === undefined) return [];\n\tif (!Array.isArray(input) || input.length === 0)\n\t\tthrow invalid(\"Discovery document paths must be non-empty arrays.\");\n\treturn input.map((path) => claimPath(path, paths));\n}\n\nfunction claimPath(input: string, paths: Set<string>): string {\n\tif (\n\t\ttypeof input !== \"string\" ||\n\t\t!/^\\/?[A-Za-z0-9._~-]+(?:\\/[A-Za-z0-9._~-]+)*\\/?$/u.test(input)\n\t) {\n\t\tthrow invalid(\n\t\t\t\"HTTP route paths must be literal paths without queries, fragments, or router patterns.\",\n\t\t);\n\t}\n\tconst path = input.replace(/^\\//u, \"\").replace(/\\/$/u, \"\");\n\tif (path.split(\"/\").some((segment) => segment === \".\" || segment === \"..\"))\n\t\tthrow invalid(\"HTTP route paths cannot contain dot segments.\");\n\t// Express is case-insensitive by default; reject collisions consistently on both adapters.\n\tconst key = path.toLowerCase();\n\tif (paths.has(key)) throw invalid(`Duplicate MCP HTTP route path \"${path}\".`);\n\tpaths.add(key);\n\treturn path;\n}\n\nfunction decorators(input: readonly ClassDecorator[] | undefined): readonly ClassDecorator[] {\n\tif (input === undefined) return [];\n\tif (!Array.isArray(input) || input.some((decorator) => typeof decorator !== \"function\"))\n\t\tthrow invalid(\"HTTP route decorators must be class decorator functions.\");\n\treturn [...input];\n}\n\nfunction invalid(message: string): McpModuleError {\n\treturn new McpModuleError(\"INVALID_OPTIONS\", message);\n}\n","import { ConfigurableModuleBuilder } from \"@nestjs/common\";\nimport { withMcpCollaborators } from \"./mcp-provider.registry.ts\";\nimport { MCP_MODULE_OPTIONS } from \"./mcp.tokens.ts\";\nimport type { McpModuleExtras, McpModuleOptions } from \"./mcp.types.ts\";\nimport { withMcpHttpRoutes } from \"./http/mcp-http-routes.ts\";\n\nexport const { ConfigurableModuleClass, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } =\n\tnew ConfigurableModuleBuilder<McpModuleOptions>({\n\t\toptionsInjectionToken: MCP_MODULE_OPTIONS,\n\t})\n\t\t.setClassMethodName(\"forRoot\")\n\t\t.setFactoryMethodName(\"createMcpOptions\")\n\t\t.setExtras<McpModuleExtras>(\n\t\t\t{ isGlobal: false, imports: [], collaborators: {}, httpRoutes: [] },\n\t\t\t(definition, extras) => ({\n\t\t\t\t...withMcpHttpRoutes(\n\t\t\t\t\twithMcpCollaborators(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...definition,\n\t\t\t\t\t\t\timports: [...new Set([...(definition.imports ?? []), ...(extras.imports ?? [])])],\n\t\t\t\t\t\t},\n\t\t\t\t\t\textras.collaborators,\n\t\t\t\t\t),\n\t\t\t\t\textras.httpRoutes,\n\t\t\t\t),\n\t\t\t\tglobal: extras.isGlobal === true,\n\t\t\t}),\n\t\t)\n\t\t.build();\n\nexport type McpForRootOptions = typeof OPTIONS_TYPE;\nexport type McpForRootAsyncOptions = typeof ASYNC_OPTIONS_TYPE;\n","import { Module } from \"@nestjs/common\";\nimport type { DynamicModule } from \"@nestjs/common\";\nimport { DiscoveryModule } from \"@nestjs/core\";\nimport { McpServerRegistry } from \"@nest-mcp/server\";\nimport {\n\tConfigurableModuleClass,\n\ttype McpForRootAsyncOptions,\n\ttype McpForRootOptions,\n} from \"./mcp.module-definition.ts\";\nimport { McpCapabilitiesService } from \"./mcp-capabilities.service.ts\";\nimport { McpRuntimeService } from \"./mcp-runtime.service.ts\";\nimport { McpOAuthService } from \"./oauth/mcp-oauth.service.ts\";\nimport { McpHandlerExplorer } from \"./discovery/mcp-handler.explorer.ts\";\nimport { McpHandlerRegistry } from \"./discovery/mcp-handler.registry.ts\";\n\nconst MCP_PROVIDERS = [\n\tMcpServerRegistry,\n\tMcpHandlerRegistry,\n\tMcpCapabilitiesService,\n\tMcpHandlerExplorer,\n\tMcpRuntimeService,\n\tMcpOAuthService,\n];\n\n@Module({\n\timports: [DiscoveryModule],\n\tproviders: MCP_PROVIDERS,\n\texports: [McpCapabilitiesService, McpRuntimeService, McpOAuthService],\n})\nexport class McpModule extends ConfigurableModuleClass {\n\tstatic override forRoot(options: McpForRootOptions = {}): DynamicModule {\n\t\treturn super.forRoot(options);\n\t}\n\n\tstatic override forRootAsync(options: McpForRootAsyncOptions): DynamicModule {\n\t\treturn super.forRootAsync(options);\n\t}\n}\n","import { createMcpPassthroughMiddleware } from \"@nest-mcp/core\";\n\nimport type {\n\tMcpHandlerInvocationInput,\n\tMcpHandlerInvocationOutput,\n\tMcpHandlerMiddleware,\n\tMcpHandlerOperationContext,\n\tMcpHandlerPassthroughMiddleware,\n} from \"./mcp.types.ts\";\n\n/**\n * Creates handler middleware that can observe the validated invocation while\n * preserving the exact SDK result produced by the downstream capability.\n */\nexport function createMcpHandlerPassthroughMiddleware(\n\tmiddleware: McpHandlerPassthroughMiddleware,\n): McpHandlerMiddleware {\n\treturn createMcpPassthroughMiddleware<\n\t\tMcpHandlerInvocationInput,\n\t\tMcpHandlerInvocationOutput,\n\t\tMcpHandlerOperationContext\n\t>(middleware);\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,MAAa,+BAA+B;AAC5C,MAAa,gCAAgC;;;AC8F7C,SAAgB,KACf,SACmC;CACnC,OAAO,uBAAuB,qBAAqB,OAAO,CAAC;AAC5D;AAEA,SAAgB,SACf,SAC+B;CAC/B,OAAO,uBAAuB,yBAAyB,OAAO,CAAC;AAChE;AAEA,SAAgB,OACf,SACoC;CACpC,OAAO,uBAAuB,uBAAuB,OAAO,CAAC;AAC9D;;AAGA,SAAgB,QAAQ,GAAG,aAA6D;CACvF,MAAM,aAAa,iBAAiB,WAAW;CAC/C,OAAO,YAAY,sBAAsB,UAAU;AACpD;AAEA,SAAS,uBACR,YACgC;CAChC,MAAM,YAAY,YAAY,sBAAsB,UAAU;CAC9D,QAAQ,QAAQ,aAAa,eAAe;EAC3C,UAAU,QAAQ,aAAa,UAAU;CAC1C;AACD;AAEA,SAAS,qBAAqB,SAA6C;CAC1E,MAAM,EAAE,MAAM,GAAG,eAAe;CAChC,MAAM,iBAAiB,cAAc,IAAI;CACzC,OAAO,OAAO,OAAO;EACpB,MAAM;EACN,SAAS,cAAc;GACtB,GAAG;GACH,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,eAAe;EAChE,CAAC;CACF,CAAC;AACF;AAEA,SAAS,yBAAyB,SAAqD;CACtF,OAAO,OAAO,OAAO;EAAE,MAAM;EAAY,SAAS,cAAc,OAAO;CAAE,CAAC;AAC3E;AAEA,SAAS,uBAAuB,SAAiD;CAChF,OAAO,OAAO,OAAO;EAAE,MAAM;EAAU,SAAS,cAAc,OAAO;CAAE,CAAC;AACzE;AAEA,SAAS,cAA6C,SAA2B;CAChF,MAAM,UA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,OAAO;CAClC;AACD;AAbC,YAAA,WAAA,CAAA,OAAO;CACP,SAAS,CAAC,eAAe;CACzB,WAAW;CACX,SAAS;EAAC;EAAwB;EAAmB;CAAe;AACrE,CAAC,CAAA,GAAA,SAAA;;;;;;;ACdD,SAAgB,sCACf,YACuB;CACvB,OAAO,+BAIL,UAAU;AACb"}
@@ -0,0 +1,47 @@
1
+ import { a as McpModuleErrorCode, i as McpModuleError, n as McpNestCollaborators, r as McpProviderToken, t as McpProviderRegistry } from "../mcp-provider.registry-dnQfMj1w.mjs";
2
+ import { DynamicModule, OnModuleDestroy } from "@nestjs/common";
3
+ import { McpLifecycleObserver } from "@nest-mcp/core";
4
+ import { McpRuntimeGenerationResolver, McpRuntimeManager, McpRuntimeManagerOptions, McpRuntimeStateTransitionEvent } from "@nest-mcp/manager";
5
+ //#region src/manager/mcp-manager.types.d.ts
6
+ interface McpManagerClock {
7
+ now(): number;
8
+ }
9
+ interface McpManagerStateListenerErrorReporter {
10
+ report(error: unknown, event: McpRuntimeStateTransitionEvent): void | PromiseLike<void>;
11
+ }
12
+ interface McpManagerModuleOptions extends Omit<McpRuntimeManagerOptions, "generationResolver" | "now" | "observer" | "onListenerError"> {
13
+ readonly generationResolver: McpProviderToken<McpRuntimeGenerationResolver>;
14
+ readonly observer?: McpProviderToken<McpLifecycleObserver>;
15
+ readonly clock?: McpProviderToken<McpManagerClock>;
16
+ readonly listenerErrorReporter?: McpProviderToken<McpManagerStateListenerErrorReporter>;
17
+ }
18
+ interface McpManagerModuleExtras {
19
+ /** Make the manager service globally injectable. Defaults to false. */
20
+ readonly isGlobal?: boolean;
21
+ /** Singleton providers referenced by the manager module's provider-token options. */
22
+ readonly collaborators?: McpNestCollaborators;
23
+ }
24
+ //#endregion
25
+ //#region src/manager/mcp-manager.module-definition.d.ts
26
+ declare const ConfigurableMcpManagerModuleClass: import("@nestjs/common").ConfigurableModuleCls<McpManagerModuleOptions, "forRoot", "createMcpManagerOptions", McpManagerModuleExtras>, MCP_MANAGER_OPTIONS_TYPE: McpManagerModuleOptions & Partial<McpManagerModuleExtras>, MCP_MANAGER_ASYNC_OPTIONS_TYPE: import("@nestjs/common").ConfigurableModuleAsyncOptions<McpManagerModuleOptions, "createMcpManagerOptions"> & Partial<McpManagerModuleExtras>;
27
+ type McpManagerForRootOptions = typeof MCP_MANAGER_OPTIONS_TYPE;
28
+ type McpManagerForRootAsyncOptions = typeof MCP_MANAGER_ASYNC_OPTIONS_TYPE;
29
+ //#endregion
30
+ //#region src/manager/mcp-manager.module.d.ts
31
+ declare class McpManagerModule extends ConfigurableMcpManagerModuleClass {
32
+ static forRoot(options: McpManagerForRootOptions): DynamicModule;
33
+ static forRootAsync(options: McpManagerForRootAsyncOptions): DynamicModule;
34
+ }
35
+ //#endregion
36
+ //#region src/manager/mcp-manager.service.d.ts
37
+ /** Nest-owned dynamic MCP runtime manager with deterministic module shutdown. */
38
+ declare class McpManagerService extends McpRuntimeManager implements OnModuleDestroy {
39
+ #private;
40
+ constructor(options: McpManagerModuleOptions, providers: McpProviderRegistry);
41
+ /** Last cleanup failure contained by the Nest destroy hook, if any. */
42
+ get shutdownError(): AggregateError | undefined;
43
+ onModuleDestroy(): Promise<void>;
44
+ }
45
+ //#endregion
46
+ export { type McpManagerClock, type McpManagerForRootAsyncOptions, type McpManagerForRootOptions, McpManagerModule, type McpManagerModuleExtras, type McpManagerModuleOptions, McpManagerService, type McpManagerStateListenerErrorReporter, McpModuleError, type McpModuleErrorCode, type McpNestCollaborators, type McpProviderToken };
47
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/manager/mcp-manager.types.ts","../../src/manager/mcp-manager.module-definition.ts","../../src/manager/mcp-manager.module.ts","../../src/manager/mcp-manager.service.ts"],"mappings":";;;;;UASiB;EAChB;;UAGgB;EAChB,OAAO,gBAAgB,OAAO,wCAAwC;;UAGtD,gCAAgC,KAChD;WAGS,oBAAoB,iBAAiB;WACrC,WAAW,iBAAiB;WAC5B,QAAQ,iBAAiB;WACzB,wBAAwB,iBAAiB;;UAGlC;;WAEP;;WAEA,gBAAgB;;;;cCxBA,4DAAiC,sBAAA,+DAAA,yBAC5C,0BAAwB,0BAAA,QAAA,yBAClB,yDAA8B,+BAAA,sDAAA,QAAA;KAevC,kCAAkC;KAClC,uCAAuC;;;cCXtC,yBAAyB;SACrB,QAAQ,SAAS,2BAA2B;SAI5C,aAAa,SAAS,gCAAgC;;;;;cCJ1D,0BAA0B,6BAA6B;;EAGnE,YACqC,SAAS,yBAC7C,WAAW;;MAMR,iBAAiB;EAIf,mBAAmB"}