@casys/mcp-server 0.21.1 → 0.23.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.
@@ -0,0 +1,661 @@
1
+ /**
2
+ * Streamable HTTP request-metadata headers (spec 2026-07-28, SEP-2243).
3
+ *
4
+ * The transport mirrors selected JSON-RPC body fields into HTTP headers so that
5
+ * load balancers, gateways and observability tooling can route and meter without
6
+ * parsing the body. Because two components then read two sources of truth, the
7
+ * spec requires the server to **prove they agree**: any divergence is a
8
+ * `HeaderMismatch` (`-32020`) with HTTP 400.
9
+ *
10
+ * Everything here is pure — no `Request`, no server state — so the encoding
11
+ * rules can be asserted directly. `validateRequestHeaders` is the only entry
12
+ * point the transport needs.
13
+ *
14
+ * @module lib/server/transport/request-headers
15
+ */
16
+
17
+ /** `HeaderMismatch` — headers disagree with the body, or a required one is absent. */
18
+ export const MCP_HEADER_MISMATCH = -32020;
19
+
20
+ /**
21
+ * Sentinel wrapper for values that cannot travel as plain ASCII.
22
+ *
23
+ * Case-sensitive and lowercase, per spec. Clients must also encode a plain-ASCII
24
+ * value that happens to look like the sentinel, so an encoded payload is never
25
+ * ambiguous with a literal one.
26
+ */
27
+ const SENTINEL_PREFIX = "=?base64?";
28
+ const SENTINEL_SUFFIX = "?=";
29
+
30
+ /** Methods whose `Mcp-Name` is required, and which body field it mirrors. */
31
+ const NAME_SOURCE: Readonly<Record<string, "name" | "uri" | "taskId">> = {
32
+ "tools/call": "name",
33
+ "prompts/get": "name",
34
+ "resources/read": "uri",
35
+ // Tasks extension: the routing header carries the task id, so a gateway can
36
+ // route or meter per task without reading the body — the same rationale as
37
+ // for a tool name.
38
+ "tasks/get": "taskId",
39
+ "tasks/update": "taskId",
40
+ "tasks/cancel": "taskId",
41
+ };
42
+
43
+ /** RFC 9110 §5.1 token: the only shape a header *name* may take. */
44
+ const HTTP_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
45
+
46
+ /**
47
+ * Field values are limited to visible ASCII, space and horizontal tab, and may
48
+ * not carry leading or trailing whitespace. The empty value is valid too: it is
49
+ * how a present string parameter with value `""` is mirrored on the wire.
50
+ */
51
+ const HEADER_SAFE_VALUE = /^(?:[\x21-\x7E](?:[\x20-\x7E\t]*[\x21-\x7E])?)?$/;
52
+
53
+ /**
54
+ * What went wrong, as data rather than prose.
55
+ *
56
+ * The `message` is for a human reading a log. `detail` is for the caller that has
57
+ * to fix the request: an agent should never have to parse an English sentence to
58
+ * learn which header was wrong and what to send instead.
59
+ */
60
+ export interface HeaderValidationDetail {
61
+ /** Which rule failed. Switch on this, not on the message text. */
62
+ readonly problem:
63
+ | "missing_header"
64
+ | "header_body_mismatch"
65
+ | "malformed_encoding"
66
+ | "unmirrorable_body";
67
+ /** The header at fault, in canonical casing. */
68
+ readonly header: string;
69
+ /** Value the body implies the header should carry, when one exists. */
70
+ readonly expected?: string;
71
+ /** Value that actually arrived, decoded, when one did. */
72
+ readonly received?: string;
73
+ /** The body field this header mirrors, e.g. `params.name`. */
74
+ readonly bodyField?: string;
75
+ /** One concrete corrective action. */
76
+ readonly recovery: string;
77
+ }
78
+
79
+ export interface HeaderValidationFailure {
80
+ readonly ok: false;
81
+ /** Human-readable reason; travels in the JSON-RPC error message. */
82
+ readonly message: string;
83
+ /** Machine-readable equivalent; travels in the JSON-RPC error `data`. */
84
+ readonly detail: HeaderValidationDetail;
85
+ }
86
+
87
+ export type HeaderValidationResult =
88
+ | { readonly ok: true }
89
+ | HeaderValidationFailure;
90
+
91
+ /**
92
+ * Decode a header value, unwrapping the base64 sentinel when present.
93
+ *
94
+ * Returns `null` when the sentinel is malformed — a client that wrapped a value
95
+ * badly is not the same as one that sent a plain value, and the caller must
96
+ * reject rather than silently compare the raw bytes.
97
+ */
98
+ export function decodeHeaderValue(raw: string): string | null {
99
+ if (!raw.startsWith(SENTINEL_PREFIX) || !raw.endsWith(SENTINEL_SUFFIX)) {
100
+ return raw;
101
+ }
102
+ const payload = raw.slice(
103
+ SENTINEL_PREFIX.length,
104
+ raw.length - SENTINEL_SUFFIX.length,
105
+ );
106
+ try {
107
+ // atob yields Latin-1 bytes; the payload is UTF-8, so re-decode it as such.
108
+ const bytes = Uint8Array.from(atob(payload), (ch) => ch.charCodeAt(0));
109
+ // `ignoreBOM: true` is load-bearing despite its name: it means "do not treat
110
+ // a leading U+FEFF specially", so the BOM stays in the output. The default
111
+ // (false) STRIPS it — which was a validation bypass: an encoded
112
+ // "\uFEFFfoo" decoded to "foo" and compared equal to a body value of
113
+ // "foo", letting a client mirror a header that does not match its body.
114
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
115
+ .decode(bytes);
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Encode a value for transport, applying the sentinel only when necessary.
123
+ *
124
+ * Exported for clients and tests; the server never needs it to validate. Note
125
+ * the deliberate asymmetry with {@link decodeHeaderValue}: a plain value that
126
+ * *looks* like the sentinel must be encoded, or decoding would unwrap something
127
+ * that was never wrapped.
128
+ */
129
+ export function encodeHeaderValue(value: string): string {
130
+ const looksLikeSentinel = value.startsWith(SENTINEL_PREFIX) &&
131
+ value.endsWith(SENTINEL_SUFFIX);
132
+ if (HEADER_SAFE_VALUE.test(value) && !looksLikeSentinel) return value;
133
+
134
+ const utf8 = new TextEncoder().encode(value);
135
+ let latin1 = "";
136
+ for (const byte of utf8) latin1 += String.fromCharCode(byte);
137
+ return `${SENTINEL_PREFIX}${btoa(latin1)}${SENTINEL_SUFFIX}`;
138
+ }
139
+
140
+ /**
141
+ * Whether `Mcp-Name` is required for this method, and the value it must mirror.
142
+ *
143
+ * The requirement follows the **method**, not the body. An earlier version
144
+ * returned `undefined` whenever the body field was not a string, which meant a
145
+ * malformed `tools/call` (no `name`, or a non-string one) escaped `Mcp-Name`
146
+ * validation entirely instead of being rejected.
147
+ */
148
+ export function mcpNameRequirement(
149
+ method: string,
150
+ params: Record<string, unknown> | undefined,
151
+ ): {
152
+ required: boolean;
153
+ expected?: string;
154
+ sourceField?: "name" | "uri" | "taskId";
155
+ } {
156
+ const field = NAME_SOURCE[method];
157
+ if (field === undefined) return { required: false };
158
+ const value = params?.[field];
159
+ return {
160
+ required: true,
161
+ sourceField: field,
162
+ ...(typeof value === "string" ? { expected: value } : {}),
163
+ };
164
+ }
165
+
166
+ /**
167
+ * Validate an `x-mcp-header` annotation.
168
+ *
169
+ * Enforced when a tool is registered rather than when it is called: a malformed
170
+ * annotation is a server-authoring bug, and the spec makes conforming clients
171
+ * drop the whole tool from `tools/list` over it. Failing at registration turns a
172
+ * silently-missing tool into an immediate, located error.
173
+ *
174
+ * @returns `null` when valid, else the reason it is not.
175
+ */
176
+ export function validateXMcpHeaderName(name: unknown): string | null {
177
+ if (typeof name !== "string" || name.length === 0) {
178
+ return "x-mcp-header must be a non-empty string";
179
+ }
180
+ if (!HTTP_TOKEN.test(name)) {
181
+ return `x-mcp-header "${name}" is not a valid HTTP field-name token (RFC 9110 §5.1)`;
182
+ }
183
+ return null;
184
+ }
185
+
186
+ /** Primitive JSON Schema types a mirrored parameter may declare. */
187
+ const MIRRORABLE_TYPES = new Set(["string", "integer", "boolean"]);
188
+
189
+ /**
190
+ * Validate that a parameter declaring `x-mcp-header` may actually be mirrored.
191
+ *
192
+ * `number` is excluded by the spec — a float has no single canonical decimal
193
+ * string, so header and body could never be compared reliably.
194
+ */
195
+ export function validateXMcpHeaderType(type: unknown): string | null {
196
+ if (typeof type !== "string" || !MIRRORABLE_TYPES.has(type)) {
197
+ return `x-mcp-header may only annotate string, integer or boolean parameters (got ${
198
+ typeof type === "string" ? `"${type}"` : "no type"
199
+ })`;
200
+ }
201
+ return null;
202
+ }
203
+
204
+ /**
205
+ * Compare a decoded header value against the body value it mirrors.
206
+ *
207
+ * Integers compare **numerically**, not as strings: the spec calls out that
208
+ * `42.0` and `42` are the same value, and a string comparison would reject a
209
+ * conforming client over formatting.
210
+ */
211
+ function valueMatches(headerValue: string, bodyValue: unknown): boolean {
212
+ if (typeof bodyValue === "number") {
213
+ const asNumber = Number(headerValue);
214
+ if (Number.isNaN(asNumber)) return false;
215
+ // The spec bounds mirrored integers to the JS safe range. Outside it,
216
+ // `Number()` silently collapses distinct values onto the same float, so two
217
+ // different integers would compare equal — a mismatch bypass.
218
+ if (
219
+ !Number.isSafeInteger(bodyValue) ||
220
+ !Number.isSafeInteger(asNumber) && Number.isInteger(asNumber)
221
+ ) {
222
+ return false;
223
+ }
224
+ return asNumber === bodyValue;
225
+ }
226
+ if (typeof bodyValue === "boolean") {
227
+ return headerValue === String(bodyValue);
228
+ }
229
+ return headerValue === bodyValue;
230
+ }
231
+
232
+ /** Read a value at a chain of `properties` keys. Absent → `undefined`. */
233
+ function readAtPath(
234
+ args: Record<string, unknown>,
235
+ path: readonly string[],
236
+ ): unknown {
237
+ let cursor: unknown = args;
238
+ for (const key of path) {
239
+ // Own properties only. Walking with plain `cursor[key]` would resolve
240
+ // inherited members, so a parameter annotated `toString` or `constructor`
241
+ // would read off the prototype instead of the arguments.
242
+ if (!isRecord(cursor) || !Object.hasOwn(cursor, key)) return undefined;
243
+ cursor = cursor[key];
244
+ }
245
+ return cursor;
246
+ }
247
+
248
+ function isRecord(v: unknown): v is Record<string, unknown> {
249
+ return typeof v === "object" && v !== null && !Array.isArray(v);
250
+ }
251
+
252
+ /** A parameter the server has asked clients to mirror into a header. */
253
+ export interface MirroredParam {
254
+ /** The `{Name}` in `Mcp-Param-{Name}`. */
255
+ readonly headerName: string;
256
+ /** Chain of `properties` keys leading to the annotated property. */
257
+ readonly path: readonly string[];
258
+ }
259
+
260
+ export interface ValidateHeadersInput {
261
+ /** Case-insensitive lookup, e.g. Hono's `c.req.header`. */
262
+ readonly getHeader: (name: string) => string | undefined;
263
+ readonly method: string;
264
+ readonly params: Record<string, unknown> | undefined;
265
+ /** Version already read from `_meta`; the header must agree with it. */
266
+ readonly bodyProtocolVersion: string;
267
+ /**
268
+ * Parameters the called tool asked to mirror. Empty for anything that is not a
269
+ * `tools/call`, or for a tool with no annotations.
270
+ */
271
+ readonly mirroredParams?: readonly MirroredParam[];
272
+ }
273
+
274
+ /**
275
+ * Enforce the request-metadata contract for one POST.
276
+ *
277
+ * Checks, in the order a client is most likely to get wrong:
278
+ * 1. `MCP-Protocol-Version` present and equal to the body's `_meta` value.
279
+ * 2. `Mcp-Method` present and equal to `method`.
280
+ * 3. `Mcp-Name` present and equal to `params.name` / `params.uri`, for the
281
+ * three methods that require it.
282
+ * 4. Every mirrored `Mcp-Param-*` present-and-equal when its argument is
283
+ * present, and absent when it is not.
284
+ *
285
+ * Header *names* are matched case-insensitively (RFC 9110); header *values* are
286
+ * compared case-sensitively, since method and tool names are case-sensitive.
287
+ */
288
+ export function validateRequestHeaders(
289
+ input: ValidateHeadersInput,
290
+ ): HeaderValidationResult {
291
+ const { getHeader, method, params, bodyProtocolVersion } = input;
292
+
293
+ const versionHeader = getHeader("MCP-Protocol-Version");
294
+ if (versionHeader === undefined) {
295
+ return {
296
+ ok: false,
297
+ message:
298
+ "Missing required header 'MCP-Protocol-Version'. Every POST to the MCP endpoint must carry it, matching _meta['io.modelcontextprotocol/protocolVersion'].",
299
+ detail: {
300
+ problem: "missing_header",
301
+ header: "MCP-Protocol-Version",
302
+ expected: bodyProtocolVersion,
303
+ bodyField: "params._meta['io.modelcontextprotocol/protocolVersion']",
304
+ recovery:
305
+ `Send the header 'MCP-Protocol-Version: ${bodyProtocolVersion}' on every POST.`,
306
+ },
307
+ };
308
+ }
309
+ if (versionHeader !== bodyProtocolVersion) {
310
+ return {
311
+ ok: false,
312
+ message:
313
+ `MCP-Protocol-Version header "${versionHeader}" does not match _meta protocolVersion "${bodyProtocolVersion}"`,
314
+ detail: {
315
+ problem: "header_body_mismatch",
316
+ header: "MCP-Protocol-Version",
317
+ expected: bodyProtocolVersion,
318
+ received: versionHeader,
319
+ bodyField: "params._meta['io.modelcontextprotocol/protocolVersion']",
320
+ recovery:
321
+ `Set the header to "${bodyProtocolVersion}", or change the body's _meta to "${versionHeader}". They must agree.`,
322
+ },
323
+ };
324
+ }
325
+
326
+ const methodHeader = getHeader("Mcp-Method");
327
+ if (methodHeader === undefined) {
328
+ return {
329
+ ok: false,
330
+ message:
331
+ "Missing required header 'Mcp-Method'. It must mirror the JSON-RPC 'method' field.",
332
+ detail: {
333
+ problem: "missing_header",
334
+ header: "Mcp-Method",
335
+ expected: method,
336
+ bodyField: "method",
337
+ recovery: `Send the header 'Mcp-Method: ${method}'.`,
338
+ },
339
+ };
340
+ }
341
+ if (methodHeader !== method) {
342
+ return {
343
+ ok: false,
344
+ message:
345
+ `Mcp-Method header "${methodHeader}" does not match body method "${method}"`,
346
+ detail: {
347
+ problem: "header_body_mismatch",
348
+ header: "Mcp-Method",
349
+ expected: method,
350
+ received: methodHeader,
351
+ bodyField: "method",
352
+ recovery: `Set the header to "${method}" to match the body.`,
353
+ },
354
+ };
355
+ }
356
+
357
+ const nameRule = mcpNameRequirement(method, params);
358
+ if (nameRule.required) {
359
+ const bodyField = `params.${nameRule.sourceField}`;
360
+ const raw = getHeader("Mcp-Name");
361
+ if (raw === undefined) {
362
+ return {
363
+ ok: false,
364
+ message:
365
+ `Missing required header 'Mcp-Name' for ${method}. It must mirror ${bodyField}.`,
366
+ detail: {
367
+ problem: "missing_header",
368
+ header: "Mcp-Name",
369
+ ...(nameRule.expected !== undefined
370
+ ? { expected: nameRule.expected }
371
+ : {}),
372
+ bodyField,
373
+ recovery: nameRule.expected !== undefined
374
+ ? `Send 'Mcp-Name: ${encodeHeaderValue(nameRule.expected)}'.`
375
+ : `Send 'Mcp-Name' mirroring ${bodyField}.`,
376
+ },
377
+ };
378
+ }
379
+ const decoded = decodeHeaderValue(raw);
380
+ if (decoded === null) {
381
+ return {
382
+ ok: false,
383
+ message:
384
+ "Mcp-Name header uses the =?base64?…?= sentinel but its payload is not valid base64-encoded UTF-8",
385
+ detail: {
386
+ problem: "malformed_encoding",
387
+ header: "Mcp-Name",
388
+ received: raw,
389
+ bodyField,
390
+ recovery:
391
+ "Re-encode as =?base64?<base64url of the UTF-8 bytes>?=, or send the plain value when it is header-safe ASCII.",
392
+ },
393
+ };
394
+ }
395
+ // A value outside the header-safe set MUST arrive sentinel-encoded. When the
396
+ // decode was a no-op (raw === decoded) the client sent it raw, which is a
397
+ // violation regardless of whether it happens to match the body.
398
+ if (raw === decoded && !HEADER_SAFE_VALUE.test(raw)) {
399
+ return {
400
+ ok: false,
401
+ message:
402
+ "Mcp-Name contains characters that are not valid in an HTTP field value and was not sentinel-encoded",
403
+ detail: {
404
+ problem: "malformed_encoding",
405
+ header: "Mcp-Name",
406
+ received: raw,
407
+ bodyField,
408
+ recovery: `Wrap the value: 'Mcp-Name: ${encodeHeaderValue(raw)}'.`,
409
+ },
410
+ };
411
+ }
412
+ if (nameRule.expected === undefined) {
413
+ return {
414
+ ok: false,
415
+ message:
416
+ `${method} requires ${bodyField} to be a string for Mcp-Name to mirror`,
417
+ detail: {
418
+ problem: "unmirrorable_body",
419
+ header: "Mcp-Name",
420
+ received: decoded,
421
+ bodyField,
422
+ recovery: `Set ${bodyField} to a string; ${method} requires it.`,
423
+ },
424
+ };
425
+ }
426
+ if (decoded !== nameRule.expected) {
427
+ return {
428
+ ok: false,
429
+ message:
430
+ `Mcp-Name header "${decoded}" does not match body value "${nameRule.expected}"`,
431
+ detail: {
432
+ problem: "header_body_mismatch",
433
+ header: "Mcp-Name",
434
+ expected: nameRule.expected,
435
+ received: decoded,
436
+ bodyField,
437
+ recovery: `Set the header to mirror the body: 'Mcp-Name: ${
438
+ encodeHeaderValue(nameRule.expected)
439
+ }'.`,
440
+ },
441
+ };
442
+ }
443
+ }
444
+
445
+ const mirrored = input.mirroredParams ?? [];
446
+ if (mirrored.length > 0) {
447
+ const args = isRecord(params?.["arguments"]) ? params["arguments"] : {};
448
+ for (const { headerName, path } of mirrored) {
449
+ const header = `Mcp-Param-${headerName}`;
450
+ const bodyField = `params.arguments.${path.join(".")}`;
451
+ const raw = getHeader(header);
452
+ const bodyValue = readAtPath(args, path);
453
+ const bodyAbsent = bodyValue === undefined || bodyValue === null;
454
+
455
+ if (bodyAbsent) {
456
+ // Client must omit the header; a present one has nothing to mirror.
457
+ if (raw !== undefined) {
458
+ return {
459
+ ok: false,
460
+ message:
461
+ `${header} header is present but "${bodyField}" is absent from the arguments`,
462
+ detail: {
463
+ problem: "header_body_mismatch",
464
+ header,
465
+ received: raw,
466
+ bodyField,
467
+ recovery:
468
+ `Omit ${header}, or supply ${bodyField} in the arguments.`,
469
+ },
470
+ };
471
+ }
472
+ continue;
473
+ }
474
+
475
+ const expected = String(bodyValue);
476
+ if (raw === undefined) {
477
+ return {
478
+ ok: false,
479
+ message:
480
+ `Missing required header '${header}' mirroring argument "${bodyField}"`,
481
+ detail: {
482
+ problem: "missing_header",
483
+ header,
484
+ expected,
485
+ bodyField,
486
+ recovery: `Send '${header}: ${encodeHeaderValue(expected)}'.`,
487
+ },
488
+ };
489
+ }
490
+ const decoded = decodeHeaderValue(raw);
491
+ if (decoded === null) {
492
+ return {
493
+ ok: false,
494
+ message:
495
+ `${header} uses the =?base64?…?= sentinel but its payload is not valid base64-encoded UTF-8`,
496
+ detail: {
497
+ problem: "malformed_encoding",
498
+ header,
499
+ expected,
500
+ received: raw,
501
+ bodyField,
502
+ recovery:
503
+ "Re-encode as =?base64?<base64url of the UTF-8 bytes>?=, or send the plain value when it is header-safe ASCII.",
504
+ },
505
+ };
506
+ }
507
+ if (!HEADER_SAFE_VALUE.test(raw) && raw === decoded) {
508
+ return {
509
+ ok: false,
510
+ message:
511
+ `${header} contains characters that are not valid in an HTTP field value and was not sentinel-encoded`,
512
+ detail: {
513
+ problem: "malformed_encoding",
514
+ header,
515
+ expected,
516
+ received: raw,
517
+ bodyField,
518
+ recovery: `Wrap the value: '${header}: ${
519
+ encodeHeaderValue(expected)
520
+ }'.`,
521
+ },
522
+ };
523
+ }
524
+ if (!valueMatches(decoded, bodyValue)) {
525
+ return {
526
+ ok: false,
527
+ message:
528
+ `${header} header "${decoded}" does not match argument "${bodyField}"`,
529
+ detail: {
530
+ problem: "header_body_mismatch",
531
+ header,
532
+ expected,
533
+ received: decoded,
534
+ bodyField,
535
+ recovery: `Set the header to mirror the argument: '${header}: ${
536
+ encodeHeaderValue(expected)
537
+ }'.`,
538
+ },
539
+ };
540
+ }
541
+ }
542
+ }
543
+
544
+ return { ok: true };
545
+ }
546
+
547
+ /**
548
+ * Collect the `x-mcp-header` annotations of an `inputSchema`.
549
+ *
550
+ * Only *statically reachable* properties count: the chain from the root must
551
+ * consist solely of `properties` keys. A path crossing `items`, `oneOf`/`anyOf`/
552
+ * `allOf`/`not`, `if`/`then`/`else` or `$ref` cannot be resolved to one value
553
+ * without evaluating the instance, so the spec makes such an annotation — and
554
+ * the whole tool definition — invalid.
555
+ *
556
+ * @param onInvalid Called with a reason per rejected annotation. Registration
557
+ * uses it to fail loudly; a caller that only needs the valid set may ignore it.
558
+ */
559
+ export function collectMirroredParams(
560
+ inputSchema: unknown,
561
+ onInvalid?: (reason: string) => void,
562
+ ): MirroredParam[] {
563
+ const found: MirroredParam[] = [];
564
+ const seen = new Set<string>();
565
+
566
+ /**
567
+ * Keywords whose subschemas are NOT statically reachable: resolving a path
568
+ * through them needs the instance. An `x-mcp-header` anywhere below one is
569
+ * invalid per spec, so these subtrees are scanned only to *report* offenders.
570
+ */
571
+ const UNREACHABLE_KEYWORDS = [
572
+ "items",
573
+ "prefixItems",
574
+ "additionalItems",
575
+ "contains",
576
+ "oneOf",
577
+ "anyOf",
578
+ "allOf",
579
+ "not",
580
+ "if",
581
+ "then",
582
+ "else",
583
+ "additionalProperties",
584
+ "patternProperties",
585
+ "propertyNames",
586
+ "$defs",
587
+ "definitions",
588
+ ];
589
+
590
+ /** Report any annotation buried in a non-statically-reachable subtree. */
591
+ const reportUnreachable = (node: unknown, where: string): void => {
592
+ if (!isRecord(node)) {
593
+ if (Array.isArray(node)) {
594
+ for (const item of node) reportUnreachable(item, where);
595
+ }
596
+ return;
597
+ }
598
+ if (node["x-mcp-header"] !== undefined) {
599
+ onInvalid?.(
600
+ `x-mcp-header "${
601
+ String(node["x-mcp-header"])
602
+ }" is not statically reachable (it sits under "${where}"). The spec ` +
603
+ `requires the path from the schema root to consist solely of ` +
604
+ `"properties" keys; such an annotation invalidates the tool definition.`,
605
+ );
606
+ }
607
+ for (const value of Object.values(node)) reportUnreachable(value, where);
608
+ };
609
+
610
+ const walk = (schema: unknown, path: readonly string[]): void => {
611
+ if (!isRecord(schema)) return;
612
+
613
+ // Scan the forbidden branches for offenders before descending the legal one.
614
+ for (const keyword of UNREACHABLE_KEYWORDS) {
615
+ if (schema[keyword] !== undefined) {
616
+ reportUnreachable(schema[keyword], keyword);
617
+ }
618
+ }
619
+ // `$ref` cannot be followed at all (and MUST NOT be dereferenced over the
620
+ // network), so an annotated property behind one is unreachable by definition.
621
+ if (typeof schema["$ref"] === "string" && path.length > 0) {
622
+ onInvalid?.(
623
+ `property "${
624
+ path.join(".")
625
+ }" resolves through a $ref, so any x-mcp-header below it is not statically reachable`,
626
+ );
627
+ }
628
+
629
+ const properties = schema["properties"];
630
+ if (!isRecord(properties)) return;
631
+
632
+ for (const [key, raw] of Object.entries(properties)) {
633
+ if (!isRecord(raw)) continue;
634
+ const here = [...path, key];
635
+ const annotation = raw["x-mcp-header"];
636
+
637
+ if (annotation !== undefined) {
638
+ const nameError = validateXMcpHeaderName(annotation);
639
+ const typeError = validateXMcpHeaderType(raw["type"]);
640
+ const headerName = annotation as string;
641
+ if (nameError) {
642
+ onInvalid?.(nameError);
643
+ } else if (typeError) {
644
+ onInvalid?.(`${typeError} (at "${here.join(".")}")`);
645
+ } else if (seen.has(headerName.toLowerCase())) {
646
+ onInvalid?.(
647
+ `duplicate x-mcp-header "${headerName}" — values must be unique case-insensitively within one inputSchema`,
648
+ );
649
+ } else {
650
+ seen.add(headerName.toLowerCase());
651
+ found.push({ headerName, path: here });
652
+ }
653
+ }
654
+
655
+ walk(raw, here);
656
+ }
657
+ };
658
+
659
+ walk(inputSchema, []);
660
+ return found;
661
+ }