@webpieces/mcp-server 0.4.787 → 0.4.789

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.
package/README.md CHANGED
@@ -163,22 +163,45 @@ hour and MCP access tokens at 30 days.
163
163
  ## Error boundary
164
164
 
165
165
  `WpMcpErrorTranslator` is the one place a failure becomes an MCP reply, mirroring
166
- `ApiErrorHttpMapper`. Each entry point has exactly one catch that only delegates to it; the dispatcher
167
- and the local/remote invokers have none. Classification is the shared `ApiErrorBoundary` rule (a
168
- non-`ApiError`, or a caller-local `ApiConnectionError`, publishes as kind `implementation`), and each
169
- failure is logged once at the same per-kind level as HTTP, with `requestId`, JSON-RPC id and tool
170
- name. The boundary never substitutes an object for the thrown error, so the operator line names the
171
- class that actually failed and an app's `McpErrorTranslators` can `instanceof` its own error classes.
172
-
173
- | Where | Reply |
174
- |---|---|
175
- | `tools/call`, tool found: bad arguments, `@WpMcpAuthJwt` denial, JWT/OIDC mint failure, any local or remote failure, output-schema or serialization failure | `isError: true` result |
176
- | `tools/call`, unknown tool name | JSON-RPC `-32602` `Unknown tool: <name>` |
177
- | `tools/list` | JSON-RPC `-32602` (bad request) or `-32603` `Internal Error` |
178
- | before the SDK: bearer, `Origin`, malformed body | HTTP 401 + `WWW-Authenticate` / 403 / 400, anything else 500 |
166
+ `ApiErrorHttpMapper`: an error in, the exact wire shape out. Each entry point has exactly one catch
167
+ that only delegates to it; the dispatcher and the local/remote invokers have none. Classification is
168
+ the shared `ApiErrorBoundary.encode` rule (a non-`ApiError`, or a caller-local `ApiConnectionError`,
169
+ publishes as kind `implementation`). The boundary never substitutes an object for the thrown error,
170
+ so an app's `McpErrorTranslators` can `instanceof` its own error classes.
171
+
172
+ There is ONE method per BOUNDARY, named for the boundary it guards. They cannot be one shape — the
173
+ MCP spec fixes each — so the three-ness is made obvious rather than accidental:
174
+
175
+ | Boundary | Method | Reply |
176
+ |---|---|---|
177
+ | before the SDK: bearer, `Origin`, malformed body | `toBearerBoundaryResponse(error): HttpResponseDto<McpHttpErrorBody>` | HTTP 401 + `WWW-Authenticate` / 403 / 400, anything else 500 |
178
+ | `tools/list` | `toListError(error): never` | throws JSON-RPC `-32602` (bad request) or `-32603` `Internal Error` |
179
+ | `tools/call`, tool found: bad arguments, `@WpMcpAuthJwt` denial, JWT/OIDC mint failure, any local or remote failure, output-schema or serialization failure | `toToolCallResult(error): CallToolResult` | `isError: true` result |
180
+ | `tools/call`, unknown tool name | `unknownTool(name)` | JSON-RPC `-32602` `Unknown tool: <name>` |
181
+
182
+ The pre-SDK boundary produces a VALUE like every other API in the framework and `WpMcpServer` writes
183
+ it through the same `ExpressResponseWriter` the ordinary HTTP path uses — it does not hand-roll
184
+ `res.status(...).json(...)`. The body stays JSON-RPC shaped because an MCP client expects that;
185
+ `HttpResponseDto` is generic and its header LIST carries `WWW-Authenticate`.
186
+
187
+ `toListError` is typed `never` — it THROWS rather than returning a value the caller must remember to
188
+ throw — and it is LOAD-BEARING for disclosure, not defence in depth: the official SDK wraps a foreign
189
+ throw in `-32603` but copies its `message` onto the wire verbatim (measured and pinned by
190
+ `McpSdkForeignThrow.spec.ts`).
191
+
192
+ **Operator logging is NOT in the translator.** The edges with no filter chain above them — bearer
193
+ verification, `Origin`, a malformed body, `tools/list` — are wrapped in `LogApiCall`, which is this
194
+ repo's one line on logging; `tools/call` dispatches through the ordinary filter chain, so
195
+ `LogApiFilter` owns its line. Exactly one `[API-server-resp-FAIL]` / `-OTHER` line per failure, with
196
+ the request, the identity and the timing on it, and none of the barer second line
197
+ `ApiErrorBoundary.logOperatorDetail` used to add.
179
198
 
180
199
  `subscriptions/listen` is served entirely by the SDK's listen router, so Webpieces has no handler there.
181
200
 
201
+ `requestId` comes from `RequestContext` and the JSON-RPC id and tool name from the request scope,
202
+ so none of the three methods takes a correlation parameter — the deleted `McpFailureScope` was a copy
203
+ of context the renderers can already read.
204
+
182
205
  What the model reads inside an `isError` result: an `ApiEndUserError` message verbatim plus
183
206
  `errorCode` (it survives the remote hop byte-for-byte); an `ApiBadRequestError`'s `callerMessage` and
184
207
  `field`, never its operator `message`; for an implementation failure, generic text naming the tool and
@@ -192,16 +215,20 @@ Every reply carries the requestId so a user can quote it: `_meta["webpieces/requ
192
215
 
193
216
  ### The application's own `tools/call` translation
194
217
 
195
- An app owns its error taxonomy and owns how those errors should be explained to a model, so it gets
196
- FIRST REFUSAL on every `tools/call` failure — the same convention `ExpressWrapper.handleError`
197
- applies on the HTTP path through `ClientRegistry.tryTranslateToWire`. Register one with
218
+ An app owns its error taxonomy and owns how those errors should be explained to a model, so a
219
+ registered translator REPLACES the webpieces default for every `tools/call` failure — the same
220
+ convention `ExpressWrapper.handleError` applies on the HTTP path. Register one with
198
221
  `WpMcpServerConfig.setErrorTranslator(...)`; it is a setter and not a global, because `WpMcpServer` is
199
222
  constructed by app code and two servers may run in one process.
200
223
 
201
224
  ```ts
202
225
  class LangMcpErrorTranslators implements McpErrorTranslators {
203
- toToolResult(error: Error, scope: McpFailureScope): CallToolResult | undefined {
204
- if (!(error instanceof LangPassageLockedError)) return undefined; // not mine
226
+ private readonly fallback = new McpDefaultToolCallRenderer();
227
+
228
+ toToolCallResult(error: Error): CallToolResult {
229
+ if (!(error instanceof LangPassageLockedError)) {
230
+ return this.fallback.toToolCallResult(error); // not mine -> webpieces default
231
+ }
205
232
  return {
206
233
  content: [{ type: 'text', text: `Passage ${error.passageId} is locked.` }],
207
234
  structuredContent: { passageId: error.passageId, action: 'ask_the_user_to_unlock' },
@@ -213,13 +240,14 @@ class LangMcpErrorTranslators implements McpErrorTranslators {
213
240
 
214
241
  - `error` is the thrown value itself — webpieces never substitutes another object for it, so
215
242
  `instanceof` on the app's own classes works.
216
- - Returning `undefined` means "not mine" and the webpieces default renders, unchanged.
243
+ - There is no "not mine" return. Decline by DELEGATING to `McpDefaultToolCallRenderer`, the public
244
+ class that IS the webpieces default, so declining is byte-identical to registering nothing.
217
245
  - A claimed error owns the ENTIRE `CallToolResult` — content, `structuredContent`, `isError`.
218
246
  - webpieces default-fills `_meta["webpieces/requestId"]` only when the returned result has no
219
247
  `_meta`; an app that sets `_meta` keeps it untouched.
220
- - Operator-detail logging has already run when the translator is called, so claiming an error can
221
- never silently kill observability. A translator that THROWS is itself reported through the same
222
- boundary and the original error still renders the reply.
248
+ - The failure has already been logged by the filter chain when the translator is called, so claiming
249
+ an error can never silently kill observability. A translator that THROWS is reported on its own
250
+ line and the original error still renders the reply.
223
251
  - The scope is `tools/call` ONLY. `tools/list` and the pre-SDK HTTP boundary stay framework-owned:
224
252
  that boundary emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` MCP clients depend
225
253
  on for OAuth discovery, and an app rewriting it breaks connector onboarding in a way that is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/mcp-server",
3
- "version": "0.4.787",
3
+ "version": "0.4.789",
4
4
  "description": "Secure MCP tool generation from annotated Webpieces API contracts",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,15 +24,15 @@
24
24
  "dependencies": {
25
25
  "@modelcontextprotocol/node": "2.0.0",
26
26
  "@modelcontextprotocol/server": "2.0.0",
27
- "@webpieces/core-context": "0.4.787",
28
- "@webpieces/core-util": "0.4.787",
29
- "@webpieces/http-routing": "0.4.787",
27
+ "@webpieces/core-context": "0.4.789",
28
+ "@webpieces/core-util": "0.4.789",
29
+ "@webpieces/http-routing": "0.4.789",
30
+ "@webpieces/http-server": "0.4.789",
30
31
  "express": "5.1.0",
31
32
  "reflect-metadata": "0.2.2",
32
33
  "tslib": "2.8.1"
33
34
  },
34
35
  "devDependencies": {
35
- "@webpieces/http-client-node": "0.4.787",
36
- "@webpieces/http-server": "0.4.787"
36
+ "@webpieces/http-client-node": "0.4.789"
37
37
  }
38
38
  }
package/src/McpAuth.d.ts CHANGED
@@ -143,8 +143,9 @@ export declare class WpMcpServerConfig<TGrant, TMintRequest> {
143
143
  */
144
144
  setRequiredScopes(requiredScopes: readonly string[]): this;
145
145
  /**
146
- * OPTIONAL. The application's `tools/call` error translators — first refusal on every tool
147
- * failure, owning the ENTIRE result it claims. See {@link McpErrorTranslators}.
146
+ * OPTIONAL. The application's `tools/call` error translator — it REPLACES the webpieces default
147
+ * for every tool failure, owning the ENTIRE result, and declines by delegating to
148
+ * `new McpDefaultToolCallRenderer().toToolCallResult(error)`. See {@link McpErrorTranslators}.
148
149
  */
149
150
  setErrorTranslator(translators: McpErrorTranslators): this;
150
151
  /** OPTIONAL ceiling, 1 second to 1 hour. Defaults to 1 hour. */
package/src/McpAuth.js CHANGED
@@ -204,13 +204,14 @@ class WpMcpServerConfig {
204
204
  return this;
205
205
  }
206
206
  /**
207
- * OPTIONAL. The application's `tools/call` error translators — first refusal on every tool
208
- * failure, owning the ENTIRE result it claims. See {@link McpErrorTranslators}.
207
+ * OPTIONAL. The application's `tools/call` error translator — it REPLACES the webpieces default
208
+ * for every tool failure, owning the ENTIRE result, and declines by delegating to
209
+ * `new McpDefaultToolCallRenderer().toToolCallResult(error)`. See {@link McpErrorTranslators}.
209
210
  */
210
211
  setErrorTranslator(translators) {
211
212
  const value = this.requirePresent(translators, 'setErrorTranslator');
212
- if (typeof value.toToolResult !== 'function') {
213
- throw new Error('WpMcpServerConfig.setErrorTranslator(...) requires a toToolResult(error, scope) method.');
213
+ if (typeof value.toToolCallResult !== 'function') {
214
+ throw new Error('WpMcpServerConfig.setErrorTranslator(...) requires a toToolCallResult(error) method.');
214
215
  }
215
216
  this.errorTranslatorValue = value;
216
217
  return this;
@@ -1 +1 @@
1
- {"version":3,"file":"McpAuth.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/McpAuth.ts"],"names":[],"mappings":";;;AAIa,QAAA,qCAAqC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;AAC1D,QAAA,sCAAsC,GAAG,EAAE,GAAG,EAAE,CAAC;AACjD,QAAA,qCAAqC,GAAG,EAAE,GAAG,EAAE,CA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AAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,qBAAqB,MAAM,yBAAyB,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,IAAI,CAAI,KAAoB,EAAE,MAAc;QAChD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,gCAAgC,MAAM,OAAO,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AA5QD,8CA4QC","sourcesContent":["import { JwtHook } from '@webpieces/http-routing';\nimport { ContextTuple } from '@webpieces/core-util';\nimport { McpErrorTranslators } from './WpMcpErrorTranslator';\n\nexport const MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;\nexport const MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS = 60 * 60;\nexport const MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS = 60 * 60;\n\n/** Framework-normalized access-token result. The token representation remains application-owned. */\nexport class MintedMcpAccessToken {\n constructor(\n public readonly token: string,\n public readonly resource: string,\n public readonly issuedAtEpochSeconds: number,\n public readonly expiresAtEpochSeconds: number,\n ) {\n if (token.trim() === '' || resource.trim() === '') {\n throw new Error('Minted MCP access token and resource must be non-empty.');\n }\n if (!Number.isFinite(issuedAtEpochSeconds) || !Number.isFinite(expiresAtEpochSeconds)) {\n throw new Error(\n 'Minted MCP access token timestamps must be finite epoch-second values.',\n );\n }\n if (expiresAtEpochSeconds <= issuedAtEpochSeconds) {\n throw new Error('MCP access token expiry must be after issuance.');\n }\n if (expiresAtEpochSeconds - issuedAtEpochSeconds > MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS) {\n throw new Error('MCP access token lifetime must not exceed 30 days.');\n }\n }\n}\n\n/**\n * Fresh, authoritative security facts resolved at the MCP resource boundary. Implementations must\n * verify issuer, exact resource/audience, expiry, token type/version, key/algorithm policy, and\n * current account state. Opaque access tokens are fully supported.\n */\nexport class VerifiedMcpCredential {\n constructor(\n public readonly subject: string,\n public readonly issuer: string,\n public readonly resource: string,\n public readonly issuedAtEpochSeconds: number,\n public readonly expiresAtEpochSeconds: number,\n public readonly scopes: readonly string[],\n /** When current enabled/revoked state and roles were read from the authoritative source. */\n public readonly accountValidatedAtEpochSeconds: number,\n /** Advisory tools/list filtering only. Endpoint authorization always runs again. */\n public readonly listingRoles: readonly string[] = [],\n /** Trusted delegated identity derived only by the access-token authority. */\n public readonly trustedContext: readonly ContextTuple[] = [],\n ) {}\n}\n\n/**\n * Application-owned paired mint/verify authority for resource-bound MCP access tokens.\n * `verifyAccessToken` must throw `ApiUnauthorizedError` for a token it rejects (the bind boundary\n * answers 401 + `WWW-Authenticate`); any other throw is treated as an implementation failure (500).\n */\nexport interface McpAccessTokenAuthority<TGrant> {\n mintAccessToken(grant: TGrant): Promise<MintedMcpAccessToken>;\n verifyAccessToken(\n accessToken: string,\n expectedResource: string,\n ): Promise<VerifiedMcpCredential>;\n}\n\n/** Minimal tool identity supplied when the app creates its own endpoint-JWT mint request. */\nexport class McpEndpointDescriptor {\n constructor(\n public readonly toolName: string,\n public readonly apiClassName: string,\n public readonly methodName: string,\n ) {}\n}\n\n/** Application mapping from verified MCP identity to its unconstrained JwtHook mint request. */\nexport type McpEndpointMintRequestFactory<TMintRequest> = (\n credential: VerifiedMcpCredential,\n endpoint: McpEndpointDescriptor,\n) => TMintRequest;\n\n/** RFC 9728-style metadata exposed by the MCP protected resource. */\nexport class McpProtectedResourceMetadata {\n readonly resource: string;\n readonly authorization_servers: readonly string[];\n readonly bearer_methods_supported = ['header'];\n readonly scopes_supported?: readonly string[];\n\n constructor(\n resource: string,\n authorizationServers: readonly string[],\n scopesSupported?: readonly string[],\n ) {\n this.resource = resource;\n this.authorization_servers = authorizationServers;\n this.scopes_supported = scopesSupported;\n }\n}\n\n/**\n * Node MCP server configuration, built with fluent setters: every name sits next to its own value, so\n * no two settings can be swapped, and a future setting is an additive setter rather than a breaking\n * signature change. Pass the same concrete application authority to both\n * `setAccessTokenAuthority(...)` and `setEndpointJwtAuthority(...)` when it implements both security\n * seams.\n *\n * SINGLE CANONICAL ORIGIN: one server serves exactly one protected resource. {@link setResource} is\n * fixed for the lifetime of the process, is the audience of every access token, and is never derived\n * from the request `Host` — see that setter for why a host-derived audience is a confused deputy.\n *\n * Each setter validates its own value immediately and names itself in the failure. Setters cannot\n * make a field impossible to forget the way a positional constructor could, so\n * {@link WpMcpServerConfig.validate} runs from `WpMcpServer.bind(...)` and fails at startup listing\n * EVERY missing required setter at once. A misconfiguration is therefore a boot failure naming the\n * setter, instead of a first-request 401 + `WWW-Authenticate` — which is the OAuth discovery signal,\n * so the client's correct response is to re-authenticate and fail again, forever.\n *\n * ```ts\n * const config = new WpMcpServerConfig<MyGrant, MyMintRequest>()\n * .setName('my-server')\n * .setVersion('1.0.0')\n * .setResource('https://api.example.com/mcp')\n * .setAccessTokenAuthority(authority)\n * .setEndpointJwtAuthority(jwtHook)\n * .setEndpointMintRequest((credential) => new MyMintRequest(credential.subject))\n * .setAuthorizationServers(['https://login.example.com'])\n * .setRequiredScopes(['tools'])\n * .setErrorTranslator(new MyMcpErrorTranslators());\n * ```\n */\nexport class WpMcpServerConfig<TGrant, TMintRequest> {\n private nameValue?: string;\n private versionValue?: string;\n private resourceValue?: string;\n private accessTokenAuthorityValue?: McpAccessTokenAuthority<TGrant>;\n private endpointJwtAuthorityValue?: JwtHook<TMintRequest>;\n private endpointMintRequestValue?: McpEndpointMintRequestFactory<TMintRequest>;\n private authorizationServersValue?: readonly string[];\n private requiredScopesValue?: readonly string[];\n private errorTranslatorValue?: McpErrorTranslators;\n private maxAccountValidationAgeSecondsValue = MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS;\n private maxEndpointJwtLifetimeSecondsValue = MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS;\n\n /** REQUIRED. The MCP server name reported by `initialize`. */\n setName(name: string): this {\n this.nameValue = this.requireText(name, 'setName');\n return this;\n }\n\n /** REQUIRED. The MCP server version; the registry revision is appended to it at bind time. */\n setVersion(version: string): this {\n this.versionValue = this.requireText(version, 'setVersion');\n return this;\n }\n\n /**\n * REQUIRED. The ONE canonical protected-resource URI, which must be an absolute URL: it is the\n * exact audience every access token is checked against, and {@link resourceMetadataUrl} is\n * derived from it for the 401 challenge, so a non-URL here is always a mistake — including a\n * name or version landed on it.\n *\n * It is fixed for the lifetime of the process and must NEVER be derived from the request `Host`\n * header: the boundary compares a token's audience against this value, so a host-derived\n * resource compares two values both taken from caller-controlled input — the confused-deputy\n * shape this check exists to prevent. Its path must equal `McpBindOptions.endpointPath`, which\n * `WpMcpServer.bind(...)` verifies. A second hostname is a second deployment, not a second\n * audience.\n */\n setResource(resource: string): this {\n this.resourceValue = this.requireUrl(resource, 'setResource');\n return this;\n }\n\n /** REQUIRED. Application-owned paired mint/verify authority for MCP access tokens. */\n setAccessTokenAuthority(authority: McpAccessTokenAuthority<TGrant>): this {\n this.accessTokenAuthorityValue = this.requirePresent(authority, 'setAccessTokenAuthority');\n return this;\n }\n\n /** REQUIRED. The `JwtHook` minting the short-lived per-endpoint JWT for local bindings. */\n setEndpointJwtAuthority(authority: JwtHook<TMintRequest>): this {\n this.endpointJwtAuthorityValue = this.requirePresent(authority, 'setEndpointJwtAuthority');\n return this;\n }\n\n /** REQUIRED. Maps a verified MCP identity plus tool identity to that JwtHook's mint request. */\n setEndpointMintRequest(factory: McpEndpointMintRequestFactory<TMintRequest>): this {\n if (typeof factory !== 'function') {\n throw new Error('WpMcpServerConfig.setEndpointMintRequest(...) requires a function.');\n }\n this.endpointMintRequestValue = factory;\n return this;\n }\n\n /**\n * REQUIRED. The trusted token issuers. Every entry must be an absolute URL, because each is\n * compared against a token's `issuer` claim and published as an `authorization_servers` entry —\n * which is what makes a scope list landed here fail at boot rather than on the first request.\n */\n setAuthorizationServers(authorizationServers: readonly string[]): this {\n const servers = this.requireArray(authorizationServers, 'setAuthorizationServers');\n if (servers.length === 0) {\n throw new Error(\n 'WpMcpServerConfig.setAuthorizationServers(...) requires at least one issuer URL.',\n );\n }\n for (const server of servers) this.requireUrl(server, 'setAuthorizationServers');\n this.authorizationServersValue = servers;\n return this;\n }\n\n /**\n * REQUIRED, and empty only by saying so explicitly. Scopes every access token must carry before\n * any tool is dispatched.\n */\n setRequiredScopes(requiredScopes: readonly string[]): this {\n const scopes = this.requireArray(requiredScopes, 'setRequiredScopes');\n for (const scope of scopes) this.requireText(scope, 'setRequiredScopes');\n this.requiredScopesValue = scopes;\n return this;\n }\n\n /**\n * OPTIONAL. The application's `tools/call` error translators — first refusal on every tool\n * failure, owning the ENTIRE result it claims. See {@link McpErrorTranslators}.\n */\n setErrorTranslator(translators: McpErrorTranslators): this {\n const value = this.requirePresent(translators, 'setErrorTranslator');\n if (typeof value.toToolResult !== 'function') {\n throw new Error(\n 'WpMcpServerConfig.setErrorTranslator(...) requires a toToolResult(error, scope) method.',\n );\n }\n this.errorTranslatorValue = value;\n return this;\n }\n\n /** OPTIONAL ceiling, 1 second to 1 hour. Defaults to 1 hour. */\n setMaxAccountValidationAgeSeconds(seconds: number): this {\n this.maxAccountValidationAgeSecondsValue = this.requireSeconds(\n seconds,\n MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS,\n 'setMaxAccountValidationAgeSeconds',\n );\n return this;\n }\n\n /** OPTIONAL ceiling, 1 second to 1 hour. Defaults to 1 hour. */\n setMaxEndpointJwtLifetimeSeconds(seconds: number): this {\n this.maxEndpointJwtLifetimeSecondsValue = this.requireSeconds(\n seconds,\n MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS,\n 'setMaxEndpointJwtLifetimeSeconds',\n );\n return this;\n }\n\n /**\n * Called by `WpMcpServer.bind(...)`. Throws naming EVERY missing required setter at once, so a\n * half-built config is repaired in one pass rather than one boot failure at a time.\n */\n validate(): void {\n const missing: string[] = [];\n if (this.nameValue === undefined) missing.push('setName(...)');\n if (this.versionValue === undefined) missing.push('setVersion(...)');\n if (this.resourceValue === undefined) missing.push('setResource(...)');\n if (this.accessTokenAuthorityValue === undefined) {\n missing.push('setAccessTokenAuthority(...)');\n }\n if (this.endpointJwtAuthorityValue === undefined) {\n missing.push('setEndpointJwtAuthority(...)');\n }\n if (this.endpointMintRequestValue === undefined) {\n missing.push('setEndpointMintRequest(...)');\n }\n if (this.authorizationServersValue === undefined) {\n missing.push('setAuthorizationServers(...)');\n }\n if (this.requiredScopesValue === undefined) missing.push('setRequiredScopes(...)');\n if (missing.length > 0) {\n throw new Error(`WpMcpServerConfig is missing ${missing.join(', ')}`);\n }\n }\n\n get name(): string {\n return this.read(this.nameValue, 'setName');\n }\n\n get version(): string {\n return this.read(this.versionValue, 'setVersion');\n }\n\n get resource(): string {\n return this.read(this.resourceValue, 'setResource');\n }\n\n get accessTokenAuthority(): McpAccessTokenAuthority<TGrant> {\n return this.read(this.accessTokenAuthorityValue, 'setAccessTokenAuthority');\n }\n\n get endpointJwtAuthority(): JwtHook<TMintRequest> {\n return this.read(this.endpointJwtAuthorityValue, 'setEndpointJwtAuthority');\n }\n\n get endpointMintRequest(): McpEndpointMintRequestFactory<TMintRequest> {\n return this.read(this.endpointMintRequestValue, 'setEndpointMintRequest');\n }\n\n get authorizationServers(): readonly string[] {\n return this.read(this.authorizationServersValue, 'setAuthorizationServers');\n }\n\n get requiredScopes(): readonly string[] {\n return this.read(this.requiredScopesValue, 'setRequiredScopes');\n }\n\n /** `undefined` when the app registered none: webpieces then renders every tool failure. */\n get errorTranslator(): McpErrorTranslators | undefined {\n return this.errorTranslatorValue;\n }\n\n get maxAccountValidationAgeSeconds(): number {\n return this.maxAccountValidationAgeSecondsValue;\n }\n\n get maxEndpointJwtLifetimeSeconds(): number {\n return this.maxEndpointJwtLifetimeSecondsValue;\n }\n\n /**\n * RFC 9728 §3.1: the URL of this resource's protected-resource METADATA DOCUMENT, derived from\n * {@link resource} by inserting `/.well-known/oauth-protected-resource` between origin and path\n * (`https://host/mcp` → `https://host/.well-known/oauth-protected-resource/mcp`).\n *\n * This — never the resource identifier itself — is what RFC 9728 §5.1 defines `resource_metadata`\n * to be, so it is the value webpieces puts in the 401 `WWW-Authenticate` challenge. webpieces\n * mounts no `.well-known` route; publish {@link protectedResourceMetadata} at this URL.\n */\n get resourceMetadataUrl(): string {\n const url = new URL(this.resource);\n const path = url.pathname === '/' ? '' : url.pathname;\n return `${url.origin}/.well-known/oauth-protected-resource${path}`;\n }\n\n protectedResourceMetadata(): McpProtectedResourceMetadata {\n return new McpProtectedResourceMetadata(\n this.resource,\n this.authorizationServers,\n this.requiredScopes,\n );\n }\n\n private requireText(value: string, setter: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires a non-empty string.`);\n }\n return value;\n }\n\n private requireUrl(value: string, setter: string): string {\n this.requireText(value, setter);\n if (!URL.canParse(value)) {\n throw new Error(\n `WpMcpServerConfig.${setter}(...) requires an absolute URL, got '${value}'.`,\n );\n }\n return value;\n }\n\n private requireArray(value: readonly string[], setter: string): readonly string[] {\n if (!Array.isArray(value)) {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires an array of strings.`);\n }\n return value;\n }\n\n private requireSeconds(value: number, ceiling: number, setter: string): number {\n if (!Number.isFinite(value) || value <= 0 || value > ceiling) {\n throw new Error(\n `WpMcpServerConfig.${setter}(...) requires 1..${ceiling} seconds, got ${String(value)}.`,\n );\n }\n return value;\n }\n\n private requirePresent<T>(value: T, setter: string): T {\n if (value === undefined || value === null) {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires a value.`);\n }\n return value;\n }\n\n private read<T>(value: T | undefined, setter: string): T {\n if (value === undefined) {\n throw new Error(`WpMcpServerConfig is missing ${setter}(...)`);\n }\n return value;\n }\n}\n"]}
1
+ {"version":3,"file":"McpAuth.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/McpAuth.ts"],"names":[],"mappings":";;;AAIa,QAA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AAO,iBAAiB,MAAM,CAAC,KAAK,CAAC,GAAG,CAC3F,CAAC;QACN,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,cAAc,CAAI,KAAQ,EAAE,MAAc;QAC9C,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACxC,MAAM,IAAI,KAAK,CAAC,qBAAqB,MAAM,yBAAyB,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,IAAI,CAAI,KAAoB,EAAE,MAAc;QAChD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,gCAAgC,MAAM,OAAO,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AA7QD,8CA6QC","sourcesContent":["import { JwtHook } from '@webpieces/http-routing';\nimport { ContextTuple } from '@webpieces/core-util';\nimport { McpErrorTranslators } from './WpMcpErrorTranslator';\n\nexport const MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;\nexport const MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS = 60 * 60;\nexport const MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS = 60 * 60;\n\n/** Framework-normalized access-token result. The token representation remains application-owned. */\nexport class MintedMcpAccessToken {\n constructor(\n public readonly token: string,\n public readonly resource: string,\n public readonly issuedAtEpochSeconds: number,\n public readonly expiresAtEpochSeconds: number,\n ) {\n if (token.trim() === '' || resource.trim() === '') {\n throw new Error('Minted MCP access token and resource must be non-empty.');\n }\n if (!Number.isFinite(issuedAtEpochSeconds) || !Number.isFinite(expiresAtEpochSeconds)) {\n throw new Error(\n 'Minted MCP access token timestamps must be finite epoch-second values.',\n );\n }\n if (expiresAtEpochSeconds <= issuedAtEpochSeconds) {\n throw new Error('MCP access token expiry must be after issuance.');\n }\n if (expiresAtEpochSeconds - issuedAtEpochSeconds > MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS) {\n throw new Error('MCP access token lifetime must not exceed 30 days.');\n }\n }\n}\n\n/**\n * Fresh, authoritative security facts resolved at the MCP resource boundary. Implementations must\n * verify issuer, exact resource/audience, expiry, token type/version, key/algorithm policy, and\n * current account state. Opaque access tokens are fully supported.\n */\nexport class VerifiedMcpCredential {\n constructor(\n public readonly subject: string,\n public readonly issuer: string,\n public readonly resource: string,\n public readonly issuedAtEpochSeconds: number,\n public readonly expiresAtEpochSeconds: number,\n public readonly scopes: readonly string[],\n /** When current enabled/revoked state and roles were read from the authoritative source. */\n public readonly accountValidatedAtEpochSeconds: number,\n /** Advisory tools/list filtering only. Endpoint authorization always runs again. */\n public readonly listingRoles: readonly string[] = [],\n /** Trusted delegated identity derived only by the access-token authority. */\n public readonly trustedContext: readonly ContextTuple[] = [],\n ) {}\n}\n\n/**\n * Application-owned paired mint/verify authority for resource-bound MCP access tokens.\n * `verifyAccessToken` must throw `ApiUnauthorizedError` for a token it rejects (the bind boundary\n * answers 401 + `WWW-Authenticate`); any other throw is treated as an implementation failure (500).\n */\nexport interface McpAccessTokenAuthority<TGrant> {\n mintAccessToken(grant: TGrant): Promise<MintedMcpAccessToken>;\n verifyAccessToken(\n accessToken: string,\n expectedResource: string,\n ): Promise<VerifiedMcpCredential>;\n}\n\n/** Minimal tool identity supplied when the app creates its own endpoint-JWT mint request. */\nexport class McpEndpointDescriptor {\n constructor(\n public readonly toolName: string,\n public readonly apiClassName: string,\n public readonly methodName: string,\n ) {}\n}\n\n/** Application mapping from verified MCP identity to its unconstrained JwtHook mint request. */\nexport type McpEndpointMintRequestFactory<TMintRequest> = (\n credential: VerifiedMcpCredential,\n endpoint: McpEndpointDescriptor,\n) => TMintRequest;\n\n/** RFC 9728-style metadata exposed by the MCP protected resource. */\nexport class McpProtectedResourceMetadata {\n readonly resource: string;\n readonly authorization_servers: readonly string[];\n readonly bearer_methods_supported = ['header'];\n readonly scopes_supported?: readonly string[];\n\n constructor(\n resource: string,\n authorizationServers: readonly string[],\n scopesSupported?: readonly string[],\n ) {\n this.resource = resource;\n this.authorization_servers = authorizationServers;\n this.scopes_supported = scopesSupported;\n }\n}\n\n/**\n * Node MCP server configuration, built with fluent setters: every name sits next to its own value, so\n * no two settings can be swapped, and a future setting is an additive setter rather than a breaking\n * signature change. Pass the same concrete application authority to both\n * `setAccessTokenAuthority(...)` and `setEndpointJwtAuthority(...)` when it implements both security\n * seams.\n *\n * SINGLE CANONICAL ORIGIN: one server serves exactly one protected resource. {@link setResource} is\n * fixed for the lifetime of the process, is the audience of every access token, and is never derived\n * from the request `Host` — see that setter for why a host-derived audience is a confused deputy.\n *\n * Each setter validates its own value immediately and names itself in the failure. Setters cannot\n * make a field impossible to forget the way a positional constructor could, so\n * {@link WpMcpServerConfig.validate} runs from `WpMcpServer.bind(...)` and fails at startup listing\n * EVERY missing required setter at once. A misconfiguration is therefore a boot failure naming the\n * setter, instead of a first-request 401 + `WWW-Authenticate` — which is the OAuth discovery signal,\n * so the client's correct response is to re-authenticate and fail again, forever.\n *\n * ```ts\n * const config = new WpMcpServerConfig<MyGrant, MyMintRequest>()\n * .setName('my-server')\n * .setVersion('1.0.0')\n * .setResource('https://api.example.com/mcp')\n * .setAccessTokenAuthority(authority)\n * .setEndpointJwtAuthority(jwtHook)\n * .setEndpointMintRequest((credential) => new MyMintRequest(credential.subject))\n * .setAuthorizationServers(['https://login.example.com'])\n * .setRequiredScopes(['tools'])\n * .setErrorTranslator(new MyMcpErrorTranslators());\n * ```\n */\nexport class WpMcpServerConfig<TGrant, TMintRequest> {\n private nameValue?: string;\n private versionValue?: string;\n private resourceValue?: string;\n private accessTokenAuthorityValue?: McpAccessTokenAuthority<TGrant>;\n private endpointJwtAuthorityValue?: JwtHook<TMintRequest>;\n private endpointMintRequestValue?: McpEndpointMintRequestFactory<TMintRequest>;\n private authorizationServersValue?: readonly string[];\n private requiredScopesValue?: readonly string[];\n private errorTranslatorValue?: McpErrorTranslators;\n private maxAccountValidationAgeSecondsValue = MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS;\n private maxEndpointJwtLifetimeSecondsValue = MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS;\n\n /** REQUIRED. The MCP server name reported by `initialize`. */\n setName(name: string): this {\n this.nameValue = this.requireText(name, 'setName');\n return this;\n }\n\n /** REQUIRED. The MCP server version; the registry revision is appended to it at bind time. */\n setVersion(version: string): this {\n this.versionValue = this.requireText(version, 'setVersion');\n return this;\n }\n\n /**\n * REQUIRED. The ONE canonical protected-resource URI, which must be an absolute URL: it is the\n * exact audience every access token is checked against, and {@link resourceMetadataUrl} is\n * derived from it for the 401 challenge, so a non-URL here is always a mistake — including a\n * name or version landed on it.\n *\n * It is fixed for the lifetime of the process and must NEVER be derived from the request `Host`\n * header: the boundary compares a token's audience against this value, so a host-derived\n * resource compares two values both taken from caller-controlled input — the confused-deputy\n * shape this check exists to prevent. Its path must equal `McpBindOptions.endpointPath`, which\n * `WpMcpServer.bind(...)` verifies. A second hostname is a second deployment, not a second\n * audience.\n */\n setResource(resource: string): this {\n this.resourceValue = this.requireUrl(resource, 'setResource');\n return this;\n }\n\n /** REQUIRED. Application-owned paired mint/verify authority for MCP access tokens. */\n setAccessTokenAuthority(authority: McpAccessTokenAuthority<TGrant>): this {\n this.accessTokenAuthorityValue = this.requirePresent(authority, 'setAccessTokenAuthority');\n return this;\n }\n\n /** REQUIRED. The `JwtHook` minting the short-lived per-endpoint JWT for local bindings. */\n setEndpointJwtAuthority(authority: JwtHook<TMintRequest>): this {\n this.endpointJwtAuthorityValue = this.requirePresent(authority, 'setEndpointJwtAuthority');\n return this;\n }\n\n /** REQUIRED. Maps a verified MCP identity plus tool identity to that JwtHook's mint request. */\n setEndpointMintRequest(factory: McpEndpointMintRequestFactory<TMintRequest>): this {\n if (typeof factory !== 'function') {\n throw new Error('WpMcpServerConfig.setEndpointMintRequest(...) requires a function.');\n }\n this.endpointMintRequestValue = factory;\n return this;\n }\n\n /**\n * REQUIRED. The trusted token issuers. Every entry must be an absolute URL, because each is\n * compared against a token's `issuer` claim and published as an `authorization_servers` entry —\n * which is what makes a scope list landed here fail at boot rather than on the first request.\n */\n setAuthorizationServers(authorizationServers: readonly string[]): this {\n const servers = this.requireArray(authorizationServers, 'setAuthorizationServers');\n if (servers.length === 0) {\n throw new Error(\n 'WpMcpServerConfig.setAuthorizationServers(...) requires at least one issuer URL.',\n );\n }\n for (const server of servers) this.requireUrl(server, 'setAuthorizationServers');\n this.authorizationServersValue = servers;\n return this;\n }\n\n /**\n * REQUIRED, and empty only by saying so explicitly. Scopes every access token must carry before\n * any tool is dispatched.\n */\n setRequiredScopes(requiredScopes: readonly string[]): this {\n const scopes = this.requireArray(requiredScopes, 'setRequiredScopes');\n for (const scope of scopes) this.requireText(scope, 'setRequiredScopes');\n this.requiredScopesValue = scopes;\n return this;\n }\n\n /**\n * OPTIONAL. The application's `tools/call` error translator — it REPLACES the webpieces default\n * for every tool failure, owning the ENTIRE result, and declines by delegating to\n * `new McpDefaultToolCallRenderer().toToolCallResult(error)`. See {@link McpErrorTranslators}.\n */\n setErrorTranslator(translators: McpErrorTranslators): this {\n const value = this.requirePresent(translators, 'setErrorTranslator');\n if (typeof value.toToolCallResult !== 'function') {\n throw new Error(\n 'WpMcpServerConfig.setErrorTranslator(...) requires a toToolCallResult(error) method.',\n );\n }\n this.errorTranslatorValue = value;\n return this;\n }\n\n /** OPTIONAL ceiling, 1 second to 1 hour. Defaults to 1 hour. */\n setMaxAccountValidationAgeSeconds(seconds: number): this {\n this.maxAccountValidationAgeSecondsValue = this.requireSeconds(\n seconds,\n MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS,\n 'setMaxAccountValidationAgeSeconds',\n );\n return this;\n }\n\n /** OPTIONAL ceiling, 1 second to 1 hour. Defaults to 1 hour. */\n setMaxEndpointJwtLifetimeSeconds(seconds: number): this {\n this.maxEndpointJwtLifetimeSecondsValue = this.requireSeconds(\n seconds,\n MAX_MCP_ENDPOINT_JWT_LIFETIME_SECONDS,\n 'setMaxEndpointJwtLifetimeSeconds',\n );\n return this;\n }\n\n /**\n * Called by `WpMcpServer.bind(...)`. Throws naming EVERY missing required setter at once, so a\n * half-built config is repaired in one pass rather than one boot failure at a time.\n */\n validate(): void {\n const missing: string[] = [];\n if (this.nameValue === undefined) missing.push('setName(...)');\n if (this.versionValue === undefined) missing.push('setVersion(...)');\n if (this.resourceValue === undefined) missing.push('setResource(...)');\n if (this.accessTokenAuthorityValue === undefined) {\n missing.push('setAccessTokenAuthority(...)');\n }\n if (this.endpointJwtAuthorityValue === undefined) {\n missing.push('setEndpointJwtAuthority(...)');\n }\n if (this.endpointMintRequestValue === undefined) {\n missing.push('setEndpointMintRequest(...)');\n }\n if (this.authorizationServersValue === undefined) {\n missing.push('setAuthorizationServers(...)');\n }\n if (this.requiredScopesValue === undefined) missing.push('setRequiredScopes(...)');\n if (missing.length > 0) {\n throw new Error(`WpMcpServerConfig is missing ${missing.join(', ')}`);\n }\n }\n\n get name(): string {\n return this.read(this.nameValue, 'setName');\n }\n\n get version(): string {\n return this.read(this.versionValue, 'setVersion');\n }\n\n get resource(): string {\n return this.read(this.resourceValue, 'setResource');\n }\n\n get accessTokenAuthority(): McpAccessTokenAuthority<TGrant> {\n return this.read(this.accessTokenAuthorityValue, 'setAccessTokenAuthority');\n }\n\n get endpointJwtAuthority(): JwtHook<TMintRequest> {\n return this.read(this.endpointJwtAuthorityValue, 'setEndpointJwtAuthority');\n }\n\n get endpointMintRequest(): McpEndpointMintRequestFactory<TMintRequest> {\n return this.read(this.endpointMintRequestValue, 'setEndpointMintRequest');\n }\n\n get authorizationServers(): readonly string[] {\n return this.read(this.authorizationServersValue, 'setAuthorizationServers');\n }\n\n get requiredScopes(): readonly string[] {\n return this.read(this.requiredScopesValue, 'setRequiredScopes');\n }\n\n /** `undefined` when the app registered none: webpieces then renders every tool failure. */\n get errorTranslator(): McpErrorTranslators | undefined {\n return this.errorTranslatorValue;\n }\n\n get maxAccountValidationAgeSeconds(): number {\n return this.maxAccountValidationAgeSecondsValue;\n }\n\n get maxEndpointJwtLifetimeSeconds(): number {\n return this.maxEndpointJwtLifetimeSecondsValue;\n }\n\n /**\n * RFC 9728 §3.1: the URL of this resource's protected-resource METADATA DOCUMENT, derived from\n * {@link resource} by inserting `/.well-known/oauth-protected-resource` between origin and path\n * (`https://host/mcp` → `https://host/.well-known/oauth-protected-resource/mcp`).\n *\n * This — never the resource identifier itself — is what RFC 9728 §5.1 defines `resource_metadata`\n * to be, so it is the value webpieces puts in the 401 `WWW-Authenticate` challenge. webpieces\n * mounts no `.well-known` route; publish {@link protectedResourceMetadata} at this URL.\n */\n get resourceMetadataUrl(): string {\n const url = new URL(this.resource);\n const path = url.pathname === '/' ? '' : url.pathname;\n return `${url.origin}/.well-known/oauth-protected-resource${path}`;\n }\n\n protectedResourceMetadata(): McpProtectedResourceMetadata {\n return new McpProtectedResourceMetadata(\n this.resource,\n this.authorizationServers,\n this.requiredScopes,\n );\n }\n\n private requireText(value: string, setter: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires a non-empty string.`);\n }\n return value;\n }\n\n private requireUrl(value: string, setter: string): string {\n this.requireText(value, setter);\n if (!URL.canParse(value)) {\n throw new Error(\n `WpMcpServerConfig.${setter}(...) requires an absolute URL, got '${value}'.`,\n );\n }\n return value;\n }\n\n private requireArray(value: readonly string[], setter: string): readonly string[] {\n if (!Array.isArray(value)) {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires an array of strings.`);\n }\n return value;\n }\n\n private requireSeconds(value: number, ceiling: number, setter: string): number {\n if (!Number.isFinite(value) || value <= 0 || value > ceiling) {\n throw new Error(\n `WpMcpServerConfig.${setter}(...) requires 1..${ceiling} seconds, got ${String(value)}.`,\n );\n }\n return value;\n }\n\n private requirePresent<T>(value: T, setter: string): T {\n if (value === undefined || value === null) {\n throw new Error(`WpMcpServerConfig.${setter}(...) requires a value.`);\n }\n return value;\n }\n\n private read<T>(value: T | undefined, setter: string): T {\n if (value === undefined) {\n throw new Error(`WpMcpServerConfig is missing ${setter}(...)`);\n }\n return value;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { CallToolResult, ProtocolError } from '@modelcontextprotocol/server';
2
- import { Response } from 'express';
2
+ import { ContextKey, HttpResponseDto } from '@webpieces/core-util';
3
3
  /** `_meta` key carrying the Webpieces requestId on every tools/call result, success or failure. */
4
4
  export declare const MCP_REQUEST_ID_META_KEY = "webpieces/requestId";
5
5
  /** JSON-RPC error `data` so a user can quote the requestId of any protocol-level failure. */
@@ -7,39 +7,27 @@ export declare class McpErrorData {
7
7
  readonly requestId: string;
8
8
  constructor(requestId: string);
9
9
  }
10
- /** Correlation facts for one failure; rendered into the single operator log line. */
11
- export declare class McpFailureScope {
12
- readonly requestId: string;
13
- readonly jsonRpcId: string | number | null;
14
- readonly method: string;
15
- readonly toolName?: string | undefined;
16
- constructor(requestId: string, jsonRpcId: string | number | null, method: string, toolName?: string | undefined);
17
- describe(): string;
18
- }
19
10
  /**
20
- * The application's own `tools/call` error translation — the MCP twin of the `ErrorTranslators` that
21
- * `ExpressWrapper.handleError` consults through `ClientRegistry.tryTranslateToWire` on the HTTP path.
22
- * Register one with `WpMcpServerConfig.setErrorTranslator(...)`; it is NOT a global, because
23
- * `WpMcpServer` is constructed by app code and two servers may run in one process.
24
- *
25
- * An app owns its error taxonomy and owns how those errors should be explained to a model, so a
26
- * claimed error yields the ENTIRE `CallToolResult` — content, `structuredContent`, `isError`, the lot.
11
+ * The two per-request facts a renderer needs that are NOT the error: the JSON-RPC `id` it must echo,
12
+ * and the tool being called. They are stamped into the request scope by `WpMcpServer` rather than
13
+ * threaded through every renderer signature, because `requestId` already travels that way
14
+ * ({@link WebpiecesCoreHeaders.REQUEST_ID}) and a second, parallel correlation parameter was a COPY
15
+ * of the context — which is what the deleted `McpFailureScope` was.
27
16
  *
28
- * Contract:
29
- * - `error` is the RAW thrown value: an app must be able to `instanceof` its own error classes.
30
- * `ApiErrorBoundary` never substitutes an object for the thrown error, so there is exactly one
31
- * error value on this path.
32
- * - return `undefined` for "not mine" — webpieces then renders its own default, unchanged.
33
- * - webpieces default-fills `_meta['webpieces/requestId']` only when the returned result has NO
34
- * `_meta`. An app that sets `_meta` owns it untouched.
35
- * - operator-detail logging has ALREADY happened when this is called, so claiming an error can never
36
- * silently kill observability.
37
- * - scope is `tools/call` ONLY. The pre-SDK HTTP boundary and `tools/list` stay framework-owned:
38
- * that boundary emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` MCP clients
39
- * depend on for OAuth discovery, and an app rewriting it breaks connector onboarding.
17
+ * Context-only and never logged: the logging backends read `RequestContext` for correlation on every
18
+ * record already, and this object exists purely so the renderers can be one-argument functions.
40
19
  */
41
- export interface McpErrorTranslators {
42
- toToolResult(error: Error, scope: McpFailureScope): CallToolResult | undefined;
20
+ export declare class McpCorrelation {
21
+ readonly jsonRpcId: string | number | null;
22
+ readonly toolName?: string | undefined;
23
+ static readonly KEY: ContextKey<McpCorrelation, "untrusted">;
24
+ constructor(jsonRpcId: string | number | null, toolName?: string | undefined);
25
+ /** Stamp what this request knows so far; `WpMcpServer` re-stamps once the tool name is known. */
26
+ static stamp(correlation: McpCorrelation): void;
27
+ /** A renderer reached before anything stamped (a failure with no parseable body) still renders. */
28
+ static current(): McpCorrelation;
29
+ /** The webpieces requestId of the request being served, as every MCP reply reports it. */
30
+ static requestId(): string;
43
31
  }
44
32
  /** The only error shape rendered into model-visible MCP tool content. */
45
33
  export declare class ModelVisibleToolError {
@@ -67,52 +55,112 @@ export declare class McpHttpErrorDetail {
67
55
  constructor(code: number, message: string, data: McpErrorData);
68
56
  }
69
57
  /**
70
- * The ONE place every MCP failure is mapped to a reply, mirroring `ApiErrorHttpMapper` for HTTP.
71
- * Each MCP entry point (the bind HTTP handler, tools/list, tools/call) has exactly one catch that
72
- * only delegates here. Classification and per-kind log levels are the shared `ApiErrorBoundary`
73
- * rules, and published text comes only from `ApiErrorBoundary.encode`: this class never puts an
74
- * error's own message on the wire unless it is an `ApiEndUserError`.
58
+ * The application's own `tools/call` error translation — the MCP twin of the `ErrorTranslators` an
59
+ * app registers on `ClientRegistry` for the HTTP path. Register one with
60
+ * `WpMcpServerConfig.setErrorTranslator(...)`; it is NOT a global, because `WpMcpServer` is
61
+ * constructed by app code and two servers may run in one process.
62
+ *
63
+ * An app owns its error taxonomy and owns how those errors should be explained to a model, so a
64
+ * claimed error yields the ENTIRE `CallToolResult` — content, `structuredContent`, `isError`, the lot.
65
+ *
66
+ * Contract:
67
+ * - `error` is the RAW thrown value: an app must be able to `instanceof` its own error classes.
68
+ * `ApiErrorBoundary` never substitutes an object for the thrown error, so there is exactly one
69
+ * error value on this path.
70
+ * - There is no "not mine" return. A registered translator REPLACES the webpieces default and
71
+ * declines by DELEGATING to it: `new McpDefaultToolCallRenderer().toToolCallResult(error)`.
72
+ * - webpieces default-fills `_meta['webpieces/requestId']` only when the returned result has NO
73
+ * `_meta`. An app that sets `_meta` owns it untouched.
74
+ * - scope is `tools/call` ONLY. The pre-SDK HTTP boundary and `tools/list` stay framework-owned:
75
+ * that boundary emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` MCP clients
76
+ * depend on for OAuth discovery, and an app rewriting it breaks connector onboarding.
77
+ */
78
+ export interface McpErrorTranslators {
79
+ toToolCallResult(error: Error): CallToolResult;
80
+ }
81
+ /**
82
+ * webpieces' DEFAULT `tools/call` rendering, as a public class so an app's own
83
+ * {@link McpErrorTranslators} can DECLINE an error by delegating to it — the MCP twin of
84
+ * `ApiErrorHttpMapper.toResponse` on the HTTP side.
85
+ *
86
+ * Published text comes only from {@link ApiErrorBoundary.encode}: this never puts an error's own
87
+ * message in front of a model unless it is an `ApiEndUserError`.
88
+ */
89
+ export declare class McpDefaultToolCallRenderer implements McpErrorTranslators {
90
+ private readonly boundary;
91
+ toToolCallResult(error: Error): CallToolResult;
92
+ private modelVisible;
93
+ }
94
+ /**
95
+ * The ONE place every MCP failure becomes a reply, mirroring `ApiErrorHttpMapper` for HTTP: an error
96
+ * in, the exact wire shape out. There is one method per BOUNDARY, and the MCP spec is what makes
97
+ * them three rather than one:
98
+ *
99
+ * | Boundary | Who writes HTTP | Failure shape |
100
+ * |--------------------------------|-----------------|-------------------------------------|
101
+ * | pre-SDK bearer / Origin / body | **webpieces** | `HttpResponseDto<McpHttpErrorBody>` |
102
+ * | `tools/list` | the SDK | `throw ProtocolError` |
103
+ * | `tools/call` | the SDK | `CallToolResult` with `isError` |
104
+ *
105
+ * Classification and published text are the shared {@link ApiErrorBoundary} rules. Operator logging
106
+ * is NOT here: `LogApiCall` wraps each of those boundaries in `WpMcpServer`, so every failure gets
107
+ * exactly one `[API-server-resp-*]` line with the request and the identity on it.
75
108
  */
76
109
  export declare class WpMcpErrorTranslator {
110
+ private readonly challenge;
77
111
  private readonly appTranslators?;
78
112
  private readonly boundary;
79
- /** `appTranslators` is the app's `tools/call` seam; `undefined` means webpieces renders all. */
80
- constructor(appTranslators?: McpErrorTranslators | undefined);
113
+ private readonly defaultToolCall;
81
114
  /**
82
- * Pre-SDK failures: 401 + WWW-Authenticate, 403, 400 (-32700), anything else 500 (-32603).
83
- * A failure after response headers were sent can only end the stream.
115
+ * @param challenge - the `WWW-Authenticate` value for a 401, read lazily because
116
+ * `WpMcpServerConfig` is only fully validated at `bind(...)` time.
117
+ * @param appTranslators - the app's `tools/call` seam; `undefined` means webpieces renders all.
84
118
  */
85
- toHttp(thrown: Error, res: Response, scope: McpFailureScope, wwwAuthenticate: string): void;
86
- /** Express body-parser failures (malformed JSON, body too large) are caller input errors. */
87
- toHttpBodyFailure(cause: Error, res: Response, scope: McpFailureScope, wwwAuth: string): void;
88
- /** tools/list and other result-less methods: bad-request → -32602, anything else → -32603. */
89
- toProtocolError(thrown: Error, scope: McpFailureScope): ProtocolError;
119
+ constructor(challenge: () => string, appTranslators?: McpErrorTranslators | undefined);
120
+ /**
121
+ * Boundary #1: everything webpieces itself rejects before the SDK is involved — bearer
122
+ * verification, `Origin`, a malformed body. This is 401/403/400/500 today and any status
123
+ * tomorrow, so it produces a VALUE like every other API in the framework and `WpMcpServer` hands
124
+ * it to the shared express writer. The BODY stays JSON-RPC shaped because an MCP client expects
125
+ * that; `HttpResponseDto` is generic, and its header LIST carries `WWW-Authenticate`.
126
+ */
127
+ toBearerBoundaryResponse(error: Error): HttpResponseDto<McpHttpErrorBody>;
128
+ /**
129
+ * Boundary #2: `tools/list` has no tool-result channel, so a failure IS a JSON-RPC error. It
130
+ * THROWS rather than returning a value the caller must remember to throw, and is typed `never`
131
+ * so the compiler knows the call is terminal.
132
+ *
133
+ * This is LOAD-BEARING for disclosure, not defence in depth. Measured on
134
+ * `@modelcontextprotocol/server` 2.0.0 and pinned by `McpSdkForeignThrow.spec.ts`: the SDK wraps
135
+ * a foreign (non-`ProtocolError`) throw in `-32603` but copies its `message` onto the wire
136
+ * VERBATIM. So a `tools/list` handler that lets any error escape un-translated publishes that
137
+ * error's operator text to the caller.
138
+ */
139
+ toListError(error: Error): never;
90
140
  /** tools/call with a name no binding registered: a JSON-RPC protocol error per MCP 2026-07-28. */
91
- unknownTool(toolName: string, scope: McpFailureScope): ProtocolError;
141
+ unknownTool(toolName: string): ProtocolError;
92
142
  /**
93
- * Every tools/call failure after the tool is found: an `isError: true` result the model sees.
143
+ * Boundary #3: every tools/call failure after the tool is found — an `isError: true` result the
144
+ * model sees.
94
145
  *
95
- * The app's {@link McpErrorTranslators} gets FIRST REFUSAL — the same convention
96
- * `ExpressWrapper.handleError` applies on the HTTP path — and owns the entire result it claims.
97
- * Operator-detail logging runs BEFORE it, so exactly one operator line is written per failure
98
- * whoever renders the reply.
146
+ * A registered {@link McpErrorTranslators} REPLACES the default and declines by delegating to
147
+ * {@link McpDefaultToolCallRenderer}, so "no translator registered" and "a translator that does
148
+ * not claim this error" produce byte-identical results.
99
149
  */
100
- toToolResult(thrown: Error, scope: McpFailureScope): CallToolResult;
150
+ toToolCallResult(failure: Error): CallToolResult;
101
151
  /** The `_meta` every tools/call result carries so a user can quote its requestId. */
102
152
  resultMeta(requestId: string): Record<string, string>;
103
153
  /**
104
- * The app's first refusal. A translator that THROWS must not replace the failure being reported:
105
- * the throw is reported through the same boundary as its own implementation failure and the
106
- * ORIGINAL error still renders through the webpieces default, so the model still gets a reply
107
- * carrying the requestId.
154
+ * An app translator that THROWS must not replace the failure being reported: its own bug is
155
+ * logged here and the ORIGINAL error still renders through the webpieces default, so the model
156
+ * still gets a reply carrying the requestId.
108
157
  */
109
- private appToolResult;
158
+ private appOrDefault;
110
159
  /**
111
160
  * webpieces fills `_meta` only when the app left it off, keeping the README's "every reply
112
161
  * carries the requestId" promise a DEFAULT rather than a restriction: an app that set `_meta`
113
162
  * keeps it byte-for-byte.
114
163
  */
115
164
  private withDefaultMeta;
116
- private modelVisible;
117
- private writeHttp;
165
+ private httpError;
118
166
  }