@casys/mcp-server 0.26.0 → 0.27.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.
Files changed (299) hide show
  1. package/CHANGELOG.md +1779 -0
  2. package/LICENSE +21 -0
  3. package/README.md +19 -5
  4. package/esm/_dnt.polyfills.d.ts +12 -0
  5. package/esm/_dnt.polyfills.d.ts.map +1 -0
  6. package/esm/_dnt.polyfills.js +15 -0
  7. package/esm/_dnt.shims.d.ts +2 -0
  8. package/esm/_dnt.shims.d.ts.map +1 -0
  9. package/esm/_dnt.shims.js +57 -0
  10. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
  11. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
  12. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
  13. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
  14. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
  15. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
  16. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
  17. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
  18. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
  19. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
  20. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
  21. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
  22. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
  23. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
  24. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
  25. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
  26. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
  27. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
  28. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
  29. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
  30. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
  31. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
  32. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
  33. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
  34. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
  35. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
  36. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
  37. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
  38. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
  39. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
  40. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
  41. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
  42. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
  43. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
  44. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
  45. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
  46. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
  47. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
  48. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
  49. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
  50. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
  51. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
  52. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
  53. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
  54. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
  55. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
  56. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
  57. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
  58. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
  59. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
  60. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
  61. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
  62. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
  63. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
  64. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
  65. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
  66. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
  67. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
  68. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
  69. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
  70. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
  71. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
  72. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
  73. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
  74. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
  75. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
  76. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
  77. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
  78. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
  79. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
  80. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
  81. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
  82. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
  83. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
  84. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
  85. package/esm/mod.d.ts +102 -0
  86. package/esm/mod.d.ts.map +1 -0
  87. package/esm/mod.js +103 -0
  88. package/esm/package.json +3 -0
  89. package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
  90. package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
  91. package/esm/src/auth/as-metadata-proxy.js +171 -0
  92. package/esm/src/auth/config.d.ts +117 -0
  93. package/esm/src/auth/config.d.ts.map +1 -0
  94. package/esm/src/auth/config.js +219 -0
  95. package/esm/src/auth/jwt-provider.d.ts +157 -0
  96. package/esm/src/auth/jwt-provider.d.ts.map +1 -0
  97. package/esm/src/auth/jwt-provider.js +187 -0
  98. package/esm/src/auth/middleware.d.ts +61 -0
  99. package/esm/src/auth/middleware.d.ts.map +1 -0
  100. package/esm/src/auth/middleware.js +209 -0
  101. package/esm/src/auth/mod.d.ts +23 -0
  102. package/esm/src/auth/mod.d.ts.map +1 -0
  103. package/esm/src/auth/mod.js +27 -0
  104. package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
  105. package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
  106. package/esm/src/auth/multi-tenant-middleware.js +128 -0
  107. package/esm/src/auth/presets.d.ts +231 -0
  108. package/esm/src/auth/presets.d.ts.map +1 -0
  109. package/esm/src/auth/presets.js +223 -0
  110. package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
  111. package/esm/src/auth/provider.d.ts.map +1 -0
  112. package/esm/src/auth/provider.js +34 -0
  113. package/esm/src/auth/scope-middleware.d.ts +30 -0
  114. package/esm/src/auth/scope-middleware.d.ts.map +1 -0
  115. package/esm/src/auth/scope-middleware.js +48 -0
  116. package/esm/src/auth/static-token-provider.d.ts +155 -0
  117. package/esm/src/auth/static-token-provider.d.ts.map +1 -0
  118. package/esm/src/auth/static-token-provider.js +256 -0
  119. package/esm/src/auth/types.d.ts +151 -0
  120. package/esm/src/auth/types.d.ts.map +1 -0
  121. package/esm/src/auth/types.js +64 -0
  122. package/esm/src/client-auth/callback-server.d.ts +34 -0
  123. package/esm/src/client-auth/callback-server.d.ts.map +1 -0
  124. package/esm/src/client-auth/callback-server.js +141 -0
  125. package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
  126. package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
  127. package/esm/src/client-auth/client-id-metadata.js +149 -0
  128. package/esm/src/client-auth/connect.d.ts +32 -0
  129. package/esm/src/client-auth/connect.d.ts.map +1 -0
  130. package/esm/src/client-auth/connect.js +47 -0
  131. package/esm/src/client-auth/mod.d.ts +19 -0
  132. package/esm/src/client-auth/mod.d.ts.map +1 -0
  133. package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
  134. package/esm/src/client-auth/provider.d.ts +78 -0
  135. package/esm/src/client-auth/provider.d.ts.map +1 -0
  136. package/esm/src/client-auth/provider.js +246 -0
  137. package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
  138. package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
  139. package/esm/src/client-auth/token-store/file-store.js +62 -0
  140. package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
  141. package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
  142. package/esm/src/client-auth/token-store/memory-store.js +25 -0
  143. package/esm/src/client-auth/types.d.ts +89 -0
  144. package/esm/src/client-auth/types.d.ts.map +1 -0
  145. package/esm/src/client-auth/types.js +10 -0
  146. package/esm/src/concurrency/rate-limiter.d.ts +87 -0
  147. package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
  148. package/esm/src/concurrency/rate-limiter.js +165 -0
  149. package/esm/src/concurrency/request-queue.d.ts +71 -0
  150. package/esm/src/concurrency/request-queue.d.ts.map +1 -0
  151. package/esm/src/concurrency/request-queue.js +128 -0
  152. package/esm/src/http/body.d.ts +20 -0
  153. package/esm/src/http/body.d.ts.map +1 -0
  154. package/esm/src/http/body.js +63 -0
  155. package/esm/src/http/request-guards.d.ts +54 -0
  156. package/esm/src/http/request-guards.d.ts.map +1 -0
  157. package/esm/src/http/request-guards.js +114 -0
  158. package/esm/src/http/wire.d.ts +26 -0
  159. package/esm/src/http/wire.d.ts.map +1 -0
  160. package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
  161. package/esm/src/inspector/launcher.d.ts +48 -0
  162. package/esm/src/inspector/launcher.d.ts.map +1 -0
  163. package/esm/src/inspector/launcher.js +100 -0
  164. package/esm/src/mcp-app.d.ts +728 -0
  165. package/esm/src/mcp-app.d.ts.map +1 -0
  166. package/esm/src/mcp-app.js +3530 -0
  167. package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
  168. package/esm/src/middleware/backpressure.d.ts.map +1 -0
  169. package/esm/src/middleware/backpressure.js +31 -0
  170. package/esm/src/middleware/mod.d.ts +11 -0
  171. package/esm/src/middleware/mod.d.ts.map +1 -0
  172. package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
  173. package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
  174. package/esm/src/middleware/rate-limit.d.ts.map +1 -0
  175. package/esm/src/middleware/rate-limit.js +33 -0
  176. package/esm/src/middleware/runner.d.ts +32 -0
  177. package/esm/src/middleware/runner.d.ts.map +1 -0
  178. package/esm/src/middleware/runner.js +49 -0
  179. package/esm/src/middleware/types.d.ts +76 -0
  180. package/esm/src/middleware/types.d.ts.map +1 -0
  181. package/esm/src/middleware/types.js +9 -0
  182. package/esm/src/middleware/validation.d.ts +24 -0
  183. package/esm/src/middleware/validation.d.ts.map +1 -0
  184. package/esm/src/middleware/validation.js +30 -0
  185. package/esm/src/mrtr/capability-check.d.ts +75 -0
  186. package/esm/src/mrtr/capability-check.d.ts.map +1 -0
  187. package/esm/src/mrtr/capability-check.js +233 -0
  188. package/esm/src/mrtr/mod.d.ts +18 -0
  189. package/esm/src/mrtr/mod.d.ts.map +1 -0
  190. package/esm/src/mrtr/mod.js +12 -0
  191. package/esm/src/mrtr/replay-store.d.ts +50 -0
  192. package/esm/src/mrtr/replay-store.d.ts.map +1 -0
  193. package/esm/src/mrtr/replay-store.js +61 -0
  194. package/esm/src/mrtr/request-state.d.ts +181 -0
  195. package/esm/src/mrtr/request-state.d.ts.map +1 -0
  196. package/esm/src/mrtr/request-state.js +313 -0
  197. package/esm/src/mrtr/retry-guard.d.ts +61 -0
  198. package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
  199. package/esm/src/mrtr/retry-guard.js +53 -0
  200. package/esm/src/mrtr/types.d.ts +99 -0
  201. package/esm/src/mrtr/types.d.ts.map +1 -0
  202. package/esm/src/mrtr/types.js +14 -0
  203. package/esm/src/observability/metrics.d.ts +104 -0
  204. package/esm/src/observability/metrics.d.ts.map +1 -0
  205. package/esm/src/observability/metrics.js +207 -0
  206. package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
  207. package/esm/src/observability/mod.d.ts.map +1 -0
  208. package/esm/src/observability/mod.js +11 -0
  209. package/esm/src/observability/otel.d.ts +73 -0
  210. package/esm/src/observability/otel.d.ts.map +1 -0
  211. package/esm/src/observability/otel.js +260 -0
  212. package/esm/src/runtime/runtime.d.ts +10 -0
  213. package/esm/src/runtime/runtime.d.ts.map +1 -0
  214. package/esm/src/runtime/runtime.deno.d.ts +50 -0
  215. package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
  216. package/esm/src/runtime/runtime.deno.js +120 -0
  217. package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
  218. package/esm/src/runtime/runtime.node.d.ts +51 -0
  219. package/esm/src/runtime/runtime.node.d.ts.map +1 -0
  220. package/esm/src/runtime/runtime.node.js +268 -0
  221. package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
  222. package/esm/src/runtime/types.d.ts.map +1 -0
  223. package/esm/src/runtime/types.js +12 -0
  224. package/esm/src/security/channel-hmac.d.ts +43 -0
  225. package/esm/src/security/channel-hmac.d.ts.map +1 -0
  226. package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
  227. package/esm/src/security/csp.d.ts +50 -0
  228. package/esm/src/security/csp.d.ts.map +1 -0
  229. package/esm/src/security/csp.js +63 -0
  230. package/esm/src/security/message-signer.d.ts +88 -0
  231. package/esm/src/security/message-signer.d.ts.map +1 -0
  232. package/esm/src/security/message-signer.js +166 -0
  233. package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
  234. package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
  235. package/esm/src/subscriptions/subscription-registry.js +406 -0
  236. package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
  237. package/esm/src/tasks/mod.d.ts.map +1 -0
  238. package/esm/src/tasks/mod.js +11 -0
  239. package/esm/src/tasks/task-store.d.ts +342 -0
  240. package/esm/src/tasks/task-store.d.ts.map +1 -0
  241. package/esm/src/tasks/task-store.js +649 -0
  242. package/esm/src/transport/request-headers.d.ts +145 -0
  243. package/esm/src/transport/request-headers.d.ts.map +1 -0
  244. package/esm/src/transport/request-headers.js +525 -0
  245. package/esm/src/types.d.ts +776 -0
  246. package/esm/src/types.d.ts.map +1 -0
  247. package/esm/src/types.js +92 -0
  248. package/esm/src/ui/viewer-utils.d.ts +45 -0
  249. package/esm/src/ui/viewer-utils.d.ts.map +1 -0
  250. package/esm/src/ui/viewer-utils.js +97 -0
  251. package/esm/src/validation/schema-validator.d.ts +115 -0
  252. package/esm/src/validation/schema-validator.d.ts.map +1 -0
  253. package/esm/src/validation/schema-validator.js +249 -0
  254. package/package.json +35 -23
  255. package/mod.ts +0 -302
  256. package/src/auth/as-metadata-proxy.ts +0 -288
  257. package/src/auth/config.ts +0 -368
  258. package/src/auth/jwt-provider.ts +0 -327
  259. package/src/auth/middleware.ts +0 -257
  260. package/src/auth/mod.ts +0 -89
  261. package/src/auth/multi-tenant-middleware.ts +0 -236
  262. package/src/auth/presets.ts +0 -351
  263. package/src/auth/scope-middleware.ts +0 -59
  264. package/src/auth/static-token-provider.ts +0 -197
  265. package/src/auth/types.ts +0 -207
  266. package/src/client-auth/callback-server.ts +0 -166
  267. package/src/client-auth/client-id-metadata.ts +0 -260
  268. package/src/client-auth/connect.ts +0 -72
  269. package/src/client-auth/provider.ts +0 -300
  270. package/src/client-auth/token-store/file-store.ts +0 -73
  271. package/src/client-auth/token-store/memory-store.ts +0 -32
  272. package/src/client-auth/types.ts +0 -95
  273. package/src/concurrency/rate-limiter.ts +0 -190
  274. package/src/concurrency/request-queue.ts +0 -140
  275. package/src/http/body.ts +0 -72
  276. package/src/http/request-guards.ts +0 -137
  277. package/src/inspector/launcher.ts +0 -131
  278. package/src/mcp-app.ts +0 -4426
  279. package/src/middleware/runner.ts +0 -63
  280. package/src/middleware/types.ts +0 -104
  281. package/src/middleware/validation.ts +0 -28
  282. package/src/mrtr/capability-check.ts +0 -303
  283. package/src/mrtr/mod.ts +0 -46
  284. package/src/mrtr/replay-store.ts +0 -103
  285. package/src/mrtr/request-state.ts +0 -435
  286. package/src/mrtr/types.ts +0 -107
  287. package/src/observability/metrics.ts +0 -336
  288. package/src/observability/otel.ts +0 -330
  289. package/src/runtime/runtime.deno.ts +0 -149
  290. package/src/runtime/runtime.node.ts +0 -324
  291. package/src/security/csp.ts +0 -89
  292. package/src/security/message-signer.ts +0 -223
  293. package/src/subscriptions/subscription-registry.ts +0 -558
  294. package/src/tasks/task-store.ts +0 -1014
  295. package/src/testdata/stdio-e2e-server.ts +0 -110
  296. package/src/transport/request-headers.ts +0 -661
  297. package/src/types.ts +0 -907
  298. package/src/ui/viewer-utils.ts +0 -117
  299. package/src/validation/schema-validator.ts +0 -307
@@ -0,0 +1,145 @@
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
+ /** `HeaderMismatch` — headers disagree with the body, or a required one is absent. */
17
+ export declare const MCP_HEADER_MISMATCH = -32020;
18
+ /**
19
+ * What went wrong, as data rather than prose.
20
+ *
21
+ * The `message` is for a human reading a log. `detail` is for the caller that has
22
+ * to fix the request: an agent should never have to parse an English sentence to
23
+ * learn which header was wrong and what to send instead.
24
+ */
25
+ export interface HeaderValidationDetail {
26
+ /** Which rule failed. Switch on this, not on the message text. */
27
+ readonly problem: "missing_header" | "header_body_mismatch" | "malformed_encoding" | "unmirrorable_body";
28
+ /** The header at fault, in canonical casing. */
29
+ readonly header: string;
30
+ /** Value the body implies the header should carry, when one exists. */
31
+ readonly expected?: string;
32
+ /** Value that actually arrived, decoded, when one did. */
33
+ readonly received?: string;
34
+ /** The body field this header mirrors, e.g. `params.name`. */
35
+ readonly bodyField?: string;
36
+ /** One concrete corrective action. */
37
+ readonly recovery: string;
38
+ }
39
+ export interface HeaderValidationFailure {
40
+ readonly ok: false;
41
+ /** Human-readable reason; travels in the JSON-RPC error message. */
42
+ readonly message: string;
43
+ /** Machine-readable equivalent; travels in the JSON-RPC error `data`. */
44
+ readonly detail: HeaderValidationDetail;
45
+ }
46
+ export type HeaderValidationResult = {
47
+ readonly ok: true;
48
+ } | HeaderValidationFailure;
49
+ /**
50
+ * Decode a header value, unwrapping the base64 sentinel when present.
51
+ *
52
+ * Returns `null` when the sentinel is malformed — a client that wrapped a value
53
+ * badly is not the same as one that sent a plain value, and the caller must
54
+ * reject rather than silently compare the raw bytes.
55
+ */
56
+ export declare function decodeHeaderValue(raw: string): string | null;
57
+ /**
58
+ * Encode a value for transport, applying the sentinel only when necessary.
59
+ *
60
+ * Exported for clients and tests; the server never needs it to validate. Note
61
+ * the deliberate asymmetry with {@link decodeHeaderValue}: a plain value that
62
+ * *looks* like the sentinel must be encoded, or decoding would unwrap something
63
+ * that was never wrapped.
64
+ */
65
+ export declare function encodeHeaderValue(value: string): string;
66
+ /**
67
+ * Whether `Mcp-Name` is required for this method, and the value it must mirror.
68
+ *
69
+ * The requirement follows the **method**, not the body. An earlier version
70
+ * returned `undefined` whenever the body field was not a string, which meant a
71
+ * malformed `tools/call` (no `name`, or a non-string one) escaped `Mcp-Name`
72
+ * validation entirely instead of being rejected.
73
+ */
74
+ export declare function mcpNameRequirement(method: string, params: Record<string, unknown> | undefined): {
75
+ required: boolean;
76
+ expected?: string;
77
+ sourceField?: "name" | "uri" | "taskId";
78
+ };
79
+ /**
80
+ * Validate an `x-mcp-header` annotation.
81
+ *
82
+ * Enforced when a tool is registered rather than when it is called: a malformed
83
+ * annotation is a server-authoring bug, and the spec makes conforming clients
84
+ * drop the whole tool from `tools/list` over it. Failing at registration turns a
85
+ * silently-missing tool into an immediate, located error.
86
+ *
87
+ * @returns `null` when valid, else the reason it is not.
88
+ */
89
+ export declare function validateXMcpHeaderName(name: unknown): string | null;
90
+ /**
91
+ * Validate that a parameter declaring `x-mcp-header` may actually be mirrored.
92
+ *
93
+ * `number` is excluded by the spec — a float has no single canonical decimal
94
+ * string, so header and body could never be compared reliably.
95
+ */
96
+ export declare function validateXMcpHeaderType(type: unknown): string | null;
97
+ /** A parameter the server has asked clients to mirror into a header. */
98
+ export interface MirroredParam {
99
+ /** The `{Name}` in `Mcp-Param-{Name}`. */
100
+ readonly headerName: string;
101
+ /** Chain of `properties` keys leading to the annotated property. */
102
+ readonly path: readonly string[];
103
+ }
104
+ export interface ValidateHeadersInput {
105
+ /** Case-insensitive lookup, e.g. Hono's `c.req.header`. */
106
+ readonly getHeader: (name: string) => string | undefined;
107
+ readonly method: string;
108
+ readonly params: Record<string, unknown> | undefined;
109
+ /** Version already read from `_meta`; the header must agree with it. */
110
+ readonly bodyProtocolVersion: string;
111
+ /**
112
+ * Parameters the called tool asked to mirror. Empty for anything that is not a
113
+ * `tools/call`, or for a tool with no annotations.
114
+ */
115
+ readonly mirroredParams?: readonly MirroredParam[];
116
+ }
117
+ /**
118
+ * Enforce the request-metadata contract for one POST.
119
+ *
120
+ * Checks, in the order a client is most likely to get wrong:
121
+ * 1. `MCP-Protocol-Version` present and equal to the body's `_meta` value.
122
+ * 2. `Mcp-Method` present and equal to `method`.
123
+ * 3. `Mcp-Name` present and equal to `params.name` / `params.uri`, for the
124
+ * three methods that require it.
125
+ * 4. Every mirrored `Mcp-Param-*` present-and-equal when its argument is
126
+ * present, and absent when it is not.
127
+ *
128
+ * Header *names* are matched case-insensitively (RFC 9110); header *values* are
129
+ * compared case-sensitively, since method and tool names are case-sensitive.
130
+ */
131
+ export declare function validateRequestHeaders(input: ValidateHeadersInput): HeaderValidationResult;
132
+ /**
133
+ * Collect the `x-mcp-header` annotations of an `inputSchema`.
134
+ *
135
+ * Only *statically reachable* properties count: the chain from the root must
136
+ * consist solely of `properties` keys. A path crossing `items`, `oneOf`/`anyOf`/
137
+ * `allOf`/`not`, `if`/`then`/`else` or `$ref` cannot be resolved to one value
138
+ * without evaluating the instance, so the spec makes such an annotation — and
139
+ * the whole tool definition — invalid.
140
+ *
141
+ * @param onInvalid Called with a reason per rejected annotation. Registration
142
+ * uses it to fail loudly; a caller that only needs the valid set may ignore it.
143
+ */
144
+ export declare function collectMirroredParams(inputSchema: unknown, onInvalid?: (reason: string) => void): MirroredParam[];
145
+ //# sourceMappingURL=request-headers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-headers.d.ts","sourceRoot":"","sources":["../../../src/src/transport/request-headers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sFAAsF;AACtF,eAAO,MAAM,mBAAmB,SAAS,CAAC;AAmC1C;;;;;;GAMG;AACH,MAAM,WAAW,sBAAsB;IACrC,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EACZ,gBAAgB,GAChB,sBAAsB,GACtB,oBAAoB,GACpB,mBAAmB,CAAC;IACxB,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,uEAAuE;IACvE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,0DAA0D;IAC1D,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,8DAA8D;IAC9D,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,sCAAsC;IACtC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,oEAAoE;IACpE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,sBAAsB,CAAC;CACzC;AAED,MAAM,MAAM,sBAAsB,GAC9B;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAA;CAAE,GACrB,uBAAuB,CAAC;AAE5B;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqB5D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CASvD;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GAC1C;IACD,QAAQ,EAAE,OAAO,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;CACzC,CASA;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAQnE;AAKD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAOnE;AAkDD,wEAAwE;AACxE,MAAM,WAAW,aAAa;IAC5B,0CAA0C;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;CAClC;AAED,MAAM,WAAW,oBAAoB;IACnC,2DAA2D;IAC3D,QAAQ,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IACzD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACrD,wEAAwE;IACxE,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;CACpD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,oBAAoB,GAC1B,sBAAsB,CA+PxB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,OAAO,EACpB,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GACnC,aAAa,EAAE,CAmGjB"}
@@ -0,0 +1,525 @@
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
+ /** `HeaderMismatch` — headers disagree with the body, or a required one is absent. */
17
+ export const MCP_HEADER_MISMATCH = -32020;
18
+ /**
19
+ * Sentinel wrapper for values that cannot travel as plain ASCII.
20
+ *
21
+ * Case-sensitive and lowercase, per spec. Clients must also encode a plain-ASCII
22
+ * value that happens to look like the sentinel, so an encoded payload is never
23
+ * ambiguous with a literal one.
24
+ */
25
+ const SENTINEL_PREFIX = "=?base64?";
26
+ const SENTINEL_SUFFIX = "?=";
27
+ /** Methods whose `Mcp-Name` is required, and which body field it mirrors. */
28
+ const NAME_SOURCE = {
29
+ "tools/call": "name",
30
+ "prompts/get": "name",
31
+ "resources/read": "uri",
32
+ // Tasks extension: the routing header carries the task id, so a gateway can
33
+ // route or meter per task without reading the body — the same rationale as
34
+ // for a tool name.
35
+ "tasks/get": "taskId",
36
+ "tasks/update": "taskId",
37
+ "tasks/cancel": "taskId",
38
+ };
39
+ /** RFC 9110 §5.1 token: the only shape a header *name* may take. */
40
+ const HTTP_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
41
+ /**
42
+ * Field values are limited to visible ASCII, space and horizontal tab, and may
43
+ * not carry leading or trailing whitespace. The empty value is valid too: it is
44
+ * how a present string parameter with value `""` is mirrored on the wire.
45
+ */
46
+ const HEADER_SAFE_VALUE = /^(?:[\x21-\x7E](?:[\x20-\x7E\t]*[\x21-\x7E])?)?$/;
47
+ /**
48
+ * Decode a header value, unwrapping the base64 sentinel when present.
49
+ *
50
+ * Returns `null` when the sentinel is malformed — a client that wrapped a value
51
+ * badly is not the same as one that sent a plain value, and the caller must
52
+ * reject rather than silently compare the raw bytes.
53
+ */
54
+ export function decodeHeaderValue(raw) {
55
+ if (!raw.startsWith(SENTINEL_PREFIX) || !raw.endsWith(SENTINEL_SUFFIX)) {
56
+ return raw;
57
+ }
58
+ const payload = raw.slice(SENTINEL_PREFIX.length, raw.length - SENTINEL_SUFFIX.length);
59
+ try {
60
+ // atob yields Latin-1 bytes; the payload is UTF-8, so re-decode it as such.
61
+ const bytes = Uint8Array.from(atob(payload), (ch) => ch.charCodeAt(0));
62
+ // `ignoreBOM: true` is load-bearing despite its name: it means "do not treat
63
+ // a leading U+FEFF specially", so the BOM stays in the output. The default
64
+ // (false) STRIPS it — which was a validation bypass: an encoded
65
+ // "\uFEFFfoo" decoded to "foo" and compared equal to a body value of
66
+ // "foo", letting a client mirror a header that does not match its body.
67
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
68
+ .decode(bytes);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ /**
75
+ * Encode a value for transport, applying the sentinel only when necessary.
76
+ *
77
+ * Exported for clients and tests; the server never needs it to validate. Note
78
+ * the deliberate asymmetry with {@link decodeHeaderValue}: a plain value that
79
+ * *looks* like the sentinel must be encoded, or decoding would unwrap something
80
+ * that was never wrapped.
81
+ */
82
+ export function encodeHeaderValue(value) {
83
+ const looksLikeSentinel = value.startsWith(SENTINEL_PREFIX) &&
84
+ value.endsWith(SENTINEL_SUFFIX);
85
+ if (HEADER_SAFE_VALUE.test(value) && !looksLikeSentinel)
86
+ return value;
87
+ const utf8 = new TextEncoder().encode(value);
88
+ let latin1 = "";
89
+ for (const byte of utf8)
90
+ latin1 += String.fromCharCode(byte);
91
+ return `${SENTINEL_PREFIX}${btoa(latin1)}${SENTINEL_SUFFIX}`;
92
+ }
93
+ /**
94
+ * Whether `Mcp-Name` is required for this method, and the value it must mirror.
95
+ *
96
+ * The requirement follows the **method**, not the body. An earlier version
97
+ * returned `undefined` whenever the body field was not a string, which meant a
98
+ * malformed `tools/call` (no `name`, or a non-string one) escaped `Mcp-Name`
99
+ * validation entirely instead of being rejected.
100
+ */
101
+ export function mcpNameRequirement(method, params) {
102
+ const field = NAME_SOURCE[method];
103
+ if (field === undefined)
104
+ return { required: false };
105
+ const value = params?.[field];
106
+ return {
107
+ required: true,
108
+ sourceField: field,
109
+ ...(typeof value === "string" ? { expected: value } : {}),
110
+ };
111
+ }
112
+ /**
113
+ * Validate an `x-mcp-header` annotation.
114
+ *
115
+ * Enforced when a tool is registered rather than when it is called: a malformed
116
+ * annotation is a server-authoring bug, and the spec makes conforming clients
117
+ * drop the whole tool from `tools/list` over it. Failing at registration turns a
118
+ * silently-missing tool into an immediate, located error.
119
+ *
120
+ * @returns `null` when valid, else the reason it is not.
121
+ */
122
+ export function validateXMcpHeaderName(name) {
123
+ if (typeof name !== "string" || name.length === 0) {
124
+ return "x-mcp-header must be a non-empty string";
125
+ }
126
+ if (!HTTP_TOKEN.test(name)) {
127
+ return `x-mcp-header "${name}" is not a valid HTTP field-name token (RFC 9110 §5.1)`;
128
+ }
129
+ return null;
130
+ }
131
+ /** Primitive JSON Schema types a mirrored parameter may declare. */
132
+ const MIRRORABLE_TYPES = new Set(["string", "integer", "boolean"]);
133
+ /**
134
+ * Validate that a parameter declaring `x-mcp-header` may actually be mirrored.
135
+ *
136
+ * `number` is excluded by the spec — a float has no single canonical decimal
137
+ * string, so header and body could never be compared reliably.
138
+ */
139
+ export function validateXMcpHeaderType(type) {
140
+ if (typeof type !== "string" || !MIRRORABLE_TYPES.has(type)) {
141
+ return `x-mcp-header may only annotate string, integer or boolean parameters (got ${typeof type === "string" ? `"${type}"` : "no type"})`;
142
+ }
143
+ return null;
144
+ }
145
+ /**
146
+ * Compare a decoded header value against the body value it mirrors.
147
+ *
148
+ * Integers compare **numerically**, not as strings: the spec calls out that
149
+ * `42.0` and `42` are the same value, and a string comparison would reject a
150
+ * conforming client over formatting.
151
+ */
152
+ function valueMatches(headerValue, bodyValue) {
153
+ if (typeof bodyValue === "number") {
154
+ const asNumber = Number(headerValue);
155
+ if (Number.isNaN(asNumber))
156
+ return false;
157
+ // The spec bounds mirrored integers to the JS safe range. Outside it,
158
+ // `Number()` silently collapses distinct values onto the same float, so two
159
+ // different integers would compare equal — a mismatch bypass.
160
+ if (!Number.isSafeInteger(bodyValue) ||
161
+ !Number.isSafeInteger(asNumber) && Number.isInteger(asNumber)) {
162
+ return false;
163
+ }
164
+ return asNumber === bodyValue;
165
+ }
166
+ if (typeof bodyValue === "boolean") {
167
+ return headerValue === String(bodyValue);
168
+ }
169
+ return headerValue === bodyValue;
170
+ }
171
+ /** Read a value at a chain of `properties` keys. Absent → `undefined`. */
172
+ function readAtPath(args, path) {
173
+ let cursor = args;
174
+ for (const key of path) {
175
+ // Own properties only. Walking with plain `cursor[key]` would resolve
176
+ // inherited members, so a parameter annotated `toString` or `constructor`
177
+ // would read off the prototype instead of the arguments.
178
+ if (!isRecord(cursor) || !Object.hasOwn(cursor, key))
179
+ return undefined;
180
+ cursor = cursor[key];
181
+ }
182
+ return cursor;
183
+ }
184
+ function isRecord(v) {
185
+ return typeof v === "object" && v !== null && !Array.isArray(v);
186
+ }
187
+ /**
188
+ * Enforce the request-metadata contract for one POST.
189
+ *
190
+ * Checks, in the order a client is most likely to get wrong:
191
+ * 1. `MCP-Protocol-Version` present and equal to the body's `_meta` value.
192
+ * 2. `Mcp-Method` present and equal to `method`.
193
+ * 3. `Mcp-Name` present and equal to `params.name` / `params.uri`, for the
194
+ * three methods that require it.
195
+ * 4. Every mirrored `Mcp-Param-*` present-and-equal when its argument is
196
+ * present, and absent when it is not.
197
+ *
198
+ * Header *names* are matched case-insensitively (RFC 9110); header *values* are
199
+ * compared case-sensitively, since method and tool names are case-sensitive.
200
+ */
201
+ export function validateRequestHeaders(input) {
202
+ const { getHeader, method, params, bodyProtocolVersion } = input;
203
+ const versionHeader = getHeader("MCP-Protocol-Version");
204
+ if (versionHeader === undefined) {
205
+ return {
206
+ ok: false,
207
+ message: "Missing required header 'MCP-Protocol-Version'. Every POST to the MCP endpoint must carry it, matching _meta['io.modelcontextprotocol/protocolVersion'].",
208
+ detail: {
209
+ problem: "missing_header",
210
+ header: "MCP-Protocol-Version",
211
+ expected: bodyProtocolVersion,
212
+ bodyField: "params._meta['io.modelcontextprotocol/protocolVersion']",
213
+ recovery: `Send the header 'MCP-Protocol-Version: ${bodyProtocolVersion}' on every POST.`,
214
+ },
215
+ };
216
+ }
217
+ if (versionHeader !== bodyProtocolVersion) {
218
+ return {
219
+ ok: false,
220
+ message: `MCP-Protocol-Version header "${versionHeader}" does not match _meta protocolVersion "${bodyProtocolVersion}"`,
221
+ detail: {
222
+ problem: "header_body_mismatch",
223
+ header: "MCP-Protocol-Version",
224
+ expected: bodyProtocolVersion,
225
+ received: versionHeader,
226
+ bodyField: "params._meta['io.modelcontextprotocol/protocolVersion']",
227
+ recovery: `Set the header to "${bodyProtocolVersion}", or change the body's _meta to "${versionHeader}". They must agree.`,
228
+ },
229
+ };
230
+ }
231
+ const methodHeader = getHeader("Mcp-Method");
232
+ if (methodHeader === undefined) {
233
+ return {
234
+ ok: false,
235
+ message: "Missing required header 'Mcp-Method'. It must mirror the JSON-RPC 'method' field.",
236
+ detail: {
237
+ problem: "missing_header",
238
+ header: "Mcp-Method",
239
+ expected: method,
240
+ bodyField: "method",
241
+ recovery: `Send the header 'Mcp-Method: ${method}'.`,
242
+ },
243
+ };
244
+ }
245
+ if (methodHeader !== method) {
246
+ return {
247
+ ok: false,
248
+ message: `Mcp-Method header "${methodHeader}" does not match body method "${method}"`,
249
+ detail: {
250
+ problem: "header_body_mismatch",
251
+ header: "Mcp-Method",
252
+ expected: method,
253
+ received: methodHeader,
254
+ bodyField: "method",
255
+ recovery: `Set the header to "${method}" to match the body.`,
256
+ },
257
+ };
258
+ }
259
+ const nameRule = mcpNameRequirement(method, params);
260
+ if (nameRule.required) {
261
+ const bodyField = `params.${nameRule.sourceField}`;
262
+ const raw = getHeader("Mcp-Name");
263
+ if (raw === undefined) {
264
+ return {
265
+ ok: false,
266
+ message: `Missing required header 'Mcp-Name' for ${method}. It must mirror ${bodyField}.`,
267
+ detail: {
268
+ problem: "missing_header",
269
+ header: "Mcp-Name",
270
+ ...(nameRule.expected !== undefined
271
+ ? { expected: nameRule.expected }
272
+ : {}),
273
+ bodyField,
274
+ recovery: nameRule.expected !== undefined
275
+ ? `Send 'Mcp-Name: ${encodeHeaderValue(nameRule.expected)}'.`
276
+ : `Send 'Mcp-Name' mirroring ${bodyField}.`,
277
+ },
278
+ };
279
+ }
280
+ const decoded = decodeHeaderValue(raw);
281
+ if (decoded === null) {
282
+ return {
283
+ ok: false,
284
+ message: "Mcp-Name header uses the =?base64?…?= sentinel but its payload is not valid base64-encoded UTF-8",
285
+ detail: {
286
+ problem: "malformed_encoding",
287
+ header: "Mcp-Name",
288
+ received: raw,
289
+ bodyField,
290
+ recovery: "Re-encode as =?base64?<base64url of the UTF-8 bytes>?=, or send the plain value when it is header-safe ASCII.",
291
+ },
292
+ };
293
+ }
294
+ // A value outside the header-safe set MUST arrive sentinel-encoded. When the
295
+ // decode was a no-op (raw === decoded) the client sent it raw, which is a
296
+ // violation regardless of whether it happens to match the body.
297
+ if (raw === decoded && !HEADER_SAFE_VALUE.test(raw)) {
298
+ return {
299
+ ok: false,
300
+ message: "Mcp-Name contains characters that are not valid in an HTTP field value and was not sentinel-encoded",
301
+ detail: {
302
+ problem: "malformed_encoding",
303
+ header: "Mcp-Name",
304
+ received: raw,
305
+ bodyField,
306
+ recovery: `Wrap the value: 'Mcp-Name: ${encodeHeaderValue(raw)}'.`,
307
+ },
308
+ };
309
+ }
310
+ if (nameRule.expected === undefined) {
311
+ return {
312
+ ok: false,
313
+ message: `${method} requires ${bodyField} to be a string for Mcp-Name to mirror`,
314
+ detail: {
315
+ problem: "unmirrorable_body",
316
+ header: "Mcp-Name",
317
+ received: decoded,
318
+ bodyField,
319
+ recovery: `Set ${bodyField} to a string; ${method} requires it.`,
320
+ },
321
+ };
322
+ }
323
+ if (decoded !== nameRule.expected) {
324
+ return {
325
+ ok: false,
326
+ message: `Mcp-Name header "${decoded}" does not match body value "${nameRule.expected}"`,
327
+ detail: {
328
+ problem: "header_body_mismatch",
329
+ header: "Mcp-Name",
330
+ expected: nameRule.expected,
331
+ received: decoded,
332
+ bodyField,
333
+ recovery: `Set the header to mirror the body: 'Mcp-Name: ${encodeHeaderValue(nameRule.expected)}'.`,
334
+ },
335
+ };
336
+ }
337
+ }
338
+ const mirrored = input.mirroredParams ?? [];
339
+ if (mirrored.length > 0) {
340
+ const args = isRecord(params?.["arguments"]) ? params["arguments"] : {};
341
+ for (const { headerName, path } of mirrored) {
342
+ const header = `Mcp-Param-${headerName}`;
343
+ const bodyField = `params.arguments.${path.join(".")}`;
344
+ const raw = getHeader(header);
345
+ const bodyValue = readAtPath(args, path);
346
+ const bodyAbsent = bodyValue === undefined || bodyValue === null;
347
+ if (bodyAbsent) {
348
+ // Client must omit the header; a present one has nothing to mirror.
349
+ if (raw !== undefined) {
350
+ return {
351
+ ok: false,
352
+ message: `${header} header is present but "${bodyField}" is absent from the arguments`,
353
+ detail: {
354
+ problem: "header_body_mismatch",
355
+ header,
356
+ received: raw,
357
+ bodyField,
358
+ recovery: `Omit ${header}, or supply ${bodyField} in the arguments.`,
359
+ },
360
+ };
361
+ }
362
+ continue;
363
+ }
364
+ const expected = String(bodyValue);
365
+ if (raw === undefined) {
366
+ return {
367
+ ok: false,
368
+ message: `Missing required header '${header}' mirroring argument "${bodyField}"`,
369
+ detail: {
370
+ problem: "missing_header",
371
+ header,
372
+ expected,
373
+ bodyField,
374
+ recovery: `Send '${header}: ${encodeHeaderValue(expected)}'.`,
375
+ },
376
+ };
377
+ }
378
+ const decoded = decodeHeaderValue(raw);
379
+ if (decoded === null) {
380
+ return {
381
+ ok: false,
382
+ message: `${header} uses the =?base64?…?= sentinel but its payload is not valid base64-encoded UTF-8`,
383
+ detail: {
384
+ problem: "malformed_encoding",
385
+ header,
386
+ expected,
387
+ received: raw,
388
+ bodyField,
389
+ recovery: "Re-encode as =?base64?<base64url of the UTF-8 bytes>?=, or send the plain value when it is header-safe ASCII.",
390
+ },
391
+ };
392
+ }
393
+ if (!HEADER_SAFE_VALUE.test(raw) && raw === decoded) {
394
+ return {
395
+ ok: false,
396
+ message: `${header} contains characters that are not valid in an HTTP field value and was not sentinel-encoded`,
397
+ detail: {
398
+ problem: "malformed_encoding",
399
+ header,
400
+ expected,
401
+ received: raw,
402
+ bodyField,
403
+ recovery: `Wrap the value: '${header}: ${encodeHeaderValue(expected)}'.`,
404
+ },
405
+ };
406
+ }
407
+ if (!valueMatches(decoded, bodyValue)) {
408
+ return {
409
+ ok: false,
410
+ message: `${header} header "${decoded}" does not match argument "${bodyField}"`,
411
+ detail: {
412
+ problem: "header_body_mismatch",
413
+ header,
414
+ expected,
415
+ received: decoded,
416
+ bodyField,
417
+ recovery: `Set the header to mirror the argument: '${header}: ${encodeHeaderValue(expected)}'.`,
418
+ },
419
+ };
420
+ }
421
+ }
422
+ }
423
+ return { ok: true };
424
+ }
425
+ /**
426
+ * Collect the `x-mcp-header` annotations of an `inputSchema`.
427
+ *
428
+ * Only *statically reachable* properties count: the chain from the root must
429
+ * consist solely of `properties` keys. A path crossing `items`, `oneOf`/`anyOf`/
430
+ * `allOf`/`not`, `if`/`then`/`else` or `$ref` cannot be resolved to one value
431
+ * without evaluating the instance, so the spec makes such an annotation — and
432
+ * the whole tool definition — invalid.
433
+ *
434
+ * @param onInvalid Called with a reason per rejected annotation. Registration
435
+ * uses it to fail loudly; a caller that only needs the valid set may ignore it.
436
+ */
437
+ export function collectMirroredParams(inputSchema, onInvalid) {
438
+ const found = [];
439
+ const seen = new Set();
440
+ /**
441
+ * Keywords whose subschemas are NOT statically reachable: resolving a path
442
+ * through them needs the instance. An `x-mcp-header` anywhere below one is
443
+ * invalid per spec, so these subtrees are scanned only to *report* offenders.
444
+ */
445
+ const UNREACHABLE_KEYWORDS = [
446
+ "items",
447
+ "prefixItems",
448
+ "additionalItems",
449
+ "contains",
450
+ "oneOf",
451
+ "anyOf",
452
+ "allOf",
453
+ "not",
454
+ "if",
455
+ "then",
456
+ "else",
457
+ "additionalProperties",
458
+ "patternProperties",
459
+ "propertyNames",
460
+ "$defs",
461
+ "definitions",
462
+ ];
463
+ /** Report any annotation buried in a non-statically-reachable subtree. */
464
+ const reportUnreachable = (node, where) => {
465
+ if (!isRecord(node)) {
466
+ if (Array.isArray(node)) {
467
+ for (const item of node)
468
+ reportUnreachable(item, where);
469
+ }
470
+ return;
471
+ }
472
+ if (node["x-mcp-header"] !== undefined) {
473
+ onInvalid?.(`x-mcp-header "${String(node["x-mcp-header"])}" is not statically reachable (it sits under "${where}"). The spec ` +
474
+ `requires the path from the schema root to consist solely of ` +
475
+ `"properties" keys; such an annotation invalidates the tool definition.`);
476
+ }
477
+ for (const value of Object.values(node))
478
+ reportUnreachable(value, where);
479
+ };
480
+ const walk = (schema, path) => {
481
+ if (!isRecord(schema))
482
+ return;
483
+ // Scan the forbidden branches for offenders before descending the legal one.
484
+ for (const keyword of UNREACHABLE_KEYWORDS) {
485
+ if (schema[keyword] !== undefined) {
486
+ reportUnreachable(schema[keyword], keyword);
487
+ }
488
+ }
489
+ // `$ref` cannot be followed at all (and MUST NOT be dereferenced over the
490
+ // network), so an annotated property behind one is unreachable by definition.
491
+ if (typeof schema["$ref"] === "string" && path.length > 0) {
492
+ onInvalid?.(`property "${path.join(".")}" resolves through a $ref, so any x-mcp-header below it is not statically reachable`);
493
+ }
494
+ const properties = schema["properties"];
495
+ if (!isRecord(properties))
496
+ return;
497
+ for (const [key, raw] of Object.entries(properties)) {
498
+ if (!isRecord(raw))
499
+ continue;
500
+ const here = [...path, key];
501
+ const annotation = raw["x-mcp-header"];
502
+ if (annotation !== undefined) {
503
+ const nameError = validateXMcpHeaderName(annotation);
504
+ const typeError = validateXMcpHeaderType(raw["type"]);
505
+ const headerName = annotation;
506
+ if (nameError) {
507
+ onInvalid?.(nameError);
508
+ }
509
+ else if (typeError) {
510
+ onInvalid?.(`${typeError} (at "${here.join(".")}")`);
511
+ }
512
+ else if (seen.has(headerName.toLowerCase())) {
513
+ onInvalid?.(`duplicate x-mcp-header "${headerName}" — values must be unique case-insensitively within one inputSchema`);
514
+ }
515
+ else {
516
+ seen.add(headerName.toLowerCase());
517
+ found.push({ headerName, path: here });
518
+ }
519
+ }
520
+ walk(raw, here);
521
+ }
522
+ };
523
+ walk(inputSchema, []);
524
+ return found;
525
+ }