codebase-snapshot 0.20.12 → 0.20.13

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/CHANGELOG.md CHANGED
@@ -31,6 +31,17 @@ deprecated with an explanatory message instead. `latest` has pointed at 0.9.0 si
31
31
 
32
32
  ---
33
33
 
34
+ ## 0.20.13
35
+
36
+ **MCP 2026-07-28 conformance: the modern HTTP headers, cache metadata and resource error code now match the revision, and an independent client drives both modern transports.**
37
+
38
+ - Streamable HTTP validates `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` against the parsed body before dispatch, returns HTTP `400` with `-32020` for a missing or mismatched header, decodes the Base64 sentinel, and allows the headers in CORS preflights.
39
+ - `server/discover`, `tools/list`, `prompts/list`, `resources/list`, `resources/read` and `resources/templates/list` carry the required `ttlMs` and `cacheScope` fields in the modern era. `ttlMs` is `0` and the scope is `private`: a regenerated snapshot must not be served from a stale cache.
40
+ - A missing modern resource returns `-32602` (Invalid Params); legacy clients keep `-32002`. Unknown methods and unsupported versions use the modern HTTP statuses (404 and 400).
41
+ - Modern requests are stateless: an `mcp-session-id` is ignored rather than looked up, and a modern request never mints or echoes one.
42
+ - New tests drive the server through the official MCP v2 client over modern stdio and modern HTTP (`server/discover`, `tools/list`, `tools/call`, `resources/read`), and a Windows CI job builds and runs the transport suites. The client is a dev-only dependency; the runtime still depends only on `typescript`.
43
+ - The docs now state the modern header, caching and error rules, and the security review names the header/body agreement check.
44
+
34
45
  ## 0.20.12
35
46
 
36
47
  **Live execution of the fourth audit's hypotheses: every claim was reproduced against the built CLI before it was fixed, and each class has a regression test.**
package/README.md CHANGED
@@ -212,7 +212,7 @@ Everything an agent needs is available as data, and the tool can install its own
212
212
  ```bash
213
213
  npx codebase-snapshot describe --format json # contract: workflow, options, exit codes
214
214
  npx codebase-snapshot skill --install # into .claude/skills + .cursor/rules
215
- npx -y codebase-snapshot@0.20.9 mcp # or serve it over MCP
215
+ npx -y codebase-snapshot@0.20.12 mcp # or serve it over MCP
216
216
  ```
217
217
 
218
218
  An agent told only "use `npx codebase-snapshot`" can read the contract, follow its ordered
@@ -224,6 +224,11 @@ tree, so an excluded file stays excluded and a redacted value stays redacted, an
224
224
  `snapshot_validate` answers the question an agent otherwise cannot ask: is the context I was given
225
225
  still true?
226
226
 
227
+ It speaks both protocol eras, including the `2026-07-28` revision: stateless `server/discover`,
228
+ required `MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` HTTP headers, cache hints on every
229
+ cacheable result, and the modern resource-not-found code. The suite drives it through the official
230
+ MCP v2 client over both modern stdio and modern HTTP.
231
+
227
232
  → [Using this with an AI agent](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/agent.md) · [MCP server](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/mcp.md) · [AGENTS.md](https://github.com/ankurhalder/codebase-snapshot/blob/main/AGENTS.md) · [llms.txt](https://github.com/ankurhalder/codebase-snapshot/blob/main/llms.txt)
228
233
 
229
234
  ## Configuration
@@ -278,12 +283,12 @@ others.
278
283
  | [Benchmarks](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/benchmarks.md) | Reproducible token and time numbers for the three modes |
279
284
  | [Security review](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/security-review.md) | Threat model, controls, tests and residual risks |
280
285
  | [Deploy](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/deploy.md) | Container, compose and systemd, with the token requirement |
281
- | [Migrating](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/migration.md) | What changed from 0.12.14 to 0.20.12, and the behaviour changes that matter |
286
+ | [Migrating](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/migration.md) | What changed from 0.12.14 to 0.20.13, and the behaviour changes that matter |
282
287
  | [Workspaces](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/workspace.md) | `--workspace`: one snapshot per member, plus the index |
283
288
  | [Token budget](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/budget.md) | `--budget-tokens`: whole files chosen to fit a limit, not torn to fit a part |
284
289
  | [The brief](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/brief.md) | The half of PROMPT.md only you can write, and what is refused |
285
290
  | [AI agents](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/agent.md) | The contract, the skill, what an agent should avoid |
286
- | [MCP server](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/mcp.md) | 26 tools, resources, both protocol eras |
291
+ | [MCP server](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/mcp.md) | 26 tools, resources, both protocol eras, modern HTTP conformance |
287
292
  | [Troubleshooting](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/troubleshooting.md) | Every message and what to do about it |
288
293
  | [Changelog](https://github.com/ankurhalder/codebase-snapshot/blob/main/CHANGELOG.md) | Release history and breaking changes |
289
294
 
package/dist/bin.js CHANGED
@@ -2565,7 +2565,7 @@ function verifySnapshotSignature(snapshotDir) {
2565
2565
 
2566
2566
  // src/version.ts
2567
2567
  var GENERATOR_NAME = "codebase-snapshot";
2568
- var GENERATOR_VERSION = "0.20.12";
2568
+ var GENERATOR_VERSION = "0.20.13";
2569
2569
  var SCHEMA_VERSION = "3.0.0";
2570
2570
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2571
2571
  function isOurGeneratorName(name) {
@@ -10930,7 +10930,7 @@ function assembleGroup(group, index, total, contentFingerprint) {
10930
10930
  }
10931
10931
  const pathLines = group.sections.map((s) => displayPath(s.file.relativePath));
10932
10932
  const listFence = fenceForText(pathLines.join("\n"), 3);
10933
- const header = [
10933
+ const header2 = [
10934
10934
  `# Codebase Snapshot Part ${zeroPad(index + 1)} of ${zeroPad(total)}`,
10935
10935
  "",
10936
10936
  `- Previous: ${prev}`,
@@ -10951,7 +10951,7 @@ function assembleGroup(group, index, total, contentFingerprint) {
10951
10951
  "## Contents",
10952
10952
  ""
10953
10953
  ].join("\n");
10954
- const assembled = (header + group.sections.map((s) => s.text).join("")).replace(
10954
+ const assembled = (header2 + group.sections.map((s) => s.text).join("")).replace(
10955
10955
  /\r\n|\r/g,
10956
10956
  "\n"
10957
10957
  );
@@ -11599,10 +11599,10 @@ function headerPaths(value) {
11599
11599
  }
11600
11600
  function diffSectionPaths(body) {
11601
11601
  const paths = /* @__PURE__ */ new Set();
11602
- let header = null;
11602
+ let header2 = null;
11603
11603
  for (const line of body.split("\n")) {
11604
11604
  if (line.startsWith("diff --git ")) {
11605
- header = line.slice("diff --git ".length);
11605
+ header2 = line.slice("diff --git ".length);
11606
11606
  continue;
11607
11607
  }
11608
11608
  if (line.startsWith("+++ ")) {
@@ -11615,8 +11615,8 @@ function diffSectionPaths(body) {
11615
11615
  if (path29 !== null) paths.add(path29);
11616
11616
  }
11617
11617
  }
11618
- if (paths.size === 0 && header !== null) {
11619
- for (const path29 of headerPaths(header)) paths.add(path29);
11618
+ if (paths.size === 0 && header2 !== null) {
11619
+ for (const path29 of headerPaths(header2)) paths.add(path29);
11620
11620
  }
11621
11621
  return [...paths];
11622
11622
  }
@@ -13015,13 +13015,22 @@ var ERROR_CODES = {
13015
13015
  */
13016
13016
  resourceTooLarge: -32e3,
13017
13017
  /**
13018
- * A known resource that this snapshot does not contain.
13018
+ * A known resource that this snapshot does not contain, under a legacy revision.
13019
13019
  *
13020
- * `-32002` is the MCP code for "resource not found". Answering `-32602` ("Unknown resource")
13021
- * for `snapshot://prompt` in a snapshot generated with `--skip-artifacts prompt` told the
13022
- * client its URI was wrong when the artifact had simply been left out.
13020
+ * `-32002` was the resource-not-found code through protocol revision `2025-11-25`. The
13021
+ * `2026-07-28` revision assigns missing resources to `-32602` and says clients SHOULD still
13022
+ * accept `-32002` from older servers. The dispatcher therefore chooses by era: `-32602` for
13023
+ * modern requests and this code for legacy ones. Answering `-32602` for `snapshot://prompt`
13024
+ * in a snapshot generated with `--skip-artifacts prompt` would tell a legacy client its URI
13025
+ * was wrong when the artifact had simply been left out.
13023
13026
  */
13024
13027
  resourceNotFound: -32002,
13028
+ /**
13029
+ * Streamable HTTP headers that are missing, malformed or disagree with the request body.
13030
+ *
13031
+ * Protocol revision `2026-07-28` reserves `-32020` for this. The HTTP status is `400`.
13032
+ */
13033
+ headerMismatch: -32020,
13025
13034
  /**
13026
13035
  * The server is at its concurrency limit.
13027
13036
  *
@@ -16390,7 +16399,7 @@ var readTool = {
16390
16399
  }
16391
16400
  const returnedLines = body.length === 0 ? truncatedByBytes && !clippedInsideLine && window.fromLine <= window.totalLines ? 1 : 0 : body.split("\n").length;
16392
16401
  const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
16393
- const header = [
16402
+ const header2 = [
16394
16403
  `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
16395
16404
  // The line range is the answer to "where am I in this file", and it is computed from the
16396
16405
  // body the window was taken from, so it is just as meaningful for a preview as for a full
@@ -16405,7 +16414,7 @@ var readTool = {
16405
16414
  ] : [],
16406
16415
  window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : clippedInsideLine ? `Line ${window.fromLine} of ${window.totalLines}: this line is longer than one result can carry, so this page ends mid-line.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
16407
16416
  ];
16408
- const lines = [...header, "", body];
16417
+ const lines = [...header2, "", body];
16409
16418
  if (moreRemain) {
16410
16419
  const next = window.fromLine + returnedLines;
16411
16420
  lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
@@ -18375,15 +18384,20 @@ function createMcpServer(options) {
18375
18384
  websiteUrl: options.info.websiteUrl
18376
18385
  });
18377
18386
  const ok = (id, result, modern) => successResponse(id, result, modern, options.info);
18387
+ const cacheable = (result) => ({
18388
+ ...result,
18389
+ cacheScope: "private",
18390
+ ttlMs: 0
18391
+ });
18378
18392
  const cancellations = /* @__PURE__ */ new Map();
18379
18393
  function handleNotification(method, params) {
18380
18394
  if (method === METHOD3.initialized && session.era === "legacy") session.ready = true;
18381
18395
  if (method === "notifications/cancelled") {
18382
- const requestId = params?.requestId;
18383
- if (typeof requestId === "string" || typeof requestId === "number") {
18384
- const cancel = cancellations.get(requestId);
18396
+ const requestId2 = params?.requestId;
18397
+ if (typeof requestId2 === "string" || typeof requestId2 === "number") {
18398
+ const cancel = cancellations.get(requestId2);
18385
18399
  if (cancel !== void 0) {
18386
- cancellations.delete(requestId);
18400
+ cancellations.delete(requestId2);
18387
18401
  cancel();
18388
18402
  }
18389
18403
  }
@@ -18411,15 +18425,11 @@ function createMcpServer(options) {
18411
18425
  function discover(id) {
18412
18426
  return ok(
18413
18427
  id,
18414
- {
18428
+ cacheable({
18415
18429
  supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
18416
18430
  capabilities: capabilities(),
18417
- instructions: options.instructions,
18418
- // The capability set depends on which repository the server was started for, so the answer
18419
- // may be cached only by the client that asked, and not at all after this response.
18420
- cacheScope: "private",
18421
- ttlMs: 0
18422
- },
18431
+ instructions: options.instructions
18432
+ }),
18423
18433
  true
18424
18434
  );
18425
18435
  }
@@ -18433,7 +18443,7 @@ function createMcpServer(options) {
18433
18443
  annotations: tool.annotations,
18434
18444
  _meta: { "codebase-snapshot/cost": tool.cost }
18435
18445
  }));
18436
- return ok(id, { tools }, modern);
18446
+ return ok(id, cacheable({ tools }), modern);
18437
18447
  }
18438
18448
  async function callTool(id, modern, params) {
18439
18449
  const name = params?.name;
@@ -18509,7 +18519,7 @@ function createMcpServer(options) {
18509
18519
  }
18510
18520
  async function listResources(id, modern) {
18511
18521
  const resources = await options.resources.list(options.context);
18512
- return ok(id, { resources }, modern);
18522
+ return ok(id, cacheable({ resources }), modern);
18513
18523
  }
18514
18524
  async function readResource(id, modern, params) {
18515
18525
  const uri = params?.uri;
@@ -18521,7 +18531,12 @@ function createMcpServer(options) {
18521
18531
  contents = await options.resources.read(uri, options.context);
18522
18532
  } catch (error) {
18523
18533
  if (error instanceof ResourceNotFoundError) {
18524
- return errorResponse(id, ERROR_CODES.resourceNotFound, error.message, { uri: error.uri });
18534
+ return errorResponse(
18535
+ id,
18536
+ modern ? ERROR_CODES.invalidParams : ERROR_CODES.resourceNotFound,
18537
+ error.message,
18538
+ { uri: error.uri }
18539
+ );
18525
18540
  }
18526
18541
  if (error instanceof ResourceTooLargeError) {
18527
18542
  options.context.log(
@@ -18538,7 +18553,7 @@ function createMcpServer(options) {
18538
18553
  if (!contents) {
18539
18554
  return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
18540
18555
  }
18541
- return ok(id, { contents: [contents] }, modern);
18556
+ return ok(id, cacheable({ contents: [contents] }), modern);
18542
18557
  }
18543
18558
  function listPrompts(id, modern) {
18544
18559
  const prompts = options.prompts.map((prompt) => ({
@@ -18547,7 +18562,7 @@ function createMcpServer(options) {
18547
18562
  description: prompt.description,
18548
18563
  arguments: prompt.arguments
18549
18564
  }));
18550
- return ok(id, { prompts }, modern);
18565
+ return ok(id, cacheable({ prompts }), modern);
18551
18566
  }
18552
18567
  function getPrompt(id, modern, params) {
18553
18568
  const name = params?.name;
@@ -18618,7 +18633,7 @@ function createMcpServer(options) {
18618
18633
  case METHOD3.resourcesRead:
18619
18634
  return readResource(id, modern, params);
18620
18635
  case METHOD3.resourceTemplatesList:
18621
- return ok(id, { resourceTemplates: options.resources.templates() }, modern);
18636
+ return ok(id, cacheable({ resourceTemplates: options.resources.templates() }), modern);
18622
18637
  case METHOD3.promptsList:
18623
18638
  return listPrompts(id, modern);
18624
18639
  case METHOD3.promptsGet:
@@ -18924,18 +18939,218 @@ async function runStdioServer(options) {
18924
18939
  }
18925
18940
 
18926
18941
  // src/auth.ts
18927
- function parseBearerToken(header) {
18928
- if (typeof header !== "string") return null;
18942
+ function parseBearerToken(header2) {
18943
+ if (typeof header2 !== "string") return null;
18929
18944
  const scheme = "bearer";
18930
- if (header.length <= scheme.length) return null;
18931
- if (header.slice(0, scheme.length).toLowerCase() !== scheme) return null;
18945
+ if (header2.length <= scheme.length) return null;
18946
+ if (header2.slice(0, scheme.length).toLowerCase() !== scheme) return null;
18932
18947
  let index = scheme.length;
18933
- if (header[index] !== " " && header[index] !== " ") return null;
18934
- while (index < header.length && (header[index] === " " || header[index] === " ")) index += 1;
18935
- const token = header.slice(index).trim();
18948
+ if (header2[index] !== " " && header2[index] !== " ") return null;
18949
+ while (index < header2.length && (header2[index] === " " || header2[index] === " ")) index += 1;
18950
+ const token = header2.slice(index).trim();
18936
18951
  return token.length > 0 ? token : null;
18937
18952
  }
18938
18953
 
18954
+ // src/mcp/http-headers.ts
18955
+ var PROTOCOL_HEADER = "mcp-protocol-version";
18956
+ var METHOD_HEADER = "mcp-method";
18957
+ var NAME_HEADER = "mcp-name";
18958
+ var BASE64_PREFIX = "=?base64?";
18959
+ var BASE64_SUFFIX = "?=";
18960
+ var NAMED_METHODS = /* @__PURE__ */ new Set(["tools/call", "resources/read", "prompts/get"]);
18961
+ function requestId(message) {
18962
+ const raw = message.id;
18963
+ return typeof raw === "string" || typeof raw === "number" ? raw : null;
18964
+ }
18965
+ function header(request, name) {
18966
+ const value = request.headers[name];
18967
+ return typeof value === "string" ? value : null;
18968
+ }
18969
+ function isSafeHeaderValue(value) {
18970
+ return /^[\x20-\x7e\t]+$/.test(value);
18971
+ }
18972
+ function decodeMcpHeaderValue(value) {
18973
+ if (!value.startsWith(BASE64_PREFIX)) {
18974
+ return isSafeHeaderValue(value) ? value : null;
18975
+ }
18976
+ if (!value.endsWith(BASE64_SUFFIX)) return null;
18977
+ const encoded = value.slice(BASE64_PREFIX.length, -BASE64_SUFFIX.length);
18978
+ if (encoded.length === 0 || encoded.length % 4 !== 0) return null;
18979
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) return null;
18980
+ const decoded = Buffer.from(encoded, "base64").toString("utf8");
18981
+ if (Buffer.from(decoded, "utf8").toString("base64") !== encoded) return null;
18982
+ return decoded;
18983
+ }
18984
+ function isModernHttpMessage(request, message) {
18985
+ if (Array.isArray(message)) {
18986
+ return message.some((item) => isModernHttpMessage(request, item));
18987
+ }
18988
+ if (!isJsonObject(message)) return false;
18989
+ if (message.method === "server/discover") return true;
18990
+ const params = isJsonObject(message.params) ? message.params : void 0;
18991
+ const meta = isJsonObject(params?._meta) ? params._meta : void 0;
18992
+ if (meta !== void 0 && (META_KEYS.protocolVersion in meta || META_KEYS.clientCapabilities in meta)) {
18993
+ return true;
18994
+ }
18995
+ return header(request, METHOD_HEADER) !== null || header(request, NAME_HEADER) !== null;
18996
+ }
18997
+ function refuse(id, code, message, data) {
18998
+ return errorResponse(id, code, message, data);
18999
+ }
19000
+ function validateModernHttpHeaders(request, message) {
19001
+ if (!isModernHttpMessage(request, message)) return { modern: false };
19002
+ if (Array.isArray(message)) {
19003
+ return {
19004
+ modern: true,
19005
+ error: refuse(null, ERROR_CODES.invalidRequest, "Batch requests are not supported.")
19006
+ };
19007
+ }
19008
+ if (!isJsonObject(message)) {
19009
+ return {
19010
+ modern: true,
19011
+ error: refuse(null, ERROR_CODES.invalidRequest, "Message is not a JSON object.")
19012
+ };
19013
+ }
19014
+ const id = requestId(message);
19015
+ const method = message.method;
19016
+ const params = isJsonObject(message.params) ? message.params : void 0;
19017
+ if (typeof method !== "string" || method.length === 0) {
19018
+ return {
19019
+ modern: true,
19020
+ error: refuse(id, ERROR_CODES.invalidRequest, 'Message must carry a "method" string.')
19021
+ };
19022
+ }
19023
+ const versionHeader = header(request, PROTOCOL_HEADER);
19024
+ if (versionHeader === null) {
19025
+ return {
19026
+ modern: true,
19027
+ error: refuse(
19028
+ id,
19029
+ ERROR_CODES.headerMismatch,
19030
+ `Header mismatch: ${PROTOCOL_HEADER} is required for a modern request.`
19031
+ )
19032
+ };
19033
+ }
19034
+ if (!isSafeHeaderValue(versionHeader)) {
19035
+ return {
19036
+ modern: true,
19037
+ error: refuse(
19038
+ id,
19039
+ ERROR_CODES.headerMismatch,
19040
+ `Header mismatch: ${PROTOCOL_HEADER} contains invalid characters.`
19041
+ )
19042
+ };
19043
+ }
19044
+ const meta = inspectModernMeta(params);
19045
+ if (meta.kind !== "present") {
19046
+ const missing = meta.kind === "incomplete" ? meta.missing : META_KEYS.protocolVersion;
19047
+ return {
19048
+ modern: true,
19049
+ error: refuse(
19050
+ id,
19051
+ ERROR_CODES.invalidParams,
19052
+ `The request _meta is missing the required key "${missing}".`
19053
+ )
19054
+ };
19055
+ }
19056
+ if (versionHeader !== meta.meta.version) {
19057
+ return {
19058
+ modern: true,
19059
+ error: refuse(
19060
+ id,
19061
+ ERROR_CODES.headerMismatch,
19062
+ `Header mismatch: ${PROTOCOL_HEADER} "${versionHeader}" does not match body value "${meta.meta.version}".`
19063
+ )
19064
+ };
19065
+ }
19066
+ const methodHeader = header(request, METHOD_HEADER);
19067
+ if (methodHeader === null) {
19068
+ return {
19069
+ modern: true,
19070
+ error: refuse(
19071
+ id,
19072
+ ERROR_CODES.headerMismatch,
19073
+ `Header mismatch: ${METHOD_HEADER} is required for a modern request.`
19074
+ )
19075
+ };
19076
+ }
19077
+ if (!isSafeHeaderValue(methodHeader) || methodHeader !== method) {
19078
+ return {
19079
+ modern: true,
19080
+ error: refuse(
19081
+ id,
19082
+ ERROR_CODES.headerMismatch,
19083
+ `Header mismatch: ${METHOD_HEADER} value "${methodHeader}" does not match body value "${method}".`
19084
+ )
19085
+ };
19086
+ }
19087
+ if (NAMED_METHODS.has(method)) {
19088
+ const nameHeader = header(request, NAME_HEADER);
19089
+ if (nameHeader === null) {
19090
+ return {
19091
+ modern: true,
19092
+ error: refuse(
19093
+ id,
19094
+ ERROR_CODES.headerMismatch,
19095
+ `Header mismatch: ${NAME_HEADER} is required for ${method}.`
19096
+ )
19097
+ };
19098
+ }
19099
+ const decoded = decodeMcpHeaderValue(nameHeader);
19100
+ if (decoded === null) {
19101
+ return {
19102
+ modern: true,
19103
+ error: refuse(
19104
+ id,
19105
+ ERROR_CODES.headerMismatch,
19106
+ `Header mismatch: ${NAME_HEADER} contains an invalid value.`
19107
+ )
19108
+ };
19109
+ }
19110
+ const bodyValue = method === "resources/read" ? params?.uri : params?.name;
19111
+ if (typeof bodyValue !== "string") {
19112
+ return {
19113
+ modern: true,
19114
+ error: refuse(
19115
+ id,
19116
+ ERROR_CODES.invalidParams,
19117
+ `${method} requires a "${method === "resources/read" ? "uri" : "name"}" string.`
19118
+ )
19119
+ };
19120
+ }
19121
+ if (decoded !== bodyValue) {
19122
+ return {
19123
+ modern: true,
19124
+ error: refuse(
19125
+ id,
19126
+ ERROR_CODES.headerMismatch,
19127
+ `Header mismatch: ${NAME_HEADER} value "${decoded}" does not match body value "${bodyValue}".`
19128
+ )
19129
+ };
19130
+ }
19131
+ }
19132
+ return { modern: true };
19133
+ }
19134
+ function modernHttpStatus(response) {
19135
+ if (!("error" in response)) return 200;
19136
+ switch (response.error.code) {
19137
+ case ERROR_CODES.headerMismatch:
19138
+ case ERROR_CODES.unsupportedProtocolVersion:
19139
+ case ERROR_CODES.invalidParams:
19140
+ case ERROR_CODES.invalidRequest:
19141
+ case ERROR_CODES.parseError:
19142
+ return 400;
19143
+ case ERROR_CODES.methodNotFound:
19144
+ return 404;
19145
+ case ERROR_CODES.internalError:
19146
+ return 500;
19147
+ case ERROR_CODES.overloaded:
19148
+ return 503;
19149
+ default:
19150
+ return 200;
19151
+ }
19152
+ }
19153
+
18939
19154
  // src/mcp/http.ts
18940
19155
  var DEFAULT_PORT = 4789;
18941
19156
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
@@ -18966,8 +19181,8 @@ function timingSafeEqual2(left, right) {
18966
19181
  return crypto5.timingSafeEqual(a, b);
18967
19182
  }
18968
19183
  function sessionHeader(request) {
18969
- const header = request.headers["mcp-session-id"];
18970
- return typeof header === "string" ? header.trim() : "";
19184
+ const header2 = request.headers["mcp-session-id"];
19185
+ return typeof header2 === "string" ? header2.trim() : "";
18971
19186
  }
18972
19187
  function isObject(value) {
18973
19188
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -18978,12 +19193,6 @@ function isToolCall(message) {
18978
19193
  function methodOf(message) {
18979
19194
  return isObject(message) && typeof message.method === "string" ? message.method : null;
18980
19195
  }
18981
- function hasModernMeta(message) {
18982
- const messages = Array.isArray(message) ? message : [message];
18983
- return messages.some(
18984
- (item) => isJsonObject(item) && isJsonObject(item.params) && inspectModernMeta(item.params).kind === "present"
18985
- );
18986
- }
18987
19196
  function createMcpHttpHandler(options) {
18988
19197
  const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
18989
19198
  const token = options.token;
@@ -19109,7 +19318,7 @@ function createMcpHttpHandler(options) {
19109
19318
  return {
19110
19319
  "access-control-allow-origin": allowed,
19111
19320
  vary: "origin",
19112
- "access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id",
19321
+ "access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id, mcp-method, mcp-name",
19113
19322
  // Without this a browser can send the header but cannot read it: mcp-session-id is not a
19114
19323
  // CORS-safelisted response header, so every cross-origin client silently lost its session.
19115
19324
  "access-control-expose-headers": "mcp-session-id",
@@ -19317,6 +19526,12 @@ function createMcpHttpHandler(options) {
19317
19526
  send(response, 400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
19318
19527
  return;
19319
19528
  }
19529
+ const headers = validateModernHttpHeaders(request, message);
19530
+ if (headers.error !== void 0) {
19531
+ send(response, 400, headers.error, cors);
19532
+ return;
19533
+ }
19534
+ const modern = headers.modern;
19320
19535
  if (batch.length > 1 && rateLimited(request, batch.length - 1)) {
19321
19536
  tooMany(response, cors);
19322
19537
  return;
@@ -19335,6 +19550,8 @@ function createMcpHttpHandler(options) {
19335
19550
  rememberAnonymous(anonymousKey(request), server);
19336
19551
  responseSession = newSessionId();
19337
19552
  rememberSession(responseSession, server, Date.now());
19553
+ } else if (modern) {
19554
+ server = createMcp();
19338
19555
  } else if (supplied !== "") {
19339
19556
  const now = Date.now();
19340
19557
  pruneSessions(now);
@@ -19346,8 +19563,6 @@ function createMcpHttpHandler(options) {
19346
19563
  existing.lastSeen = now;
19347
19564
  server = existing.server;
19348
19565
  responseSession = supplied;
19349
- } else if (hasModernMeta(message)) {
19350
- server = createMcp();
19351
19566
  } else {
19352
19567
  server = fallbackServer(request);
19353
19568
  }
@@ -19371,7 +19586,8 @@ function createMcpHttpHandler(options) {
19371
19586
  send(response, 202, "", sessionHeaders);
19372
19587
  return;
19373
19588
  }
19374
- send(response, 200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
19589
+ const status = modern ? modernHttpStatus(answers[0]) : 200;
19590
+ send(response, status, Array.isArray(message) ? answers : answers[0], sessionHeaders);
19375
19591
  })().catch((error) => {
19376
19592
  log("mcp/http: " + error.message);
19377
19593
  send(response, 500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
@@ -19505,7 +19721,7 @@ async function startHttpTransport(options) {
19505
19721
  if (allowed !== null) {
19506
19722
  cors["access-control-allow-origin"] = allowed;
19507
19723
  cors.vary = "origin";
19508
- cors["access-control-allow-headers"] = "authorization, content-type, mcp-protocol-version, mcp-session-id";
19724
+ cors["access-control-allow-headers"] = "authorization, content-type, mcp-protocol-version, mcp-session-id, mcp-method, mcp-name";
19509
19725
  cors["access-control-expose-headers"] = "mcp-session-id";
19510
19726
  cors["access-control-allow-methods"] = "POST, GET, OPTIONS, DELETE";
19511
19727
  cors["access-control-max-age"] = "600";
@@ -21573,13 +21789,13 @@ function auditSnapshot(options) {
21573
21789
  const text2 = partTexts.get(part.filename);
21574
21790
  const sections = partSections.get(part.filename);
21575
21791
  if (text2 === void 0 || sections === void 0) continue;
21576
- const header = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text2);
21577
- if (header !== null) {
21578
- if (Number(header[1]) !== part.index) {
21579
- structureProblems.push(part.filename + " says part " + header[1] + ", the manifest says " + part.index);
21792
+ const header2 = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text2);
21793
+ if (header2 !== null) {
21794
+ if (Number(header2[1]) !== part.index) {
21795
+ structureProblems.push(part.filename + " says part " + header2[1] + ", the manifest says " + part.index);
21580
21796
  }
21581
- if (Number(header[2]) !== manifest.parts.length) {
21582
- structureProblems.push(part.filename + " says " + header[2] + " parts, the manifest holds " + manifest.parts.length);
21797
+ if (Number(header2[2]) !== manifest.parts.length) {
21798
+ structureProblems.push(part.filename + " says " + header2[2] + " parts, the manifest holds " + manifest.parts.length);
21583
21799
  }
21584
21800
  }
21585
21801
  const filesLine = /^- Files: (\d+)$/m.exec(text2);