@casys/mcp-server 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -0
- package/mod.ts +3 -0
- package/package.json +1 -1
- package/src/client-auth/provider.ts +157 -3
- package/src/client-auth/types.ts +14 -1
- package/src/mcp-app.ts +239 -22
- package/src/mrtr/mod.ts +7 -0
- package/src/mrtr/replay-store.ts +103 -0
- package/src/mrtr/types.ts +14 -0
- package/src/observability/mod.ts +1 -0
- package/src/observability/otel.ts +222 -1
- package/src/testdata/stdio-e2e-server.ts +30 -0
- package/src/validation/schema-validator.ts +14 -1
package/README.md
CHANGED
|
@@ -239,6 +239,59 @@ MCP_AUTH_AUDIENCE=https://prod.example.com ./my-server --http --port 3000
|
|
|
239
239
|
|
|
240
240
|
Priority: `programmatic > env vars > YAML > no auth`
|
|
241
241
|
|
|
242
|
+
### MRTR requestState replay protection
|
|
243
|
+
|
|
244
|
+
When a tool returns `resultType: "input_required"`, configure a signing key so
|
|
245
|
+
the framework can bind the continuation to the principal, method, arguments,
|
|
246
|
+
expiry, and a random nonce:
|
|
247
|
+
|
|
248
|
+
```typescript
|
|
249
|
+
const server = new McpApp({
|
|
250
|
+
name: "my-api",
|
|
251
|
+
version: "1.0.0",
|
|
252
|
+
mrtr: {
|
|
253
|
+
signingKey: Deno.env.get("MCP_MRTR_SIGNING_KEY"),
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Each verified nonce is consumed before the handler runs. With no explicit
|
|
259
|
+
`replayStore`, the built-in `MemoryMrtrReplayStore` rejects a second use within
|
|
260
|
+
one continuously running process.
|
|
261
|
+
|
|
262
|
+
Multi-instance or restart-safe deployments must inject one durable atomic store
|
|
263
|
+
shared by every instance:
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
import type { MrtrReplayStore } from "@casys/mcp-server";
|
|
267
|
+
|
|
268
|
+
const replayStore: MrtrReplayStore = {
|
|
269
|
+
async consume(nonce, expiresAt) {
|
|
270
|
+
// Atomically reserve the nonce until its signed expiry.
|
|
271
|
+
// Redis equivalent: SET mrtr:<nonce> 1 NX EXAT <expiresAt>
|
|
272
|
+
return await reserveNonce(nonce, expiresAt);
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const server = new McpApp({
|
|
277
|
+
name: "my-api",
|
|
278
|
+
version: "1.0.0",
|
|
279
|
+
mrtr: {
|
|
280
|
+
signingKey: Deno.env.get("MCP_MRTR_SIGNING_KEY"),
|
|
281
|
+
replayStore,
|
|
282
|
+
},
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
`consume()` must return `true` only for the caller that wins the atomic
|
|
287
|
+
reservation, `false` for a nonce already consumed, and throw when the store is
|
|
288
|
+
unavailable. Store failures are fail-closed; the handler is not executed.
|
|
289
|
+
|
|
290
|
+
This is at-most-once admission, not exactly-once completion. If business logic
|
|
291
|
+
commits and the response is lost, replaying the same token is rejected.
|
|
292
|
+
Returning the prior result safely requires a separate idempotency/result ledger,
|
|
293
|
+
ideally paired with idempotency support in the downstream system.
|
|
294
|
+
|
|
242
295
|
### RFC 9728
|
|
243
296
|
|
|
244
297
|
When auth is configured, the framework automatically exposes
|
package/mod.ts
CHANGED
|
@@ -275,11 +275,14 @@ export type {
|
|
|
275
275
|
InputRequestEntry,
|
|
276
276
|
InputRequestMethod,
|
|
277
277
|
InputRequiredSignal,
|
|
278
|
+
MemoryMrtrReplayStoreOptions,
|
|
278
279
|
MrtrOptions,
|
|
280
|
+
MrtrReplayStore,
|
|
279
281
|
} from "./src/mrtr/mod.js";
|
|
280
282
|
export {
|
|
281
283
|
exportStateKey,
|
|
282
284
|
generateStateKey,
|
|
285
|
+
MemoryMrtrReplayStore,
|
|
283
286
|
sealRequestState,
|
|
284
287
|
verifyRequestState,
|
|
285
288
|
} from "./src/mrtr/mod.js";
|
package/package.json
CHANGED
|
@@ -13,7 +13,10 @@ import type {
|
|
|
13
13
|
OAuthClientMetadata,
|
|
14
14
|
OAuthTokens,
|
|
15
15
|
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
16
|
-
import type {
|
|
16
|
+
import type {
|
|
17
|
+
OAuthClientProvider,
|
|
18
|
+
OAuthDiscoveryState,
|
|
19
|
+
} from "@modelcontextprotocol/sdk/client/auth.js";
|
|
17
20
|
import type { OAuthClientConfig } from "./types.js";
|
|
18
21
|
import {
|
|
19
22
|
CimdConfigError,
|
|
@@ -22,12 +25,52 @@ import {
|
|
|
22
25
|
validateCimdClientConfig,
|
|
23
26
|
} from "./client-id-metadata.js";
|
|
24
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Normalise an authorization server identifier before comparing it.
|
|
30
|
+
*
|
|
31
|
+
* `https://as.example.com` and `https://as.example.com/` name the same server,
|
|
32
|
+
* and so do `HTTPS://AS.Example.com` and an explicit `:443`. Comparing raw
|
|
33
|
+
* strings would read those as a server change and wipe valid credentials on
|
|
34
|
+
* every call — a self-inflicted login loop. Falls back to the raw string if it
|
|
35
|
+
* does not parse, which then simply never matches.
|
|
36
|
+
*/
|
|
37
|
+
function canonicalIssuer(value: string): string {
|
|
38
|
+
try {
|
|
39
|
+
return new URL(value).href;
|
|
40
|
+
} catch {
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* An authorization server URL, safe to put in a log line.
|
|
47
|
+
*
|
|
48
|
+
* A URL may carry `userinfo` credentials, and a query string may carry a token
|
|
49
|
+
* or an internal identifier. Origin and path are enough to tell an operator
|
|
50
|
+
* which server is involved; the rest is only a way for secrets to reach a log
|
|
51
|
+
* aggregator.
|
|
52
|
+
*/
|
|
53
|
+
function redactUrl(value: string): string {
|
|
54
|
+
try {
|
|
55
|
+
const url = new URL(value);
|
|
56
|
+
return `${url.origin}${url.pathname}`;
|
|
57
|
+
} catch {
|
|
58
|
+
return "<unparseable url>";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
25
62
|
export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
26
63
|
private serverUrl: string;
|
|
27
64
|
private config: OAuthClientConfig;
|
|
28
65
|
private _codeVerifier = "";
|
|
29
66
|
private _clientInfo: OAuthClientInformationMixed | undefined;
|
|
30
67
|
private _redirectUrl: string | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* Issuer the SDK resolved for the request currently being authorized
|
|
70
|
+
* (SEP-2352). Set by {@link saveDiscoveryState}, which `auth()` calls after
|
|
71
|
+
* discovery and before it asks for tokens.
|
|
72
|
+
*/
|
|
73
|
+
private _currentIssuer: string | undefined;
|
|
31
74
|
|
|
32
75
|
constructor(serverUrl: string, config: OAuthClientConfig) {
|
|
33
76
|
const mode = resolveClientMode(config);
|
|
@@ -95,9 +138,93 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
95
138
|
return Promise.resolve();
|
|
96
139
|
}
|
|
97
140
|
|
|
141
|
+
/**
|
|
142
|
+
* Record the authorization server the SDK just resolved (SEP-2352).
|
|
143
|
+
*
|
|
144
|
+
* `auth()` calls this after RFC 9728 discovery and before {@link tokens},
|
|
145
|
+
* which is what makes the check there possible.
|
|
146
|
+
*
|
|
147
|
+
* The binding is the **discovered URL**, not `metadata.issuer`. That
|
|
148
|
+
* distinction is the whole protection: `issuer` is a field the authorization
|
|
149
|
+
* server publishes about itself, so an attacker's server reached at
|
|
150
|
+
* `https://attacker.example.com` can claim
|
|
151
|
+
* `issuer: "https://as-one.example.com"` and, since SDK 1.29 validates the
|
|
152
|
+
* metadata's shape without checking it against the URL it was fetched from,
|
|
153
|
+
* would be handed the credentials minted by the real AS-one. The URL the
|
|
154
|
+
* client actually resolved is the one thing in this exchange the server
|
|
155
|
+
* cannot forge.
|
|
156
|
+
*
|
|
157
|
+
* RFC 8414 does require `issuer` to match the discovery URL. A mismatch is
|
|
158
|
+
* therefore a broken or hostile authorization server, and it is logged —
|
|
159
|
+
* but nothing here depends on the claim being honest.
|
|
160
|
+
*/
|
|
161
|
+
saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
|
|
162
|
+
const resolved = canonicalIssuer(state.authorizationServerUrl);
|
|
163
|
+
const claimed = state.authorizationServerMetadata?.issuer;
|
|
164
|
+
|
|
165
|
+
if (claimed !== undefined && canonicalIssuer(claimed) !== resolved) {
|
|
166
|
+
this.log(
|
|
167
|
+
`authorization server at ${redactUrl(state.authorizationServerUrl)} ` +
|
|
168
|
+
`claims issuer "${redactUrl(claimed)}" ` +
|
|
169
|
+
"(RFC 8414 requires them to match); " +
|
|
170
|
+
"binding credentials to the discovered URL",
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
this._currentIssuer = resolved;
|
|
175
|
+
return Promise.resolve();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Stored tokens, unless they were issued by a different authorization server.
|
|
180
|
+
*
|
|
181
|
+
* SEP-2352 makes this a MUST, and the reason is concrete rather than
|
|
182
|
+
* bureaucratic. `auth()` hands whatever this returns to
|
|
183
|
+
* `refreshAuthorization(authorizationServerUrl, …)`, where the URL comes from
|
|
184
|
+
* the MCP server's own protected-resource metadata. A server that changes —
|
|
185
|
+
* or is made to advertise — a different authorization server would therefore
|
|
186
|
+
* receive a refresh token minted by the previous one. The client must not let
|
|
187
|
+
* the resource server pick who sees its credentials.
|
|
188
|
+
*
|
|
189
|
+
* The check only runs once an issuer is known, which is the case inside
|
|
190
|
+
* `auth()`. A transport asking for the bearer to attach to an ordinary
|
|
191
|
+
* request has no issuer in hand, and that path is not the exposure: those
|
|
192
|
+
* tokens go to the MCP server they were minted for, not to an authorization
|
|
193
|
+
* server.
|
|
194
|
+
*/
|
|
98
195
|
async tokens(): Promise<OAuthTokens | undefined> {
|
|
99
196
|
const stored = await this.config.tokenStore.get(this.serverUrl);
|
|
100
|
-
|
|
197
|
+
if (!stored) return undefined;
|
|
198
|
+
if (this._currentIssuer === undefined) return stored.tokens;
|
|
199
|
+
|
|
200
|
+
if (stored.authServerUrl === undefined) {
|
|
201
|
+
// Written before this binding existed: nothing proves which authorization
|
|
202
|
+
// server minted them. Treated as unusable rather than trusted once —
|
|
203
|
+
// the whole point is to stop handing credentials to an unverified party,
|
|
204
|
+
// and "probably fine" is the assumption this check exists to remove. The
|
|
205
|
+
// cost is one re-authorization per stored credential, at upgrade time.
|
|
206
|
+
await this.config.tokenStore.delete(this.serverUrl);
|
|
207
|
+
this.log(
|
|
208
|
+
"discarding stored credentials with no recorded issuer (SEP-2352); re-authorization required",
|
|
209
|
+
);
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (canonicalIssuer(stored.authServerUrl) !== this._currentIssuer) {
|
|
214
|
+
// A legitimate migration lands here too, and is handled the same way:
|
|
215
|
+
// drop the old credentials and let the flow re-authorize against the new
|
|
216
|
+
// server. What must not happen is the old refresh token travelling there.
|
|
217
|
+
await this.config.tokenStore.delete(this.serverUrl);
|
|
218
|
+
this.log(
|
|
219
|
+
`authorization server changed for ${redactUrl(this.serverUrl)} ` +
|
|
220
|
+
`(${redactUrl(stored.authServerUrl)} → ` +
|
|
221
|
+
`${redactUrl(this._currentIssuer)}); ` +
|
|
222
|
+
"stored credentials discarded, re-authorization required",
|
|
223
|
+
);
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return stored.tokens;
|
|
101
228
|
}
|
|
102
229
|
|
|
103
230
|
async saveTokens(tokens: OAuthTokens): Promise<void> {
|
|
@@ -105,8 +232,20 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
105
232
|
// This get/set is not atomic; concurrent saves for one serverUrl are unsupported
|
|
106
233
|
// because refresh is serialized by the caller.
|
|
107
234
|
const stored = await this.config.tokenStore.get(this.serverUrl);
|
|
235
|
+
|
|
236
|
+
// …but only from the same authorization server. `auth({ authorizationCode })`
|
|
237
|
+
// reaches here without going through `tokens()`, so this is the one path
|
|
238
|
+
// where a credential from a previous issuer can survive: if the code
|
|
239
|
+
// exchange returns no refresh token, carrying the old one over would
|
|
240
|
+
// re-label another server's secret with the new issuer and hand it over on
|
|
241
|
+
// the next refresh. A legacy record has no recorded issuer, so it cannot
|
|
242
|
+
// clear this bar either.
|
|
243
|
+
const inheritable = stored?.authServerUrl !== undefined &&
|
|
244
|
+
this._currentIssuer !== undefined &&
|
|
245
|
+
canonicalIssuer(stored.authServerUrl) === this._currentIssuer;
|
|
246
|
+
|
|
108
247
|
const tokensToStore = tokens.refresh_token === undefined &&
|
|
109
|
-
stored?.tokens.refresh_token !== undefined
|
|
248
|
+
inheritable && stored?.tokens.refresh_token !== undefined
|
|
110
249
|
? { ...tokens, refresh_token: stored.tokens.refresh_token }
|
|
111
250
|
: tokens;
|
|
112
251
|
|
|
@@ -114,9 +253,18 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
114
253
|
serverUrl: this.serverUrl,
|
|
115
254
|
tokens: tokensToStore,
|
|
116
255
|
obtainedAt: Date.now(),
|
|
256
|
+
// Binds the credentials to their minter. Without it every save produces
|
|
257
|
+
// exactly the legacy record `tokens()` has to throw away.
|
|
258
|
+
...(this._currentIssuer !== undefined
|
|
259
|
+
? { authServerUrl: this._currentIssuer }
|
|
260
|
+
: {}),
|
|
117
261
|
});
|
|
118
262
|
}
|
|
119
263
|
|
|
264
|
+
private log(message: string): void {
|
|
265
|
+
this.config.logger?.(`[client-auth] ${message}`);
|
|
266
|
+
}
|
|
267
|
+
|
|
120
268
|
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
|
|
121
269
|
await this.config.openBrowser(authorizationUrl.toString());
|
|
122
270
|
}
|
|
@@ -142,5 +290,11 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
142
290
|
if (scope === "all" || scope === "client") {
|
|
143
291
|
this._clientInfo = undefined;
|
|
144
292
|
}
|
|
293
|
+
if (scope === "all" || scope === "discovery") {
|
|
294
|
+
// Keeping a stale issuer would make the next `tokens()` compare against
|
|
295
|
+
// an authorization server the SDK has already given up on, and discard
|
|
296
|
+
// credentials that are in fact still valid.
|
|
297
|
+
this._currentIssuer = undefined;
|
|
298
|
+
}
|
|
145
299
|
}
|
|
146
300
|
}
|
package/src/client-auth/types.ts
CHANGED
|
@@ -18,7 +18,12 @@ export interface StoredCredentials {
|
|
|
18
18
|
tokens: OAuthTokens;
|
|
19
19
|
/** When the tokens were obtained (Unix epoch ms) */
|
|
20
20
|
obtainedAt: number;
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Issuer that minted these credentials (SEP-2352).
|
|
23
|
+
*
|
|
24
|
+
* Absent on records written before the binding existed; `tokens()` treats
|
|
25
|
+
* that as unusable, since nothing proves who minted them.
|
|
26
|
+
*/
|
|
22
27
|
authServerUrl?: string;
|
|
23
28
|
}
|
|
24
29
|
|
|
@@ -48,6 +53,14 @@ export interface OAuthClientConfigBase {
|
|
|
48
53
|
callbackPort?: number;
|
|
49
54
|
/** Timeout for user to complete OAuth flow (ms, default: 120_000) */
|
|
50
55
|
authTimeout?: number;
|
|
56
|
+
/**
|
|
57
|
+
* Optional sink for credential-lifecycle events.
|
|
58
|
+
*
|
|
59
|
+
* Notably an authorization-server change (SEP-2352): the client silently
|
|
60
|
+
* drops its stored credentials and re-authorizes, and an operator debugging
|
|
61
|
+
* an unexpected login prompt has no other way to see why.
|
|
62
|
+
*/
|
|
63
|
+
logger?: (message: string) => void;
|
|
51
64
|
}
|
|
52
65
|
|
|
53
66
|
/** Static OAuth client registration (default, backwards-compatible mode). */
|
package/src/mcp-app.ts
CHANGED
|
@@ -18,8 +18,10 @@ import {
|
|
|
18
18
|
type ClientCapabilities,
|
|
19
19
|
ErrorCode,
|
|
20
20
|
type Implementation,
|
|
21
|
+
type JSONRPCRequest,
|
|
21
22
|
ListResourcesRequestSchema,
|
|
22
23
|
ListToolsRequestSchema,
|
|
24
|
+
McpError,
|
|
23
25
|
type ReadResourceRequest,
|
|
24
26
|
ReadResourceRequestSchema,
|
|
25
27
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
@@ -88,6 +90,8 @@ import {
|
|
|
88
90
|
importStateKey,
|
|
89
91
|
type InputRequestEntry,
|
|
90
92
|
type InputRequiredSignal,
|
|
93
|
+
MemoryMrtrReplayStore,
|
|
94
|
+
type MrtrReplayStore,
|
|
91
95
|
paramsDigest,
|
|
92
96
|
sealRequestState,
|
|
93
97
|
verifyRequestState,
|
|
@@ -100,7 +104,12 @@ import {
|
|
|
100
104
|
type SubscriptionSink,
|
|
101
105
|
} from "./subscriptions/subscription-registry.js";
|
|
102
106
|
import { ServerMetrics } from "./observability/metrics.js";
|
|
103
|
-
import {
|
|
107
|
+
import type { SpanContext } from "@opentelemetry/api";
|
|
108
|
+
import {
|
|
109
|
+
endToolCallSpan,
|
|
110
|
+
parseTraceParent,
|
|
111
|
+
startToolCallSpan,
|
|
112
|
+
} from "./observability/otel.js";
|
|
104
113
|
import {
|
|
105
114
|
BodyTooLargeError,
|
|
106
115
|
DEFAULT_MAX_BODY_BYTES,
|
|
@@ -158,6 +167,16 @@ const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
|
|
|
158
167
|
*/
|
|
159
168
|
const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
|
|
160
169
|
|
|
170
|
+
/**
|
|
171
|
+
* W3C trace context keys in `params._meta` (spec 2026-07-28, SEP-414).
|
|
172
|
+
*
|
|
173
|
+
* Unlike every other per-request field these are NOT namespaced — the revision
|
|
174
|
+
* documents the bare W3C names, so that a `_meta` envelope carries the same
|
|
175
|
+
* key a caller would put in an HTTP header.
|
|
176
|
+
*/
|
|
177
|
+
const TRACEPARENT_KEY = "traceparent";
|
|
178
|
+
const TRACESTATE_KEY = "tracestate";
|
|
179
|
+
|
|
161
180
|
/** Protocol version whose wire format this server implements natively */
|
|
162
181
|
const SPEC_2026_07_28 = "2026-07-28";
|
|
163
182
|
|
|
@@ -210,6 +229,34 @@ interface StatelessClientMeta {
|
|
|
210
229
|
readonly clientInfo?: Implementation;
|
|
211
230
|
readonly clientCapabilities?: ClientCapabilities;
|
|
212
231
|
readonly logLevel?: McpLogLevel;
|
|
232
|
+
/** Caller's W3C trace context, so the tool span joins their trace. */
|
|
233
|
+
readonly traceContext?: SpanContext;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Read the W3C trace context out of `params._meta` (spec 2026-07-28, SEP-414).
|
|
238
|
+
*
|
|
239
|
+
* A malformed header leaves the span unparented rather than failing the call:
|
|
240
|
+
* losing the trace join is an observability gap, refusing the tool call would
|
|
241
|
+
* be an outage.
|
|
242
|
+
*
|
|
243
|
+
* `baggage` is deliberately NOT read. It is an unbounded, caller-controlled
|
|
244
|
+
* key/value list that routinely carries tenant, user and session identifiers,
|
|
245
|
+
* and the only thing this server could do with it is copy it into spans —
|
|
246
|
+
* exporting whatever a caller put there to the trace backend, with no way to
|
|
247
|
+
* know whether it holds a PII or a secret. Propagating it properly means the
|
|
248
|
+
* OTel baggage API and an explicit allowlist of keys; until there is a use case
|
|
249
|
+
* asking for that, reading it at all is a liability. The key stays reserved by
|
|
250
|
+
* the spec, and this server ignores it.
|
|
251
|
+
*/
|
|
252
|
+
function readTraceContext(
|
|
253
|
+
meta: Record<string, unknown>,
|
|
254
|
+
): { traceContext?: SpanContext } {
|
|
255
|
+
const traceContext = parseTraceParent(
|
|
256
|
+
meta[TRACEPARENT_KEY],
|
|
257
|
+
meta[TRACESTATE_KEY],
|
|
258
|
+
);
|
|
259
|
+
return traceContext ? { traceContext } : {};
|
|
213
260
|
}
|
|
214
261
|
|
|
215
262
|
/** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
|
|
@@ -440,6 +487,14 @@ export class McpApp {
|
|
|
440
487
|
*/
|
|
441
488
|
private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
|
|
442
489
|
|
|
490
|
+
/**
|
|
491
|
+
* Consumes a verified requestState nonce before the handler runs.
|
|
492
|
+
*
|
|
493
|
+
* A signed deployment always has a store: process-local by default, or the
|
|
494
|
+
* shared atomic implementation supplied by the consumer.
|
|
495
|
+
*/
|
|
496
|
+
private readonly mrtrReplayStore: MrtrReplayStore | null;
|
|
497
|
+
|
|
443
498
|
/**
|
|
444
499
|
* Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
|
|
445
500
|
* an integer — clients are told to ignore a negative one, which would make a
|
|
@@ -512,6 +567,23 @@ export class McpApp {
|
|
|
512
567
|
"or the exported generateStateKey() + exportStateKey() helpers.",
|
|
513
568
|
);
|
|
514
569
|
}
|
|
570
|
+
if (
|
|
571
|
+
options.mrtr?.replayStore !== undefined && mrtrKey === undefined
|
|
572
|
+
) {
|
|
573
|
+
throw new Error(
|
|
574
|
+
"[McpApp] mrtr.replayStore requires mrtr.signingKey. " +
|
|
575
|
+
"Only a verified token exposes a trusted nonce to consume.",
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
this.mrtrReplayStore = mrtrKey === undefined
|
|
579
|
+
? null
|
|
580
|
+
: options.mrtr?.replayStore ?? new MemoryMrtrReplayStore();
|
|
581
|
+
if (mrtrKey !== undefined && options.mrtr?.replayStore === undefined) {
|
|
582
|
+
(options.logger ?? console.error)(
|
|
583
|
+
"[McpApp] WARNING: MRTR replay protection is process-local. " +
|
|
584
|
+
"Load-balanced deployments must configure one shared atomic mrtr.replayStore.",
|
|
585
|
+
);
|
|
586
|
+
}
|
|
515
587
|
|
|
516
588
|
// Create SDK MCP server
|
|
517
589
|
this.mcpServer = new McpServer(
|
|
@@ -634,9 +706,31 @@ export class McpApp {
|
|
|
634
706
|
const toolName = request.params.name;
|
|
635
707
|
const args = request.params.arguments || {};
|
|
636
708
|
|
|
709
|
+
// Per-request `_meta` is transport-independent. Trace context matters
|
|
710
|
+
// here because a local server is exactly where a detached span is
|
|
711
|
+
// hardest to correlate back to the host that caused it; `logLevel` is
|
|
712
|
+
// read for the same reason it is on HTTP — the spec makes it
|
|
713
|
+
// per-request, and a handler must stay silent without it.
|
|
714
|
+
const meta = request.params._meta;
|
|
715
|
+
const clientMeta: StatelessClientMeta | undefined = isRecord(meta)
|
|
716
|
+
? {
|
|
717
|
+
...readTraceContext(meta),
|
|
718
|
+
...(readLogLevel(meta) !== undefined
|
|
719
|
+
? { logLevel: readLogLevel(meta) }
|
|
720
|
+
: {}),
|
|
721
|
+
}
|
|
722
|
+
: undefined;
|
|
723
|
+
|
|
637
724
|
let result: unknown;
|
|
638
725
|
try {
|
|
639
|
-
result = await this.executeToolCall(
|
|
726
|
+
result = await this.executeToolCall(
|
|
727
|
+
toolName,
|
|
728
|
+
args,
|
|
729
|
+
undefined,
|
|
730
|
+
undefined,
|
|
731
|
+
undefined,
|
|
732
|
+
clientMeta,
|
|
733
|
+
);
|
|
640
734
|
} catch (error) {
|
|
641
735
|
return this.handleToolError(error, toolName);
|
|
642
736
|
}
|
|
@@ -646,6 +740,66 @@ export class McpApp {
|
|
|
646
740
|
return this.buildToolCallResult(toolName, result);
|
|
647
741
|
},
|
|
648
742
|
);
|
|
743
|
+
|
|
744
|
+
// `server/discover` over stdio (spec 2026-07-28, SEP-2575).
|
|
745
|
+
//
|
|
746
|
+
// The spec makes this RPC a MUST for every server and names stdio as a
|
|
747
|
+
// primary use: a client probes it for backward compatibility. That matters
|
|
748
|
+
// here precisely because the SDK's stdio handshake still negotiates
|
|
749
|
+
// 2025-11-25 — `server/discover` is then the only way for a peer to learn
|
|
750
|
+
// this server also speaks 2026-07-28 over HTTP.
|
|
751
|
+
//
|
|
752
|
+
// Routed through `fallbackRequestHandler` rather than `setRequestHandler`
|
|
753
|
+
// because the latter takes a Zod schema, and the method is absent from the
|
|
754
|
+
// SDK's type surface. Adding a Zod dependency to declare one schema would
|
|
755
|
+
// put a peer dependency in the public API for a single string comparison.
|
|
756
|
+
// Every other unknown method keeps its previous answer: MethodNotFound.
|
|
757
|
+
server.fallbackRequestHandler = (request: JSONRPCRequest) => {
|
|
758
|
+
if (request.method !== "server/discover") {
|
|
759
|
+
// Same text the SDK used for an unrouted method. It still reaches the
|
|
760
|
+
// wire as "MCP error -32601: Method not found" — `McpError` prefixes
|
|
761
|
+
// its own message and a handler cannot raise the code without it. The
|
|
762
|
+
// code is unchanged, which is what a peer switches on; the string
|
|
763
|
+
// difference is pinned by a test and noted in the changelog. Appending
|
|
764
|
+
// the method name on top of that would have been a second, gratuitous
|
|
765
|
+
// change to the same field.
|
|
766
|
+
throw new McpError(ErrorCode.MethodNotFound, "Method not found");
|
|
767
|
+
}
|
|
768
|
+
return Promise.resolve(this.buildDiscoverResult());
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* The `server/discover` result (spec 2026-07-28, SEP-2575).
|
|
774
|
+
*
|
|
775
|
+
* Single source of truth for both transports. They used to be one inline
|
|
776
|
+
* object on the HTTP path; a stdio copy would have been the second place to
|
|
777
|
+
* forget `instructions` or a new capability.
|
|
778
|
+
*
|
|
779
|
+
* Always stamped as 2026-07-28 regardless of what the transport negotiated.
|
|
780
|
+
* That is deliberate but not free: nothing gates the method, so a peer that
|
|
781
|
+
* negotiated `2025-11-25` over stdio can call it and receive an envelope it
|
|
782
|
+
* never agreed to. The alternative is worse — stamping the negotiated version
|
|
783
|
+
* would make the probe answer "2025" to the client asking whether this server
|
|
784
|
+
* speaks 2026, which is the one question it exists to answer. Treat
|
|
785
|
+
* `server/discover` as a cross-version exception: its result describes what
|
|
786
|
+
* the server supports, not what the current transport negotiated.
|
|
787
|
+
*/
|
|
788
|
+
private buildDiscoverResult(): Record<string, unknown> {
|
|
789
|
+
return this.stampResult(
|
|
790
|
+
this.withCacheHints({
|
|
791
|
+
supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
|
|
792
|
+
capabilities: this.buildServerCapabilities(),
|
|
793
|
+
serverInfo: {
|
|
794
|
+
name: this.options.name,
|
|
795
|
+
version: this.options.version,
|
|
796
|
+
},
|
|
797
|
+
...(this.options.instructions
|
|
798
|
+
? { instructions: this.options.instructions }
|
|
799
|
+
: {}),
|
|
800
|
+
}, SPEC_2026_07_28),
|
|
801
|
+
SPEC_2026_07_28,
|
|
802
|
+
);
|
|
649
803
|
}
|
|
650
804
|
|
|
651
805
|
/**
|
|
@@ -981,12 +1135,16 @@ export class McpApp {
|
|
|
981
1135
|
};
|
|
982
1136
|
|
|
983
1137
|
// OTel span + metrics
|
|
984
|
-
const span = startToolCallSpan(
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1138
|
+
const span = startToolCallSpan(
|
|
1139
|
+
toolName,
|
|
1140
|
+
{
|
|
1141
|
+
"mcp.tool.name": toolName,
|
|
1142
|
+
"mcp.server.name": this.options.name,
|
|
1143
|
+
"mcp.transport": request ? "http" : "stdio",
|
|
1144
|
+
"mcp.session.id": sessionId,
|
|
1145
|
+
},
|
|
1146
|
+
clientMeta?.traceContext,
|
|
1147
|
+
);
|
|
990
1148
|
|
|
991
1149
|
// Update gauges before execution
|
|
992
1150
|
const queueMetrics = this.requestQueue.getMetrics();
|
|
@@ -1900,20 +2058,7 @@ export class McpApp {
|
|
|
1900
2058
|
return c.json({
|
|
1901
2059
|
jsonrpc: "2.0",
|
|
1902
2060
|
id,
|
|
1903
|
-
result: this.
|
|
1904
|
-
this.withCacheHints({
|
|
1905
|
-
supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
|
|
1906
|
-
capabilities: this.buildServerCapabilities(),
|
|
1907
|
-
serverInfo: {
|
|
1908
|
-
name: this.options.name,
|
|
1909
|
-
version: this.options.version,
|
|
1910
|
-
},
|
|
1911
|
-
...(this.options.instructions
|
|
1912
|
-
? { instructions: this.options.instructions }
|
|
1913
|
-
: {}),
|
|
1914
|
-
}, statelessVersion),
|
|
1915
|
-
statelessVersion,
|
|
1916
|
-
),
|
|
2061
|
+
result: this.buildDiscoverResult(),
|
|
1917
2062
|
});
|
|
1918
2063
|
}
|
|
1919
2064
|
|
|
@@ -1978,6 +2123,7 @@ export class McpApp {
|
|
|
1978
2123
|
STATELESS_CLIENT_CAPABILITIES_KEY
|
|
1979
2124
|
] as ClientCapabilities | undefined,
|
|
1980
2125
|
logLevel: readLogLevel(params["_meta"]),
|
|
2126
|
+
...readTraceContext(params["_meta"]),
|
|
1981
2127
|
}
|
|
1982
2128
|
: undefined;
|
|
1983
2129
|
|
|
@@ -2121,6 +2267,77 @@ export class McpApp {
|
|
|
2121
2267
|
400,
|
|
2122
2268
|
);
|
|
2123
2269
|
}
|
|
2270
|
+
|
|
2271
|
+
const replayStore = this.mrtrReplayStore;
|
|
2272
|
+
if (replayStore === null) {
|
|
2273
|
+
return jsonRpcResponse(
|
|
2274
|
+
{
|
|
2275
|
+
jsonrpc: "2.0",
|
|
2276
|
+
id,
|
|
2277
|
+
error: {
|
|
2278
|
+
code: ErrorCode.InternalError,
|
|
2279
|
+
message: "MRTR replay protection is unavailable",
|
|
2280
|
+
data: {
|
|
2281
|
+
problem: "mrtr_replay_store_unavailable",
|
|
2282
|
+
recovery:
|
|
2283
|
+
"Configure mrtr.signingKey with a working replay store and retry the full interaction.",
|
|
2284
|
+
},
|
|
2285
|
+
},
|
|
2286
|
+
},
|
|
2287
|
+
500,
|
|
2288
|
+
{ "MCP-Protocol-Version": statelessVersion },
|
|
2289
|
+
);
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
let consumed: boolean;
|
|
2293
|
+
try {
|
|
2294
|
+
const storeResult = await replayStore.consume(
|
|
2295
|
+
verdict.payload.nonce,
|
|
2296
|
+
verdict.payload.exp,
|
|
2297
|
+
);
|
|
2298
|
+
if (storeResult !== true && storeResult !== false) {
|
|
2299
|
+
throw new Error(
|
|
2300
|
+
"mrtr.replayStore.consume() must return a boolean",
|
|
2301
|
+
);
|
|
2302
|
+
}
|
|
2303
|
+
consumed = storeResult;
|
|
2304
|
+
} catch {
|
|
2305
|
+
this.log(
|
|
2306
|
+
"[WARN] MRTR replay store unavailable; retry rejected before handler",
|
|
2307
|
+
);
|
|
2308
|
+
return jsonRpcResponse(
|
|
2309
|
+
{
|
|
2310
|
+
jsonrpc: "2.0",
|
|
2311
|
+
id,
|
|
2312
|
+
error: {
|
|
2313
|
+
code: ErrorCode.InternalError,
|
|
2314
|
+
message: "MRTR replay protection is unavailable",
|
|
2315
|
+
data: {
|
|
2316
|
+
problem: "mrtr_replay_store_unavailable",
|
|
2317
|
+
recovery:
|
|
2318
|
+
"Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
|
|
2319
|
+
},
|
|
2320
|
+
},
|
|
2321
|
+
},
|
|
2322
|
+
500,
|
|
2323
|
+
{ "MCP-Protocol-Version": statelessVersion },
|
|
2324
|
+
);
|
|
2325
|
+
}
|
|
2326
|
+
if (!consumed) {
|
|
2327
|
+
return jsonRpcResponse(
|
|
2328
|
+
{
|
|
2329
|
+
jsonrpc: "2.0",
|
|
2330
|
+
id,
|
|
2331
|
+
error: {
|
|
2332
|
+
code: JSONRPC_INVALID_PARAMS,
|
|
2333
|
+
message: "Invalid requestState: replayed",
|
|
2334
|
+
data: { reason: "replayed" },
|
|
2335
|
+
},
|
|
2336
|
+
},
|
|
2337
|
+
400,
|
|
2338
|
+
{ "MCP-Protocol-Version": statelessVersion },
|
|
2339
|
+
);
|
|
2340
|
+
}
|
|
2124
2341
|
retryVerified = true;
|
|
2125
2342
|
}
|
|
2126
2343
|
}
|
package/src/mrtr/mod.ts
CHANGED
|
@@ -15,6 +15,13 @@ export type {
|
|
|
15
15
|
MrtrOptions,
|
|
16
16
|
} from "./types.js";
|
|
17
17
|
|
|
18
|
+
// Atomic single-use enforcement for verified requestState nonces.
|
|
19
|
+
export type {
|
|
20
|
+
MemoryMrtrReplayStoreOptions,
|
|
21
|
+
MrtrReplayStore,
|
|
22
|
+
} from "./replay-store.js";
|
|
23
|
+
export { MemoryMrtrReplayStore } from "./replay-store.js";
|
|
24
|
+
|
|
18
25
|
// requestState seal/verify (HMAC-SHA256 integrity protection)
|
|
19
26
|
export type {
|
|
20
27
|
RequestStatePayload,
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomic nonce consumption for MRTR requestState tokens.
|
|
3
|
+
*
|
|
4
|
+
* Integrity verification proves that a token was minted by the server and is
|
|
5
|
+
* bound to the current request. A replay store adds the separate single-use
|
|
6
|
+
* property by reserving the signed nonce before business logic runs.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Store used to consume a verified MRTR nonce exactly once.
|
|
11
|
+
*
|
|
12
|
+
* Implementations MUST make the check-and-reserve operation atomic. Return
|
|
13
|
+
* `true` only for the caller that reserved the nonce, `false` when it was
|
|
14
|
+
* already consumed, and throw when availability cannot be established.
|
|
15
|
+
*
|
|
16
|
+
* `expiresAt` is the signed token expiry as Unix epoch seconds. Stores should
|
|
17
|
+
* remove the reservation after that time; retaining it longer is safe but
|
|
18
|
+
* wastes capacity.
|
|
19
|
+
*
|
|
20
|
+
* A load-balanced deployment MUST provide one shared implementation to every
|
|
21
|
+
* McpApp instance. Redis can implement the contract with `SET key 1 NX EXAT`.
|
|
22
|
+
*/
|
|
23
|
+
export interface MrtrReplayStore {
|
|
24
|
+
consume(nonce: string, expiresAt: number): boolean | Promise<boolean>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface MemoryMrtrReplayStoreOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Maximum live reservations before the store fails closed.
|
|
30
|
+
*
|
|
31
|
+
* Default: 100,000.
|
|
32
|
+
*/
|
|
33
|
+
maxEntries?: number;
|
|
34
|
+
|
|
35
|
+
/** Test seam for the current Unix epoch time in seconds. */
|
|
36
|
+
nowSecs?: () => number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Process-local replay protection.
|
|
41
|
+
*
|
|
42
|
+
* This is the safe default for one continuously running McpApp process. It
|
|
43
|
+
* cannot coordinate separate processes or survive a restart; horizontally
|
|
44
|
+
* scaled or restart-safe deployments must inject a durable shared
|
|
45
|
+
* `MrtrReplayStore`.
|
|
46
|
+
*/
|
|
47
|
+
export class MemoryMrtrReplayStore implements MrtrReplayStore {
|
|
48
|
+
private readonly entries = new Map<string, number>();
|
|
49
|
+
private readonly maxEntries: number;
|
|
50
|
+
private readonly nowSecs: () => number;
|
|
51
|
+
|
|
52
|
+
constructor(options: MemoryMrtrReplayStoreOptions = {}) {
|
|
53
|
+
const maxEntries = options.maxEntries ?? 100_000;
|
|
54
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`MemoryMrtrReplayStore maxEntries must be a positive integer (got ${maxEntries})`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
this.maxEntries = maxEntries;
|
|
60
|
+
this.nowSecs = options.nowSecs ?? (() => Math.floor(Date.now() / 1000));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
consume(nonce: string, expiresAt: number): boolean {
|
|
64
|
+
if (!/^[0-9a-f]{32}$/.test(nonce)) {
|
|
65
|
+
throw new Error("MRTR replay nonce must be 32 lowercase hex characters");
|
|
66
|
+
}
|
|
67
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
"MRTR replay expiry must be a non-negative safe-integer Unix timestamp",
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const now = this.nowSecs();
|
|
74
|
+
if (!Number.isSafeInteger(now) || now < 0) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
"MRTR replay clock must return a non-negative safe-integer Unix timestamp",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const existingExpiry = this.entries.get(nonce);
|
|
80
|
+
if (existingExpiry !== undefined) {
|
|
81
|
+
if (existingExpiry > now) return false;
|
|
82
|
+
this.entries.delete(nonce);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (expiresAt <= now) return false;
|
|
86
|
+
|
|
87
|
+
if (this.entries.size >= this.maxEntries) {
|
|
88
|
+
for (const [storedNonce, storedExpiry] of this.entries) {
|
|
89
|
+
if (storedExpiry <= now) this.entries.delete(storedNonce);
|
|
90
|
+
}
|
|
91
|
+
if (this.entries.size >= this.maxEntries) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`MRTR replay store capacity exceeded (${this.maxEntries} live nonces)`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// No await may occur between the check and this write. In one JS process,
|
|
99
|
+
// that makes the reservation atomic across concurrent request continuations.
|
|
100
|
+
this.entries.set(nonce, expiresAt);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/mrtr/types.ts
CHANGED
|
@@ -90,4 +90,18 @@ export interface MrtrOptions {
|
|
|
90
90
|
* shared store on the first use).
|
|
91
91
|
*/
|
|
92
92
|
defaultTtlSecs?: number;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Atomic store used to reject a second use of the same signed requestState.
|
|
96
|
+
*
|
|
97
|
+
* With a signing key and no explicit store, McpApp uses a process-local
|
|
98
|
+
* MemoryMrtrReplayStore. That protects one continuously running process only:
|
|
99
|
+
* a restart loses its reservations. Every instance in a load-balanced
|
|
100
|
+
* deployment MUST receive the same durable shared store implementation.
|
|
101
|
+
*
|
|
102
|
+
* The nonce is consumed before the handler runs. This provides at-most-once
|
|
103
|
+
* admission, not exactly-once completion: if the handler commits a mutation
|
|
104
|
+
* and its response is lost, the same token is still rejected on retry.
|
|
105
|
+
*/
|
|
106
|
+
replayStore?: import("./replay-store.js").MrtrReplayStore;
|
|
93
107
|
}
|
package/src/observability/mod.ts
CHANGED
|
@@ -11,15 +11,225 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import {
|
|
14
|
+
type Context,
|
|
15
|
+
context as otelContext,
|
|
14
16
|
type Span,
|
|
17
|
+
type SpanContext,
|
|
15
18
|
SpanStatusCode,
|
|
16
19
|
trace,
|
|
20
|
+
TraceFlags,
|
|
17
21
|
type Tracer,
|
|
22
|
+
type TraceState,
|
|
18
23
|
} from "@opentelemetry/api";
|
|
19
24
|
import { env } from "../runtime/runtime.js";
|
|
20
25
|
|
|
21
26
|
let serverTracer: Tracer | null = null;
|
|
22
27
|
|
|
28
|
+
/**
|
|
29
|
+
* W3C `traceparent`: `<2 hex version>-<32 hex trace-id>-<16 hex parent-id>-<2 hex flags>`.
|
|
30
|
+
*
|
|
31
|
+
* Matches the 55-character prefix only — the trailing-content rule depends on
|
|
32
|
+
* the version and is applied separately, see {@link parseTraceParent}.
|
|
33
|
+
*
|
|
34
|
+
* Case-sensitive on purpose. The spec mandates lowercase hex, and accepting
|
|
35
|
+
* uppercase produces a trace id that will not match the same trace elsewhere in
|
|
36
|
+
* the pipeline: a silently broken join is worse than a dropped header.
|
|
37
|
+
*/
|
|
38
|
+
const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})/;
|
|
39
|
+
|
|
40
|
+
/** `00-` + 32 + `-` + 16 + `-` + 2 = 55. */
|
|
41
|
+
const TRACEPARENT_PREFIX_LENGTH = 55;
|
|
42
|
+
|
|
43
|
+
/** All-zero ids are explicitly invalid in the W3C spec. */
|
|
44
|
+
const INVALID_TRACE_ID = "0".repeat(32);
|
|
45
|
+
const INVALID_SPAN_ID = "0".repeat(16);
|
|
46
|
+
|
|
47
|
+
/** W3C caps `tracestate` at 32 list members; the rest are dropped. */
|
|
48
|
+
const TRACESTATE_MAX_MEMBERS = 32;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* W3C `tracestate` key, both forms of the ABNF:
|
|
52
|
+
* - simple: `lcalpha 0*255(lcalpha / DIGIT / "_" / "-" / "*" / "/")`
|
|
53
|
+
* - multi-tenant: `tenant-id "@" system-id`
|
|
54
|
+
*/
|
|
55
|
+
const TRACESTATE_KEY =
|
|
56
|
+
/^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* W3C `tracestate` value — the ABNF is `0*255(chr) nblk-chr`:
|
|
60
|
+
*
|
|
61
|
+
* - `chr` is printable ASCII except comma and equals. `=` inside a value is
|
|
62
|
+
* forbidden, so a member carrying one is malformed, not a value to preserve.
|
|
63
|
+
* - the final character is `nblk-chr`, which additionally excludes SP. That
|
|
64
|
+
* makes the value **non-empty** and forbids a trailing space, so `vendor=`
|
|
65
|
+
* is not a valid member.
|
|
66
|
+
*/
|
|
67
|
+
const TRACESTATE_VALUE =
|
|
68
|
+
/^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The grammar's optional whitespace around a list member is SP and HTAB only.
|
|
72
|
+
* `String.trim()` also eats CR, LF, FF, VT and Unicode spaces — none of which
|
|
73
|
+
* are legal separators here, so trimming with it would silently accept a
|
|
74
|
+
* malformed list.
|
|
75
|
+
*/
|
|
76
|
+
function trimOws(member: string): string {
|
|
77
|
+
return member.replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* `tracestate` carried to the next hop.
|
|
82
|
+
*
|
|
83
|
+
* `@opentelemetry/api` declares the interface but ships no implementation —
|
|
84
|
+
* that lives in `@opentelemetry/core`. Pulling in the SDK package for one
|
|
85
|
+
* key/value list would put a second OTel dependency in the public API, so this
|
|
86
|
+
* is the minimum that satisfies the interface.
|
|
87
|
+
*
|
|
88
|
+
* Members are validated against the W3C ABNF rather than passed through: the
|
|
89
|
+
* spec permits discarding invalid entries, and this list is re-serialised onto
|
|
90
|
+
* the next hop — accepting a malformed member here means emitting a malformed
|
|
91
|
+
* `tracestate` downstream, turning one peer's bug into ours.
|
|
92
|
+
*/
|
|
93
|
+
class ListTraceState implements TraceState {
|
|
94
|
+
readonly #entries: ReadonlyArray<readonly [string, string]>;
|
|
95
|
+
|
|
96
|
+
constructor(entries: ReadonlyArray<readonly [string, string]>) {
|
|
97
|
+
this.#entries = entries;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
static #isValid(key: string, value: string): boolean {
|
|
101
|
+
return TRACESTATE_KEY.test(key) && TRACESTATE_VALUE.test(value);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
static parse(raw: string): ListTraceState | undefined {
|
|
105
|
+
const seen = new Set<string>();
|
|
106
|
+
const entries: Array<readonly [string, string]> = [];
|
|
107
|
+
|
|
108
|
+
for (const member of raw.split(",")) {
|
|
109
|
+
// Optional whitespace around a list member is part of the grammar; the
|
|
110
|
+
// key and value themselves are matched exactly.
|
|
111
|
+
const trimmed = trimOws(member);
|
|
112
|
+
if (trimmed.length === 0) continue;
|
|
113
|
+
|
|
114
|
+
const at = trimmed.indexOf("=");
|
|
115
|
+
if (at <= 0) continue;
|
|
116
|
+
|
|
117
|
+
const key = trimmed.slice(0, at);
|
|
118
|
+
const value = trimmed.slice(at + 1);
|
|
119
|
+
// Duplicate keys are invalid; the first occurrence is the live one.
|
|
120
|
+
if (seen.has(key)) continue;
|
|
121
|
+
if (!ListTraceState.#isValid(key, value)) continue;
|
|
122
|
+
|
|
123
|
+
seen.add(key);
|
|
124
|
+
entries.push([key, value]);
|
|
125
|
+
if (entries.length === TRACESTATE_MAX_MEMBERS) break;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return entries.length > 0 ? new ListTraceState(entries) : undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
get(key: string): string | undefined {
|
|
132
|
+
return this.#entries.find(([k]) => k === key)?.[1];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
set(key: string, value: string): TraceState {
|
|
136
|
+
// Returns the state unchanged rather than throwing. The OpenTelemetry
|
|
137
|
+
// specification is explicit that "API methods MUST NOT throw unhandled
|
|
138
|
+
// exceptions when used incorrectly by end users" — telemetry is not worth
|
|
139
|
+
// taking an application down for. Rejecting the mutation still keeps the
|
|
140
|
+
// invalid member off the wire, which is the property that matters.
|
|
141
|
+
if (!ListTraceState.#isValid(key, value)) return this;
|
|
142
|
+
// W3C: a mutated key moves to the front of the list.
|
|
143
|
+
return new ListTraceState([
|
|
144
|
+
[key, value] as const,
|
|
145
|
+
...this.#entries.filter(([k]) => k !== key),
|
|
146
|
+
].slice(0, TRACESTATE_MAX_MEMBERS));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
unset(key: string): TraceState {
|
|
150
|
+
return new ListTraceState(this.#entries.filter(([k]) => k !== key));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
serialize(): string {
|
|
154
|
+
return this.#entries.map(([k, v]) => `${k}=${v}`).join(",");
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Parse a W3C trace context into an OTel `SpanContext` (spec 2026-07-28).
|
|
160
|
+
*
|
|
161
|
+
* The revision documents `traceparent` / `tracestate` / `baggage` as `_meta`
|
|
162
|
+
* keys so a tool call joins the caller's trace instead of starting a detached
|
|
163
|
+
* one. Returns `undefined` for anything malformed — a bad header leaves the span
|
|
164
|
+
* unparented, it never fails the call.
|
|
165
|
+
*
|
|
166
|
+
* Version handling follows the W3C forward-compatibility rule, which is not
|
|
167
|
+
* "reject anything unfamiliar":
|
|
168
|
+
*
|
|
169
|
+
* - `ff` is forbidden outright.
|
|
170
|
+
* - `00` is a fixed 55-character format; anything longer is malformed.
|
|
171
|
+
* - a higher version MAY carry fields this implementation does not know. The
|
|
172
|
+
* receiver parses the first 55 characters and ignores the rest, provided the
|
|
173
|
+
* next character is a `-`. Rejecting those would make this server drop trace
|
|
174
|
+
* context the day a new version ships — the exact breakage the rule exists to
|
|
175
|
+
* prevent.
|
|
176
|
+
*/
|
|
177
|
+
export function parseTraceParent(
|
|
178
|
+
traceparent: unknown,
|
|
179
|
+
tracestate?: unknown,
|
|
180
|
+
): SpanContext | undefined {
|
|
181
|
+
if (typeof traceparent !== "string") return undefined;
|
|
182
|
+
if (traceparent.length < TRACEPARENT_PREFIX_LENGTH) return undefined;
|
|
183
|
+
|
|
184
|
+
const match = TRACEPARENT.exec(traceparent);
|
|
185
|
+
if (!match) return undefined;
|
|
186
|
+
|
|
187
|
+
const [, version, traceId, spanId, flags] = match;
|
|
188
|
+
if (version === "ff") return undefined;
|
|
189
|
+
|
|
190
|
+
if (version === "00") {
|
|
191
|
+
if (traceparent.length !== TRACEPARENT_PREFIX_LENGTH) return undefined;
|
|
192
|
+
} else if (
|
|
193
|
+
traceparent.length > TRACEPARENT_PREFIX_LENGTH &&
|
|
194
|
+
traceparent[TRACEPARENT_PREFIX_LENGTH] !== "-"
|
|
195
|
+
) {
|
|
196
|
+
// Longer, but not a well-formed continuation: the extra characters are not
|
|
197
|
+
// a new field, so the whole header is suspect.
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const traceState = typeof tracestate === "string"
|
|
206
|
+
? ListTraceState.parse(tracestate)
|
|
207
|
+
: undefined;
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
traceId,
|
|
211
|
+
spanId,
|
|
212
|
+
// Only the sampled bit is defined; the rest of the byte is reserved.
|
|
213
|
+
traceFlags: (parseInt(flags, 16) & TraceFlags.SAMPLED) as TraceFlags,
|
|
214
|
+
isRemote: true,
|
|
215
|
+
...(traceState ? { traceState } : {}),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The OTel context a remote `SpanContext` should parent, or the active one.
|
|
221
|
+
*
|
|
222
|
+
* Note the fallback is the *active* context, not `ROOT_CONTEXT`: with no
|
|
223
|
+
* caller-supplied trace context the span attaches to whatever span is active in
|
|
224
|
+
* this process, and only becomes a root when there is none. That is the right
|
|
225
|
+
* default — it preserves in-process nesting — but it means "no traceparent" and
|
|
226
|
+
* "root span" are not synonyms.
|
|
227
|
+
*/
|
|
228
|
+
function parentContext(remote?: SpanContext): Context {
|
|
229
|
+
const active = otelContext.active();
|
|
230
|
+
return remote ? trace.setSpanContext(active, remote) : active;
|
|
231
|
+
}
|
|
232
|
+
|
|
23
233
|
/**
|
|
24
234
|
* Get or create the MCP server tracer
|
|
25
235
|
*/
|
|
@@ -46,13 +256,24 @@ export interface ToolCallSpanAttributes {
|
|
|
46
256
|
/**
|
|
47
257
|
* Start a span for a tool call.
|
|
48
258
|
* Caller MUST call span.end() when done.
|
|
259
|
+
*
|
|
260
|
+
* `remoteParent` is the caller's trace context, read from the request's `_meta`
|
|
261
|
+
* (spec 2026-07-28). With it the span joins the caller's trace; without it the
|
|
262
|
+
* span falls back to the active context, which is what every call produced
|
|
263
|
+
* before the `_meta` keys were wired in — a server-side trace nobody could
|
|
264
|
+
* correlate to the client that caused it.
|
|
49
265
|
*/
|
|
50
266
|
export function startToolCallSpan(
|
|
51
267
|
toolName: string,
|
|
52
268
|
attributes: ToolCallSpanAttributes,
|
|
269
|
+
remoteParent?: SpanContext,
|
|
53
270
|
): Span {
|
|
54
271
|
const tracer = getServerTracer();
|
|
55
|
-
return tracer.startSpan(
|
|
272
|
+
return tracer.startSpan(
|
|
273
|
+
`mcp.tool.call ${toolName}`,
|
|
274
|
+
{ attributes },
|
|
275
|
+
parentContext(remoteParent),
|
|
276
|
+
);
|
|
56
277
|
}
|
|
57
278
|
|
|
58
279
|
/**
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A real stdio server, started the way a consumer starts one.
|
|
3
|
+
*
|
|
4
|
+
* Spawned as a subprocess by `stdio-e2e_test.ts`. Kept as a fixture rather than
|
|
5
|
+
* written to a temp file at run time so the thing under test is readable and
|
|
6
|
+
* versioned: this is exactly the five lines from the README.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { McpApp } from "../mcp-app.js";
|
|
10
|
+
|
|
11
|
+
const app = new McpApp({
|
|
12
|
+
name: "e2e-stdio",
|
|
13
|
+
version: "9.9.9",
|
|
14
|
+
logger: () => {},
|
|
15
|
+
instructions: "fixture server",
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
app.registerTool(
|
|
19
|
+
{
|
|
20
|
+
name: "echo",
|
|
21
|
+
description: "Echo the input",
|
|
22
|
+
inputSchema: {
|
|
23
|
+
type: "object",
|
|
24
|
+
properties: { value: { type: "string" } },
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
(args) => args.value ?? "empty",
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
await app.start();
|
|
@@ -8,7 +8,20 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
// deno-lint-ignore-file no-explicit-any
|
|
11
|
-
|
|
11
|
+
// Draft 2020-12, not ajv's default export (draft-07). Spec 2026-07-28
|
|
12
|
+
// (SEP-2106) allows any JSON Schema 2020-12 keyword in `inputSchema` /
|
|
13
|
+
// `outputSchema`, and the draft-07 build treats the keywords added in 2020-12 —
|
|
14
|
+
// `prefixItems`, `unevaluatedProperties`, `unevaluatedItems`, `$dynamicRef` —
|
|
15
|
+
// as unknown. Combined with `strict: false` that failure is silent: the schema
|
|
16
|
+
// compiles, the constraint is never applied, and a violating payload validates
|
|
17
|
+
// clean. A tool author's declared boundary has to actually hold.
|
|
18
|
+
//
|
|
19
|
+
// Spelled as the full `dist/` path, not `ajv/2020`: `build-node.sh` copies
|
|
20
|
+
// import specifiers verbatim into the npm distribution, and ajv 8 ships no
|
|
21
|
+
// `exports` map and no root-level `2020.js`, so `ajv/2020` resolves under
|
|
22
|
+
// Deno's import map and then fails at runtime in Node with ERR_MODULE_NOT_FOUND.
|
|
23
|
+
// This path resolves under both.
|
|
24
|
+
import AjvDefault from "ajv/dist/2020.js";
|
|
12
25
|
|
|
13
26
|
// Get the Ajv constructor (handles ESM/CJS differences)
|
|
14
27
|
const Ajv = (AjvDefault as any).default ?? AjvDefault;
|