@casys/mcp-server 0.24.1 → 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/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 +141 -22
- 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/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";
|
|
@@ -102,7 +104,12 @@ import {
|
|
|
102
104
|
type SubscriptionSink,
|
|
103
105
|
} from "./subscriptions/subscription-registry.js";
|
|
104
106
|
import { ServerMetrics } from "./observability/metrics.js";
|
|
105
|
-
import {
|
|
107
|
+
import type { SpanContext } from "@opentelemetry/api";
|
|
108
|
+
import {
|
|
109
|
+
endToolCallSpan,
|
|
110
|
+
parseTraceParent,
|
|
111
|
+
startToolCallSpan,
|
|
112
|
+
} from "./observability/otel.js";
|
|
106
113
|
import {
|
|
107
114
|
BodyTooLargeError,
|
|
108
115
|
DEFAULT_MAX_BODY_BYTES,
|
|
@@ -160,6 +167,16 @@ const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
|
|
|
160
167
|
*/
|
|
161
168
|
const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
|
|
162
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
|
+
|
|
163
180
|
/** Protocol version whose wire format this server implements natively */
|
|
164
181
|
const SPEC_2026_07_28 = "2026-07-28";
|
|
165
182
|
|
|
@@ -212,6 +229,34 @@ interface StatelessClientMeta {
|
|
|
212
229
|
readonly clientInfo?: Implementation;
|
|
213
230
|
readonly clientCapabilities?: ClientCapabilities;
|
|
214
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 } : {};
|
|
215
260
|
}
|
|
216
261
|
|
|
217
262
|
/** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
|
|
@@ -661,9 +706,31 @@ export class McpApp {
|
|
|
661
706
|
const toolName = request.params.name;
|
|
662
707
|
const args = request.params.arguments || {};
|
|
663
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
|
+
|
|
664
724
|
let result: unknown;
|
|
665
725
|
try {
|
|
666
|
-
result = await this.executeToolCall(
|
|
726
|
+
result = await this.executeToolCall(
|
|
727
|
+
toolName,
|
|
728
|
+
args,
|
|
729
|
+
undefined,
|
|
730
|
+
undefined,
|
|
731
|
+
undefined,
|
|
732
|
+
clientMeta,
|
|
733
|
+
);
|
|
667
734
|
} catch (error) {
|
|
668
735
|
return this.handleToolError(error, toolName);
|
|
669
736
|
}
|
|
@@ -673,6 +740,66 @@ export class McpApp {
|
|
|
673
740
|
return this.buildToolCallResult(toolName, result);
|
|
674
741
|
},
|
|
675
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
|
+
);
|
|
676
803
|
}
|
|
677
804
|
|
|
678
805
|
/**
|
|
@@ -1008,12 +1135,16 @@ export class McpApp {
|
|
|
1008
1135
|
};
|
|
1009
1136
|
|
|
1010
1137
|
// OTel span + metrics
|
|
1011
|
-
const span = startToolCallSpan(
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
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
|
+
);
|
|
1017
1148
|
|
|
1018
1149
|
// Update gauges before execution
|
|
1019
1150
|
const queueMetrics = this.requestQueue.getMetrics();
|
|
@@ -1927,20 +2058,7 @@ export class McpApp {
|
|
|
1927
2058
|
return c.json({
|
|
1928
2059
|
jsonrpc: "2.0",
|
|
1929
2060
|
id,
|
|
1930
|
-
result: this.
|
|
1931
|
-
this.withCacheHints({
|
|
1932
|
-
supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
|
|
1933
|
-
capabilities: this.buildServerCapabilities(),
|
|
1934
|
-
serverInfo: {
|
|
1935
|
-
name: this.options.name,
|
|
1936
|
-
version: this.options.version,
|
|
1937
|
-
},
|
|
1938
|
-
...(this.options.instructions
|
|
1939
|
-
? { instructions: this.options.instructions }
|
|
1940
|
-
: {}),
|
|
1941
|
-
}, statelessVersion),
|
|
1942
|
-
statelessVersion,
|
|
1943
|
-
),
|
|
2061
|
+
result: this.buildDiscoverResult(),
|
|
1944
2062
|
});
|
|
1945
2063
|
}
|
|
1946
2064
|
|
|
@@ -2005,6 +2123,7 @@ export class McpApp {
|
|
|
2005
2123
|
STATELESS_CLIENT_CAPABILITIES_KEY
|
|
2006
2124
|
] as ClientCapabilities | undefined,
|
|
2007
2125
|
logLevel: readLogLevel(params["_meta"]),
|
|
2126
|
+
...readTraceContext(params["_meta"]),
|
|
2008
2127
|
}
|
|
2009
2128
|
: undefined;
|
|
2010
2129
|
|
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;
|