@webpieces/mcp-server 0.4.789 → 0.4.791
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -17
- package/package.json +6 -6
- package/src/McpApiDispatcher.js +6 -0
- package/src/McpApiDispatcher.js.map +1 -1
- package/src/McpAuth.d.ts +4 -12
- package/src/McpAuth.js +4 -20
- package/src/McpAuth.js.map +1 -1
- package/src/McpRegistry.d.ts +40 -0
- package/src/McpRegistry.js +54 -0
- package/src/McpRegistry.js.map +1 -0
- package/src/McpToolCallRendering.d.ts +111 -0
- package/src/McpToolCallRendering.js +135 -0
- package/src/McpToolCallRendering.js.map +1 -0
- package/src/WpMcpErrorTranslator.d.ts +12 -100
- package/src/WpMcpErrorTranslator.js +28 -158
- package/src/WpMcpErrorTranslator.js.map +1 -1
- package/src/WpMcpServer.d.ts +7 -2
- package/src/WpMcpServer.js +27 -14
- package/src/WpMcpServer.js.map +1 -1
- package/src/__tests__/LegacyMcpHttpTestHarness.d.ts +24 -0
- package/src/__tests__/LegacyMcpHttpTestHarness.js +69 -0
- package/src/__tests__/LegacyMcpHttpTestHarness.js.map +1 -0
- package/src/__tests__/McpRemoteFixtures.d.ts +4 -3
- package/src/__tests__/McpRemoteFixtures.js +11 -11
- package/src/__tests__/McpRemoteFixtures.js.map +1 -1
- package/src/__tests__/WpMcpServerTestFixtures.d.ts +6 -0
- package/src/__tests__/WpMcpServerTestFixtures.js +7 -1
- package/src/__tests__/WpMcpServerTestFixtures.js.map +1 -1
- package/src/index.d.ts +4 -2
- package/src/index.js +12 -8
- package/src/index.js.map +1 -1
|
@@ -1,141 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WpMcpErrorTranslator =
|
|
3
|
+
exports.WpMcpErrorTranslator = void 0;
|
|
4
4
|
const server_1 = require("@modelcontextprotocol/server");
|
|
5
5
|
const core_util_1 = require("@webpieces/core-util");
|
|
6
|
-
const
|
|
6
|
+
const McpRegistry_1 = require("./McpRegistry");
|
|
7
|
+
const McpToolCallRendering_1 = require("./McpToolCallRendering");
|
|
7
8
|
const log = core_util_1.LogManager.getLogger('WpMcpErrorTranslator');
|
|
8
|
-
/** `_meta` key carrying the Webpieces requestId on every tools/call result, success or failure. */
|
|
9
|
-
exports.MCP_REQUEST_ID_META_KEY = 'webpieces/requestId';
|
|
10
|
-
/** JSON-RPC error `data` so a user can quote the requestId of any protocol-level failure. */
|
|
11
|
-
class McpErrorData {
|
|
12
|
-
requestId;
|
|
13
|
-
constructor(requestId) {
|
|
14
|
-
this.requestId = requestId;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
exports.McpErrorData = McpErrorData;
|
|
18
|
-
/**
|
|
19
|
-
* The two per-request facts a renderer needs that are NOT the error: the JSON-RPC `id` it must echo,
|
|
20
|
-
* and the tool being called. They are stamped into the request scope by `WpMcpServer` rather than
|
|
21
|
-
* threaded through every renderer signature, because `requestId` already travels that way
|
|
22
|
-
* ({@link WebpiecesCoreHeaders.REQUEST_ID}) and a second, parallel correlation parameter was a COPY
|
|
23
|
-
* of the context — which is what the deleted `McpFailureScope` was.
|
|
24
|
-
*
|
|
25
|
-
* Context-only and never logged: the logging backends read `RequestContext` for correlation on every
|
|
26
|
-
* record already, and this object exists purely so the renderers can be one-argument functions.
|
|
27
|
-
*/
|
|
28
|
-
class McpCorrelation {
|
|
29
|
-
jsonRpcId;
|
|
30
|
-
toolName;
|
|
31
|
-
// webpieces-disable no-any-unknown -- ContextKey value types are per-key; this one is context-only
|
|
32
|
-
static KEY = core_util_1.ContextKey.untrusted('webpieces-mcp-correlation', undefined, false,
|
|
33
|
-
/*isLogged*/ false);
|
|
34
|
-
constructor(jsonRpcId, toolName) {
|
|
35
|
-
this.jsonRpcId = jsonRpcId;
|
|
36
|
-
this.toolName = toolName;
|
|
37
|
-
}
|
|
38
|
-
/** Stamp what this request knows so far; `WpMcpServer` re-stamps once the tool name is known. */
|
|
39
|
-
// webpieces-disable no-function-outside-class -- static accessor trio for one context key
|
|
40
|
-
static stamp(correlation) {
|
|
41
|
-
core_context_1.RequestContext.putUntrusted(McpCorrelation.KEY, correlation);
|
|
42
|
-
}
|
|
43
|
-
/** A renderer reached before anything stamped (a failure with no parseable body) still renders. */
|
|
44
|
-
// webpieces-disable no-function-outside-class -- static accessor trio for one context key
|
|
45
|
-
static current() {
|
|
46
|
-
return core_context_1.RequestContext.getUntrusted(McpCorrelation.KEY) ?? new McpCorrelation(null);
|
|
47
|
-
}
|
|
48
|
-
/** The webpieces requestId of the request being served, as every MCP reply reports it. */
|
|
49
|
-
// webpieces-disable no-function-outside-class -- static accessor trio for one context key
|
|
50
|
-
static requestId() {
|
|
51
|
-
return core_context_1.RequestContext.getUntrusted(core_util_1.WebpiecesCoreHeaders.REQUEST_ID) ?? 'missing-request-id';
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
exports.McpCorrelation = McpCorrelation;
|
|
55
|
-
/** The only error shape rendered into model-visible MCP tool content. */
|
|
56
|
-
class ModelVisibleToolError {
|
|
57
|
-
kind;
|
|
58
|
-
message;
|
|
59
|
-
requestId;
|
|
60
|
-
field;
|
|
61
|
-
callerMessage;
|
|
62
|
-
errorCode;
|
|
63
|
-
retryAfterSeconds;
|
|
64
|
-
statusCode;
|
|
65
|
-
constructor(kind, message, requestId, field, callerMessage, errorCode, retryAfterSeconds, statusCode) {
|
|
66
|
-
this.kind = kind;
|
|
67
|
-
this.message = message;
|
|
68
|
-
this.requestId = requestId;
|
|
69
|
-
this.field = field;
|
|
70
|
-
this.callerMessage = callerMessage;
|
|
71
|
-
this.errorCode = errorCode;
|
|
72
|
-
this.retryAfterSeconds = retryAfterSeconds;
|
|
73
|
-
this.statusCode = statusCode;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
exports.ModelVisibleToolError = ModelVisibleToolError;
|
|
77
|
-
/** JSON-RPC error body written by the HTTP boundary before the SDK is involved. */
|
|
78
|
-
class McpHttpErrorBody {
|
|
79
|
-
error;
|
|
80
|
-
id;
|
|
81
|
-
jsonrpc = '2.0';
|
|
82
|
-
constructor(error, id) {
|
|
83
|
-
this.error = error;
|
|
84
|
-
this.id = id;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
exports.McpHttpErrorBody = McpHttpErrorBody;
|
|
88
|
-
class McpHttpErrorDetail {
|
|
89
|
-
code;
|
|
90
|
-
message;
|
|
91
|
-
data;
|
|
92
|
-
constructor(code, message, data) {
|
|
93
|
-
this.code = code;
|
|
94
|
-
this.message = message;
|
|
95
|
-
this.data = data;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
exports.McpHttpErrorDetail = McpHttpErrorDetail;
|
|
99
|
-
/**
|
|
100
|
-
* webpieces' DEFAULT `tools/call` rendering, as a public class so an app's own
|
|
101
|
-
* {@link McpErrorTranslators} can DECLINE an error by delegating to it — the MCP twin of
|
|
102
|
-
* `ApiErrorHttpMapper.toResponse` on the HTTP side.
|
|
103
|
-
*
|
|
104
|
-
* Published text comes only from {@link ApiErrorBoundary.encode}: this never puts an error's own
|
|
105
|
-
* message in front of a model unless it is an `ApiEndUserError`.
|
|
106
|
-
*/
|
|
107
|
-
class McpDefaultToolCallRenderer {
|
|
108
|
-
boundary = new core_util_1.ApiErrorBoundary();
|
|
109
|
-
toToolCallResult(error) {
|
|
110
|
-
const requestId = McpCorrelation.requestId();
|
|
111
|
-
const visible = this.modelVisible(this.boundary.encode(error), requestId);
|
|
112
|
-
const text = JSON.stringify(visible);
|
|
113
|
-
return {
|
|
114
|
-
content: [{ type: 'text', text }],
|
|
115
|
-
isError: true,
|
|
116
|
-
_meta: { [exports.MCP_REQUEST_ID_META_KEY]: requestId },
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
modelVisible(payload, requestId) {
|
|
120
|
-
switch (payload.kind) {
|
|
121
|
-
case 'end-user':
|
|
122
|
-
return new ModelVisibleToolError(payload.kind, payload.message, requestId, undefined, undefined, payload.errorCode);
|
|
123
|
-
case 'bad-request':
|
|
124
|
-
return new ModelVisibleToolError(payload.kind, payload.callerMessage ?? payload.message, requestId, payload.field, payload.callerMessage);
|
|
125
|
-
case 'coded':
|
|
126
|
-
return new ModelVisibleToolError(payload.kind, payload.message, requestId, undefined, undefined, payload.errorCode, undefined, payload.statusCode);
|
|
127
|
-
case 'implementation':
|
|
128
|
-
return new ModelVisibleToolError(payload.kind, `Internal error in tool ${McpCorrelation.current().toolName ?? 'unknown'} ` +
|
|
129
|
-
`(requestId ${requestId}). This is a bug in the tool, not in your ` +
|
|
130
|
-
'arguments; retrying with different arguments will not help.', requestId);
|
|
131
|
-
default:
|
|
132
|
-
return new ModelVisibleToolError(payload.kind, payload.message, requestId, undefined, undefined, undefined, payload.retryAfterSeconds);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
exports.McpDefaultToolCallRenderer = McpDefaultToolCallRenderer;
|
|
137
9
|
/**
|
|
138
|
-
* The ONE place every MCP failure becomes a reply, mirroring `
|
|
10
|
+
* The ONE place every MCP failure becomes a reply, mirroring `WebpiecesDefaultErrorTranslator` for HTTP: an error
|
|
139
11
|
* in, the exact wire shape out. There is one method per BOUNDARY, and the MCP spec is what makes
|
|
140
12
|
* them three rather than one:
|
|
141
13
|
*
|
|
@@ -151,17 +23,14 @@ exports.McpDefaultToolCallRenderer = McpDefaultToolCallRenderer;
|
|
|
151
23
|
*/
|
|
152
24
|
class WpMcpErrorTranslator {
|
|
153
25
|
challenge;
|
|
154
|
-
appTranslators;
|
|
155
26
|
boundary = new core_util_1.ApiErrorBoundary();
|
|
156
|
-
defaultToolCall = new McpDefaultToolCallRenderer();
|
|
27
|
+
defaultToolCall = new McpToolCallRendering_1.McpDefaultToolCallRenderer();
|
|
157
28
|
/**
|
|
158
29
|
* @param challenge - the `WWW-Authenticate` value for a 401, read lazily because
|
|
159
30
|
* `WpMcpServerConfig` is only fully validated at `bind(...)` time.
|
|
160
|
-
* @param appTranslators - the app's `tools/call` seam; `undefined` means webpieces renders all.
|
|
161
31
|
*/
|
|
162
|
-
constructor(challenge
|
|
32
|
+
constructor(challenge) {
|
|
163
33
|
this.challenge = challenge;
|
|
164
|
-
this.appTranslators = appTranslators;
|
|
165
34
|
}
|
|
166
35
|
/**
|
|
167
36
|
* Boundary #1: everything webpieces itself rejects before the SDK is involved — bearer
|
|
@@ -199,51 +68,52 @@ class WpMcpErrorTranslator {
|
|
|
199
68
|
*/
|
|
200
69
|
toListError(error) {
|
|
201
70
|
const payload = this.boundary.encode(error);
|
|
202
|
-
const requestId = McpCorrelation.requestId();
|
|
71
|
+
const requestId = McpToolCallRendering_1.McpCorrelation.requestId();
|
|
203
72
|
if (payload.kind === 'bad-request') {
|
|
204
|
-
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, payload.callerMessage ?? payload.message, new McpErrorData(requestId));
|
|
73
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, payload.callerMessage ?? payload.message, new McpToolCallRendering_1.McpErrorData(requestId));
|
|
205
74
|
}
|
|
206
75
|
const message = payload.kind === 'end-user' ? payload.message : 'Internal Error';
|
|
207
|
-
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InternalError, message, new McpErrorData(requestId));
|
|
76
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InternalError, message, new McpToolCallRendering_1.McpErrorData(requestId));
|
|
208
77
|
}
|
|
209
|
-
/** tools/call with a name no binding registered: a JSON-RPC protocol error
|
|
78
|
+
/** tools/call with a name no binding registered: a JSON-RPC protocol error in either MCP era. */
|
|
210
79
|
unknownTool(toolName) {
|
|
211
|
-
const requestId = McpCorrelation.requestId();
|
|
80
|
+
const requestId = McpToolCallRendering_1.McpCorrelation.requestId();
|
|
212
81
|
log.info(`Unknown MCP tool: ${toolName} requestId=${requestId}`);
|
|
213
|
-
return new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, `Unknown tool: ${toolName}`, new McpErrorData(requestId));
|
|
82
|
+
return new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, `Unknown tool: ${toolName}`, new McpToolCallRendering_1.McpErrorData(requestId));
|
|
214
83
|
}
|
|
215
84
|
/**
|
|
216
85
|
* Boundary #3: every tools/call failure after the tool is found — an `isError: true` result the
|
|
217
86
|
* model sees.
|
|
218
87
|
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
88
|
+
* ONE unconditional line: {@link McpRegistry.getErrorTranslator} is never undefined, so there is
|
|
89
|
+
* no "was one registered" branch. A registered {@link McpErrorTranslator} REPLACES the default and
|
|
90
|
+
* declines by delegating to {@link McpDefaultToolCallRenderer}, so "no translator registered" and
|
|
91
|
+
* "a translator that does not claim this error" produce byte-identical results.
|
|
222
92
|
*/
|
|
223
93
|
toToolCallResult(failure) {
|
|
224
|
-
|
|
225
|
-
if (!renderer)
|
|
226
|
-
return this.defaultToolCall.toToolCallResult(failure);
|
|
227
|
-
return this.withDefaultMeta(this.appOrDefault(renderer, failure));
|
|
94
|
+
return this.withDefaultMeta(this.appOrDefault(McpRegistry_1.McpRegistry.getErrorTranslator(), failure));
|
|
228
95
|
}
|
|
229
96
|
/** The `_meta` every tools/call result carries so a user can quote its requestId. */
|
|
230
97
|
resultMeta(requestId) {
|
|
231
|
-
return { [
|
|
98
|
+
return { [McpToolCallRendering_1.MCP_REQUEST_ID_META_KEY]: requestId };
|
|
232
99
|
}
|
|
233
100
|
/**
|
|
234
101
|
* An app translator that THROWS must not replace the failure being reported: its own bug is
|
|
235
102
|
* logged here and the ORIGINAL error still renders through the webpieces default, so the model
|
|
236
103
|
* still gets a reply carrying the requestId.
|
|
104
|
+
*
|
|
105
|
+
* This is BUG CONTAINMENT, not a "did anyone register one" branch — the same shape as
|
|
106
|
+
* `ClientErrorTranslator.throwIfFailure` on the HTTP side.
|
|
237
107
|
*/
|
|
238
108
|
appOrDefault(renderer, failure) {
|
|
239
109
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- an app translator's own bug must not replace the failure it was asked to render
|
|
240
110
|
try {
|
|
241
|
-
return renderer.
|
|
111
|
+
return renderer.toWire(failure);
|
|
242
112
|
}
|
|
243
113
|
catch (err) {
|
|
244
114
|
const error = (0, core_util_1.toError)(err);
|
|
245
|
-
log.error('Application
|
|
246
|
-
return this.defaultToolCall.
|
|
115
|
+
log.error('Application McpErrorTranslator.toWire threw; rendering the webpieces default.', error);
|
|
116
|
+
return this.defaultToolCall.toWire(failure);
|
|
247
117
|
}
|
|
248
118
|
}
|
|
249
119
|
/**
|
|
@@ -254,12 +124,12 @@ class WpMcpErrorTranslator {
|
|
|
254
124
|
withDefaultMeta(result) {
|
|
255
125
|
if (result._meta !== undefined)
|
|
256
126
|
return result;
|
|
257
|
-
return { ...result, _meta: this.resultMeta(McpCorrelation.requestId()) };
|
|
127
|
+
return { ...result, _meta: this.resultMeta(McpToolCallRendering_1.McpCorrelation.requestId()) };
|
|
258
128
|
}
|
|
259
129
|
httpError(status, code, message, headers) {
|
|
260
|
-
const correlation = McpCorrelation.current();
|
|
261
|
-
const requestId = McpCorrelation.requestId();
|
|
262
|
-
return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(status, message), headers, new McpHttpErrorBody(new McpHttpErrorDetail(code, message, new McpErrorData(requestId)), correlation.jsonRpcId));
|
|
130
|
+
const correlation = McpToolCallRendering_1.McpCorrelation.current();
|
|
131
|
+
const requestId = McpToolCallRendering_1.McpCorrelation.requestId();
|
|
132
|
+
return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(status, message), headers, new McpToolCallRendering_1.McpHttpErrorBody(new McpToolCallRendering_1.McpHttpErrorDetail(code, message, new McpToolCallRendering_1.McpErrorData(requestId)), correlation.jsonRpcId));
|
|
263
133
|
}
|
|
264
134
|
}
|
|
265
135
|
exports.WpMcpErrorTranslator = WpMcpErrorTranslator;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WpMcpErrorTranslator.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/WpMcpErrorTranslator.ts"],"names":[],"mappings":";;;AAAA,yDAAgG;AAChG,oDAW8B;AAC9B,0DAAyD;AAEzD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;AAEzD,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;IACA;IAVpB,mGAAmG;IACnG,MAAM,CAAU,GAAG,GAAG,sBAAU,CAAC,SAAS,CACtC,2BAA2B,EAC3B,SAAS,EACT,KAAK;IACL,YAAY,CAAC,KAAK,CACrB,CAAC;IAEF,YACoB,SAAiC,EACjC,QAAiB;QADjB,cAAS,GAAT,SAAS,CAAwB;QACjC,aAAQ,GAAR,QAAQ,CAAS;IAClC,CAAC;IAEJ,iGAAiG;IACjG,0FAA0F;IAC1F,MAAM,CAAC,KAAK,CAAC,WAA2B;QACpC,6BAAc,CAAC,YAAY,CAAC,cAAc,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IACjE,CAAC;IAED,mGAAmG;IACnG,0FAA0F;IAC1F,MAAM,CAAC,OAAO;QACV,OAAO,6BAAc,CAAC,YAAY,CAAC,cAAc,CAAC,GAAG,CAAC,IAAI,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC;IACvF,CAAC;IAED,0FAA0F;IAC1F,0FAA0F;IAC1F,MAAM,CAAC,SAAS;QACZ,OAAO,6BAAc,CAAC,YAAY,CAAC,gCAAoB,CAAC,UAAU,CAAC,IAAI,oBAAoB,CAAC;IAChG,CAAC;;AA9BL,wCA+BC;AAED,yEAAyE;AACzE,MAAa,qBAAqB;IAEV;IACA;IACA;IACA;IAC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gB,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,GAAG,CAAC,KAAK,CACL,0FAA0F,EAC1F,KAAK,CACR,CAAC;YACF,OAAO,IAAI,CAAC,eAAe,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAC1D,CAAC;IACL,CAAC;IAED;;;;OAIG;IACK,eAAe,CAAC,MAAsB;QAC1C,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,MAAM,CAAC;QAC9C,OAAO,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC,EAAE,CAAC;IAC7E,CAAC;IAEO,SAAS,CACb,MAAc,EACd,IAAY,EACZ,OAAe,EACf,OAAqB;QAErB,MAAM,WAAW,GAAG,cAAc,CAAC,OAAO,EAAE,CAAC;QAC7C,MAAM,SAAS,GAAG,cAAc,CAAC,SAAS,EAAE,CAAC;QAC7C,OAAO,IAAI,2BAAe,CACtB,IAAI,8BAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,OAAO,EACP,IAAI,gBAAgB,CAChB,IAAI,kBAAkB,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,YAAY,CAAC,SAAS,CAAC,CAAC,EAClE,WAAW,CAAC,SAAS,CACxB,CACJ,CAAC;IACN,CAAC;CACJ;AA/ID,oDA+IC","sourcesContent":["import { CallToolResult, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';\nimport {\n ApiErrorBoundary,\n ApiErrorPayload,\n ContextKey,\n DtoValue,\n HttpHeader,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\n\nconst log = LogManager.getLogger('WpMcpErrorTranslator');\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 ) {}\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 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/** 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 `ErrorTranslators` an\n * app registers on `ClientRegistry` for the HTTP path. Register one with\n * `WpMcpServerConfig.setErrorTranslator(...)`; it is NOT a global, because `WpMcpServer` is\n * constructed by app code and two servers may run in one process.\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 * 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().toToolCallResult(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. The pre-SDK HTTP boundary and `tools/list` stay framework-owned:\n * that boundary emits the `401 + WWW-Authenticate: Bearer resource_metadata=...` MCP clients\n * depend on for OAuth discovery, and an app rewriting it breaks connector onboarding.\n */\nexport interface McpErrorTranslators {\n toToolCallResult(error: Error): CallToolResult;\n}\n\n/**\n * webpieces' DEFAULT `tools/call` rendering, as a public class so an app's own\n * {@link McpErrorTranslators} can DECLINE an error by delegating to it — the MCP twin of\n * `ApiErrorHttpMapper.toResponse` 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 McpErrorTranslators {\n private readonly boundary = new ApiErrorBoundary();\n\n toToolCallResult(error: Error): CallToolResult {\n const requestId = McpCorrelation.requestId();\n const visible = this.modelVisible(this.boundary.encode(error), requestId);\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 private modelVisible(payload: ApiErrorPayload, requestId: string): ModelVisibleToolError {\n switch (payload.kind) {\n case 'end-user':\n return new ModelVisibleToolError(\n payload.kind,\n payload.message,\n requestId,\n undefined,\n undefined,\n payload.errorCode,\n );\n case 'bad-request':\n return new ModelVisibleToolError(\n payload.kind,\n payload.callerMessage ?? payload.message,\n requestId,\n payload.field,\n payload.callerMessage,\n );\n case 'coded':\n return new ModelVisibleToolError(\n payload.kind,\n payload.message,\n requestId,\n undefined,\n undefined,\n payload.errorCode,\n undefined,\n payload.statusCode,\n );\n case 'implementation':\n return new ModelVisibleToolError(\n payload.kind,\n `Internal error in tool ${McpCorrelation.current().toolName ?? 'unknown'} ` +\n `(requestId ${requestId}). This is a bug in the tool, not in your ` +\n 'arguments; retrying with different arguments will not help.',\n requestId,\n );\n default:\n return new ModelVisibleToolError(\n payload.kind,\n payload.message,\n requestId,\n undefined,\n undefined,\n undefined,\n payload.retryAfterSeconds,\n );\n }\n }\n}\n\n/**\n * The ONE place every MCP failure becomes a reply, mirroring `ApiErrorHttpMapper` for HTTP: an error\n * in, the exact wire shape out. There is one method per BOUNDARY, and the MCP spec is what makes\n * them three rather than one:\n *\n * | Boundary | Who writes HTTP | Failure shape |\n * |--------------------------------|-----------------|-------------------------------------|\n * | pre-SDK bearer / Origin / body | **webpieces** | `HttpResponseDto<McpHttpErrorBody>` |\n * | `tools/list` | the SDK | `throw ProtocolError` |\n * | `tools/call` | the SDK | `CallToolResult` with `isError` |\n *\n * Classification and published text are the shared {@link ApiErrorBoundary} rules. Operator logging\n * is NOT here: `LogApiCall` wraps each of those boundaries in `WpMcpServer`, so every failure gets\n * exactly one `[API-server-resp-*]` line with the request and the identity on it.\n */\nexport class WpMcpErrorTranslator {\n private readonly boundary = new ApiErrorBoundary();\n private readonly defaultToolCall = new McpDefaultToolCallRenderer();\n\n /**\n * @param challenge - the `WWW-Authenticate` value for a 401, read lazily because\n * `WpMcpServerConfig` is only fully validated at `bind(...)` time.\n * @param appTranslators - the app's `tools/call` seam; `undefined` means webpieces renders all.\n */\n constructor(\n private readonly challenge: () => string,\n private readonly appTranslators?: McpErrorTranslators,\n ) {}\n\n /**\n * Boundary #1: everything webpieces itself rejects before the SDK is involved — bearer\n * verification, `Origin`, a malformed body. This is 401/403/400/500 today and any status\n * tomorrow, so it produces a VALUE like every other API in the framework and `WpMcpServer` hands\n * it to the shared express writer. The BODY stays JSON-RPC shaped because an MCP client expects\n * that; `HttpResponseDto` is generic, and its header LIST carries `WWW-Authenticate`.\n */\n toBearerBoundaryResponse(error: Error): HttpResponseDto<McpHttpErrorBody> {\n const payload = this.boundary.encode(error);\n const generic = payload.message;\n switch (payload.kind) {\n case 'unauthorized':\n return this.httpError(401, -32_000, generic, [\n new HttpHeader('WWW-Authenticate', this.challenge()),\n ]);\n case 'forbidden':\n return this.httpError(403, -32_000, generic, []);\n case 'bad-request':\n return this.httpError(400, ProtocolErrorCode.ParseError, generic, []);\n default:\n return this.httpError(500, ProtocolErrorCode.InternalError, 'Internal Error', []);\n }\n }\n\n /**\n * Boundary #2: `tools/list` has no tool-result channel, so a failure IS a JSON-RPC error. It\n * THROWS rather than returning a value the caller must remember to throw, and is typed `never`\n * so the compiler knows the call is terminal.\n *\n * This is LOAD-BEARING for disclosure, not defence in depth. Measured on\n * `@modelcontextprotocol/server` 2.0.0 and pinned by `McpSdkForeignThrow.spec.ts`: the SDK wraps\n * a foreign (non-`ProtocolError`) throw in `-32603` but copies its `message` onto the wire\n * VERBATIM. So a `tools/list` handler that lets any error escape un-translated publishes that\n * error's operator text to the caller.\n */\n toListError(error: Error): never {\n const payload = this.boundary.encode(error);\n const requestId = McpCorrelation.requestId();\n if (payload.kind === 'bad-request') {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n payload.callerMessage ?? payload.message,\n new McpErrorData(requestId),\n );\n }\n const message = payload.kind === 'end-user' ? payload.message : 'Internal Error';\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n message,\n new McpErrorData(requestId),\n );\n }\n\n /** tools/call with a name no binding registered: a JSON-RPC protocol error per MCP 2026-07-28. */\n unknownTool(toolName: string): ProtocolError {\n const requestId = McpCorrelation.requestId();\n log.info(`Unknown MCP tool: ${toolName} requestId=${requestId}`);\n return new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown tool: ${toolName}`,\n new McpErrorData(requestId),\n );\n }\n\n /**\n * Boundary #3: every tools/call failure after the tool is found — an `isError: true` result the\n * model sees.\n *\n * A registered {@link McpErrorTranslators} REPLACES the default and declines by delegating to\n * {@link McpDefaultToolCallRenderer}, so \"no translator registered\" and \"a translator that does\n * not claim this error\" produce byte-identical results.\n */\n toToolCallResult(failure: Error): CallToolResult {\n const renderer = this.appTranslators;\n if (!renderer) return this.defaultToolCall.toToolCallResult(failure);\n return this.withDefaultMeta(this.appOrDefault(renderer, failure));\n }\n\n /** The `_meta` every tools/call result carries so a user can quote its requestId. */\n resultMeta(requestId: string): Record<string, string> {\n return { [MCP_REQUEST_ID_META_KEY]: requestId };\n }\n\n /**\n * An app translator that THROWS must not replace the failure being reported: its own bug is\n * logged here and the ORIGINAL error still renders through the webpieces default, so the model\n * still gets a reply carrying the requestId.\n */\n private appOrDefault(renderer: McpErrorTranslators, failure: Error): CallToolResult {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- an app translator's own bug must not replace the failure it was asked to render\n try {\n return renderer.toToolCallResult(failure);\n } catch (err: unknown) {\n const error = toError(err);\n log.error(\n 'Application McpErrorTranslators.toToolCallResult threw; rendering the webpieces default.',\n error,\n );\n return this.defaultToolCall.toToolCallResult(failure);\n }\n }\n\n /**\n * webpieces fills `_meta` only when the app left it off, keeping the README's \"every reply\n * carries the requestId\" promise a DEFAULT rather than a restriction: an app that set `_meta`\n * keeps it byte-for-byte.\n */\n private withDefaultMeta(result: CallToolResult): CallToolResult {\n if (result._meta !== undefined) return result;\n return { ...result, _meta: this.resultMeta(McpCorrelation.requestId()) };\n }\n\n private httpError(\n status: number,\n code: number,\n message: string,\n headers: HttpHeader[],\n ): HttpResponseDto<McpHttpErrorBody> {\n const correlation = McpCorrelation.current();\n const requestId = McpCorrelation.requestId();\n return new HttpResponseDto<McpHttpErrorBody>(\n new HttpResponseStatus(status, message),\n headers,\n new McpHttpErrorBody(\n new McpHttpErrorDetail(code, message, new McpErrorData(requestId)),\n correlation.jsonRpcId,\n ),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WpMcpErrorTranslator.js","sourceRoot":"","sources":["../../../../../packages/http/mcp-server/src/WpMcpErrorTranslator.ts"],"names":[],"mappings":";;;AAAA,yDAAgG;AAChG,oDAO8B;AAC9B,+CAA4C;AAC5C,iEAQgC;AAEhC,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;AAEzD;;;;;;;;;;;;;;GAcG;AACH,MAAa,oBAAoB;IAQA;IAPZ,QAAQ,GAAG,IAAI,4BAAgB,EAAE,CAAC;IAClC,eAAe,GAAG,IAAI,iDAA0B,EAAE,CAAC;IAEpE;;;OAGG;IACH,YAA6B,SAAuB;QAAvB,cAAS,GAAT,SAAS,CAAc;IAAG,CAAC;IAExD;;;;;;OAMG;IACH,wBAAwB,CAAC,KAAY;QACjC,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAChC,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,cAAc;gBACf,O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,EACf,OAAqB;QAErB,MAAM,WAAW,GAAG,qCAAc,CAAC,OAAO,EAAE,CAAC;QAC7C,MAAM,SAAS,GAAG,qCAAc,CAAC,SAAS,EAAE,CAAC;QAC7C,OAAO,IAAI,2BAAe,CACtB,IAAI,8BAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,OAAO,EACP,IAAI,uCAAgB,CAChB,IAAI,yCAAkB,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,mCAAY,CAAC,SAAS,CAAC,CAAC,EAClE,WAAW,CAAC,SAAS,CACxB,CACJ,CAAC;IACN,CAAC;CACJ;AA7ID,oDA6IC","sourcesContent":["import { CallToolResult, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';\nimport {\n ApiErrorBoundary,\n HttpHeader,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n toError,\n} from '@webpieces/core-util';\nimport { McpRegistry } from './McpRegistry';\nimport {\n McpCorrelation,\n McpDefaultToolCallRenderer,\n McpErrorData,\n McpErrorTranslator,\n McpHttpErrorBody,\n McpHttpErrorDetail,\n MCP_REQUEST_ID_META_KEY,\n} from './McpToolCallRendering';\n\nconst log = LogManager.getLogger('WpMcpErrorTranslator');\n\n/**\n * The ONE place every MCP failure becomes a reply, mirroring `WebpiecesDefaultErrorTranslator` for HTTP: an error\n * in, the exact wire shape out. There is one method per BOUNDARY, and the MCP spec is what makes\n * them three rather than one:\n *\n * | Boundary | Who writes HTTP | Failure shape |\n * |--------------------------------|-----------------|-------------------------------------|\n * | pre-SDK bearer / Origin / body | **webpieces** | `HttpResponseDto<McpHttpErrorBody>` |\n * | `tools/list` | the SDK | `throw ProtocolError` |\n * | `tools/call` | the SDK | `CallToolResult` with `isError` |\n *\n * Classification and published text are the shared {@link ApiErrorBoundary} rules. Operator logging\n * is NOT here: `LogApiCall` wraps each of those boundaries in `WpMcpServer`, so every failure gets\n * exactly one `[API-server-resp-*]` line with the request and the identity on it.\n */\nexport class WpMcpErrorTranslator {\n private readonly boundary = new ApiErrorBoundary();\n private readonly defaultToolCall = new McpDefaultToolCallRenderer();\n\n /**\n * @param challenge - the `WWW-Authenticate` value for a 401, read lazily because\n * `WpMcpServerConfig` is only fully validated at `bind(...)` time.\n */\n constructor(private readonly challenge: () => string) {}\n\n /**\n * Boundary #1: everything webpieces itself rejects before the SDK is involved — bearer\n * verification, `Origin`, a malformed body. This is 401/403/400/500 today and any status\n * tomorrow, so it produces a VALUE like every other API in the framework and `WpMcpServer` hands\n * it to the shared express writer. The BODY stays JSON-RPC shaped because an MCP client expects\n * that; `HttpResponseDto` is generic, and its header LIST carries `WWW-Authenticate`.\n */\n toBearerBoundaryResponse(error: Error): HttpResponseDto<McpHttpErrorBody> {\n const payload = this.boundary.encode(error);\n const generic = payload.message;\n switch (payload.kind) {\n case 'unauthorized':\n return this.httpError(401, -32_000, generic, [\n new HttpHeader('WWW-Authenticate', this.challenge()),\n ]);\n case 'forbidden':\n return this.httpError(403, -32_000, generic, []);\n case 'bad-request':\n return this.httpError(400, ProtocolErrorCode.ParseError, generic, []);\n default:\n return this.httpError(500, ProtocolErrorCode.InternalError, 'Internal Error', []);\n }\n }\n\n /**\n * Boundary #2: `tools/list` has no tool-result channel, so a failure IS a JSON-RPC error. It\n * THROWS rather than returning a value the caller must remember to throw, and is typed `never`\n * so the compiler knows the call is terminal.\n *\n * This is LOAD-BEARING for disclosure, not defence in depth. Measured on\n * `@modelcontextprotocol/server` 2.0.0 and pinned by `McpSdkForeignThrow.spec.ts`: the SDK wraps\n * a foreign (non-`ProtocolError`) throw in `-32603` but copies its `message` onto the wire\n * VERBATIM. So a `tools/list` handler that lets any error escape un-translated publishes that\n * error's operator text to the caller.\n */\n toListError(error: Error): never {\n const payload = this.boundary.encode(error);\n const requestId = McpCorrelation.requestId();\n if (payload.kind === 'bad-request') {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n payload.callerMessage ?? payload.message,\n new McpErrorData(requestId),\n );\n }\n const message = payload.kind === 'end-user' ? payload.message : 'Internal Error';\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n message,\n new McpErrorData(requestId),\n );\n }\n\n /** tools/call with a name no binding registered: a JSON-RPC protocol error in either MCP era. */\n unknownTool(toolName: string): ProtocolError {\n const requestId = McpCorrelation.requestId();\n log.info(`Unknown MCP tool: ${toolName} requestId=${requestId}`);\n return new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown tool: ${toolName}`,\n new McpErrorData(requestId),\n );\n }\n\n /**\n * Boundary #3: every tools/call failure after the tool is found — an `isError: true` result the\n * model sees.\n *\n * ONE unconditional line: {@link McpRegistry.getErrorTranslator} is never undefined, so there is\n * no \"was one registered\" branch. A registered {@link McpErrorTranslator} REPLACES the default and\n * declines by delegating to {@link McpDefaultToolCallRenderer}, so \"no translator registered\" and\n * \"a translator that does not claim this error\" produce byte-identical results.\n */\n toToolCallResult(failure: Error): CallToolResult {\n return this.withDefaultMeta(this.appOrDefault(McpRegistry.getErrorTranslator(), failure));\n }\n\n /** The `_meta` every tools/call result carries so a user can quote its requestId. */\n resultMeta(requestId: string): Record<string, string> {\n return { [MCP_REQUEST_ID_META_KEY]: requestId };\n }\n\n /**\n * An app translator that THROWS must not replace the failure being reported: its own bug is\n * logged here and the ORIGINAL error still renders through the webpieces default, so the model\n * still gets a reply carrying the requestId.\n *\n * This is BUG CONTAINMENT, not a \"did anyone register one\" branch — the same shape as\n * `ClientErrorTranslator.throwIfFailure` on the HTTP side.\n */\n private appOrDefault(renderer: McpErrorTranslator, failure: Error): CallToolResult {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- an app translator's own bug must not replace the failure it was asked to render\n try {\n return renderer.toWire(failure);\n } catch (err: unknown) {\n const error = toError(err);\n log.error(\n 'Application McpErrorTranslator.toWire threw; rendering the webpieces default.',\n error,\n );\n return this.defaultToolCall.toWire(failure);\n }\n }\n\n /**\n * webpieces fills `_meta` only when the app left it off, keeping the README's \"every reply\n * carries the requestId\" promise a DEFAULT rather than a restriction: an app that set `_meta`\n * keeps it byte-for-byte.\n */\n private withDefaultMeta(result: CallToolResult): CallToolResult {\n if (result._meta !== undefined) return result;\n return { ...result, _meta: this.resultMeta(McpCorrelation.requestId()) };\n }\n\n private httpError(\n status: number,\n code: number,\n message: string,\n headers: HttpHeader[],\n ): HttpResponseDto<McpHttpErrorBody> {\n const correlation = McpCorrelation.current();\n const requestId = McpCorrelation.requestId();\n return new HttpResponseDto<McpHttpErrorBody>(\n new HttpResponseStatus(status, message),\n headers,\n new McpHttpErrorBody(\n new McpHttpErrorDetail(code, message, new McpErrorData(requestId)),\n correlation.jsonRpcId,\n ),\n );\n }\n}\n"]}
|
package/src/WpMcpServer.d.ts
CHANGED
|
@@ -2,7 +2,12 @@ import { Express } from 'express';
|
|
|
2
2
|
import { McpProtectedResourceMetadata, WpMcpServerConfig } from './McpAuth';
|
|
3
3
|
import { McpBindOptions } from './McpBindOptions';
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
5
|
+
* MCP adapter around the official SDK's request-scoped HTTP handler, serving BOTH wire eras from
|
|
6
|
+
* one tool registry: modern (2026-07-28, per-request `_meta` envelope) and legacy (the 2025-11-25
|
|
7
|
+
* family, negotiated by `initialize`). The SDK routes each request to the leg its shape selects and
|
|
8
|
+
* negotiates the revision; only a revision no era knows is refused. Pinning one era instead made
|
|
9
|
+
* every shipping client unreachable (issue #969), and the MCP lifecycle spec is explicit that a
|
|
10
|
+
* server answers with a revision it supports rather than erroring.
|
|
6
11
|
*
|
|
7
12
|
* Error boundary: every failure is mapped by the one `WpMcpErrorTranslator`, and each entry point
|
|
8
13
|
* has exactly one catch that only delegates to it: the bind HTTP handler
|
|
@@ -22,7 +27,7 @@ export declare class WpMcpServer<TGrant, TMintRequest> {
|
|
|
22
27
|
*/
|
|
23
28
|
private readonly logApiCall;
|
|
24
29
|
private readonly responseWriter;
|
|
25
|
-
/** tools/call
|
|
30
|
+
/** tools/call reads `McpRegistry`; every other reply stays framework-owned. See McpErrorTranslator. */
|
|
26
31
|
private readonly translator;
|
|
27
32
|
private registry?;
|
|
28
33
|
private handler?;
|
package/src/WpMcpServer.js
CHANGED
|
@@ -12,6 +12,7 @@ const McpAuth_1 = require("./McpAuth");
|
|
|
12
12
|
const McpApiDispatcher_1 = require("./McpApiDispatcher");
|
|
13
13
|
const McpInvocationContext_1 = require("./McpInvocationContext");
|
|
14
14
|
const McpToolRegistry_1 = require("./McpToolRegistry");
|
|
15
|
+
const McpToolCallRendering_1 = require("./McpToolCallRendering");
|
|
15
16
|
const WpMcpErrorTranslator_1 = require("./WpMcpErrorTranslator");
|
|
16
17
|
const log = core_util_1.LogManager.getLogger('WpMcpServer');
|
|
17
18
|
/**
|
|
@@ -56,7 +57,12 @@ class WpSdkMcpServer extends server_1.McpServer {
|
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
/**
|
|
59
|
-
*
|
|
60
|
+
* MCP adapter around the official SDK's request-scoped HTTP handler, serving BOTH wire eras from
|
|
61
|
+
* one tool registry: modern (2026-07-28, per-request `_meta` envelope) and legacy (the 2025-11-25
|
|
62
|
+
* family, negotiated by `initialize`). The SDK routes each request to the leg its shape selects and
|
|
63
|
+
* negotiates the revision; only a revision no era knows is refused. Pinning one era instead made
|
|
64
|
+
* every shipping client unreachable (issue #969), and the MCP lifecycle spec is explicit that a
|
|
65
|
+
* server answers with a revision it supports rather than erroring.
|
|
60
66
|
*
|
|
61
67
|
* Error boundary: every failure is mapped by the one `WpMcpErrorTranslator`, and each entry point
|
|
62
68
|
* has exactly one catch that only delegates to it: the bind HTTP handler
|
|
@@ -76,7 +82,7 @@ class WpMcpServer {
|
|
|
76
82
|
*/
|
|
77
83
|
logApiCall = new core_util_1.LogApiCallImpl(new core_context_1.RequestContextApiCallContext());
|
|
78
84
|
responseWriter = new http_server_1.ExpressResponseWriter();
|
|
79
|
-
/** tools/call
|
|
85
|
+
/** tools/call reads `McpRegistry`; every other reply stays framework-owned. See McpErrorTranslator. */
|
|
80
86
|
translator;
|
|
81
87
|
registry;
|
|
82
88
|
handler;
|
|
@@ -86,7 +92,7 @@ class WpMcpServer {
|
|
|
86
92
|
revision;
|
|
87
93
|
constructor(config) {
|
|
88
94
|
this.config = config;
|
|
89
|
-
this.translator = new WpMcpErrorTranslator_1.WpMcpErrorTranslator(() => this.challenge()
|
|
95
|
+
this.translator = new WpMcpErrorTranslator_1.WpMcpErrorTranslator(() => this.challenge());
|
|
90
96
|
}
|
|
91
97
|
/**
|
|
92
98
|
* Mounts this MCP endpoint on `app`: POST at `options.endpointPath`, plus a 405 (`Allow: POST`)
|
|
@@ -131,9 +137,11 @@ class WpMcpServer {
|
|
|
131
137
|
(bodyError, req, res, _next) => {
|
|
132
138
|
void this.handleBodyFailure(bodyError, req, res);
|
|
133
139
|
});
|
|
134
|
-
// Registered AFTER the POST route so POST still wins.
|
|
135
|
-
// (`subscriptions/listen` is a POST method),
|
|
136
|
-
//
|
|
140
|
+
// Registered AFTER the POST route so POST still wins. NEITHER era served here has a session
|
|
141
|
+
// GET: 2026-07-28 has none at all (`subscriptions/listen` is a POST method), and the legacy
|
|
142
|
+
// leg is the SDK's STATELESS fallback, which answers the 2025 session GET/DELETE with the
|
|
143
|
+
// same 405. So every other method is a method error — and a discovery probe gets that
|
|
144
|
+
// instead of Express' bare 404.
|
|
137
145
|
app.all(options.endpointPath, (_req, res) => {
|
|
138
146
|
res.setHeader('Allow', 'POST');
|
|
139
147
|
res.status(405).json(new McpMethodNotAllowedBody());
|
|
@@ -155,7 +163,9 @@ class WpMcpServer {
|
|
|
155
163
|
}
|
|
156
164
|
createHandler(options, responseMode) {
|
|
157
165
|
return (0, server_1.createMcpHandler)((context) => this.buildSdkServer(context, options), {
|
|
158
|
-
|
|
166
|
+
// Both eras, one factory: `stateless` serves 2025-era traffic through a fresh
|
|
167
|
+
// instance of the SAME McpServerFactory, so the two eras can never drift apart.
|
|
168
|
+
legacy: 'stateless',
|
|
159
169
|
responseMode,
|
|
160
170
|
bus: options.deployment.bus,
|
|
161
171
|
maxSubscriptions: options.maxSubscriptions,
|
|
@@ -168,7 +178,7 @@ class WpMcpServer {
|
|
|
168
178
|
res.setHeader('X-Accel-Buffering', 'no');
|
|
169
179
|
await core_context_1.RequestContext.run(async () => {
|
|
170
180
|
new core_context_1.RequestContextHeaders().fillFromRequest(this.toHttpRequest(req));
|
|
171
|
-
|
|
181
|
+
McpToolCallRendering_1.McpCorrelation.stamp(this.correlationOf(req));
|
|
172
182
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- MCP HTTP entry point; delegates only to WpMcpErrorTranslator
|
|
173
183
|
try {
|
|
174
184
|
await this.logEdge('serve', () => this.serveExpress(req, res, options));
|
|
@@ -183,7 +193,7 @@ class WpMcpServer {
|
|
|
183
193
|
async handleBodyFailure(cause, req, res) {
|
|
184
194
|
await core_context_1.RequestContext.run(async () => {
|
|
185
195
|
new core_context_1.RequestContextHeaders().fillFromRequest(this.toHttpRequest(req));
|
|
186
|
-
|
|
196
|
+
McpToolCallRendering_1.McpCorrelation.stamp(this.correlationOf(req));
|
|
187
197
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- MCP body entry point; delegates only to WpMcpErrorTranslator
|
|
188
198
|
try {
|
|
189
199
|
await this.logEdge('body', () => this.rejectBody(cause));
|
|
@@ -254,9 +264,12 @@ class WpMcpServer {
|
|
|
254
264
|
return disconnected.signal;
|
|
255
265
|
}
|
|
256
266
|
buildSdkServer(context, options) {
|
|
267
|
+
// The era is the SDK's to decide and BOTH are served; what is not negotiable is that the
|
|
268
|
+
// request came through `bind`'s HTTP boundary, which is where the external bearer is
|
|
269
|
+
// verified. A factory call without it is a wiring mistake, never a client's doing.
|
|
257
270
|
const authentication = context.authInfo?.extra?.['webpiecesAuthentication'];
|
|
258
|
-
if (
|
|
259
|
-
throw new core_util_1.ApiImplementationError('WpMcpServer serves only MCP
|
|
271
|
+
if (!(authentication instanceof McpPostAuthentication)) {
|
|
272
|
+
throw new core_util_1.ApiImplementationError('WpMcpServer serves only MCP requests authenticated by its bind boundary.');
|
|
260
273
|
}
|
|
261
274
|
const registry = this.requireRegistry();
|
|
262
275
|
const server = new WpSdkMcpServer({ name: this.config.name, version: `${this.config.version}+${this.revision}` }, {
|
|
@@ -307,14 +320,14 @@ class WpMcpServer {
|
|
|
307
320
|
*/
|
|
308
321
|
async handleCallTool(server, request, authentication, sdkContext) {
|
|
309
322
|
const name = request.params.name;
|
|
310
|
-
|
|
323
|
+
McpToolCallRendering_1.McpCorrelation.stamp(new McpToolCallRendering_1.McpCorrelation(sdkContext.mcpReq.id, name));
|
|
311
324
|
const tool = this.requireRegistry().find(name);
|
|
312
325
|
if (!tool)
|
|
313
326
|
throw this.translator.unknownTool(name);
|
|
314
327
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- MCP tools/call entry point; delegates only to WpMcpErrorTranslator
|
|
315
328
|
try {
|
|
316
329
|
const result = await this.callTool(tool, request, authentication, sdkContext);
|
|
317
|
-
result._meta = this.translator.resultMeta(
|
|
330
|
+
result._meta = this.translator.resultMeta(McpToolCallRendering_1.McpCorrelation.requestId());
|
|
318
331
|
return server.server.projectCallToolResult(result, tool.outputSchema);
|
|
319
332
|
}
|
|
320
333
|
catch (err) {
|
|
@@ -425,7 +438,7 @@ class WpMcpServer {
|
|
|
425
438
|
const id = body?.['id'];
|
|
426
439
|
const params = this.bodyObject(body?.['params']);
|
|
427
440
|
const name = params?.['name'];
|
|
428
|
-
return new
|
|
441
|
+
return new McpToolCallRendering_1.McpCorrelation(typeof id === 'string' || typeof id === 'number' ? id : null, typeof name === 'string' ? name : undefined);
|
|
429
442
|
}
|
|
430
443
|
challenge() {
|
|
431
444
|
return `Bearer resource_metadata="${this.config.resourceMetadataUrl}"`;
|