@webpieces/mcp-server 0.4.961 → 0.4.962
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/package.json +6 -6
- package/src/McpProtocol.d.ts +15 -0
- package/src/McpProtocol.js +20 -0
- package/src/McpProtocol.js.map +1 -0
- package/src/McpToolCallRendering.d.ts +11 -1
- package/src/McpToolCallRendering.js +13 -4
- package/src/McpToolCallRendering.js.map +1 -1
- package/src/WpMcpServer.js +5 -4
- package/src/WpMcpServer.js.map +1 -1
- package/src/index.d.ts +1 -0
- package/src/index.js +3 -1
- package/src/index.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/mcp-server",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.962",
|
|
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.
|
|
28
|
-
"@webpieces/core-util": "0.4.
|
|
29
|
-
"@webpieces/http-routing": "0.4.
|
|
30
|
-
"@webpieces/http-server": "0.4.
|
|
27
|
+
"@webpieces/core-context": "0.4.962",
|
|
28
|
+
"@webpieces/core-util": "0.4.962",
|
|
29
|
+
"@webpieces/http-routing": "0.4.962",
|
|
30
|
+
"@webpieces/http-server": "0.4.962",
|
|
31
31
|
"express": "5.1.0",
|
|
32
32
|
"reflect-metadata": "0.2.2",
|
|
33
33
|
"tslib": "2.8.1"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@webpieces/http-client-node": "0.4.
|
|
36
|
+
"@webpieces/http-client-node": "0.4.962"
|
|
37
37
|
}
|
|
38
38
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The framework-owned contract CLASS for MCP protocol steps — `initialize`, `tools/list`, the HTTP
|
|
3
|
+
* edge, and a `tools/call` that failed before its tool was resolved. Those steps have no user
|
|
4
|
+
* contract, but an `ApiMethodInfo` / `CallContext` always names a contract CLASS (#1350), so they name
|
|
5
|
+
* this one. Nothing is registered for it by default, so they reach the `ALL` rung of the `CallScope`
|
|
6
|
+
* ladder; an app that wants MCP-protocol-specific classification registers for this class:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* ClientRegistry.setErrorClassifier(new MyMcpProtocolClassifier(), McpProtocol);
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* A `tools/call` whose tool WAS resolved names the tool's bound `@ApiPath` contract instead.
|
|
13
|
+
*/
|
|
14
|
+
export declare abstract class McpProtocol {
|
|
15
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.McpProtocol = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* The framework-owned contract CLASS for MCP protocol steps — `initialize`, `tools/list`, the HTTP
|
|
6
|
+
* edge, and a `tools/call` that failed before its tool was resolved. Those steps have no user
|
|
7
|
+
* contract, but an `ApiMethodInfo` / `CallContext` always names a contract CLASS (#1350), so they name
|
|
8
|
+
* this one. Nothing is registered for it by default, so they reach the `ALL` rung of the `CallScope`
|
|
9
|
+
* ladder; an app that wants MCP-protocol-specific classification registers for this class:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* ClientRegistry.setErrorClassifier(new MyMcpProtocolClassifier(), McpProtocol);
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* A `tools/call` whose tool WAS resolved names the tool's bound `@ApiPath` contract instead.
|
|
16
|
+
*/
|
|
17
|
+
class McpProtocol {
|
|
18
|
+
}
|
|
19
|
+
exports.McpProtocol = McpProtocol;
|
|
20
|
+
//# sourceMappingURL=McpProtocol.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"McpProtocol.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/McpProtocol.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;GAYG;AACH,MAAsB,WAAW;CAAG;AAApC,kCAAoC","sourcesContent":["/**\n * The framework-owned contract CLASS for MCP protocol steps — `initialize`, `tools/list`, the HTTP\n * edge, and a `tools/call` that failed before its tool was resolved. Those steps have no user\n * contract, but an `ApiMethodInfo` / `CallContext` always names a contract CLASS (#1350), so they name\n * this one. Nothing is registered for it by default, so they reach the `ALL` rung of the `CallScope`\n * ladder; an app that wants MCP-protocol-specific classification registers for this class:\n *\n * ```ts\n * ClientRegistry.setErrorClassifier(new MyMcpProtocolClassifier(), McpProtocol);\n * ```\n *\n * A `tools/call` whose tool WAS resolved names the tool's bound `@ApiPath` contract instead.\n */\nexport abstract class McpProtocol {}\n"]}
|
|
@@ -19,10 +19,20 @@ export declare class McpErrorData {
|
|
|
19
19
|
*/
|
|
20
20
|
export declare class McpCorrelation {
|
|
21
21
|
readonly jsonRpcId: string | number | null;
|
|
22
|
+
/**
|
|
23
|
+
* The contract CLASS this request is classified under: the resolved tool's bound `@ApiPath`
|
|
24
|
+
* contract, or {@link McpProtocol} while no tool is resolved (a protocol step, an unknown tool).
|
|
25
|
+
*/
|
|
26
|
+
readonly contract: Function;
|
|
22
27
|
readonly toolName?: string | undefined;
|
|
23
28
|
readonly operation?: EndpointOperation | undefined;
|
|
24
29
|
static readonly KEY: ContextKey<McpCorrelation, "untrusted">;
|
|
25
|
-
constructor(jsonRpcId: string | number | null,
|
|
30
|
+
constructor(jsonRpcId: string | number | null,
|
|
31
|
+
/**
|
|
32
|
+
* The contract CLASS this request is classified under: the resolved tool's bound `@ApiPath`
|
|
33
|
+
* contract, or {@link McpProtocol} while no tool is resolved (a protocol step, an unknown tool).
|
|
34
|
+
*/
|
|
35
|
+
contract: Function, toolName?: string | undefined, operation?: EndpointOperation | undefined);
|
|
26
36
|
/** Stamp what this request knows so far; `WpMcpServer` re-stamps once the tool name is known. */
|
|
27
37
|
static stamp(correlation: McpCorrelation): void;
|
|
28
38
|
/** A renderer reached before anything stamped (a failure with no parseable body) still renders. */
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.McpDefaultToolCallRenderer = exports.McpHttpErrorDetail = exports.McpHttpErrorBody = exports.ModelVisibleToolErrorEnvelope = exports.ModelVisibleToolError = exports.McpCorrelation = exports.McpErrorData = exports.MCP_REQUEST_ID_META_KEY = void 0;
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
5
|
const core_context_1 = require("@webpieces/core-context");
|
|
6
|
+
const McpProtocol_1 = require("./McpProtocol");
|
|
6
7
|
/** `_meta` key carrying the Webpieces requestId on every tools/call result, success or failure. */
|
|
7
8
|
exports.MCP_REQUEST_ID_META_KEY = 'webpieces/requestId';
|
|
8
9
|
/** JSON-RPC error `data` so a user can quote the requestId of any protocol-level failure. */
|
|
@@ -25,13 +26,20 @@ exports.McpErrorData = McpErrorData;
|
|
|
25
26
|
*/
|
|
26
27
|
class McpCorrelation {
|
|
27
28
|
jsonRpcId;
|
|
29
|
+
contract;
|
|
28
30
|
toolName;
|
|
29
31
|
operation;
|
|
30
32
|
// webpieces-disable no-any-unknown -- ContextKey value types are per-key; this one is context-only
|
|
31
33
|
static KEY = core_util_1.ContextKey.untrusted('webpieces-mcp-correlation', undefined, false,
|
|
32
34
|
/*isLogged*/ false);
|
|
33
|
-
constructor(jsonRpcId,
|
|
35
|
+
constructor(jsonRpcId,
|
|
36
|
+
/**
|
|
37
|
+
* The contract CLASS this request is classified under: the resolved tool's bound `@ApiPath`
|
|
38
|
+
* contract, or {@link McpProtocol} while no tool is resolved (a protocol step, an unknown tool).
|
|
39
|
+
*/
|
|
40
|
+
contract, toolName, operation) {
|
|
34
41
|
this.jsonRpcId = jsonRpcId;
|
|
42
|
+
this.contract = contract;
|
|
35
43
|
this.toolName = toolName;
|
|
36
44
|
this.operation = operation;
|
|
37
45
|
}
|
|
@@ -43,7 +51,7 @@ class McpCorrelation {
|
|
|
43
51
|
/** A renderer reached before anything stamped (a failure with no parseable body) still renders. */
|
|
44
52
|
// webpieces-disable no-function-outside-class -- static accessor trio for one context key
|
|
45
53
|
static current() {
|
|
46
|
-
return core_context_1.RequestContext.getUntrusted(McpCorrelation.KEY) ?? new McpCorrelation(null);
|
|
54
|
+
return core_context_1.RequestContext.getUntrusted(McpCorrelation.KEY) ?? new McpCorrelation(null, McpProtocol_1.McpProtocol);
|
|
47
55
|
}
|
|
48
56
|
/** The webpieces requestId of the request being served, as every MCP reply reports it. */
|
|
49
57
|
// webpieces-disable no-function-outside-class -- static accessor trio for one context key
|
|
@@ -143,8 +151,9 @@ class McpDefaultToolCallRenderer {
|
|
|
143
151
|
if (payload.kind === 'implementation') {
|
|
144
152
|
return this.bug(payload, requestId, support);
|
|
145
153
|
}
|
|
146
|
-
const
|
|
147
|
-
const
|
|
154
|
+
const correlation = McpCorrelation.current();
|
|
155
|
+
const toolName = correlation.toolName ?? 'unknown';
|
|
156
|
+
const methodInfo = new core_util_1.ApiMethodInfo('server', 'WpMcpServer', toolName, correlation.contract);
|
|
148
157
|
if (core_util_1.ClientRegistry.classify(error, methodInfo) === core_util_1.CallOutcome.TRANSIENT_FAILURE) {
|
|
149
158
|
return this.transient(payload, requestId, this.transientMessage(payload));
|
|
150
159
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpToolCallRendering.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/McpToolCallRendering.ts"],"names":[],"mappings":";;;AACA,oDAU8B;AAC9B,0DAAyD;AAEzD,mGAAmG;AACtF,QAAA,uBAAuB,GAAG,qBAAqB,CAAC;AAE7D,6FAA6F;AAC7F,MAAa,Y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AG,cAAc,CAAC,OAAO,EAAE,CAAC,SAAS,IAAI,OAAO,CAAC;QAChE,IAAI,SAAS,KAAK,OAAO,EAAE,CAAC;YACxB,OAAO,IAAI,CAAC,OAAO,CACf,OAAO,EACP,SAAS,EACT,WAAW,EACX,wBAAwB,EACxB,GAAG,OAAO,+GAA+G,CAC5H,CAAC;QACN,CAAC;QACD,MAAM,KAAK,GAAG,OAAO,CAAC,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC;QAC/E,OAAO,IAAI,CAAC,OAAO,CACf,OAAO,EACP,SAAS,EACT,WAAW,EACX,KAAK,EACL,GAAG,OAAO,qBAAqB,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,wBAAwB,OAAO,CAAC,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,UAAU,OAAO,CAAC,iBAAiB,UAAU,GAAG,CACxN,CAAC;IACN,CAAC;IAEO,OAAO,CACX,OAAwB,EACxB,SAAiB,EACjB,QAA2C,EAC3C,KAAqC,EACrC,OAAe;QAEf,OAAO,IAAI,qBAAqB,CAC5B,OAAO,CAAC,IAAI,EACZ,QAAQ,EACR,KAAK,EACL,OAAO,EACP,SAAS,EACT,OAAO,CAAC,KAAK,EACb,OAAO,CAAC,aAAa,EACrB,OAAO,CAAC,SAAS,EACjB,OAAO,CAAC,iBAAiB,EACzB,OAAO,CAAC,UAAU,CACrB,CAAC;IACN,CAAC;CACJ;AAlOD,gEAkOC","sourcesContent":["import { CallToolResult } from '@modelcontextprotocol/server';\nimport {\n ApiErrorBoundary,\n ApiErrorPayload,\n ApiMethodInfo,\n CallOutcome,\n ClientRegistry,\n ContextKey,\n DtoValue,\n EndpointOperation,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\n\n/** `_meta` key carrying the Webpieces requestId on every tools/call result, success or failure. */\nexport const MCP_REQUEST_ID_META_KEY = 'webpieces/requestId';\n\n/** JSON-RPC error `data` so a user can quote the requestId of any protocol-level failure. */\nexport class McpErrorData {\n constructor(public readonly requestId: string) {}\n}\n\n/**\n * The two per-request facts a renderer needs that are NOT the error: the JSON-RPC `id` it must echo,\n * and the tool being called. They are stamped into the request scope by `WpMcpServer` rather than\n * threaded through every renderer signature, because `requestId` already travels that way\n * ({@link WebpiecesCoreHeaders.REQUEST_ID}) and a second, parallel correlation parameter was a COPY\n * of the context — which is what the deleted `McpFailureScope` was.\n *\n * Context-only and never logged: the logging backends read `RequestContext` for correlation on every\n * record already, and this object exists purely so the renderers can be one-argument functions.\n */\nexport class McpCorrelation {\n // webpieces-disable no-any-unknown -- ContextKey value types are per-key; this one is context-only\n static readonly KEY = ContextKey.untrusted<McpCorrelation>(\n 'webpieces-mcp-correlation',\n undefined,\n false,\n /*isLogged*/ false,\n );\n\n constructor(\n public readonly jsonRpcId: string | number | null,\n public readonly toolName?: string,\n public readonly operation?: EndpointOperation,\n ) {}\n\n /** Stamp what this request knows so far; `WpMcpServer` re-stamps once the tool name is known. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static stamp(correlation: McpCorrelation): void {\n RequestContext.putUntrusted(McpCorrelation.KEY, correlation);\n }\n\n /** A renderer reached before anything stamped (a failure with no parseable body) still renders. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static current(): McpCorrelation {\n return RequestContext.getUntrusted(McpCorrelation.KEY) ?? new McpCorrelation(null);\n }\n\n /** The webpieces requestId of the request being served, as every MCP reply reports it. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static requestId(): string {\n return RequestContext.getUntrusted(WebpiecesCoreHeaders.REQUEST_ID) ?? 'missing-request-id';\n }\n}\n\n/** The only error shape rendered into model-visible MCP tool content. */\nexport class ModelVisibleToolError {\n constructor(\n public readonly kind: string,\n public readonly category: 'bug' | 'caller' | 'dependency' | 'temporary' | 'access',\n public readonly retry:\n | 'never'\n | 'after-correction'\n | 'after-delay'\n | 'safe'\n | 'unsafe-outcome-unknown',\n public readonly message: string,\n public readonly requestId: string,\n public readonly field?: string,\n public readonly callerMessage?: string,\n public readonly errorCode?: string,\n public readonly retryAfterSeconds?: number,\n public readonly statusCode?: number,\n ) {}\n}\n\n/** Explicit content-level envelope for clients that hide CallToolResult.isError. */\nexport class ModelVisibleToolErrorEnvelope {\n constructor(public readonly error: ModelVisibleToolError) {}\n}\n\n/** JSON-RPC error body written by the HTTP boundary before the SDK is involved. */\nexport class McpHttpErrorBody {\n readonly jsonrpc = '2.0';\n constructor(\n public readonly error: McpHttpErrorDetail,\n public readonly id: string | number | null,\n ) {}\n}\n\nexport class McpHttpErrorDetail {\n constructor(\n public readonly code: number,\n public readonly message: string,\n public readonly data: McpErrorData,\n ) {}\n}\n\n/**\n * The application's own `tools/call` error translation — the MCP twin of the `ErrorTranslator` an app\n * registers on `ClientRegistry` for HTTP and the `IpcErrorTranslator` it registers on `IpcRegistry`.\n * Register one with {@link McpRegistry.setErrorTranslator}.\n *\n * An app owns its error taxonomy and owns how those errors should be explained to a model, so a\n * claimed error yields the ENTIRE `CallToolResult` — content, `structuredContent`, `isError`, the lot.\n *\n * # There is NO `fromWire`, and that is the protocol, not an oversight\n *\n * The HTTP and IPC translators have two halves because webpieces sits on BOTH ends of those wires: it\n * writes the response AND, in another process, reads one. **webpieces is never the MCP client.** The\n * client is Claude (or another model host); there is no return path for webpieces to translate, so\n * the pair is one-directional by nature. Do not \"restore the symmetry\" by adding a half with nothing\n * to call it.\n *\n * # The pre-SDK boundary does NOT share the HTTP `ErrorTranslator`, despite the identical type\n *\n * `WpMcpErrorTranslator.toBearerBoundaryResponse` returns an `HttpResponseDto`, exactly like\n * `ErrorTranslator.toWire` — and it must STILL not be routed through it. Two reasons, both hard:\n *\n * - its body must stay JSON-RPC shaped (`McpHttpErrorBody`) or an MCP client cannot parse the reply\n * at all, whereas an app's HTTP translator publishes the app's own REST envelope;\n * - it emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` that MCP clients use for OAuth\n * discovery, so an app rewriting it breaks connector onboarding.\n *\n * Same TYPE, different OWNER. `tools/list` is framework-owned for the same reason.\n *\n * Contract:\n * - `error` is the RAW thrown value: an app must be able to `instanceof` its own error classes.\n * `ApiErrorBoundary` never substitutes an object for the thrown error, so there is exactly one\n * error value on this path.\n * - There is no \"not mine\" return. A registered translator REPLACES the webpieces default and\n * declines by DELEGATING to it: `new McpDefaultToolCallRenderer().toWire(error)`.\n * - webpieces default-fills `_meta['webpieces/requestId']` only when the returned result has NO\n * `_meta`. An app that sets `_meta` owns it untouched.\n * - scope is `tools/call` ONLY.\n */\nexport interface McpErrorTranslator {\n /** An error in, the whole `tools/call` reply out. Named for its HTTP and IPC twins. */\n toWire(error: Error): CallToolResult;\n}\n\n/**\n * webpieces' DEFAULT `tools/call` rendering, and what {@link McpRegistry} holds until an app installs\n * its own. Public so an app's own {@link McpErrorTranslator} can DECLINE an error by delegating to it\n * — the MCP twin of `WebpiecesDefaultErrorTranslator.toWire` on the HTTP side.\n *\n * Published text comes only from {@link ApiErrorBoundary.encode}: this never puts an error's own\n * message in front of a model unless it is an `ApiEndUserError`.\n */\nexport class McpDefaultToolCallRenderer implements McpErrorTranslator {\n private readonly boundary = new ApiErrorBoundary();\n\n toWire(error: Error): CallToolResult {\n const requestId = McpCorrelation.requestId();\n const visible = new ModelVisibleToolErrorEnvelope(\n this.modelVisible(error, this.boundary.encode(error), requestId),\n );\n const text = JSON.stringify(visible as DtoValue);\n return {\n content: [{ type: 'text', text }],\n isError: true,\n _meta: { [MCP_REQUEST_ID_META_KEY]: requestId },\n };\n }\n\n /**\n * MCP has no retry table of its own: the advice is f(outcome, operation, retryAfterSeconds), and\n * the outcome is the ONE verdict `ClientRegistry.classify` gives every other reader (RetryStrategy,\n * LogApiCall). A TRANSIENT_FAILURE becomes operation-aware retry guidance; everything else is\n * rendered by kind, with `retry: 'never'` or `'after-correction'`.\n *\n * The one thing decided before the classifier is the published `implementation` kind: the\n * boundary has already ruled that this server is at fault — including a caller-local\n * `ApiConnectionError` (#959) — so it is a bug, and a model is never told a bug is worth retrying.\n */\n private modelVisible(\n error: Error,\n payload: ApiErrorPayload,\n requestId: string,\n ): ModelVisibleToolError {\n const support = `Give requestId ${requestId} to support so the internal failure can be located and fixed.`;\n if (payload.kind === 'implementation') {\n return this.bug(payload, requestId, support);\n }\n const toolName = McpCorrelation.current().toolName ?? 'unknown';\n const methodInfo = new ApiMethodInfo('server', 'WpMcpServer', toolName, undefined);\n if (ClientRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE) {\n return this.transient(payload, requestId, this.transientMessage(payload));\n }\n return this.settled(payload, requestId, support);\n }\n\n /** Rendering for an outcome that repeating will not change: EXPECTED or FAILURE. */\n private settled(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n switch (payload.kind) {\n case 'end-user':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n payload.message,\n );\n case 'bad-request':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n payload.callerMessage ?? payload.message,\n );\n case 'unauthorized':\n case 'forbidden':\n return this.visible(\n payload,\n requestId,\n 'access',\n 'after-correction',\n 'Access was denied. Retrying unchanged credentials and arguments will not help; correct the credentials or permissions first.',\n );\n case 'not-found':\n case 'endpoint-not-found':\n case 'conflict':\n case 'unprocessable':\n case 'precondition-failed':\n case 'unsupported-media-type':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n `${payload.message}. Correct the request or current resource state before trying again.`,\n );\n default:\n return this.settledFailure(payload, requestId, support);\n }\n }\n\n /** A FAILURE the caller cannot correct: a missing operation, an exhausted or broken dependency. */\n private settledFailure(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n switch (payload.kind) {\n case 'not-implemented':\n return this.visible(\n payload,\n requestId,\n 'bug',\n 'never',\n `The tool does not implement this operation. Retrying or changing arguments will not help. ${support}`,\n );\n case 'retries-exhausted':\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream dependency kept failing after this service already retried it. Retrying now will not help. If the failure persists, ${support}`,\n );\n case 'coded':\n return this.coded(payload, requestId, support);\n default:\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream dependency failed. Retrying or changing arguments will not help. If the failure persists, ${support}`,\n );\n }\n }\n\n /** The situation text for a TRANSIENT_FAILURE; `transient` adds the operation-aware advice. */\n private transientMessage(payload: ApiErrorPayload): string {\n switch (payload.kind) {\n case 'request-timeout':\n case 'dependency-timeout':\n return 'The operation timed out; the previous operation may already have completed.';\n case 'bad-gateway':\n return 'A gateway returned an invalid upstream response; the previous operation may already have completed.';\n case 'rate-limited':\n case 'dependency-backoff':\n return payload.retryAfterSeconds === undefined\n ? 'The operation was throttled. Do not retry immediately.'\n : `The operation was throttled. Wait at least ${payload.retryAfterSeconds} seconds before retrying.`;\n case 'coded':\n return `The operation failed with HTTP ${payload.statusCode ?? 500}; the previous operation's outcome may be unknown.`;\n default:\n return 'A required service is temporarily unavailable; the previous operation may already have completed.';\n }\n }\n\n private coded(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n if ((payload.statusCode ?? 500) >= 500) {\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream service failed with HTTP ${payload.statusCode ?? 500}. Retrying or changing arguments will not help. ${support}`,\n );\n }\n return this.visible(payload, requestId, 'caller', 'after-correction', payload.message);\n }\n\n private bug(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n return this.visible(\n payload,\n requestId,\n 'bug',\n 'never',\n `The tool ${McpCorrelation.current().toolName ?? 'unknown'} encountered an internal bug. ` +\n `Retrying or changing the arguments will not help. ${support}`,\n );\n }\n\n private transient(\n payload: ApiErrorPayload,\n requestId: string,\n message: string,\n ): ModelVisibleToolError {\n const operation = McpCorrelation.current().operation ?? 'write';\n if (operation === 'write') {\n return this.visible(\n payload,\n requestId,\n 'temporary',\n 'unsafe-outcome-unknown',\n `${message} This endpoint is a non-idempotent write, so retrying could duplicate it; verify the outcome before retrying.`,\n );\n }\n const retry = payload.retryAfterSeconds === undefined ? 'safe' : 'after-delay';\n return this.visible(\n payload,\n requestId,\n 'temporary',\n retry,\n `${message} This endpoint is ${operation === 'read' ? 'read-only' : 'idempotent'}, so retrying is safe${payload.retryAfterSeconds === undefined ? ' after a delay' : ` after ${payload.retryAfterSeconds} seconds`}.`,\n );\n }\n\n private visible(\n payload: ApiErrorPayload,\n requestId: string,\n category: ModelVisibleToolError['category'],\n retry: ModelVisibleToolError['retry'],\n message: string,\n ): ModelVisibleToolError {\n return new ModelVisibleToolError(\n payload.kind,\n category,\n retry,\n message,\n requestId,\n payload.field,\n payload.callerMessage,\n payload.errorCode,\n payload.retryAfterSeconds,\n payload.statusCode,\n );\n }\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"McpToolCallRendering.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/McpToolCallRendering.ts"],"names":[],"mappings":";;;AACA,oDAU8B;AAC9B,0DAAyD;AACzD,+CAA4C;AAE5C,mGAAmG;AACtF,QAAA,uBAAuB,GAAG,qBAAqB,CAAC;AAE7D,6FAA6F;AAC7F,MAAa,YAAY;IACO;IAA5B,YAA4B,SAAiB;QAAjB,cAAS,GAAT,SAAS,CAAQ;IAAG,CAAC;CACpD;AAFD,oCAEC;AAED;;;;;;;;;GASG;AACH,MAAa,cAAc;IAUH;IAKA;IACA;IACA;IAhBpB,mGAAmG;IACnG,MAAM,CAAU,GAAG,GAAG,sBAAU,CAAC,SAAS,CACtC,2BAA2B,EAC3B,SAAS,EACT,KAAK;IACL,YAAY,CAAC,KAAK,CACrB,CAAC;IAEF,YACoB,SAAiC;IACjD;;;OAGG;IACa,QAAkB,EAClB,QAAiB,EACjB,SAA6B;QAP7B,cAAS,GAAT,SAAS,CA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iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC;QAC/E,OAAO,IAAI,CAAC,OAAO,CACf,OAAO,EACP,SAAS,EACT,WAAW,EACX,KAAK,EACL,GAAG,OAAO,qBAAqB,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,wBAAwB,OAAO,CAAC,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,UAAU,OAAO,CAAC,iBAAiB,UAAU,GAAG,CACxN,CAAC;IACN,CAAC;IAEO,OAAO,CACX,OAAwB,EACxB,SAAiB,EACjB,QAA2C,EAC3C,KAAqC,EACrC,OAAe;QAEf,OAAO,IAAI,qBAAqB,CAC5B,OAAO,CAAC,IAAI,EACZ,QAAQ,EACR,KAAK,EACL,OAAO,EACP,SAAS,EACT,OAAO,CAAC,KAAK,EACb,OAAO,CAAC,aAAa,EACrB,OAAO,CAAC,SAAS,EACjB,OAAO,CAAC,iBAAiB,EACzB,OAAO,CAAC,UAAU,CACrB,CAAC;IACN,CAAC;CACJ;AAnOD,gEAmOC","sourcesContent":["import { CallToolResult } from '@modelcontextprotocol/server';\nimport {\n ApiErrorBoundary,\n ApiErrorPayload,\n ApiMethodInfo,\n CallOutcome,\n ClientRegistry,\n ContextKey,\n DtoValue,\n EndpointOperation,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\nimport { McpProtocol } from './McpProtocol';\n\n/** `_meta` key carrying the Webpieces requestId on every tools/call result, success or failure. */\nexport const MCP_REQUEST_ID_META_KEY = 'webpieces/requestId';\n\n/** JSON-RPC error `data` so a user can quote the requestId of any protocol-level failure. */\nexport class McpErrorData {\n constructor(public readonly requestId: string) {}\n}\n\n/**\n * The two per-request facts a renderer needs that are NOT the error: the JSON-RPC `id` it must echo,\n * and the tool being called. They are stamped into the request scope by `WpMcpServer` rather than\n * threaded through every renderer signature, because `requestId` already travels that way\n * ({@link WebpiecesCoreHeaders.REQUEST_ID}) and a second, parallel correlation parameter was a COPY\n * of the context — which is what the deleted `McpFailureScope` was.\n *\n * Context-only and never logged: the logging backends read `RequestContext` for correlation on every\n * record already, and this object exists purely so the renderers can be one-argument functions.\n */\nexport class McpCorrelation {\n // webpieces-disable no-any-unknown -- ContextKey value types are per-key; this one is context-only\n static readonly KEY = ContextKey.untrusted<McpCorrelation>(\n 'webpieces-mcp-correlation',\n undefined,\n false,\n /*isLogged*/ false,\n );\n\n constructor(\n public readonly jsonRpcId: string | number | null,\n /**\n * The contract CLASS this request is classified under: the resolved tool's bound `@ApiPath`\n * contract, or {@link McpProtocol} while no tool is resolved (a protocol step, an unknown tool).\n */\n public readonly contract: Function,\n public readonly toolName?: string,\n public readonly operation?: EndpointOperation,\n ) {}\n\n /** Stamp what this request knows so far; `WpMcpServer` re-stamps once the tool name is known. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static stamp(correlation: McpCorrelation): void {\n RequestContext.putUntrusted(McpCorrelation.KEY, correlation);\n }\n\n /** A renderer reached before anything stamped (a failure with no parseable body) still renders. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static current(): McpCorrelation {\n return RequestContext.getUntrusted(McpCorrelation.KEY) ?? new McpCorrelation(null, McpProtocol);\n }\n\n /** The webpieces requestId of the request being served, as every MCP reply reports it. */\n // webpieces-disable no-function-outside-class -- static accessor trio for one context key\n static requestId(): string {\n return RequestContext.getUntrusted(WebpiecesCoreHeaders.REQUEST_ID) ?? 'missing-request-id';\n }\n}\n\n/** The only error shape rendered into model-visible MCP tool content. */\nexport class ModelVisibleToolError {\n constructor(\n public readonly kind: string,\n public readonly category: 'bug' | 'caller' | 'dependency' | 'temporary' | 'access',\n public readonly retry:\n | 'never'\n | 'after-correction'\n | 'after-delay'\n | 'safe'\n | 'unsafe-outcome-unknown',\n public readonly message: string,\n public readonly requestId: string,\n public readonly field?: string,\n public readonly callerMessage?: string,\n public readonly errorCode?: string,\n public readonly retryAfterSeconds?: number,\n public readonly statusCode?: number,\n ) {}\n}\n\n/** Explicit content-level envelope for clients that hide CallToolResult.isError. */\nexport class ModelVisibleToolErrorEnvelope {\n constructor(public readonly error: ModelVisibleToolError) {}\n}\n\n/** JSON-RPC error body written by the HTTP boundary before the SDK is involved. */\nexport class McpHttpErrorBody {\n readonly jsonrpc = '2.0';\n constructor(\n public readonly error: McpHttpErrorDetail,\n public readonly id: string | number | null,\n ) {}\n}\n\nexport class McpHttpErrorDetail {\n constructor(\n public readonly code: number,\n public readonly message: string,\n public readonly data: McpErrorData,\n ) {}\n}\n\n/**\n * The application's own `tools/call` error translation — the MCP twin of the `ErrorTranslator` an app\n * registers on `ClientRegistry` for HTTP and the `IpcErrorTranslator` it registers on `IpcRegistry`.\n * Register one with {@link McpRegistry.setErrorTranslator}.\n *\n * An app owns its error taxonomy and owns how those errors should be explained to a model, so a\n * claimed error yields the ENTIRE `CallToolResult` — content, `structuredContent`, `isError`, the lot.\n *\n * # There is NO `fromWire`, and that is the protocol, not an oversight\n *\n * The HTTP and IPC translators have two halves because webpieces sits on BOTH ends of those wires: it\n * writes the response AND, in another process, reads one. **webpieces is never the MCP client.** The\n * client is Claude (or another model host); there is no return path for webpieces to translate, so\n * the pair is one-directional by nature. Do not \"restore the symmetry\" by adding a half with nothing\n * to call it.\n *\n * # The pre-SDK boundary does NOT share the HTTP `ErrorTranslator`, despite the identical type\n *\n * `WpMcpErrorTranslator.toBearerBoundaryResponse` returns an `HttpResponseDto`, exactly like\n * `ErrorTranslator.toWire` — and it must STILL not be routed through it. Two reasons, both hard:\n *\n * - its body must stay JSON-RPC shaped (`McpHttpErrorBody`) or an MCP client cannot parse the reply\n * at all, whereas an app's HTTP translator publishes the app's own REST envelope;\n * - it emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` that MCP clients use for OAuth\n * discovery, so an app rewriting it breaks connector onboarding.\n *\n * Same TYPE, different OWNER. `tools/list` is framework-owned for the same reason.\n *\n * Contract:\n * - `error` is the RAW thrown value: an app must be able to `instanceof` its own error classes.\n * `ApiErrorBoundary` never substitutes an object for the thrown error, so there is exactly one\n * error value on this path.\n * - There is no \"not mine\" return. A registered translator REPLACES the webpieces default and\n * declines by DELEGATING to it: `new McpDefaultToolCallRenderer().toWire(error)`.\n * - webpieces default-fills `_meta['webpieces/requestId']` only when the returned result has NO\n * `_meta`. An app that sets `_meta` owns it untouched.\n * - scope is `tools/call` ONLY.\n */\nexport interface McpErrorTranslator {\n /** An error in, the whole `tools/call` reply out. Named for its HTTP and IPC twins. */\n toWire(error: Error): CallToolResult;\n}\n\n/**\n * webpieces' DEFAULT `tools/call` rendering, and what {@link McpRegistry} holds until an app installs\n * its own. Public so an app's own {@link McpErrorTranslator} can DECLINE an error by delegating to it\n * — the MCP twin of `WebpiecesDefaultErrorTranslator.toWire` on the HTTP side.\n *\n * Published text comes only from {@link ApiErrorBoundary.encode}: this never puts an error's own\n * message in front of a model unless it is an `ApiEndUserError`.\n */\nexport class McpDefaultToolCallRenderer implements McpErrorTranslator {\n private readonly boundary = new ApiErrorBoundary();\n\n toWire(error: Error): CallToolResult {\n const requestId = McpCorrelation.requestId();\n const visible = new ModelVisibleToolErrorEnvelope(\n this.modelVisible(error, this.boundary.encode(error), requestId),\n );\n const text = JSON.stringify(visible as DtoValue);\n return {\n content: [{ type: 'text', text }],\n isError: true,\n _meta: { [MCP_REQUEST_ID_META_KEY]: requestId },\n };\n }\n\n /**\n * MCP has no retry table of its own: the advice is f(outcome, operation, retryAfterSeconds), and\n * the outcome is the ONE verdict `ClientRegistry.classify` gives every other reader (RetryStrategy,\n * LogApiCall). A TRANSIENT_FAILURE becomes operation-aware retry guidance; everything else is\n * rendered by kind, with `retry: 'never'` or `'after-correction'`.\n *\n * The one thing decided before the classifier is the published `implementation` kind: the\n * boundary has already ruled that this server is at fault — including a caller-local\n * `ApiConnectionError` (#959) — so it is a bug, and a model is never told a bug is worth retrying.\n */\n private modelVisible(\n error: Error,\n payload: ApiErrorPayload,\n requestId: string,\n ): ModelVisibleToolError {\n const support = `Give requestId ${requestId} to support so the internal failure can be located and fixed.`;\n if (payload.kind === 'implementation') {\n return this.bug(payload, requestId, support);\n }\n const correlation = McpCorrelation.current();\n const toolName = correlation.toolName ?? 'unknown';\n const methodInfo = new ApiMethodInfo('server', 'WpMcpServer', toolName, correlation.contract);\n if (ClientRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE) {\n return this.transient(payload, requestId, this.transientMessage(payload));\n }\n return this.settled(payload, requestId, support);\n }\n\n /** Rendering for an outcome that repeating will not change: EXPECTED or FAILURE. */\n private settled(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n switch (payload.kind) {\n case 'end-user':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n payload.message,\n );\n case 'bad-request':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n payload.callerMessage ?? payload.message,\n );\n case 'unauthorized':\n case 'forbidden':\n return this.visible(\n payload,\n requestId,\n 'access',\n 'after-correction',\n 'Access was denied. Retrying unchanged credentials and arguments will not help; correct the credentials or permissions first.',\n );\n case 'not-found':\n case 'endpoint-not-found':\n case 'conflict':\n case 'unprocessable':\n case 'precondition-failed':\n case 'unsupported-media-type':\n return this.visible(\n payload,\n requestId,\n 'caller',\n 'after-correction',\n `${payload.message}. Correct the request or current resource state before trying again.`,\n );\n default:\n return this.settledFailure(payload, requestId, support);\n }\n }\n\n /** A FAILURE the caller cannot correct: a missing operation, an exhausted or broken dependency. */\n private settledFailure(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n switch (payload.kind) {\n case 'not-implemented':\n return this.visible(\n payload,\n requestId,\n 'bug',\n 'never',\n `The tool does not implement this operation. Retrying or changing arguments will not help. ${support}`,\n );\n case 'retries-exhausted':\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream dependency kept failing after this service already retried it. Retrying now will not help. If the failure persists, ${support}`,\n );\n case 'coded':\n return this.coded(payload, requestId, support);\n default:\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream dependency failed. Retrying or changing arguments will not help. If the failure persists, ${support}`,\n );\n }\n }\n\n /** The situation text for a TRANSIENT_FAILURE; `transient` adds the operation-aware advice. */\n private transientMessage(payload: ApiErrorPayload): string {\n switch (payload.kind) {\n case 'request-timeout':\n case 'dependency-timeout':\n return 'The operation timed out; the previous operation may already have completed.';\n case 'bad-gateway':\n return 'A gateway returned an invalid upstream response; the previous operation may already have completed.';\n case 'rate-limited':\n case 'dependency-backoff':\n return payload.retryAfterSeconds === undefined\n ? 'The operation was throttled. Do not retry immediately.'\n : `The operation was throttled. Wait at least ${payload.retryAfterSeconds} seconds before retrying.`;\n case 'coded':\n return `The operation failed with HTTP ${payload.statusCode ?? 500}; the previous operation's outcome may be unknown.`;\n default:\n return 'A required service is temporarily unavailable; the previous operation may already have completed.';\n }\n }\n\n private coded(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n if ((payload.statusCode ?? 500) >= 500) {\n return this.visible(\n payload,\n requestId,\n 'dependency',\n 'never',\n `A downstream service failed with HTTP ${payload.statusCode ?? 500}. Retrying or changing arguments will not help. ${support}`,\n );\n }\n return this.visible(payload, requestId, 'caller', 'after-correction', payload.message);\n }\n\n private bug(\n payload: ApiErrorPayload,\n requestId: string,\n support: string,\n ): ModelVisibleToolError {\n return this.visible(\n payload,\n requestId,\n 'bug',\n 'never',\n `The tool ${McpCorrelation.current().toolName ?? 'unknown'} encountered an internal bug. ` +\n `Retrying or changing the arguments will not help. ${support}`,\n );\n }\n\n private transient(\n payload: ApiErrorPayload,\n requestId: string,\n message: string,\n ): ModelVisibleToolError {\n const operation = McpCorrelation.current().operation ?? 'write';\n if (operation === 'write') {\n return this.visible(\n payload,\n requestId,\n 'temporary',\n 'unsafe-outcome-unknown',\n `${message} This endpoint is a non-idempotent write, so retrying could duplicate it; verify the outcome before retrying.`,\n );\n }\n const retry = payload.retryAfterSeconds === undefined ? 'safe' : 'after-delay';\n return this.visible(\n payload,\n requestId,\n 'temporary',\n retry,\n `${message} This endpoint is ${operation === 'read' ? 'read-only' : 'idempotent'}, so retrying is safe${payload.retryAfterSeconds === undefined ? ' after a delay' : ` after ${payload.retryAfterSeconds} seconds`}.`,\n );\n }\n\n private visible(\n payload: ApiErrorPayload,\n requestId: string,\n category: ModelVisibleToolError['category'],\n retry: ModelVisibleToolError['retry'],\n message: string,\n ): ModelVisibleToolError {\n return new ModelVisibleToolError(\n payload.kind,\n category,\n retry,\n message,\n requestId,\n payload.field,\n payload.callerMessage,\n payload.errorCode,\n payload.retryAfterSeconds,\n payload.statusCode,\n );\n }\n}\n\n"]}
|
package/src/WpMcpServer.js
CHANGED
|
@@ -15,6 +15,7 @@ const McpApiDispatcher_1 = require("./McpApiDispatcher");
|
|
|
15
15
|
const McpInvocationContext_1 = require("./McpInvocationContext");
|
|
16
16
|
const McpToolRegistry_1 = require("./McpToolRegistry");
|
|
17
17
|
const McpToolCallRendering_1 = require("./McpToolCallRendering");
|
|
18
|
+
const McpProtocol_1 = require("./McpProtocol");
|
|
18
19
|
const WpMcpErrorTranslator_1 = require("./WpMcpErrorTranslator");
|
|
19
20
|
const log = core_util_1.LogManager.getLogger('WpMcpServer');
|
|
20
21
|
/**
|
|
@@ -257,7 +258,7 @@ class WpMcpServer {
|
|
|
257
258
|
}
|
|
258
259
|
/** Run one un-filtered edge step under `LogApiCall`, so its failure gets exactly one log line. */
|
|
259
260
|
async logEdge(step, work) {
|
|
260
|
-
return this.logApiCall.execute(new core_util_1.ApiMethodInfo('server', 'McpEndpoint', step,
|
|
261
|
+
return this.logApiCall.execute(new core_util_1.ApiMethodInfo('server', 'McpEndpoint', step, McpProtocol_1.McpProtocol), new McpEdgeRequest(step), work);
|
|
261
262
|
}
|
|
262
263
|
async serveExpress(req, res, options) {
|
|
263
264
|
const origin = req.header('origin');
|
|
@@ -371,11 +372,11 @@ class WpMcpServer {
|
|
|
371
372
|
const name = request.params.name;
|
|
372
373
|
const operation = new McpSdkOperation(`tools/call ${name}`);
|
|
373
374
|
return this.sdkBoundary(operation, async () => {
|
|
374
|
-
McpToolCallRendering_1.McpCorrelation.stamp(new McpToolCallRendering_1.McpCorrelation(sdkContext.mcpReq.id, name));
|
|
375
|
+
McpToolCallRendering_1.McpCorrelation.stamp(new McpToolCallRendering_1.McpCorrelation(sdkContext.mcpReq.id, McpProtocol_1.McpProtocol, name));
|
|
375
376
|
const tool = authentication.tools.find(name);
|
|
376
377
|
if (!tool)
|
|
377
378
|
throw this.translator.unknownTool(name);
|
|
378
|
-
McpToolCallRendering_1.McpCorrelation.stamp(new McpToolCallRendering_1.McpCorrelation(sdkContext.mcpReq.id, name, tool.operation));
|
|
379
|
+
McpToolCallRendering_1.McpCorrelation.stamp(new McpToolCallRendering_1.McpCorrelation(sdkContext.mcpReq.id, tool.apiClass, name, tool.operation));
|
|
379
380
|
operation.toolStage = true;
|
|
380
381
|
const result = await this.callTool(tool, request, authentication, sdkContext);
|
|
381
382
|
result._meta = this.translator.resultMeta(McpToolCallRendering_1.McpCorrelation.requestId());
|
|
@@ -488,7 +489,7 @@ class WpMcpServer {
|
|
|
488
489
|
const id = body?.['id'];
|
|
489
490
|
const params = this.bodyObject(body?.['params']);
|
|
490
491
|
const name = params?.['name'];
|
|
491
|
-
return new McpToolCallRendering_1.McpCorrelation(typeof id === 'string' || typeof id === 'number' ? id : null, typeof name === 'string' ? name : undefined);
|
|
492
|
+
return new McpToolCallRendering_1.McpCorrelation(typeof id === 'string' || typeof id === 'number' ? id : null, McpProtocol_1.McpProtocol, typeof name === 'string' ? name : undefined);
|
|
492
493
|
}
|
|
493
494
|
challenge() {
|
|
494
495
|
return `Bearer resource_metadata="${this.config.resourceMetadataUrl}"`;
|
package/src/WpMcpServer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":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AAC,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;AAtiBD,kCAsiBC","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 Icon,\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/**\n * `Tool.annotations` exactly as tools/list publishes it: the four hints PLUS the human-readable\n * `title` (#1180). The Claude Connectors Directory checks `annotations.title`; clients on the\n * 2025-06-18+ spec render the top-level `Tool.title`, so both carry the one title — the method's\n * `@summary` JSDoc tag, read from the generated catalog (#1296).\n */\nclass McpPublishedToolAnnotations {\n readonly title: string;\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n readonly idempotentHint: boolean;\n readonly openWorldHint: boolean;\n\n constructor(tool: RegisteredMcpTool) {\n this.title = tool.title;\n this.readOnlyHint = tool.annotations.readOnlyHint;\n this.destructiveHint = tool.annotations.destructiveHint;\n this.idempotentHint = tool.annotations.idempotentHint;\n this.openWorldHint = tool.annotations.openWorldHint;\n }\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 toolProfiles: readonly string[] = [];\n private handler?: McpHttpHandler;\n private streamingHandler?: McpHttpHandler;\n private nodeHandler?: NodeMcpRequestHandler;\n private streamingNodeHandler?: NodeMcpRequestHandler;\n private revision?: string;\n private icons?: readonly Icon[];\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.toolProfiles = this.config.toolProfiles;\n this.icons = this.config.icons;\n this.registry = new McpToolRegistry(\n options.bindings,\n options.toolCatalogs,\n this.config.authorizationService,\n );\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, undefined),\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 this.toolProfiles,\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 {\n name: this.config.name,\n title: this.config.title,\n description: this.config.description,\n websiteUrl: this.config.websiteUrl,\n version: `${this.config.version}+${this.revision}`,\n ...(this.icons === undefined ? {} : { icons: [...this.icons] }),\n },\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 title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema as Tool['inputSchema'],\n outputSchema: tool.outputSchema as Tool['outputSchema'],\n annotations: new McpPublishedToolAnnotations(tool),\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.title,\n tool.description,\n tool.inputSchema,\n tool.outputSchema,\n tool.annotations,\n tool.profiles,\n ]);\n return createHash('sha256')\n .update(JSON.stringify([this.toolProfiles, surface]))\n .digest('hex')\n .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,yDAgBsC;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,+CAA4C;AAC5C,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,SA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AAI,CAAC,KAAK;YACV,IAAI,CAAC,WAAW;YAChB,IAAI,CAAC,WAAW;YAChB,IAAI,CAAC,YAAY;YACjB,IAAI,CAAC,WAAW;YAChB,IAAI,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,IAAA,wBAAU,EAAC,QAAQ,CAAC;aACtB,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC,CAAC;aACpD,MAAM,CAAC,KAAK,CAAC;aACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACtB,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;AAziBD,kCAyiBC","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 Icon,\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 { McpProtocol } from './McpProtocol';\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/**\n * `Tool.annotations` exactly as tools/list publishes it: the four hints PLUS the human-readable\n * `title` (#1180). The Claude Connectors Directory checks `annotations.title`; clients on the\n * 2025-06-18+ spec render the top-level `Tool.title`, so both carry the one title — the method's\n * `@summary` JSDoc tag, read from the generated catalog (#1296).\n */\nclass McpPublishedToolAnnotations {\n readonly title: string;\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n readonly idempotentHint: boolean;\n readonly openWorldHint: boolean;\n\n constructor(tool: RegisteredMcpTool) {\n this.title = tool.title;\n this.readOnlyHint = tool.annotations.readOnlyHint;\n this.destructiveHint = tool.annotations.destructiveHint;\n this.idempotentHint = tool.annotations.idempotentHint;\n this.openWorldHint = tool.annotations.openWorldHint;\n }\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 toolProfiles: readonly string[] = [];\n private handler?: McpHttpHandler;\n private streamingHandler?: McpHttpHandler;\n private nodeHandler?: NodeMcpRequestHandler;\n private streamingNodeHandler?: NodeMcpRequestHandler;\n private revision?: string;\n private icons?: readonly Icon[];\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.toolProfiles = this.config.toolProfiles;\n this.icons = this.config.icons;\n this.registry = new McpToolRegistry(\n options.bindings,\n options.toolCatalogs,\n this.config.authorizationService,\n );\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, McpProtocol),\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 this.toolProfiles,\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 {\n name: this.config.name,\n title: this.config.title,\n description: this.config.description,\n websiteUrl: this.config.websiteUrl,\n version: `${this.config.version}+${this.revision}`,\n ...(this.icons === undefined ? {} : { icons: [...this.icons] }),\n },\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 title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema as Tool['inputSchema'],\n outputSchema: tool.outputSchema as Tool['outputSchema'],\n annotations: new McpPublishedToolAnnotations(tool),\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, McpProtocol, name));\n const tool = authentication.tools.find(name);\n if (!tool) throw this.translator.unknownTool(name);\n McpCorrelation.stamp(\n new McpCorrelation(sdkContext.mcpReq.id, tool.apiClass, name, tool.operation),\n );\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 McpProtocol,\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.title,\n tool.description,\n tool.inputSchema,\n tool.outputSchema,\n tool.annotations,\n tool.profiles,\n ]);\n return createHash('sha256')\n .update(JSON.stringify([this.toolProfiles, surface]))\n .digest('hex')\n .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"]}
|
package/src/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export { McpDeployment } from './McpDeployment';
|
|
|
13
13
|
export type { McpDeploymentMode } from './McpDeployment';
|
|
14
14
|
export { McpApiDispatcher } from './McpApiDispatcher';
|
|
15
15
|
export { WpMcpServer } from './WpMcpServer';
|
|
16
|
+
export { McpProtocol } from './McpProtocol';
|
|
16
17
|
export { MCP_REQUEST_ID_META_KEY, McpCorrelation, McpDefaultToolCallRenderer, McpErrorData, McpHttpErrorBody, McpHttpErrorDetail, ModelVisibleToolError, } from './McpToolCallRendering';
|
|
17
18
|
export { WpMcpErrorTranslator } from './WpMcpErrorTranslator';
|
|
18
19
|
export type { McpErrorTranslator } from './McpToolCallRendering';
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.McpRegistry = exports.WpMcpErrorTranslator = exports.ModelVisibleToolError = exports.McpHttpErrorDetail = exports.McpHttpErrorBody = exports.McpErrorData = exports.McpDefaultToolCallRenderer = exports.McpCorrelation = exports.MCP_REQUEST_ID_META_KEY = exports.WpMcpServer = exports.McpApiDispatcher = exports.McpDeployment = exports.McpToolCatalog = exports.McpBindOptions = exports.McpInvocationContext = exports.MCP_INVOCATION_CONTEXT = exports.McpApiBinding = exports.RegisteredMcpTool = exports.McpToolRegistry = exports.McpIcon = exports.WpMcpServerConfig = exports.VerifiedMcpCredential = exports.McpProtectedResourceMetadata = exports.MintedMcpAccessToken = exports.MAX_MCP_SERVER_TITLE_LENGTH = exports.MAX_MCP_SERVER_DESCRIPTION_LENGTH = exports.MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS = exports.MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS = void 0;
|
|
3
|
+
exports.McpRegistry = exports.WpMcpErrorTranslator = exports.ModelVisibleToolError = exports.McpHttpErrorDetail = exports.McpHttpErrorBody = exports.McpErrorData = exports.McpDefaultToolCallRenderer = exports.McpCorrelation = exports.MCP_REQUEST_ID_META_KEY = exports.McpProtocol = exports.WpMcpServer = exports.McpApiDispatcher = exports.McpDeployment = exports.McpToolCatalog = exports.McpBindOptions = exports.McpInvocationContext = exports.MCP_INVOCATION_CONTEXT = exports.McpApiBinding = exports.RegisteredMcpTool = exports.McpToolRegistry = exports.McpIcon = exports.WpMcpServerConfig = exports.VerifiedMcpCredential = exports.McpProtectedResourceMetadata = exports.MintedMcpAccessToken = exports.MAX_MCP_SERVER_TITLE_LENGTH = exports.MAX_MCP_SERVER_DESCRIPTION_LENGTH = exports.MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS = exports.MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS = void 0;
|
|
4
4
|
var McpAuth_1 = require("./McpAuth");
|
|
5
5
|
Object.defineProperty(exports, "MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS", { enumerable: true, get: function () { return McpAuth_1.MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS; } });
|
|
6
6
|
Object.defineProperty(exports, "MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS", { enumerable: true, get: function () { return McpAuth_1.MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS; } });
|
|
@@ -30,6 +30,8 @@ var McpApiDispatcher_1 = require("./McpApiDispatcher");
|
|
|
30
30
|
Object.defineProperty(exports, "McpApiDispatcher", { enumerable: true, get: function () { return McpApiDispatcher_1.McpApiDispatcher; } });
|
|
31
31
|
var WpMcpServer_1 = require("./WpMcpServer");
|
|
32
32
|
Object.defineProperty(exports, "WpMcpServer", { enumerable: true, get: function () { return WpMcpServer_1.WpMcpServer; } });
|
|
33
|
+
var McpProtocol_1 = require("./McpProtocol");
|
|
34
|
+
Object.defineProperty(exports, "McpProtocol", { enumerable: true, get: function () { return McpProtocol_1.McpProtocol; } });
|
|
33
35
|
var McpToolCallRendering_1 = require("./McpToolCallRendering");
|
|
34
36
|
Object.defineProperty(exports, "MCP_REQUEST_ID_META_KEY", { enumerable: true, get: function () { return McpToolCallRendering_1.MCP_REQUEST_ID_META_KEY; } });
|
|
35
37
|
Object.defineProperty(exports, "McpCorrelation", { enumerable: true, get: function () { return McpToolCallRendering_1.McpCorrelation; } });
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/index.ts"],"names":[],"mappings":";;;AAAA,qCASmB;AARf,gIAAA,qCAAqC,OAAA;AACrC,iIAAA,sCAAsC,OAAA;AACtC,4HAAA,iCAAiC,OAAA;AACjC,sHAAA,2BAA2B,OAAA;AAC3B,+GAAA,oBAAoB,OAAA;AACpB,uHAAA,4BAA4B,OAAA;AAC5B,gHAAA,qBAAqB,OAAA;AACrB,4GAAA,iBAAiB,OAAA;AAIrB,qCAAoC;AAA3B,kGAAA,OAAO,OAAA;AAChB,qDAAuE;AAA9D,kHAAA,eAAe,OAAA;AAAE,oHAAA,iBAAiB,OAAA;AAC3C,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AAEtB,+DAAsF;AAA7E,8HAAA,sBAAsB,OAAA;AAAE,4HAAA,oBAAoB,OAAA;AAErD,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AACvB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AACvB,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AAEtB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,+DAQgC;AAP5B,+HAAA,uBAAuB,OAAA;AACvB,sHAAA,cAAc,OAAA;AACd,kIAAA,0BAA0B,OAAA;AAC1B,oHAAA,YAAY,OAAA;AACZ,wHAAA,gBAAgB,OAAA;AAChB,0HAAA,kBAAkB,OAAA;AAClB,6HAAA,qBAAqB,OAAA;AAEzB,+DAA8D;AAArD,4HAAA,oBAAoB,OAAA;AAE7B,6FAA6F;AAC7F,6CAA4C;AAAnC,0GAAA,WAAW,OAAA","sourcesContent":["export {\n MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS,\n MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS,\n MAX_MCP_SERVER_DESCRIPTION_LENGTH,\n MAX_MCP_SERVER_TITLE_LENGTH,\n MintedMcpAccessToken,\n McpProtectedResourceMetadata,\n VerifiedMcpCredential,\n WpMcpServerConfig,\n} from './McpAuth';\nexport type { McpAccessTokenAuthority } from './McpAuth';\nexport type { Icon } from '@modelcontextprotocol/server';\nexport { McpIcon } from './McpIcon';\nexport { McpToolRegistry, RegisteredMcpTool } from './McpToolRegistry';\nexport { McpApiBinding } from './McpApiBinding';\nexport type { McpBindingTopology } from './McpApiBinding';\nexport { MCP_INVOCATION_CONTEXT, McpInvocationContext } from './McpInvocationContext';\nexport type { McpProgressReporter } from './McpInvocationContext';\nexport { McpBindOptions } from './McpBindOptions';\nexport { McpToolCatalog } from './McpToolCatalog';\nexport { McpDeployment } from './McpDeployment';\nexport type { McpDeploymentMode } from './McpDeployment';\nexport { McpApiDispatcher } from './McpApiDispatcher';\nexport { WpMcpServer } from './WpMcpServer';\nexport {\n MCP_REQUEST_ID_META_KEY,\n McpCorrelation,\n McpDefaultToolCallRenderer,\n McpErrorData,\n McpHttpErrorBody,\n McpHttpErrorDetail,\n ModelVisibleToolError,\n} from './McpToolCallRendering';\nexport { WpMcpErrorTranslator } from './WpMcpErrorTranslator';\nexport type { McpErrorTranslator } from './McpToolCallRendering';\n// The process-global home of the ONE MCP translator, mirroring ClientRegistry / IpcRegistry.\nexport { McpRegistry } from './McpRegistry';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/index.ts"],"names":[],"mappings":";;;AAAA,qCASmB;AARf,gIAAA,qCAAqC,OAAA;AACrC,iIAAA,sCAAsC,OAAA;AACtC,4HAAA,iCAAiC,OAAA;AACjC,sHAAA,2BAA2B,OAAA;AAC3B,+GAAA,oBAAoB,OAAA;AACpB,uHAAA,4BAA4B,OAAA;AAC5B,gHAAA,qBAAqB,OAAA;AACrB,4GAAA,iBAAiB,OAAA;AAIrB,qCAAoC;AAA3B,kGAAA,OAAO,OAAA;AAChB,qDAAuE;AAA9D,kHAAA,eAAe,OAAA;AAAE,oHAAA,iBAAiB,OAAA;AAC3C,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AAEtB,+DAAsF;AAA7E,8HAAA,sBAAsB,OAAA;AAAE,4HAAA,oBAAoB,OAAA;AAErD,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AACvB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AACvB,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AAEtB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,+DAQgC;AAP5B,+HAAA,uBAAuB,OAAA;AACvB,sHAAA,cAAc,OAAA;AACd,kIAAA,0BAA0B,OAAA;AAC1B,oHAAA,YAAY,OAAA;AACZ,wHAAA,gBAAgB,OAAA;AAChB,0HAAA,kBAAkB,OAAA;AAClB,6HAAA,qBAAqB,OAAA;AAEzB,+DAA8D;AAArD,4HAAA,oBAAoB,OAAA;AAE7B,6FAA6F;AAC7F,6CAA4C;AAAnC,0GAAA,WAAW,OAAA","sourcesContent":["export {\n MAX_MCP_ACCESS_TOKEN_LIFETIME_SECONDS,\n MAX_MCP_ACCOUNT_VALIDATION_AGE_SECONDS,\n MAX_MCP_SERVER_DESCRIPTION_LENGTH,\n MAX_MCP_SERVER_TITLE_LENGTH,\n MintedMcpAccessToken,\n McpProtectedResourceMetadata,\n VerifiedMcpCredential,\n WpMcpServerConfig,\n} from './McpAuth';\nexport type { McpAccessTokenAuthority } from './McpAuth';\nexport type { Icon } from '@modelcontextprotocol/server';\nexport { McpIcon } from './McpIcon';\nexport { McpToolRegistry, RegisteredMcpTool } from './McpToolRegistry';\nexport { McpApiBinding } from './McpApiBinding';\nexport type { McpBindingTopology } from './McpApiBinding';\nexport { MCP_INVOCATION_CONTEXT, McpInvocationContext } from './McpInvocationContext';\nexport type { McpProgressReporter } from './McpInvocationContext';\nexport { McpBindOptions } from './McpBindOptions';\nexport { McpToolCatalog } from './McpToolCatalog';\nexport { McpDeployment } from './McpDeployment';\nexport type { McpDeploymentMode } from './McpDeployment';\nexport { McpApiDispatcher } from './McpApiDispatcher';\nexport { WpMcpServer } from './WpMcpServer';\nexport { McpProtocol } from './McpProtocol';\nexport {\n MCP_REQUEST_ID_META_KEY,\n McpCorrelation,\n McpDefaultToolCallRenderer,\n McpErrorData,\n McpHttpErrorBody,\n McpHttpErrorDetail,\n ModelVisibleToolError,\n} from './McpToolCallRendering';\nexport { WpMcpErrorTranslator } from './WpMcpErrorTranslator';\nexport type { McpErrorTranslator } from './McpToolCallRendering';\n// The process-global home of the ONE MCP translator, mirroring ClientRegistry / IpcRegistry.\nexport { McpRegistry } from './McpRegistry';\n"]}
|