@webpieces/mcp-server 0.4.862 → 0.4.864

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.
@@ -1 +1 @@
1
- {"version":3,"file":"WpMcpServer.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/WpMcpServer.ts"],"names":[],"mappings":";;;AAAA,mDAAqD;AACrD,6CAAyC;AACzC,yDAesC;AACtC,qDAAkF;AAClF,qCAAyE;AACzE,oDAa8B;AAC9B,0DAKiC;AACjC,wDAA+D;AAC/D,0DAAgF;AAChF,uCAMmB;AACnB,yDAAsD;AAEtD,iEAAmF;AACnF,uDAA2F;AAC3F,iEAAwD;AACxD,iEAA8D;AAE9D,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;AAIhD;;;GAGG;AACH,MAAM,eAAe;IAEW;IAD5B,SAAS,GAAG,KAAK,CAAC;IAClB,YAA4B,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;CAC/C;AAED,MAAM,cAAc;IACY;IAA5B,YAA4B,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;CAC/C;AAED,yFAAyF;AACzF,MAAM,uBAAuB;IAChB,KAAK,GAAG,oBAAoB,CAAC;CACzC;AAED,2FAA2F;AAC3F,MAAM,qBAAqB;IAEH;IACA;IACA;IACA;IAJpB,YACoB,WAAmB,EACnB,UAAiC,EACjC,gBAA6B,EAC7B,KAAyB;QAHzB,gBAAW,GAAX,WAAW,CAAQ;QACnB,eAAU,GAAV,UAAU,CAAuB;QACjC,qBAAgB,GAAhB,gBAAgB,CAAa;QAC7B,UAAK,GAAL,KAAK,CAAoB;IAC1C,CAAC;CACP;AAED;;;;GAIG;AACH,MAAM,cAAe,SAAQ,kBAAS;IAIb;IAHrB,YACI,IAAoB,EACpB,OAAsB,EACL,QAA4B;QAE7C,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,C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,IAAI,CAAC,KAAK,CAAC,SAAS,CAAa,CAAC;QACjD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACzE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAC7B,CAAC;QACD,OAAO,MAAkC,CAAC;IAC9C,CAAC;CACJ;AA/iBD,kCA+iBC","sourcesContent":["import { McpToolDeniedError } from './McpToolPolicy';\nimport { createHash } from 'node:crypto';\nimport {\n AuthInfo,\n CallToolRequest,\n CallToolResult,\n createMcpHandler,\n ListToolsResult,\n McpHttpHandler,\n McpRequestContext,\n McpServer,\n ProgressToken,\n ProtocolError,\n ServerContext,\n ServerOptions,\n Tool,\n Implementation,\n} from '@modelcontextprotocol/server';\nimport { NodeMcpRequestHandler, toNodeHandler } from '@modelcontextprotocol/node';\nimport { Express, json, NextFunction, Request, Response } from 'express';\nimport {\n ApiBadRequestError,\n ApiErrorBoundary,\n ApiForbiddenError,\n ApiImplementationError,\n ApiJsonSchemaValidator,\n ApiMethodInfo,\n ApiUnauthorizedError,\n DtoValue,\n LogApiCallImpl,\n LogManager,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport {\n HttpRequest,\n RequestContext,\n RequestContextApiCallContext,\n RequestContextHeaders,\n} from '@webpieces/core-context';\nimport { ExpressResponseWriter } from '@webpieces/http-server';\nimport { AuthenticatedCallerContext, MintedJwt } from '@webpieces/http-routing';\nimport {\n MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS,\n McpEndpointDescriptor,\n McpProtectedResourceMetadata,\n VerifiedMcpCredential,\n WpMcpServerConfig,\n} from './McpAuth';\nimport { McpApiDispatcher } from './McpApiDispatcher';\nimport { McpBindOptions } from './McpBindOptions';\nimport { McpInvocationContext, McpProgressReporter } from './McpInvocationContext';\nimport { AuthorizedMcpTools, McpToolRegistry, RegisteredMcpTool } from './McpToolRegistry';\nimport { McpCorrelation } from './McpToolCallRendering';\nimport { WpMcpErrorTranslator } from './WpMcpErrorTranslator';\n\nconst log = LogManager.getLogger('WpMcpServer');\n\ntype AuthenticatedExpressRequest = Request & { auth?: AuthInfo };\n\n/**\n * The request DTO the edge `LogApiCall` lines report. These boundaries run BEFORE (or outside) any\n * API dispatch, so there is no contract DTO to log; the step name is the fact worth having.\n */\nclass McpSdkOperation {\n toolStage = false;\n constructor(public readonly name: string) {}\n}\n\nclass McpEdgeRequest {\n constructor(public readonly step: string) {}\n}\n\n/** Body of the 405 answered for every non-POST method at the bound MCP endpoint path. */\nclass McpMethodNotAllowedBody {\n readonly error = 'method_not_allowed';\n}\n\n/** Facts established once per POST at the bind boundary and handed to the SDK handlers. */\nclass McpPostAuthentication {\n constructor(\n public readonly accessToken: string,\n public readonly credential: VerifiedMcpCredential,\n public readonly disconnectSignal: AbortSignal,\n public readonly tools: AuthorizedMcpTools,\n ) {}\n}\n\n/**\n * The official SDK server with Webpieces-owned tools/list and tools/call handlers. It answers\n * `toolInputSchemaJson` from the request-authorized view so the SDK's pre-dispatch SEP-2243\n * `Mcp-Param-*` header validation still runs without registering SDK-side tool callbacks.\n */\nclass WpSdkMcpServer extends McpServer {\n constructor(\n info: Implementation,\n options: ServerOptions,\n private readonly registry: AuthorizedMcpTools,\n ) {\n super(info, options);\n }\n\n // webpieces-disable no-any-unknown -- signature is fixed by the SDK's JSON Schema record type\n override toolInputSchemaJson(name: string): Record<string, unknown> | undefined {\n return this.registry.find(name)?.inputSchema as Record<string, DtoValue> | undefined;\n }\n}\n\n/**\n * MCP adapter around the official SDK's request-scoped HTTP handler, serving BOTH wire eras from\n * one tool registry: modern (2026-07-28, per-request `_meta` envelope) and legacy (the 2025-11-25\n * family, negotiated by `initialize`). The SDK routes each request to the leg its shape selects and\n * negotiates the revision; only a revision no era knows is refused. Pinning one era instead made\n * every shipping client unreachable (issue #969), and the MCP lifecycle spec is explicit that a\n * server answers with a revision it supports rather than erroring.\n *\n * Error boundaries: HTTP ingress owns pre-SDK replies; one shared SDK callback wrapper owns\n * protocol/list/name-resolution errors and authorized tool-result errors. The SDK writes callback\n * replies, so it cannot safely delegate those failures back to HTTP ingress.\n * `subscriptions/listen` is served entirely by the SDK's listen router, so Webpieces has no handler\n * (and no catch) there. The external bearer is verified exactly once per POST, at the HTTP\n * boundary, before the SDK is involved.\n *\n * Before tools/list and tools/call hand an IMPLEMENTATION-kind failure to the translator, they\n * `log.error` it with its stack and the requestId ({@link logImplementationFailure}, #1055). The\n * translator reduces such a failure to \"Internal Error\" for the caller, so that line is the only place\n * its cause exists.\n */\nexport class WpMcpServer<TGrant, TMintRequest> {\n private readonly callerContext = new AuthenticatedCallerContext();\n private readonly dispatcher = new McpApiDispatcher();\n /** Classifies a failure exactly as the translator will render it, so the two cannot disagree. */\n private readonly boundary = new ApiErrorBoundary();\n private readonly outputSchemas = new ApiJsonSchemaValidator();\n /**\n * These edges have NO filter chain above them — `LogApiFilter` never sees a rejected bearer, a\n * bad `Origin`, a body express could not parse, or a `tools/list` the SDK renders itself.\n * Wrapping each in `LogApiCall` is this repo's one line on logging, and it is why\n * `ApiErrorBoundary` no longer writes a second, barer line of its own.\n */\n private readonly logApiCall = new LogApiCallImpl(new RequestContextApiCallContext());\n private readonly responseWriter = new ExpressResponseWriter();\n /** tools/call reads `McpRegistry`; every other reply stays framework-owned. See McpErrorTranslator. */\n private readonly translator: WpMcpErrorTranslator;\n private registry?: McpToolRegistry;\n private handler?: McpHttpHandler;\n private streamingHandler?: McpHttpHandler;\n private nodeHandler?: NodeMcpRequestHandler;\n private streamingNodeHandler?: NodeMcpRequestHandler;\n private revision?: string;\n\n constructor(private readonly config: WpMcpServerConfig<TGrant, TMintRequest>) {\n this.translator = new WpMcpErrorTranslator((): string => this.challenge());\n }\n\n /**\n * Mounts this MCP endpoint on `app`: POST at `options.endpointPath`, plus a 405 (`Allow: POST`)\n * for every other method there.\n *\n * SINGLE CANONICAL ORIGIN: one server serves exactly one protected resource, so this may be\n * called only once and `WpMcpServerConfig.setResource(...)`'s path must equal `endpointPath`.\n * That resource URI is fixed for the lifetime of the process and is never derived from the\n * request `Host` — a host-derived audience would make the boundary's own audience check compare\n * two caller-controlled values, which is the confused deputy this check exists to prevent.\n * Serving a second hostname is a second deployment, not a second audience.\n *\n * The OAuth/discovery half stays app-owned: publish `protectedResourceMetadata()` at\n * `WpMcpServerConfig.resourceMetadataUrl`, which is where the 401 challenge sends clients.\n */\n bind(app: Express, options: McpBindOptions): void {\n if (this.handler) {\n throw new Error(\n 'WpMcpServer.bind(...) may be called only once; an MCP resource has exactly one ' +\n 'canonical URI, fixed for the lifetime of the process.',\n );\n }\n // Fail at boot naming the forgotten setter, never on the first request with a 401 the client\n // answers by re-authenticating (see WpMcpServerConfig).\n this.config.validate();\n const resourcePath = new URL(this.config.resource).pathname;\n if (resourcePath !== options.endpointPath) {\n throw new Error(\n `MCP resource path '${resourcePath}' must equal endpointPath ` +\n `'${options.endpointPath}'; the canonical resource URI ` +\n `'${this.config.resource}' and the bound route are the same endpoint.`,\n );\n }\n this.registry = new McpToolRegistry(options.bindings, options.toolCatalogs);\n this.revision = this.calculateRegistryRevision(this.registry);\n this.handler = this.createHandler(options, 'auto');\n this.streamingHandler = this.createHandler(options, 'sse');\n this.nodeHandler = toNodeHandler(this.handler, {\n onerror: (error: Error) => log.error('MCP Node transport failed', error),\n });\n this.streamingNodeHandler = toNodeHandler(this.streamingHandler, {\n onerror: (error: Error) => log.error('MCP streaming Node transport failed', error),\n });\n app.post(\n options.endpointPath,\n json(),\n async (req: Request, res: Response): Promise<void> =>\n this.handleHttp(req, res, options),\n // Express routes body-parser failures (bad JSON, body too large) to an error handler.\n (bodyError: Error, req: Request, res: Response, _next: NextFunction): void => {\n void this.handleBodyFailure(bodyError, req, res);\n },\n );\n // Registered AFTER the POST route so POST still wins. NEITHER era served here has a session\n // GET: 2026-07-28 has none at all (`subscriptions/listen` is a POST method), and the legacy\n // leg is the SDK's STATELESS fallback, which answers the 2025 session GET/DELETE with the\n // same 405. So every other method is a method error — and a discovery probe gets that\n // instead of Express' bare 404.\n app.all(options.endpointPath, (_req: Request, res: Response): void => {\n res.setHeader('Allow', 'POST');\n res.status(405).json(new McpMethodNotAllowedBody());\n });\n }\n\n protectedResourceMetadata(): McpProtectedResourceMetadata {\n return this.config.protectedResourceMetadata();\n }\n\n /** Gracefully closes active listen/request streams; clients must reconnect and refresh lists. */\n async close(): Promise<void> {\n await Promise.all([this.handler?.close(), this.streamingHandler?.close()]);\n }\n\n /** Level-triggered invalidation; the authoritative list is always fetched again by clients. */\n toolsChanged(): void {\n this.handler?.notify.toolsChanged();\n }\n\n get registryRevision(): string | undefined {\n return this.revision;\n }\n\n private createHandler(options: McpBindOptions, responseMode: 'auto' | 'sse'): McpHttpHandler {\n return createMcpHandler(\n (context: McpRequestContext) => this.buildSdkServer(context, options),\n {\n // Both eras, one factory: `stateless` serves 2025-era traffic through a fresh\n // instance of the SAME McpServerFactory, so the two eras can never drift apart.\n legacy: 'stateless',\n responseMode,\n bus: options.deployment.bus,\n maxSubscriptions: options.maxSubscriptions,\n keepAliveMs: options.keepAliveMs,\n onerror: (error: Error) => log.warn('MCP protocol request rejected', error),\n },\n );\n }\n\n /** Each HTTP entry uses the same full-request scope and ingress translation seam. */\n private async handleHttp(req: Request, res: Response, options: McpBindOptions): Promise<void> {\n res.setHeader('X-Accel-Buffering', 'no');\n await this.ingress(req, res, 'serve', () => this.serveExpress(req, res, options));\n }\n\n private async handleBodyFailure(cause: Error, req: Request, res: Response): Promise<void> {\n await this.ingress(req, res, 'body', () => this.rejectBody(cause));\n }\n\n private async ingress(\n req: Request,\n res: Response,\n step: string,\n work: () => Promise<void>,\n ): Promise<void> {\n await RequestContext.run(async () => {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- HTTP response-owning ingress boundary, including request publication and correlation failures\n try {\n new RequestContextHeaders().fillFromRequest(this.toHttpRequest(req));\n McpCorrelation.stamp(this.correlationOf(req));\n await this.logEdge(step, work);\n } catch (err: unknown) {\n const error = toError(err);\n this.writeBoundaryError(res, error);\n }\n });\n }\n\n /** A body express could not parse is a caller input error, reported through the same edge. */\n private async rejectBody(cause: Error): Promise<never> {\n throw new ApiBadRequestError(\n `MCP request body rejected: ${cause.message}`,\n undefined,\n undefined,\n cause,\n );\n }\n\n /**\n * The pre-SDK boundary owns the socket, so it produces a VALUE and writes it through the SAME\n * express writer `ExpressWrapper` uses. A failure after headers were sent can only end the\n * stream.\n */\n private writeBoundaryError(res: Response, error: Error): void {\n if (res.headersSent) {\n res.end();\n return;\n }\n this.responseWriter.write(res, this.translator.toBearerBoundaryResponse(error));\n }\n\n /** Run one un-filtered edge step under `LogApiCall`, so its failure gets exactly one log line. */\n private async logEdge<R>(step: string, work: () => Promise<R>): Promise<R> {\n return this.logApiCall.execute(\n new ApiMethodInfo('server', 'McpEndpoint', step),\n new McpEdgeRequest(step),\n work,\n );\n }\n\n private async serveExpress(\n req: Request,\n res: Response,\n options: McpBindOptions,\n ): Promise<void> {\n const origin = req.header('origin');\n if (origin && !options.allowedOrigins.includes(origin)) {\n throw new ApiForbiddenError(`MCP request Origin '${origin}' is not allowed.`);\n }\n const authentication = await this.authenticate(req);\n const request = req as AuthenticatedExpressRequest;\n request.auth = this.authInfo(authentication);\n const serve = this.hasProgressToken(req.body)\n ? this.streamingNodeHandler\n : this.nodeHandler;\n if (!serve) throw new ApiImplementationError('MCP Node handlers are not initialized.');\n await serve(request, res, req.body);\n }\n\n /** Verifies the external bearer once for this POST. Handlers never re-verify it. */\n private async authenticate(req: Request): Promise<McpPostAuthentication> {\n const match = req.header('authorization')?.match(/^Bearer ([^\\s]+)$/i);\n const token = match?.[1];\n if (!token) throw new ApiUnauthorizedError('MCP request has no bearer access token.');\n const credential = await this.config.accessTokenAuthority.verifyAccessToken(\n token,\n this.config.resource,\n );\n this.validateCredential(credential);\n this.callerContext.publish(credential.caller);\n RequestContext.putTrusted(WebpiecesCoreHeaders.SURFACE, 'llm');\n this.callerContext.reconcileWireTrust(false);\n const tools = await AuthorizedMcpTools.create(\n this.requireRegistry(),\n credential.caller,\n this.config.endpointJwtAuthority,\n );\n return new McpPostAuthentication(token, credential, this.disconnectSignal(req), tools);\n }\n\n private disconnectSignal(req: Request): AbortSignal {\n const disconnected = new AbortController();\n const res = req.res;\n const cancel = (): void => disconnected.abort();\n req.once('aborted', cancel);\n req.socket.once('close', cancel);\n res?.once('close', cancel);\n res?.once('finish', (): void => {\n req.off('aborted', cancel);\n req.socket.off('close', cancel);\n res.off('close', cancel);\n });\n return disconnected.signal;\n }\n\n private buildSdkServer(context: McpRequestContext, options: McpBindOptions): McpServer {\n // The era is the SDK's to decide and BOTH are served; what is not negotiable is that the\n // request came through `bind`'s HTTP boundary, which is where the external bearer is\n // verified. A factory call without it is a wiring mistake, never a client's doing.\n const authentication = context.authInfo?.extra?.['webpiecesAuthentication'];\n if (!(authentication instanceof McpPostAuthentication)) {\n throw new ApiImplementationError(\n 'WpMcpServer serves only MCP requests authenticated by its bind boundary.',\n );\n }\n const server = new WpSdkMcpServer(\n { name: this.config.name, version: `${this.config.version}+${this.revision}` },\n {\n capabilities: { tools: { listChanged: true } },\n cacheHints: {\n 'tools/list': { ttlMs: options.deployment.ttlMs, cacheScope: 'private' },\n 'server/discover': { ttlMs: options.deployment.ttlMs, cacheScope: 'private' },\n },\n },\n authentication.tools,\n );\n server.server.removeRequestHandler('tools/list');\n server.server.removeRequestHandler('tools/call');\n server.server.setRequestHandler(\n 'tools/list',\n async (_request: object): Promise<ListToolsResult> =>\n this.sdkBoundary(new McpSdkOperation('tools/list'), () =>\n this.logEdge('tools/list', async () => this.listTools(authentication.tools)),\n ) as Promise<ListToolsResult>,\n );\n server.server.setRequestHandler(\n 'tools/call',\n async (request: CallToolRequest, sdkContext: ServerContext): Promise<CallToolResult> =>\n this.handleCallTool(server, request, authentication, sdkContext),\n );\n return server;\n }\n\n /** ONE SDK callback catch implementation; the SDK intercepts foreign throws itself. */\n private async sdkBoundary<R>(\n operation: McpSdkOperation,\n work: () => Promise<R>,\n ): Promise<R | CallToolResult> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- shared SDK response boundary, preserving protocol versus tool envelopes\n try {\n return await work();\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof McpToolDeniedError)\n throw this.translator.unknownTool(error.toolName);\n if (!operation.toolStage && error instanceof ProtocolError) throw error;\n this.logImplementationFailure(operation.name, error);\n if (operation.toolStage) return this.translator.toToolCallResult(error);\n this.translator.toListError(error);\n }\n }\n\n private listTools(view: AuthorizedMcpTools): ListToolsResult {\n const tools: Tool[] = view.tools.map((tool) => this.toolDefinition(tool));\n return { tools };\n }\n\n private toolDefinition(tool: RegisteredMcpTool): Tool {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema as Tool['inputSchema'],\n outputSchema: tool.outputSchema as Tool['outputSchema'],\n annotations: tool.annotations,\n _meta: { webpiecesRegistryRevision: this.revision },\n };\n }\n\n /**\n * SDK tool callback: an unknown or hidden tool is a JSON-RPC -32602; every failure after the tool is found\n * is an `isError: true` result, identically for local and remote bindings.\n */\n private async handleCallTool(\n server: WpSdkMcpServer,\n request: CallToolRequest,\n authentication: McpPostAuthentication,\n sdkContext: ServerContext,\n ): Promise<CallToolResult> {\n const name = request.params.name;\n const operation = new McpSdkOperation(`tools/call ${name}`);\n return this.sdkBoundary(operation, async () => {\n McpCorrelation.stamp(new McpCorrelation(sdkContext.mcpReq.id, name));\n const tool = authentication.tools.find(name);\n if (!tool) throw this.translator.unknownTool(name);\n McpCorrelation.stamp(new McpCorrelation(sdkContext.mcpReq.id, name, tool.operation));\n operation.toolStage = true;\n const result = await this.callTool(tool, request, authentication, sdkContext);\n result._meta = this.translator.resultMeta(McpCorrelation.requestId());\n return server.server.projectCallToolResult(\n result,\n tool.outputSchema as Record<string, DtoValue>,\n );\n }) as Promise<CallToolResult>;\n }\n\n /**\n * ONE `log.error` line, with the stack and the requestId, for a failure that is THIS server's bug\n * — the `implementation` kind, which the translator reduces to \"Internal Error\" and a requestId\n * for the caller (#1055).\n *\n * `LogApiCall` does not cover this. An MCP output-schema violation is raised AFTER the controller\n * returned, so the only `LogApiCall` line for that call reads `resp-SUCCESS`; before this line\n * existed, the requestId support was handed led to a log with no error in it. Where a\n * `[API-*-resp-FAIL]` line does exist it carries the error's message, not its stack. So this line\n * is not the bare duplicate `ApiErrorBoundary` stopped writing: it is the one that says WHERE.\n *\n * Every other kind (bad-request, end-user, dependency, ...) is a caller's or a downstream's\n * failure, published to the caller with its own text, and `LogApiCall` already records it.\n */\n private logImplementationFailure(entryPoint: string, error: Error): void {\n if (this.boundary.encode(error).kind !== 'implementation') return;\n log.error(\n `MCP ${entryPoint} failed with an implementation error requestId=${McpCorrelation.requestId()}`,\n error,\n );\n }\n\n /** Everything a tool call does. No catch in here: failures propagate to handleCallTool. */\n private async callTool(\n tool: RegisteredMcpTool,\n request: CallToolRequest,\n authentication: McpPostAuthentication,\n sdkContext: ServerContext,\n ): Promise<CallToolResult> {\n const credential = authentication.credential;\n const invocation = new McpInvocationContext(\n sdkContext.mcpReq.id,\n tool.name,\n credential.subject,\n credential.principalRoles,\n AbortSignal.any([sdkContext.mcpReq.signal, authentication.disconnectSignal]),\n this.progressReporter(sdkContext),\n );\n const args = (request.params.arguments ?? {}) as DtoValue;\n const value = await this.dispatcher.call(\n tool,\n args,\n credential,\n invocation,\n this.config.endpointJwtAuthority,\n async () => (await this.mintEndpointJwt(tool, authentication)).token,\n );\n const outputFailure = this.outputSchemas.validate(tool.outputSchema, value);\n if (outputFailure) {\n throw new ApiImplementationError(\n `MCP output schema violation for ${tool.apiClass.name}.${tool.methodName}: ${outputFailure.message}`,\n );\n }\n const structured = this.record(value);\n return {\n content: [{ type: 'text', text: JSON.stringify(structured) }],\n structuredContent: structured,\n };\n }\n\n private async mintEndpointJwt(\n tool: RegisteredMcpTool,\n authentication: McpPostAuthentication,\n ): Promise<MintedJwt> {\n const descriptor = new McpEndpointDescriptor(\n tool.name,\n tool.apiClass.name,\n tool.methodName,\n );\n const minted = await this.config.endpointJwtAuthority.mint(\n this.config.endpointMintRequest(authentication.credential, descriptor),\n );\n const now = Math.floor(Date.now() / 1000);\n if (minted.token === authentication.accessToken) {\n throw new ApiImplementationError(\n `MCP access-token passthrough is forbidden (endpoint JWT for ${tool.name}).`,\n );\n }\n if (\n minted.expiresAtEpochSeconds <= now ||\n minted.expiresAtEpochSeconds - now > this.config.maxEndpointJwtLifetimeSeconds\n ) {\n throw new ApiImplementationError(\n `MCP endpoint JWT lifetime is invalid for ${tool.name}.`,\n );\n }\n return minted;\n }\n\n private validateCredential(credential: VerifiedMcpCredential): void {\n const now = Math.floor(Date.now() / 1000);\n const reject = (reason: string): never => {\n throw new ApiUnauthorizedError(`MCP access token rejected: ${reason}`);\n };\n if (credential.subject.trim() === '') reject('no subject');\n const stamps = [\n credential.issuedAtEpochSeconds,\n credential.expiresAtEpochSeconds,\n credential.accountValidatedAtEpochSeconds,\n ];\n if (!stamps.every(Number.isFinite)) reject('security timestamps must be finite');\n if (credential.resource !== this.config.resource) reject('resource mismatch');\n if (!this.config.authorizationServers.includes(credential.issuer)) {\n reject('issuer is not trusted');\n }\n if (credential.issuedAtEpochSeconds > now || credential.expiresAtEpochSeconds <= now) {\n reject('outside its valid time window');\n }\n const lifetime = credential.expiresAtEpochSeconds - credential.issuedAtEpochSeconds;\n if (lifetime > MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS) reject('lifetime exceeds 30 days');\n for (const scope of this.config.requiredScopes) {\n if (!credential.scopes.includes(scope)) reject(`missing required scope '${scope}'`);\n }\n const validatedAge = now - credential.accountValidatedAtEpochSeconds;\n if (\n credential.accountValidatedAtEpochSeconds > now ||\n validatedAge > this.config.maxAccountValidationAgeSeconds\n ) {\n reject('account authorization state is not fresh enough for dispatch');\n }\n }\n\n private authInfo(authentication: McpPostAuthentication): AuthInfo {\n const credential = authentication.credential;\n return {\n token: authentication.accessToken,\n clientId: credential.subject,\n scopes: [...credential.scopes],\n expiresAt: credential.expiresAtEpochSeconds,\n resource: new URL(credential.resource),\n extra: { webpiecesAuthentication: authentication },\n };\n }\n\n private progressReporter(context: ServerContext): McpProgressReporter | undefined {\n const token = context.mcpReq._meta?.progressToken;\n if (token === undefined) return undefined;\n return async (progress: number, total?: number, message?: string): Promise<void> => {\n await context.mcpReq.notify({\n method: 'notifications/progress',\n params: this.progressParams(token, progress, total, message),\n });\n };\n }\n\n private progressParams(\n progressToken: ProgressToken,\n progress: number,\n total?: number,\n message?: string,\n ): Record<string, DtoValue> {\n const params: Record<string, DtoValue> = { progressToken, progress };\n if (total !== undefined) params['total'] = total;\n if (message !== undefined) params['message'] = message;\n return params;\n }\n\n /** What the raw POST body tells us before the SDK has parsed anything: the id, and the tool. */\n private correlationOf(req: Request): McpCorrelation {\n const body = this.bodyObject(req.body);\n const id = body?.['id'];\n const params = this.bodyObject(body?.['params']);\n const name = params?.['name'];\n return new McpCorrelation(\n typeof id === 'string' || typeof id === 'number' ? id : null,\n typeof name === 'string' ? name : undefined,\n );\n }\n\n private challenge(): string {\n return `Bearer resource_metadata=\"${this.config.resourceMetadataUrl}\"`;\n }\n\n private bodyObject(value: DtoValue | undefined): Record<string, DtoValue> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n return value as Record<string, DtoValue>;\n }\n\n private hasProgressToken(body: DtoValue): boolean {\n const params = this.bodyObject(this.bodyObject(body)?.['params']);\n return this.bodyObject(params?.['_meta'])?.['progressToken'] !== undefined;\n }\n\n private toHttpRequest(req: Request): HttpRequest {\n const headers = new Map<string, string[]>();\n for (const [name, value] of Object.entries(req.headers)) {\n if (typeof value === 'string') headers.set(name, [value]);\n else if (Array.isArray(value)) headers.set(name, value);\n }\n return new HttpRequest(req.method, req.originalUrl || req.path, headers);\n }\n\n private calculateRegistryRevision(registry: McpToolRegistry): string {\n const surface = registry.tools.map((tool: RegisteredMcpTool) => [\n tool.name,\n tool.description,\n tool.inputSchema,\n tool.outputSchema,\n tool.annotations,\n ]);\n return createHash('sha256').update(JSON.stringify(surface)).digest('hex').slice(0, 12);\n }\n\n private requireRegistry(): McpToolRegistry {\n if (!this.registry) throw new Error('Call WpMcpServer.bind(...) before serving requests.');\n return this.registry;\n }\n\n private record(value: DtoValue): Record<string, DtoValue> {\n const jsonValue = JSON.stringify(value);\n if (jsonValue === undefined) {\n throw new ApiImplementationError('MCP structured content is not JSON serializable.');\n }\n const parsed = JSON.parse(jsonValue) as DtoValue;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { value: parsed };\n }\n return parsed as Record<string, DtoValue>;\n }\n}\n"]}
1
+ {"version":3,"file":"WpMcpServer.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/WpMcpServer.ts"],"names":[],"mappings":";;;AAAA,mDAAqD;AACrD,6CAAyC;AACzC,yDAesC;AACtC,qDAAkF;AAClF,qCAAyE;AACzE,oDAa8B;AAC9B,0DAKiC;AACjC,wDAA+D;AAC/D,0DAAqE;AACrE,uCAKmB;AACnB,yDAAsD;AAEtD,iEAAmF;AACnF,uDAA2F;AAC3F,iEAAwD;AACxD,iEAA8D;AAE9D,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;AAIhD;;;GAGG;AACH,MAAM,eAAe;IAEW;IAD5B,SAAS,GAAG,KAAK,CAAC;IAClB,YAA4B,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;CAC/C;AAED,MAAM,cAAc;IACY;IAA5B,YAA4B,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;CAC/C;AAED,yFAAyF;AACzF,MAAM,uBAAuB;IAChB,KAAK,GAAG,oBAAoB,CAAC;CACzC;AAED,2FAA2F;AAC3F,MAAM,qBAAqB;IAEH;IACA;IACA;IACA;IAJpB,YACoB,WAAmB,EACnB,UAAiC,EACjC,gBAA6B,EAC7B,KAAyB;QAHzB,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H,OAAO,IAAA,wBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC3F,CAAC;IAEO,eAAe;QACnB,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QAC3F,OAAO,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAEO,MAAM,CAAC,KAAe;QAC1B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC1B,MAAM,IAAI,kCAAsB,CAAC,kDAAkD,CAAC,CAAC;QACzF,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAa,CAAC;QACjD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACzE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAC7B,CAAC;QACD,OAAO,MAAkC,CAAC;IAC9C,CAAC;CACJ;AAhhBD,kCAghBC","sourcesContent":["import { McpToolDeniedError } from './McpToolPolicy';\nimport { createHash } from 'node:crypto';\nimport {\n AuthInfo,\n CallToolRequest,\n CallToolResult,\n createMcpHandler,\n ListToolsResult,\n McpHttpHandler,\n McpRequestContext,\n McpServer,\n ProgressToken,\n ProtocolError,\n ServerContext,\n ServerOptions,\n Tool,\n Implementation,\n} from '@modelcontextprotocol/server';\nimport { NodeMcpRequestHandler, toNodeHandler } from '@modelcontextprotocol/node';\nimport { Express, json, NextFunction, Request, Response } from 'express';\nimport {\n ApiBadRequestError,\n ApiErrorBoundary,\n ApiForbiddenError,\n ApiImplementationError,\n ApiJsonSchemaValidator,\n ApiMethodInfo,\n ApiUnauthorizedError,\n DtoValue,\n LogApiCallImpl,\n LogManager,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport {\n HttpRequest,\n RequestContext,\n RequestContextApiCallContext,\n RequestContextHeaders,\n} from '@webpieces/core-context';\nimport { ExpressResponseWriter } from '@webpieces/http-server';\nimport { AuthenticatedCallerContext } from '@webpieces/http-routing';\nimport {\n MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS,\n McpProtectedResourceMetadata,\n VerifiedMcpCredential,\n WpMcpServerConfig,\n} from './McpAuth';\nimport { McpApiDispatcher } from './McpApiDispatcher';\nimport { McpBindOptions } from './McpBindOptions';\nimport { McpInvocationContext, McpProgressReporter } from './McpInvocationContext';\nimport { AuthorizedMcpTools, McpToolRegistry, RegisteredMcpTool } from './McpToolRegistry';\nimport { McpCorrelation } from './McpToolCallRendering';\nimport { WpMcpErrorTranslator } from './WpMcpErrorTranslator';\n\nconst log = LogManager.getLogger('WpMcpServer');\n\ntype AuthenticatedExpressRequest = Request & { auth?: AuthInfo };\n\n/**\n * The request DTO the edge `LogApiCall` lines report. These boundaries run BEFORE (or outside) any\n * API dispatch, so there is no contract DTO to log; the step name is the fact worth having.\n */\nclass McpSdkOperation {\n toolStage = false;\n constructor(public readonly name: string) {}\n}\n\nclass McpEdgeRequest {\n constructor(public readonly step: string) {}\n}\n\n/** Body of the 405 answered for every non-POST method at the bound MCP endpoint path. */\nclass McpMethodNotAllowedBody {\n readonly error = 'method_not_allowed';\n}\n\n/** Facts established once per POST at the bind boundary and handed to the SDK handlers. */\nclass McpPostAuthentication {\n constructor(\n public readonly accessToken: string,\n public readonly credential: VerifiedMcpCredential,\n public readonly disconnectSignal: AbortSignal,\n public readonly tools: AuthorizedMcpTools,\n ) {}\n}\n\n/**\n * The official SDK server with Webpieces-owned tools/list and tools/call handlers. It answers\n * `toolInputSchemaJson` from the request-authorized view so the SDK's pre-dispatch SEP-2243\n * `Mcp-Param-*` header validation still runs without registering SDK-side tool callbacks.\n */\nclass WpSdkMcpServer extends McpServer {\n constructor(\n info: Implementation,\n options: ServerOptions,\n private readonly registry: AuthorizedMcpTools,\n ) {\n super(info, options);\n }\n\n // webpieces-disable no-any-unknown -- signature is fixed by the SDK's JSON Schema record type\n override toolInputSchemaJson(name: string): Record<string, unknown> | undefined {\n return this.registry.find(name)?.inputSchema as Record<string, DtoValue> | undefined;\n }\n}\n\n/**\n * MCP adapter around the official SDK's request-scoped HTTP handler, serving BOTH wire eras from\n * one tool registry: modern (2026-07-28, per-request `_meta` envelope) and legacy (the 2025-11-25\n * family, negotiated by `initialize`). The SDK routes each request to the leg its shape selects and\n * negotiates the revision; only a revision no era knows is refused. Pinning one era instead made\n * every shipping client unreachable (issue #969), and the MCP lifecycle spec is explicit that a\n * server answers with a revision it supports rather than erroring.\n *\n * Error boundaries: HTTP ingress owns pre-SDK replies; one shared SDK callback wrapper owns\n * protocol/list/name-resolution errors and authorized tool-result errors. The SDK writes callback\n * replies, so it cannot safely delegate those failures back to HTTP ingress.\n * `subscriptions/listen` is served entirely by the SDK's listen router, so Webpieces has no handler\n * (and no catch) there. The external bearer is verified exactly once per POST, at the HTTP\n * boundary, before the SDK is involved.\n *\n * Before tools/list and tools/call hand an IMPLEMENTATION-kind failure to the translator, they\n * `log.error` it with its stack and the requestId ({@link logImplementationFailure}, #1055). The\n * translator reduces such a failure to \"Internal Error\" for the caller, so that line is the only place\n * its cause exists.\n */\nexport class WpMcpServer<TGrant> {\n private readonly callerContext = new AuthenticatedCallerContext();\n private readonly dispatcher = new McpApiDispatcher();\n /** Classifies a failure exactly as the translator will render it, so the two cannot disagree. */\n private readonly boundary = new ApiErrorBoundary();\n private readonly outputSchemas = new ApiJsonSchemaValidator();\n /**\n * These edges have NO filter chain above them — `LogApiFilter` never sees a rejected bearer, a\n * bad `Origin`, a body express could not parse, or a `tools/list` the SDK renders itself.\n * Wrapping each in `LogApiCall` is this repo's one line on logging, and it is why\n * `ApiErrorBoundary` no longer writes a second, barer line of its own.\n */\n private readonly logApiCall = new LogApiCallImpl(new RequestContextApiCallContext());\n private readonly responseWriter = new ExpressResponseWriter();\n /** tools/call reads `McpRegistry`; every other reply stays framework-owned. See McpErrorTranslator. */\n private readonly translator: WpMcpErrorTranslator;\n private registry?: McpToolRegistry;\n private handler?: McpHttpHandler;\n private streamingHandler?: McpHttpHandler;\n private nodeHandler?: NodeMcpRequestHandler;\n private streamingNodeHandler?: NodeMcpRequestHandler;\n private revision?: string;\n\n constructor(private readonly config: WpMcpServerConfig<TGrant>) {\n this.translator = new WpMcpErrorTranslator((): string => this.challenge());\n }\n\n /**\n * Mounts this MCP endpoint on `app`: POST at `options.endpointPath`, plus a 405 (`Allow: POST`)\n * for every other method there.\n *\n * SINGLE CANONICAL ORIGIN: one server serves exactly one protected resource, so this may be\n * called only once and `WpMcpServerConfig.setResource(...)`'s path must equal `endpointPath`.\n * That resource URI is fixed for the lifetime of the process and is never derived from the\n * request `Host` — a host-derived audience would make the boundary's own audience check compare\n * two caller-controlled values, which is the confused deputy this check exists to prevent.\n * Serving a second hostname is a second deployment, not a second audience.\n *\n * The OAuth/discovery half stays app-owned: publish `protectedResourceMetadata()` at\n * `WpMcpServerConfig.resourceMetadataUrl`, which is where the 401 challenge sends clients.\n */\n bind(app: Express, options: McpBindOptions): void {\n if (this.handler) {\n throw new Error(\n 'WpMcpServer.bind(...) may be called only once; an MCP resource has exactly one ' +\n 'canonical URI, fixed for the lifetime of the process.',\n );\n }\n // Fail at boot naming the forgotten setter, never on the first request with a 401 the client\n // answers by re-authenticating (see WpMcpServerConfig).\n this.config.validate();\n const resourcePath = new URL(this.config.resource).pathname;\n if (resourcePath !== options.endpointPath) {\n throw new Error(\n `MCP resource path '${resourcePath}' must equal endpointPath ` +\n `'${options.endpointPath}'; the canonical resource URI ` +\n `'${this.config.resource}' and the bound route are the same endpoint.`,\n );\n }\n this.registry = new McpToolRegistry(options.bindings, options.toolCatalogs, this.config.authorizationService);\n this.revision = this.calculateRegistryRevision(this.registry);\n this.handler = this.createHandler(options, 'auto');\n this.streamingHandler = this.createHandler(options, 'sse');\n this.nodeHandler = toNodeHandler(this.handler, {\n onerror: (error: Error) => log.error('MCP Node transport failed', error),\n });\n this.streamingNodeHandler = toNodeHandler(this.streamingHandler, {\n onerror: (error: Error) => log.error('MCP streaming Node transport failed', error),\n });\n app.post(\n options.endpointPath,\n json(),\n async (req: Request, res: Response): Promise<void> =>\n this.handleHttp(req, res, options),\n // Express routes body-parser failures (bad JSON, body too large) to an error handler.\n (bodyError: Error, req: Request, res: Response, _next: NextFunction): void => {\n void this.handleBodyFailure(bodyError, req, res);\n },\n );\n // Registered AFTER the POST route so POST still wins. NEITHER era served here has a session\n // GET: 2026-07-28 has none at all (`subscriptions/listen` is a POST method), and the legacy\n // leg is the SDK's STATELESS fallback, which answers the 2025 session GET/DELETE with the\n // same 405. So every other method is a method error — and a discovery probe gets that\n // instead of Express' bare 404.\n app.all(options.endpointPath, (_req: Request, res: Response): void => {\n res.setHeader('Allow', 'POST');\n res.status(405).json(new McpMethodNotAllowedBody());\n });\n }\n\n protectedResourceMetadata(): McpProtectedResourceMetadata {\n return this.config.protectedResourceMetadata();\n }\n\n /** Gracefully closes active listen/request streams; clients must reconnect and refresh lists. */\n async close(): Promise<void> {\n await Promise.all([this.handler?.close(), this.streamingHandler?.close()]);\n }\n\n /** Level-triggered invalidation; the authoritative list is always fetched again by clients. */\n toolsChanged(): void {\n this.handler?.notify.toolsChanged();\n }\n\n get registryRevision(): string | undefined {\n return this.revision;\n }\n\n private createHandler(options: McpBindOptions, responseMode: 'auto' | 'sse'): McpHttpHandler {\n return createMcpHandler(\n (context: McpRequestContext) => this.buildSdkServer(context, options),\n {\n // Both eras, one factory: `stateless` serves 2025-era traffic through a fresh\n // instance of the SAME McpServerFactory, so the two eras can never drift apart.\n legacy: 'stateless',\n responseMode,\n bus: options.deployment.bus,\n maxSubscriptions: options.maxSubscriptions,\n keepAliveMs: options.keepAliveMs,\n onerror: (error: Error) => log.warn('MCP protocol request rejected', error),\n },\n );\n }\n\n /** Each HTTP entry uses the same full-request scope and ingress translation seam. */\n private async handleHttp(req: Request, res: Response, options: McpBindOptions): Promise<void> {\n res.setHeader('X-Accel-Buffering', 'no');\n await this.ingress(req, res, 'serve', () => this.serveExpress(req, res, options));\n }\n\n private async handleBodyFailure(cause: Error, req: Request, res: Response): Promise<void> {\n await this.ingress(req, res, 'body', () => this.rejectBody(cause));\n }\n\n private async ingress(\n req: Request,\n res: Response,\n step: string,\n work: () => Promise<void>,\n ): Promise<void> {\n await RequestContext.run(async () => {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- HTTP response-owning ingress boundary, including request publication and correlation failures\n try {\n new RequestContextHeaders().fillFromRequest(this.toHttpRequest(req));\n McpCorrelation.stamp(this.correlationOf(req));\n await this.logEdge(step, work);\n } catch (err: unknown) {\n const error = toError(err);\n this.writeBoundaryError(res, error);\n }\n });\n }\n\n /** A body express could not parse is a caller input error, reported through the same edge. */\n private async rejectBody(cause: Error): Promise<never> {\n throw new ApiBadRequestError(\n `MCP request body rejected: ${cause.message}`,\n undefined,\n undefined,\n cause,\n );\n }\n\n /**\n * The pre-SDK boundary owns the socket, so it produces a VALUE and writes it through the SAME\n * express writer `ExpressWrapper` uses. A failure after headers were sent can only end the\n * stream.\n */\n private writeBoundaryError(res: Response, error: Error): void {\n if (res.headersSent) {\n res.end();\n return;\n }\n this.responseWriter.write(res, this.translator.toBearerBoundaryResponse(error));\n }\n\n /** Run one un-filtered edge step under `LogApiCall`, so its failure gets exactly one log line. */\n private async logEdge<R>(step: string, work: () => Promise<R>): Promise<R> {\n return this.logApiCall.execute(\n new ApiMethodInfo('server', 'McpEndpoint', step),\n new McpEdgeRequest(step),\n work,\n );\n }\n\n private async serveExpress(\n req: Request,\n res: Response,\n options: McpBindOptions,\n ): Promise<void> {\n const origin = req.header('origin');\n if (origin && !options.allowedOrigins.includes(origin)) {\n throw new ApiForbiddenError(`MCP request Origin '${origin}' is not allowed.`);\n }\n const authentication = await this.authenticate(req);\n const request = req as AuthenticatedExpressRequest;\n request.auth = this.authInfo(authentication);\n const serve = this.hasProgressToken(req.body)\n ? this.streamingNodeHandler\n : this.nodeHandler;\n if (!serve) throw new ApiImplementationError('MCP Node handlers are not initialized.');\n await serve(request, res, req.body);\n }\n\n /** Verifies the external bearer once for this POST. Handlers never re-verify it. */\n private async authenticate(req: Request): Promise<McpPostAuthentication> {\n const match = req.header('authorization')?.match(/^Bearer ([^\\s]+)$/i);\n const token = match?.[1];\n if (!token) throw new ApiUnauthorizedError('MCP request has no bearer access token.');\n const credential = await this.config.accessTokenAuthority.verifyAccessToken(\n token,\n this.config.resource,\n );\n this.validateCredential(credential);\n this.callerContext.publish(credential.caller);\n RequestContext.putTrusted(WebpiecesCoreHeaders.SURFACE, 'llm');\n this.callerContext.reconcileWireTrust(false);\n const tools = await AuthorizedMcpTools.create(\n this.requireRegistry(),\n this.config.authorizationService,\n );\n return new McpPostAuthentication(token, credential, this.disconnectSignal(req), tools);\n }\n\n private disconnectSignal(req: Request): AbortSignal {\n const disconnected = new AbortController();\n const res = req.res;\n const cancel = (): void => disconnected.abort();\n req.once('aborted', cancel);\n req.socket.once('close', cancel);\n res?.once('close', cancel);\n res?.once('finish', (): void => {\n req.off('aborted', cancel);\n req.socket.off('close', cancel);\n res.off('close', cancel);\n });\n return disconnected.signal;\n }\n\n private buildSdkServer(context: McpRequestContext, options: McpBindOptions): McpServer {\n // The era is the SDK's to decide and BOTH are served; what is not negotiable is that the\n // request came through `bind`'s HTTP boundary, which is where the external bearer is\n // verified. A factory call without it is a wiring mistake, never a client's doing.\n const authentication = context.authInfo?.extra?.['webpiecesAuthentication'];\n if (!(authentication instanceof McpPostAuthentication)) {\n throw new ApiImplementationError(\n 'WpMcpServer serves only MCP requests authenticated by its bind boundary.',\n );\n }\n const server = new WpSdkMcpServer(\n { name: this.config.name, version: `${this.config.version}+${this.revision}` },\n {\n capabilities: { tools: { listChanged: true } },\n cacheHints: {\n 'tools/list': { ttlMs: options.deployment.ttlMs, cacheScope: 'private' },\n 'server/discover': { ttlMs: options.deployment.ttlMs, cacheScope: 'private' },\n },\n },\n authentication.tools,\n );\n server.server.removeRequestHandler('tools/list');\n server.server.removeRequestHandler('tools/call');\n server.server.setRequestHandler(\n 'tools/list',\n async (_request: object): Promise<ListToolsResult> =>\n this.sdkBoundary(new McpSdkOperation('tools/list'), () =>\n this.logEdge('tools/list', async () => this.listTools(authentication.tools)),\n ) as Promise<ListToolsResult>,\n );\n server.server.setRequestHandler(\n 'tools/call',\n async (request: CallToolRequest, sdkContext: ServerContext): Promise<CallToolResult> =>\n this.handleCallTool(server, request, authentication, sdkContext),\n );\n return server;\n }\n\n /** ONE SDK callback catch implementation; the SDK intercepts foreign throws itself. */\n private async sdkBoundary<R>(\n operation: McpSdkOperation,\n work: () => Promise<R>,\n ): Promise<R | CallToolResult> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- shared SDK response boundary, preserving protocol versus tool envelopes\n try {\n return await work();\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof McpToolDeniedError)\n throw this.translator.unknownTool(error.toolName);\n if (!operation.toolStage && error instanceof ProtocolError) throw error;\n this.logImplementationFailure(operation.name, error);\n if (operation.toolStage) return this.translator.toToolCallResult(error);\n this.translator.toListError(error);\n }\n }\n\n private listTools(view: AuthorizedMcpTools): ListToolsResult {\n const tools: Tool[] = view.tools.map((tool) => this.toolDefinition(tool));\n return { tools };\n }\n\n private toolDefinition(tool: RegisteredMcpTool): Tool {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema as Tool['inputSchema'],\n outputSchema: tool.outputSchema as Tool['outputSchema'],\n annotations: tool.annotations,\n _meta: { webpiecesRegistryRevision: this.revision },\n };\n }\n\n /**\n * SDK tool callback: an unknown or hidden tool is a JSON-RPC -32602; every failure after the tool is found\n * is an `isError: true` result, identically for local and remote bindings.\n */\n private async handleCallTool(\n server: WpSdkMcpServer,\n request: CallToolRequest,\n authentication: McpPostAuthentication,\n sdkContext: ServerContext,\n ): Promise<CallToolResult> {\n const name = request.params.name;\n const operation = new McpSdkOperation(`tools/call ${name}`);\n return this.sdkBoundary(operation, async () => {\n McpCorrelation.stamp(new McpCorrelation(sdkContext.mcpReq.id, name));\n const tool = authentication.tools.find(name);\n if (!tool) throw this.translator.unknownTool(name);\n McpCorrelation.stamp(new McpCorrelation(sdkContext.mcpReq.id, name, tool.operation));\n operation.toolStage = true;\n const result = await this.callTool(tool, request, authentication, sdkContext);\n result._meta = this.translator.resultMeta(McpCorrelation.requestId());\n return server.server.projectCallToolResult(\n result,\n tool.outputSchema as Record<string, DtoValue>,\n );\n }) as Promise<CallToolResult>;\n }\n\n /**\n * ONE `log.error` line, with the stack and the requestId, for a failure that is THIS server's bug\n * — the `implementation` kind, which the translator reduces to \"Internal Error\" and a requestId\n * for the caller (#1055).\n *\n * `LogApiCall` does not cover this. An MCP output-schema violation is raised AFTER the controller\n * returned, so the only `LogApiCall` line for that call reads `resp-SUCCESS`; before this line\n * existed, the requestId support was handed led to a log with no error in it. Where a\n * `[API-*-resp-FAIL]` line does exist it carries the error's message, not its stack. So this line\n * is not the bare duplicate `ApiErrorBoundary` stopped writing: it is the one that says WHERE.\n *\n * Every other kind (bad-request, end-user, dependency, ...) is a caller's or a downstream's\n * failure, published to the caller with its own text, and `LogApiCall` already records it.\n */\n private logImplementationFailure(entryPoint: string, error: Error): void {\n if (this.boundary.encode(error).kind !== 'implementation') return;\n log.error(\n `MCP ${entryPoint} failed with an implementation error requestId=${McpCorrelation.requestId()}`,\n error,\n );\n }\n\n /** Everything a tool call does. No catch in here: failures propagate to handleCallTool. */\n private async callTool(\n tool: RegisteredMcpTool,\n request: CallToolRequest,\n authentication: McpPostAuthentication,\n sdkContext: ServerContext,\n ): Promise<CallToolResult> {\n const credential = authentication.credential;\n const invocation = new McpInvocationContext(\n sdkContext.mcpReq.id,\n tool.name,\n credential.subject,\n credential.principalRoles,\n AbortSignal.any([sdkContext.mcpReq.signal, authentication.disconnectSignal]),\n this.progressReporter(sdkContext),\n );\n const args = (request.params.arguments ?? {}) as DtoValue;\n const value = await this.dispatcher.call(\n tool,\n args,\n credential,\n invocation,\n this.config.authorizationService,\n );\n const outputFailure = this.outputSchemas.validate(tool.outputSchema, value);\n if (outputFailure) {\n throw new ApiImplementationError(\n `MCP output schema violation for ${tool.apiClass.name}.${tool.methodName}: ${outputFailure.message}`,\n );\n }\n const structured = this.record(value);\n return {\n content: [{ type: 'text', text: JSON.stringify(structured) }],\n structuredContent: structured,\n };\n }\n\n private validateCredential(credential: VerifiedMcpCredential): void {\n const now = Math.floor(Date.now() / 1000);\n const reject = (reason: string): never => {\n throw new ApiUnauthorizedError(`MCP access token rejected: ${reason}`);\n };\n if (credential.subject.trim() === '') reject('no subject');\n const stamps = [\n credential.issuedAtEpochSeconds,\n credential.expiresAtEpochSeconds,\n credential.accountValidatedAtEpochSeconds,\n ];\n if (!stamps.every(Number.isFinite)) reject('security timestamps must be finite');\n if (credential.resource !== this.config.resource) reject('resource mismatch');\n if (!this.config.authorizationServers.includes(credential.issuer)) {\n reject('issuer is not trusted');\n }\n if (credential.issuedAtEpochSeconds > now || credential.expiresAtEpochSeconds <= now) {\n reject('outside its valid time window');\n }\n const lifetime = credential.expiresAtEpochSeconds - credential.issuedAtEpochSeconds;\n if (lifetime > MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS) reject('lifetime exceeds 30 days');\n for (const scope of this.config.requiredScopes) {\n if (!credential.scopes.includes(scope)) reject(`missing required scope '${scope}'`);\n }\n const validatedAge = now - credential.accountValidatedAtEpochSeconds;\n if (\n credential.accountValidatedAtEpochSeconds > now ||\n validatedAge > this.config.maxAccountValidationAgeSeconds\n ) {\n reject('account authorization state is not fresh enough for dispatch');\n }\n }\n\n private authInfo(authentication: McpPostAuthentication): AuthInfo {\n const credential = authentication.credential;\n return {\n token: authentication.accessToken,\n clientId: credential.subject,\n scopes: [...credential.scopes],\n expiresAt: credential.expiresAtEpochSeconds,\n resource: new URL(credential.resource),\n extra: { webpiecesAuthentication: authentication },\n };\n }\n\n private progressReporter(context: ServerContext): McpProgressReporter | undefined {\n const token = context.mcpReq._meta?.progressToken;\n if (token === undefined) return undefined;\n return async (progress: number, total?: number, message?: string): Promise<void> => {\n await context.mcpReq.notify({\n method: 'notifications/progress',\n params: this.progressParams(token, progress, total, message),\n });\n };\n }\n\n private progressParams(\n progressToken: ProgressToken,\n progress: number,\n total?: number,\n message?: string,\n ): Record<string, DtoValue> {\n const params: Record<string, DtoValue> = { progressToken, progress };\n if (total !== undefined) params['total'] = total;\n if (message !== undefined) params['message'] = message;\n return params;\n }\n\n /** What the raw POST body tells us before the SDK has parsed anything: the id, and the tool. */\n private correlationOf(req: Request): McpCorrelation {\n const body = this.bodyObject(req.body);\n const id = body?.['id'];\n const params = this.bodyObject(body?.['params']);\n const name = params?.['name'];\n return new McpCorrelation(\n typeof id === 'string' || typeof id === 'number' ? id : null,\n typeof name === 'string' ? name : undefined,\n );\n }\n\n private challenge(): string {\n return `Bearer resource_metadata=\"${this.config.resourceMetadataUrl}\"`;\n }\n\n private bodyObject(value: DtoValue | undefined): Record<string, DtoValue> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n return value as Record<string, DtoValue>;\n }\n\n private hasProgressToken(body: DtoValue): boolean {\n const params = this.bodyObject(this.bodyObject(body)?.['params']);\n return this.bodyObject(params?.['_meta'])?.['progressToken'] !== undefined;\n }\n\n private toHttpRequest(req: Request): HttpRequest {\n const headers = new Map<string, string[]>();\n for (const [name, value] of Object.entries(req.headers)) {\n if (typeof value === 'string') headers.set(name, [value]);\n else if (Array.isArray(value)) headers.set(name, value);\n }\n return new HttpRequest(req.method, req.originalUrl || req.path, headers);\n }\n\n private calculateRegistryRevision(registry: McpToolRegistry): string {\n const surface = registry.tools.map((tool: RegisteredMcpTool) => [\n tool.name,\n tool.description,\n tool.inputSchema,\n tool.outputSchema,\n tool.annotations,\n ]);\n return createHash('sha256').update(JSON.stringify(surface)).digest('hex').slice(0, 12);\n }\n\n private requireRegistry(): McpToolRegistry {\n if (!this.registry) throw new Error('Call WpMcpServer.bind(...) before serving requests.');\n return this.registry;\n }\n\n private record(value: DtoValue): Record<string, DtoValue> {\n const jsonValue = JSON.stringify(value);\n if (jsonValue === undefined) {\n throw new ApiImplementationError('MCP structured content is not JSON serializable.');\n }\n const parsed = JSON.parse(jsonValue) as DtoValue;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { value: parsed };\n }\n return parsed as Record<string, DtoValue>;\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { AuthenticatedMachineIdentity } from '@webpieces/http-routing';
1
2
  import 'reflect-metadata';
2
3
  import { ContextKey, ErrorTranslator, Filter, HttpResponseDto, LogLevel, Service } from '@webpieces/core-util';
3
4
  import { MethodMeta, OidcHook, WpResponse } from '@webpieces/http-routing';
@@ -95,7 +96,7 @@ export declare class RecordingOidcMinter {
95
96
  export declare class RecordingOidcVerifier extends OidcHook {
96
97
  readonly tokens: string[];
97
98
  readonly callerLists: string[][];
98
- verifyOidc(token: string, callers: string[]): Promise<void>;
99
+ verifyOidc(token: string, callers: string[]): Promise<AuthenticatedMachineIdentity>;
99
100
  }
100
101
  export declare class BoundaryProbeFilter extends Filter<MethodMeta, WpResponse<unknown>> {
101
102
  calls: number;
@@ -3,15 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RelayWebpiecesPeerErrors = exports.BoundaryProbeFilter = exports.RecordingOidcVerifier = exports.RecordingOidcMinter = exports.RemoteThrowController = exports.LocalThrowController = exports.RemoteMcpController = exports.THROW_CASES = exports.ThrowCase = exports.RemoteThrowApi = exports.LocalThrowApi = exports.OidcFailRemoteApi = exports.GarbageRemoteApi = exports.RefusedRemoteApi = exports.MissingRemoteMcpApi = exports.RemoteMcpApi = exports.GATEWAY_CATALOGS = exports.REMOTE_MCP_CATALOG = exports.RemoteResponse = exports.RemoteRequest = exports.GATEWAY_PATH = exports.LOCAL_ENDPOINT_JWT = exports.EXTERNAL_MCP_BEARER = exports.OIDC_TOKEN = exports.GARBAGE_SERVICE = exports.REFUSED_SERVICE = exports.REMOTE_SERVICE = exports.REMOTE_ROLES = exports.REMOTE_USER = void 0;
4
4
  exports.raiseFor = raiseFor;
5
5
  const tslib_1 = require("tslib");
6
+ const http_routing_1 = require("@webpieces/http-routing");
7
+ const core_util_1 = require("@webpieces/core-util");
6
8
  require("reflect-metadata");
7
9
  const inversify_1 = require("inversify");
8
- const core_util_1 = require("@webpieces/core-util");
10
+ const core_util_2 = require("@webpieces/core-util");
9
11
  const core_context_1 = require("@webpieces/core-context");
10
- const http_routing_1 = require("@webpieces/http-routing");
12
+ const http_routing_2 = require("@webpieces/http-routing");
11
13
  const McpToolCatalog_1 = require("../McpToolCatalog");
12
14
  /** Contracts, controllers and test doubles for McpRemoteBinding.integration.spec.ts. */
13
- exports.REMOTE_USER = core_util_1.ContextKey.trusted('mcpRemoteUser', 'verified by the MCP access-token authority before delegation', 'x-mcp-remote-user');
14
- exports.REMOTE_ROLES = core_util_1.ContextKey.trusted('mcpRemoteRoles', 'verified by the MCP access-token authority before delegation', 'x-mcp-remote-roles');
15
+ exports.REMOTE_USER = core_util_2.ContextKey.trusted('mcpRemoteUser', 'verified by the MCP access-token authority before delegation', 'x-mcp-remote-user');
16
+ exports.REMOTE_ROLES = core_util_2.ContextKey.trusted('mcpRemoteRoles', 'verified by the MCP access-token authority before delegation', 'x-mcp-remote-roles');
15
17
  exports.REMOTE_SERVICE = 'mcp-remote-integration';
16
18
  exports.REFUSED_SERVICE = 'mcp-remote-refused';
17
19
  exports.GARBAGE_SERVICE = 'mcp-remote-garbage';
@@ -51,12 +53,12 @@ exports.RemoteResponse = RemoteResponse;
51
53
  * TypeScript compiler API; the runtime's job is to BE HANDED a catalog.
52
54
  */
53
55
  function describedString(description) {
54
- const schema = new core_util_1.ApiJsonSchema('string');
56
+ const schema = new core_util_2.ApiJsonSchema('string');
55
57
  schema.description = description;
56
58
  return schema;
57
59
  }
58
60
  function searchTool(name, methodName, description) {
59
- return new core_util_1.McpToolDefinition(name, methodName, description, new core_util_1.WpMcpToolHints(true, false, true, false), new core_util_1.ObjectSchemaBuilder().required('query', describedString('Search text')).build(), new core_util_1.ObjectSchemaBuilder()
61
+ return new core_util_2.McpToolDefinition(name, methodName, description, new core_util_2.WpMcpToolHints(true, false, true, false), new core_util_2.ObjectSchemaBuilder().required('query', describedString('Search text')).build(), new core_util_2.ObjectSchemaBuilder()
60
62
  .required('user', describedString('Delegated user'))
61
63
  .required('roles', describedString('Delegated roles'))
62
64
  .required('result', describedString('Result'))
@@ -64,7 +66,7 @@ function searchTool(name, methodName, description) {
64
66
  }
65
67
  /** One contract's hand-built catalog, labelled as built in memory. */
66
68
  function contractCatalog(contractName, tool) {
67
- return new McpToolCatalog_1.McpToolCatalog(new core_util_1.McpToolCatalogFile(contractName, [tool]), '(built in memory by the spec)');
69
+ return new McpToolCatalog_1.McpToolCatalog(new core_util_2.McpToolCatalogFile(contractName, [tool]), '(built in memory by the spec)');
68
70
  }
69
71
  exports.REMOTE_MCP_CATALOG = contractCatalog('RemoteMcpApi', searchTool('remote_integration_search', 'search', 'Calls a remote Webpieces API.'));
70
72
  /** The catalogs of every contract the gateway binds — one per contract, exactly as a build writes them. */
@@ -84,17 +86,17 @@ let RemoteMcpApi = class RemoteMcpApi {
84
86
  };
85
87
  exports.RemoteMcpApi = RemoteMcpApi;
86
88
  tslib_1.__decorate([
87
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
88
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
89
- (0, core_util_1.Endpoint)(core_util_1.POST, '/search', core_util_1.READ, core_util_1.RPC),
90
- (0, core_util_1.WpMcpTool)('remote_integration_search'),
89
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
90
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
91
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/search', core_util_2.READ, core_util_2.RPC),
92
+ (0, core_util_2.WpMcpTool)('remote_integration_search'),
91
93
  tslib_1.__metadata("design:type", Function),
92
94
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
93
95
  tslib_1.__metadata("design:returntype", Promise)
94
96
  ], RemoteMcpApi.prototype, "search", null);
95
97
  exports.RemoteMcpApi = RemoteMcpApi = tslib_1.__decorate([
96
- (0, core_util_1.ApiPath)('/remote-mcp'),
97
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
98
+ (0, core_util_2.ApiPath)('/remote-mcp'),
99
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
98
100
  ], RemoteMcpApi);
99
101
  let MissingRemoteMcpApi = class MissingRemoteMcpApi {
100
102
  /** Intentionally absent route. */
@@ -104,17 +106,17 @@ let MissingRemoteMcpApi = class MissingRemoteMcpApi {
104
106
  };
105
107
  exports.MissingRemoteMcpApi = MissingRemoteMcpApi;
106
108
  tslib_1.__decorate([
107
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
108
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
109
- (0, core_util_1.Endpoint)(core_util_1.POST, '/search', core_util_1.READ, core_util_1.RPC),
110
- (0, core_util_1.WpMcpTool)('missing_remote_integration_search'),
109
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
110
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
111
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/search', core_util_2.READ, core_util_2.RPC),
112
+ (0, core_util_2.WpMcpTool)('missing_remote_integration_search'),
111
113
  tslib_1.__metadata("design:type", Function),
112
114
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
113
115
  tslib_1.__metadata("design:returntype", Promise)
114
116
  ], MissingRemoteMcpApi.prototype, "search", null);
115
117
  exports.MissingRemoteMcpApi = MissingRemoteMcpApi = tslib_1.__decorate([
116
- (0, core_util_1.ApiPath)('/missing-remote-mcp'),
117
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
118
+ (0, core_util_2.ApiPath)('/missing-remote-mcp'),
119
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
118
120
  ], MissingRemoteMcpApi);
119
121
  let RefusedRemoteApi = class RefusedRemoteApi {
120
122
  /** Nothing listens on this port. */
@@ -124,17 +126,17 @@ let RefusedRemoteApi = class RefusedRemoteApi {
124
126
  };
125
127
  exports.RefusedRemoteApi = RefusedRemoteApi;
126
128
  tslib_1.__decorate([
127
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
128
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
129
- (0, core_util_1.Endpoint)(core_util_1.POST, '/search', core_util_1.READ, core_util_1.RPC),
130
- (0, core_util_1.WpMcpTool)('refused_remote'),
129
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
130
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
131
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/search', core_util_2.READ, core_util_2.RPC),
132
+ (0, core_util_2.WpMcpTool)('refused_remote'),
131
133
  tslib_1.__metadata("design:type", Function),
132
134
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
133
135
  tslib_1.__metadata("design:returntype", Promise)
134
136
  ], RefusedRemoteApi.prototype, "search", null);
135
137
  exports.RefusedRemoteApi = RefusedRemoteApi = tslib_1.__decorate([
136
- (0, core_util_1.ApiPath)('/refused-remote-mcp'),
137
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
138
+ (0, core_util_2.ApiPath)('/refused-remote-mcp'),
139
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
138
140
  ], RefusedRemoteApi);
139
141
  let GarbageRemoteApi = class GarbageRemoteApi {
140
142
  /** Answers an undecodable body. */
@@ -144,17 +146,17 @@ let GarbageRemoteApi = class GarbageRemoteApi {
144
146
  };
145
147
  exports.GarbageRemoteApi = GarbageRemoteApi;
146
148
  tslib_1.__decorate([
147
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
148
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
149
- (0, core_util_1.Endpoint)(core_util_1.POST, '/search', core_util_1.READ, core_util_1.RPC),
150
- (0, core_util_1.WpMcpTool)('garbage_remote'),
149
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
150
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
151
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/search', core_util_2.READ, core_util_2.RPC),
152
+ (0, core_util_2.WpMcpTool)('garbage_remote'),
151
153
  tslib_1.__metadata("design:type", Function),
152
154
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
153
155
  tslib_1.__metadata("design:returntype", Promise)
154
156
  ], GarbageRemoteApi.prototype, "search", null);
155
157
  exports.GarbageRemoteApi = GarbageRemoteApi = tslib_1.__decorate([
156
- (0, core_util_1.ApiPath)('/garbage-remote-mcp'),
157
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
158
+ (0, core_util_2.ApiPath)('/garbage-remote-mcp'),
159
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
158
160
  ], GarbageRemoteApi);
159
161
  let OidcFailRemoteApi = class OidcFailRemoteApi {
160
162
  /** Its OIDC token cannot be minted. */
@@ -164,17 +166,17 @@ let OidcFailRemoteApi = class OidcFailRemoteApi {
164
166
  };
165
167
  exports.OidcFailRemoteApi = OidcFailRemoteApi;
166
168
  tslib_1.__decorate([
167
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
168
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
169
- (0, core_util_1.Endpoint)(core_util_1.POST, '/search', core_util_1.READ, core_util_1.RPC),
170
- (0, core_util_1.WpMcpTool)('oidc_fail_remote'),
169
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
170
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
171
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/search', core_util_2.READ, core_util_2.RPC),
172
+ (0, core_util_2.WpMcpTool)('oidc_fail_remote'),
171
173
  tslib_1.__metadata("design:type", Function),
172
174
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
173
175
  tslib_1.__metadata("design:returntype", Promise)
174
176
  ], OidcFailRemoteApi.prototype, "search", null);
175
177
  exports.OidcFailRemoteApi = OidcFailRemoteApi = tslib_1.__decorate([
176
- (0, core_util_1.ApiPath)('/oidc-fail-remote-mcp'),
177
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
178
+ (0, core_util_2.ApiPath)('/oidc-fail-remote-mcp'),
179
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
178
180
  ], OidcFailRemoteApi);
179
181
  let LocalThrowApi = class LocalThrowApi {
180
182
  /** Throws the requested failure in-process. */
@@ -184,17 +186,17 @@ let LocalThrowApi = class LocalThrowApi {
184
186
  };
185
187
  exports.LocalThrowApi = LocalThrowApi;
186
188
  tslib_1.__decorate([
187
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
188
- (0, core_util_1.WpAuthJwt)({ allRolesAllowed: true }),
189
- (0, core_util_1.Endpoint)(core_util_1.POST, '/throw', core_util_1.READ, core_util_1.RPC),
190
- (0, core_util_1.WpMcpTool)('local_throw'),
189
+ (0, core_util_1.WpAuth)([(0, core_util_1.jwt)()]),
190
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.ALL_USERS }),
191
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/throw', core_util_2.READ, core_util_2.RPC),
192
+ (0, core_util_2.WpMcpTool)('local_throw'),
191
193
  tslib_1.__metadata("design:type", Function),
192
194
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
193
195
  tslib_1.__metadata("design:returntype", Promise)
194
196
  ], LocalThrowApi.prototype, "fail", null);
195
197
  exports.LocalThrowApi = LocalThrowApi = tslib_1.__decorate([
196
- (0, core_util_1.ApiPath)('/local-throw'),
197
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
198
+ (0, core_util_2.ApiPath)('/local-throw'),
199
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
198
200
  ], LocalThrowApi);
199
201
  let RemoteThrowApi = class RemoteThrowApi {
200
202
  /** Throws the requested failure remotely. */
@@ -204,17 +206,17 @@ let RemoteThrowApi = class RemoteThrowApi {
204
206
  };
205
207
  exports.RemoteThrowApi = RemoteThrowApi;
206
208
  tslib_1.__decorate([
207
- (0, core_util_1.WpMcpAuthJwt)({ allRolesAllowed: true }),
208
- (0, core_util_1.WpAuthOidc)('mcp-gateway'),
209
- (0, core_util_1.Endpoint)(core_util_1.POST, '/throw', core_util_1.READ, core_util_1.RPC),
210
- (0, core_util_1.WpMcpTool)('remote_throw'),
209
+ (0, core_util_1.WpAuth)([(0, core_util_1.oidc)('mcp-gateway')]),
210
+ (0, core_util_1.WpAuthorization)({ authType: core_util_1.AuthorizationType.USERS_OR_SERVICES }),
211
+ (0, core_util_2.Endpoint)(core_util_2.POST, '/throw', core_util_2.READ, core_util_2.RPC),
212
+ (0, core_util_2.WpMcpTool)('remote_throw'),
211
213
  tslib_1.__metadata("design:type", Function),
212
214
  tslib_1.__metadata("design:paramtypes", [RemoteRequest]),
213
215
  tslib_1.__metadata("design:returntype", Promise)
214
216
  ], RemoteThrowApi.prototype, "fail", null);
215
217
  exports.RemoteThrowApi = RemoteThrowApi = tslib_1.__decorate([
216
- (0, core_util_1.ApiPath)('/remote-throw'),
217
- (0, core_util_1.ApiType)(core_util_1.SVC_TO_SVC, core_util_1.MCP)
218
+ (0, core_util_2.ApiPath)('/remote-throw'),
219
+ (0, core_util_2.ApiType)(core_util_2.SVC_TO_SVC, core_util_2.MCP)
218
220
  ], RemoteThrowApi);
219
221
  /**
220
222
  * One named throw, run identically behind the local and the remote binding.
@@ -239,67 +241,67 @@ class ThrowCase {
239
241
  exports.ThrowCase = ThrowCase;
240
242
  exports.THROW_CASES = [
241
243
  new ThrowCase('end-user', 'end-user', 'warn', () => {
242
- throw new core_util_1.ApiEndUserError('The two passwords you entered do not match.', 'PW_MISMATCH');
244
+ throw new core_util_2.ApiEndUserError('The two passwords you entered do not match.', 'PW_MISMATCH');
243
245
  }),
244
246
  new ThrowCase('bad-request', 'bad-request', 'warn', () => {
245
- throw new core_util_1.ApiBadRequestError('internal column name', '$.query', 'query must be a word');
247
+ throw new core_util_2.ApiBadRequestError('internal column name', '$.query', 'query must be a word');
246
248
  }),
247
249
  new ThrowCase('unauthorized', 'unauthorized', 'warn', () => {
248
- throw new core_util_1.ApiUnauthorizedError('session internals');
250
+ throw new core_util_2.ApiUnauthorizedError('session internals');
249
251
  }),
250
252
  new ThrowCase('forbidden', 'forbidden', 'warn', () => {
251
- throw new core_util_1.ApiForbiddenError('acl internals');
253
+ throw new core_util_2.ApiForbiddenError('acl internals');
252
254
  }),
253
255
  new ThrowCase('not-found', 'not-found', 'warn', () => {
254
- throw new core_util_1.ApiNotFoundError('row 7 missing');
256
+ throw new core_util_2.ApiNotFoundError('row 7 missing');
255
257
  }),
256
258
  new ThrowCase('endpoint-not-found', 'endpoint-not-found', 'warn', () => {
257
- throw new core_util_1.ApiEndpointNotFoundError('route internals');
259
+ throw new core_util_2.ApiEndpointNotFoundError('route internals');
258
260
  }),
259
261
  new ThrowCase('request-timeout', 'request-timeout', 'error', () => {
260
- throw new core_util_1.ApiRequestTimeoutError('slow internals');
262
+ throw new core_util_2.ApiRequestTimeoutError('slow internals');
261
263
  }),
262
264
  new ThrowCase('rate-limited', 'rate-limited', 'error', () => {
263
- throw new core_util_1.ApiRateLimitedError('quota internals');
265
+ throw new core_util_2.ApiRateLimitedError('quota internals');
264
266
  }),
265
267
  new ThrowCase('conflict', 'conflict', 'warn', () => {
266
- throw new core_util_1.ApiConflictError('version internals');
268
+ throw new core_util_2.ApiConflictError('version internals');
267
269
  }),
268
270
  new ThrowCase('unprocessable', 'unprocessable', 'warn', () => {
269
- throw new core_util_1.ApiUnprocessableError('rule internals');
271
+ throw new core_util_2.ApiUnprocessableError('rule internals');
270
272
  }),
271
273
  new ThrowCase('precondition-failed', 'precondition-failed', 'warn', () => {
272
- throw new core_util_1.ApiPreconditionFailedError('etag internals');
274
+ throw new core_util_2.ApiPreconditionFailedError('etag internals');
273
275
  }),
274
276
  new ThrowCase('unsupported-media-type', 'unsupported-media-type', 'warn', () => {
275
- throw new core_util_1.ApiUnsupportedMediaTypeError('parser internals');
277
+ throw new core_util_2.ApiUnsupportedMediaTypeError('parser internals');
276
278
  }),
277
279
  new ThrowCase('not-implemented', 'not-implemented', 'error', () => {
278
- throw new core_util_1.ApiNotImplementedError('feature internals');
280
+ throw new core_util_2.ApiNotImplementedError('feature internals');
279
281
  }),
280
282
  new ThrowCase('coded-4xx', 'coded', 'warn', () => {
281
- throw new core_util_1.ApiCodedError('quota internals', 460, 'QUOTA');
283
+ throw new core_util_2.ApiCodedError('quota internals', 460, 'QUOTA');
282
284
  }),
283
285
  new ThrowCase('coded-5xx', 'coded', 'error', () => {
284
- throw new core_util_1.ApiCodedError('disk internals', 507);
286
+ throw new core_util_2.ApiCodedError('disk internals', 507);
285
287
  }),
286
288
  new ThrowCase('implementation', 'implementation', 'error', () => {
287
- throw new core_util_1.ApiImplementationError('bug internals');
289
+ throw new core_util_2.ApiImplementationError('bug internals');
288
290
  }),
289
291
  new ThrowCase('dependency', 'dependency', 'error', () => {
290
- throw new core_util_1.ApiDependencyError('upstream internals');
292
+ throw new core_util_2.ApiDependencyError('upstream internals');
291
293
  }),
292
294
  new ThrowCase('unavailable', 'unavailable', 'error', () => {
293
- throw new core_util_1.ApiUnavailableError('maintenance internals');
295
+ throw new core_util_2.ApiUnavailableError('maintenance internals');
294
296
  }),
295
297
  new ThrowCase('dependency-timeout', 'dependency-timeout', 'error', () => {
296
- throw new core_util_1.ApiDependencyTimeoutError('upstream slow internals');
298
+ throw new core_util_2.ApiDependencyTimeoutError('upstream slow internals');
297
299
  }),
298
300
  new ThrowCase('dependency-backoff', 'dependency-backoff', 'error', () => {
299
- throw new core_util_1.ApiDependencyBackoffError('backoff internals', 42);
301
+ throw new core_util_2.ApiDependencyBackoffError('backoff internals', 42);
300
302
  }),
301
303
  new ThrowCase('connection', 'implementation', 'error', () => {
302
- throw new core_util_1.ApiConnectionError('ECONNRESET internals');
304
+ throw new core_util_2.ApiConnectionError('ECONNRESET internals');
303
305
  }),
304
306
  new ThrowCase('raw-error', 'implementation', 'error', () => {
305
307
  throw new Error('SECRET-raw-internals');
@@ -361,7 +363,7 @@ class RecordingOidcMinter {
361
363
  }
362
364
  }
363
365
  exports.RecordingOidcMinter = RecordingOidcMinter;
364
- class RecordingOidcVerifier extends http_routing_1.OidcHook {
366
+ class RecordingOidcVerifier extends http_routing_2.OidcHook {
365
367
  tokens = [];
366
368
  callerLists = [];
367
369
  verifyOidc(token, callers) {
@@ -369,20 +371,20 @@ class RecordingOidcVerifier extends http_routing_1.OidcHook {
369
371
  this.callerLists.push(callers);
370
372
  if (token !== exports.OIDC_TOKEN)
371
373
  throw new Error(`unexpected OIDC token '${token}'`);
372
- return Promise.resolve();
374
+ return Promise.resolve(new http_routing_1.AuthenticatedMachineIdentity('oidc', 'test-service@example.test'));
373
375
  }
374
376
  }
375
377
  exports.RecordingOidcVerifier = RecordingOidcVerifier;
376
- let BoundaryProbeFilter = class BoundaryProbeFilter extends core_util_1.Filter {
378
+ let BoundaryProbeFilter = class BoundaryProbeFilter extends core_util_2.Filter {
377
379
  calls = 0;
378
380
  sawLogIdentity = false;
379
381
  sawTrustedUser;
380
382
  filter(meta, next) {
381
383
  this.calls += 1;
382
384
  this.sawLogIdentity =
383
- core_context_1.RequestContext.getUntrusted(core_util_1.WebpiecesCoreHeaders.CONTROLLER) ===
385
+ core_context_1.RequestContext.getUntrusted(core_util_2.WebpiecesCoreHeaders.CONTROLLER) ===
384
386
  'RemoteMcpController' &&
385
- core_context_1.RequestContext.getUntrusted(core_util_1.WebpiecesCoreHeaders.METHOD) === 'search';
387
+ core_context_1.RequestContext.getUntrusted(core_util_2.WebpiecesCoreHeaders.METHOD) === 'search';
386
388
  this.sawTrustedUser = core_context_1.RequestContext.getTrusted(exports.REMOTE_USER);
387
389
  return next.invoke(meta);
388
390
  }
@@ -398,16 +400,16 @@ exports.BoundaryProbeFilter = BoundaryProbeFilter = tslib_1.__decorate([
398
400
  */
399
401
  class RelayWebpiecesPeerErrors {
400
402
  relay = true;
401
- fallback = new core_util_1.WebpiecesDefaultErrorTranslator();
403
+ fallback = new core_util_2.WebpiecesDefaultErrorTranslator();
402
404
  toWire(error) {
403
405
  return this.fallback.toWire(error);
404
406
  }
405
407
  fromWire(response) {
406
- if (this.relay && core_util_1.ApiErrorCodec.isPayload(response.body)) {
407
- const decoded = core_util_1.ApiErrorCodec.decode(response.body);
408
- const statusCode = decoded instanceof core_util_1.ApiCodedError ? decoded.statusCode : undefined;
409
- if (core_util_1.ApiErrorHttpStatus.hasCode(decoded) &&
410
- core_util_1.ApiErrorHttpStatus.codeFor(decoded.kind, statusCode) === response.status.code) {
408
+ if (this.relay && core_util_2.ApiErrorCodec.isPayload(response.body)) {
409
+ const decoded = core_util_2.ApiErrorCodec.decode(response.body);
410
+ const statusCode = decoded instanceof core_util_2.ApiCodedError ? decoded.statusCode : undefined;
411
+ if (core_util_2.ApiErrorHttpStatus.hasCode(decoded) &&
412
+ core_util_2.ApiErrorHttpStatus.codeFor(decoded.kind, statusCode) === response.status.code) {
411
413
  throw decoded;
412
414
  }
413
415
  }