@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
package/src/mcp-app.ts DELETED
@@ -1,4426 +0,0 @@
1
- /**
2
- * McpApp — Hono-style framework for MCP servers
3
- *
4
- * High-performance MCP server with built-in concurrency control
5
- * and backpressure.
6
- *
7
- * Wraps the official @modelcontextprotocol/sdk with production-ready
8
- * middleware, auth, and observability features.
9
- *
10
- * @module lib/server/mcp-app
11
- */
12
-
13
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
- import {
16
- type CallToolRequest,
17
- CallToolRequestSchema,
18
- type ClientCapabilities,
19
- ErrorCode,
20
- type Implementation,
21
- type JSONRPCRequest,
22
- ListResourcesRequestSchema,
23
- ListResourceTemplatesRequestSchema,
24
- ListToolsRequestSchema,
25
- McpError,
26
- type ReadResourceRequest,
27
- ReadResourceRequestSchema,
28
- } from "@modelcontextprotocol/sdk/types.js";
29
- import { Hono } from "hono";
30
- import { cors } from "hono/cors";
31
- import { RequestQueue } from "./concurrency/request-queue.js";
32
- import { RateLimiter } from "./concurrency/rate-limiter.js";
33
- import { SchemaValidator } from "./validation/schema-validator.js";
34
- import { createMiddlewareRunner } from "./middleware/runner.js";
35
- import { createRateLimitMiddleware } from "./middleware/rate-limit.js";
36
- import { createValidationMiddleware } from "./middleware/validation.js";
37
- import { createBackpressureMiddleware } from "./middleware/backpressure.js";
38
- import type {
39
- McpLogLevel,
40
- Middleware,
41
- MiddlewareContext,
42
- MiddlewareResult,
43
- } from "./middleware/types.js";
44
- import { serve, type ServeHandle, unrefTimer } from "./runtime/runtime.js";
45
- import {
46
- AuthError,
47
- createAuthMiddleware,
48
- createForbiddenResponse,
49
- createUnauthorizedResponse,
50
- extractBearerToken,
51
- freezeAuthInfo,
52
- } from "./auth/middleware.js";
53
- import { createScopeMiddleware } from "./auth/scope-middleware.js";
54
- import { createAuthProviderFromConfig, loadAuthConfig } from "./auth/config.js";
55
- import type { AuthProvider } from "./auth/provider.js";
56
- import type { AuthInfo } from "./auth/types.js";
57
- import type {
58
- FetchHandler,
59
- HttpRateLimitContext,
60
- HttpServerOptions,
61
- McpAppOptions,
62
- McpAppsClientCapability,
63
- MCPResource,
64
- MCPTool,
65
- QueueMetrics,
66
- ResourceContent,
67
- ResourceHandler,
68
- StructuredToolResult,
69
- ToolHandler,
70
- } from "./types.js";
71
- import { getMcpAppsCapability, MCP_APP_MIME_TYPE } from "./types.js";
72
- import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
73
- import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
74
- import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
75
- import {
76
- collectMirroredParams,
77
- type MirroredParam,
78
- validateRequestHeaders,
79
- } from "./transport/request-headers.js";
80
- import {
81
- type DetailedTask,
82
- isAsyncTaskDescriptor,
83
- TaskStore,
84
- } from "./tasks/mod.js";
85
- import {
86
- checkInputRequestCapabilities,
87
- importStateKey,
88
- type InputRequestEntry,
89
- type InputRequiredSignal,
90
- MemoryMrtrReplayStore,
91
- type MrtrReplayStore,
92
- paramsDigest,
93
- sealRequestState,
94
- verifyRequestState,
95
- } from "./mrtr/mod.js";
96
- import {
97
- buildAcknowledgedMessage,
98
- encodeSSEEvent,
99
- type SubscriptionFilter,
100
- SubscriptionRegistry,
101
- type SubscriptionSink,
102
- } from "./subscriptions/subscription-registry.js";
103
- import { ServerMetrics } from "./observability/metrics.js";
104
- import type { SpanContext } from "@opentelemetry/api";
105
- import {
106
- endToolCallSpan,
107
- parseTraceParent,
108
- startToolCallSpan,
109
- } from "./observability/otel.js";
110
- import {
111
- BodyTooLargeError,
112
- DEFAULT_MAX_BODY_BYTES,
113
- getClientIpFromHeaders,
114
- readBodyWithLimit,
115
- } from "./http/body.js";
116
- import {
117
- bytesToHexLocal,
118
- callerPrincipal,
119
- noOwnerKeyError,
120
- noPrincipalError,
121
- taskOwnerKeyFor,
122
- } from "./http/request-guards.js";
123
- import { isRecord, jsonRpcResponse } from "./http/wire.js";
124
-
125
- /**
126
- * Tool definition with handler
127
- */
128
- interface ToolWithHandler extends MCPTool {
129
- handler: ToolHandler;
130
- }
131
-
132
- /**
133
- * Internal tracking of registered resources
134
- */
135
- interface RegisteredResourceInfo {
136
- resource: MCPResource;
137
- handler: ResourceHandler;
138
- }
139
-
140
- // ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
141
-
142
- /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
143
- const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
144
-
145
- /** Namespaced clientInfo key in params._meta (SEP-2575 stateless transport) */
146
- const STATELESS_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo";
147
-
148
- /** Namespaced clientCapabilities key in params._meta (SEP-2575 stateless transport) */
149
- const STATELESS_CLIENT_CAPABILITIES_KEY =
150
- "io.modelcontextprotocol/clientCapabilities";
151
-
152
- /** Protocol versions accepted by this server in stateless mode */
153
- const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
154
- "2026-07-28",
155
- ];
156
-
157
- /** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
158
- const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
159
-
160
- /**
161
- * Namespaced per-request log level in params._meta (spec 2026-07-28).
162
- * Replaces the removed `logging/setLevel` RPC: the level is now scoped to the
163
- * request that asked for it, so there is no server-side level to mutate.
164
- */
165
- const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
166
-
167
- /**
168
- * W3C trace context keys in `params._meta` (spec 2026-07-28, SEP-414).
169
- *
170
- * Unlike every other per-request field these are NOT namespaced — the revision
171
- * documents the bare W3C names, so that a `_meta` envelope carries the same
172
- * key a caller would put in an HTTP header.
173
- */
174
- const TRACEPARENT_KEY = "traceparent";
175
- const TRACESTATE_KEY = "tracestate";
176
-
177
- /** Protocol version whose wire format this server implements natively */
178
- const SPEC_2026_07_28 = "2026-07-28";
179
-
180
- /**
181
- * Tasks extension identifier (SEP-2663).
182
- *
183
- * Declaring it in `McpAppOptions.extensions` is what switches the extension on.
184
- * The spec forbids returning a task handle to a client that did not declare
185
- * support, and forbids advertising an extension we do not implement — so the
186
- * declaration gates both directions.
187
- */
188
- const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
189
-
190
- /** Version echoed in MCP-Protocol-Version header on error responses (server's only accepted version) */
191
- const STATELESS_FALLBACK_VERSION = "2026-07-28";
192
-
193
- const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
194
-
195
- // ── Error codes (spec 2026-07-28, allocation policy) ────────────────────────
196
- //
197
- // The final spec partitions the JSON-RPC server-error range:
198
- // -32000..-32019 implementation-defined (existing SDK usage grandfathered)
199
- // -32020..-32099 reserved for the MCP specification
200
- //
201
- // The codes below were renumbered between the May 2026 Release Candidate — which
202
- // 0.21.0 shipped against — and the final revision. Do not "restore" the RC
203
- // values: -32001 and -32004 no longer carry these MCP-defined meanings.
204
- //
205
- // Note the policy is stricter than "the low range is grandfathered": the spec
206
- // says new implementations SHOULD NOT use -32000..-32019 at all, and MUST NOT
207
- // emit -32002 (which 2025-11-25 used for resource-not-found). Our auth and
208
- // session errors therefore live outside the reserved range entirely — see
209
- // auth/middleware.ts.
210
-
211
- /** Headers disagree with the request body, or a required header is missing. */
212
- const MCP_HEADER_MISMATCH = -32020;
213
-
214
- /**
215
- * Client did not declare a capability the request requires.
216
- *
217
- * Emitted by the Tasks extension guard. `data.requiredCapabilities` must list
218
- * the missing capabilities alongside it.
219
- */
220
- const MCP_MISSING_REQUIRED_CLIENT_CAPABILITY = -32021;
221
-
222
- /** Requested protocol version is not one this server implements. */
223
- const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32022;
224
-
225
- interface StatelessClientMeta {
226
- readonly clientInfo?: Implementation;
227
- readonly clientCapabilities?: ClientCapabilities;
228
- readonly logLevel?: McpLogLevel;
229
- /** Caller's W3C trace context, so the tool span joins their trace. */
230
- readonly traceContext?: SpanContext;
231
- }
232
-
233
- /**
234
- * Read the W3C trace context out of `params._meta` (spec 2026-07-28, SEP-414).
235
- *
236
- * A malformed header leaves the span unparented rather than failing the call:
237
- * losing the trace join is an observability gap, refusing the tool call would
238
- * be an outage.
239
- *
240
- * `baggage` is deliberately NOT read. It is an unbounded, caller-controlled
241
- * key/value list that routinely carries tenant, user and session identifiers,
242
- * and the only thing this server could do with it is copy it into spans —
243
- * exporting whatever a caller put there to the trace backend, with no way to
244
- * know whether it holds a PII or a secret. Propagating it properly means the
245
- * OTel baggage API and an explicit allowlist of keys; until there is a use case
246
- * asking for that, reading it at all is a liability. The key stays reserved by
247
- * the spec, and this server ignores it.
248
- */
249
- function readTraceContext(
250
- meta: Record<string, unknown>,
251
- ): { traceContext?: SpanContext } {
252
- const traceContext = parseTraceParent(
253
- meta[TRACEPARENT_KEY],
254
- meta[TRACESTATE_KEY],
255
- );
256
- return traceContext ? { traceContext } : {};
257
- }
258
-
259
- /** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
260
- const MCP_LOG_LEVELS: readonly McpLogLevel[] = [
261
- "debug",
262
- "info",
263
- "notice",
264
- "warning",
265
- "error",
266
- "critical",
267
- "alert",
268
- "emergency",
269
- ];
270
-
271
- /**
272
- * Read the per-request log level out of `params._meta`.
273
- *
274
- * An unrecognized value is dropped rather than rejected: the level is an
275
- * optional hint, and failing a whole tool call because a client sent
276
- * `"verbose"` would be a worse outcome than emitting nothing.
277
- */
278
- function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
279
- const raw = meta[STATELESS_LOG_LEVEL_KEY];
280
- return typeof raw === "string" && MCP_LOG_LEVELS.includes(raw as McpLogLevel)
281
- ? raw as McpLogLevel
282
- : undefined;
283
- }
284
-
285
- /**
286
- * Validate the client-owned subscriptions/listen filter before it reaches the
287
- * registry. The registry deliberately works with a typed SubscriptionFilter;
288
- * casting untrusted JSON into it made truthy values subscribe to list changes
289
- * and let invalid URI entries reach the SSE acknowledgement.
290
- */
291
- function validateSubscriptionFilter(
292
- filter: Record<string, unknown>,
293
- ):
294
- | { ok: true; filter: SubscriptionFilter }
295
- | {
296
- ok: false;
297
- message: string;
298
- bodyField: string;
299
- recovery: string;
300
- } {
301
- for (
302
- const field of [
303
- "toolsListChanged",
304
- "promptsListChanged",
305
- "resourcesListChanged",
306
- ] as const
307
- ) {
308
- if (filter[field] !== undefined && typeof filter[field] !== "boolean") {
309
- return {
310
- ok: false,
311
- message: `${field} must be a boolean when present`,
312
- bodyField: `params.notifications.${field}`,
313
- recovery:
314
- `Send ${field} as true or false, or omit it when that notification type is not requested.`,
315
- };
316
- }
317
- }
318
-
319
- for (const field of ["resourceSubscriptions", "taskIds"] as const) {
320
- const value = filter[field];
321
- if (value === undefined) continue;
322
- if (!Array.isArray(value)) {
323
- return {
324
- ok: false,
325
- message: `${field} must be an array of strings when present`,
326
- bodyField: `params.notifications.${field}`,
327
- recovery:
328
- `Send ${field} as an array of strings, or omit it when no identifiers are requested.`,
329
- };
330
- }
331
- const malformedIndex = value.findIndex((entry) =>
332
- typeof entry !== "string"
333
- );
334
- if (malformedIndex !== -1) {
335
- return {
336
- ok: false,
337
- message: `${field} entries must be strings`,
338
- bodyField: `params.notifications.${field}[${malformedIndex}]`,
339
- recovery:
340
- `Send only string entries in ${field}; remove or replace the malformed entry.`,
341
- };
342
- }
343
- }
344
-
345
- return { ok: true, filter: filter as SubscriptionFilter };
346
- }
347
-
348
- /**
349
- * Stamp a result with the spec-2026-07-28 envelope: the required `resultType`
350
- * (SEP-2322) and the server's identity under `_meta` (SEP-2575, SHOULD).
351
- *
352
- * `_meta` is merged, never replaced — tool results carry their own `_meta` (MCP
353
- * Apps UI hints, for instance) and losing it would break the viewers.
354
- *
355
- * Pure by design so the envelope can be asserted directly in tests without
356
- * standing up a server; the caller decides whether the envelope applies.
357
- */
358
- function completeResult(
359
- result: Record<string, unknown>,
360
- serverInfo: Implementation,
361
- ): Record<string, unknown> {
362
- const existingMeta = isRecord(result["_meta"]) ? result["_meta"] : undefined;
363
- return {
364
- ...result,
365
- resultType: "complete",
366
- _meta: { ...existingMeta, [STATELESS_SERVER_INFO_KEY]: serverInfo },
367
- };
368
- }
369
-
370
- /**
371
- * Reduce a handler-built result to the exact JSON object that will cross the
372
- * transport boundary. Preformatted proxy results bypass the normal text
373
- * serialisation path, so without this gate a BigInt or cycle could be stored as
374
- * a completed task and only explode on a later tasks/get response.
375
- */
376
- function canonicaliseWireResult(
377
- result: Record<string, unknown>,
378
- ): Record<string, unknown> {
379
- const serialised = JSON.stringify(result);
380
- if (serialised === undefined) {
381
- throw new Error("Tool result is not JSON-serialisable");
382
- }
383
- const canonical = JSON.parse(serialised);
384
- if (!isRecord(canonical)) {
385
- throw new Error("Tool result must serialise to an object");
386
- }
387
- return canonical;
388
- }
389
-
390
- // ─────────────────────────────────────────────────────────────────────────────
391
-
392
- /**
393
- * McpApp provides a high-performance MCP server
394
- *
395
- * Features:
396
- * - Wraps official @modelcontextprotocol/sdk
397
- * - Concurrency limiting (default: 10 max concurrent)
398
- * - Multiple backpressure strategies (sleep/queue/reject)
399
- * - Metrics for monitoring
400
- * - Graceful shutdown
401
- *
402
- * @example
403
- * ```typescript
404
- * const server = new McpApp({
405
- * name: "my-server",
406
- * version: "1.0.0",
407
- * maxConcurrent: 5,
408
- * backpressureStrategy: 'queue'
409
- * });
410
- *
411
- * server.registerTools(myTools, myHandlers);
412
- * await server.start();
413
- * ```
414
- */
415
- export class McpApp {
416
- /**
417
- * Server name — the identifier reported to MCP clients in `InitializeResult.serverInfo.name`.
418
- *
419
- * Exposed as a public readonly field (0.16.1) so consumers can use it for
420
- * log prefixes, tracing context, or any UI that wants to echo the server
421
- * identity without having to thread `options.name` through their code.
422
- * Immutable after construction, same value that appears in the MCP
423
- * `initialize` response.
424
- */
425
- public readonly name: string;
426
- private mcpServer: McpServer;
427
- private requestQueue: RequestQueue;
428
- private rateLimiter: RateLimiter | null = null;
429
- private schemaValidator: SchemaValidator | null = null;
430
- private tools = new Map<string, ToolWithHandler>();
431
-
432
- /**
433
- * Tool name → parameters the tool asked clients to mirror into
434
- * `Mcp-Param-{Name}` headers (spec 2026-07-28, `x-mcp-header`).
435
- *
436
- * Populated at registration so the per-request path is a map lookup rather
437
- * than a schema walk. Tools without annotations are simply absent.
438
- */
439
- private mirroredParams = new Map<string, MirroredParam[]>();
440
-
441
- /**
442
- * Task store for the Tasks extension, or `null` when the consumer did not
443
- * declare it.
444
- *
445
- * Created only on declaration: a server not using Tasks should not pay for a
446
- * sweep timer, and a `tasks/*` call against it must read as the unimplemented
447
- * method it is (404 + -32601) rather than hitting an empty store.
448
- */
449
- private taskStore: TaskStore | null;
450
-
451
- /**
452
- * Set synchronously at the top of `stop()`.
453
- *
454
- * Checked before spawning a task, because the pipeline is async: a handler that
455
- * settles during shutdown would otherwise start work in a store already drained,
456
- * producing a task that outlives its server. A synchronous flag is what makes
457
- * the check reliable — anything awaited leaves the same window open.
458
- */
459
- private stopping = false;
460
-
461
- /**
462
- * Live `subscriptions/listen` streams.
463
- *
464
- * Initialized unconditionally in startHttp(); null before the server starts
465
- * or in stdio mode.
466
- */
467
- private subscriptions: SubscriptionRegistry | null = null;
468
-
469
- /**
470
- * Imported HMAC key for sealing `requestState`, or `null` when the deployment
471
- * configured none.
472
- *
473
- * Resolved lazily on first use rather than in the constructor, because
474
- * `importStateKey` is async and a constructor cannot await.
475
- */
476
- /**
477
- * In-flight or resolved key import.
478
- *
479
- * A Promise, not a value plus a loaded flag: the flag was set before the await,
480
- * so a second request arriving during the import saw "loaded" with the key
481
- * still null, received an UNSIGNED requestState, and could then submit raw
482
- * inputResponses past the verification guard. Memoising the Promise makes every
483
- * caller await the same import.
484
- */
485
- private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
486
-
487
- /**
488
- * Consumes a verified requestState nonce before the handler runs.
489
- *
490
- * A signed deployment always has a store: process-local by default, or the
491
- * shared atomic implementation supplied by the consumer.
492
- */
493
- private readonly mrtrReplayStore: MrtrReplayStore | null;
494
-
495
- /**
496
- * Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
497
- * an integer — clients are told to ignore a negative one, which would make a
498
- * misconfiguration silently do nothing instead of failing.
499
- *
500
- * Resolved once at construction: a per-response check would pay for the same
501
- * validation on every list call, and a bad value is a deployment error that
502
- * should surface at startup (AX: fast fail early).
503
- */
504
- private readonly cacheTtlMs: number;
505
- private resources = new Map<string, RegisteredResourceInfo>();
506
- private options: McpAppOptions;
507
- private started = false;
508
- private resourceHandlersInstalled = false;
509
-
510
- // Middleware pipeline
511
- private customMiddlewares: Middleware[] = [];
512
- private middlewareRunner:
513
- | ((ctx: MiddlewareContext) => Promise<MiddlewareResult>)
514
- | null = null;
515
-
516
- // Auth provider (set from options.auth or auto-configured from env)
517
- private authProvider: AuthProvider | null = null;
518
-
519
- // Observability
520
- private serverMetrics = new ServerMetrics();
521
-
522
- constructor(options: McpAppOptions) {
523
- this.options = options;
524
- this.name = options.name;
525
-
526
- // enableSampling / samplingClient are no-ops since 0.24.0 (SamplingBridge
527
- // was removed with MCP 2026-07-28). Warn loudly so migrating consumers
528
- // know immediately rather than discovering it silently in production.
529
- if (options.enableSampling || options.samplingClient) {
530
- (options.logger ?? console.error)(
531
- "[McpApp] WARNING: enableSampling and samplingClient have no effect " +
532
- "as of 0.24.0 — the SamplingBridge was removed with MCP 2026-07-28. " +
533
- "Remove these options from your McpApp constructor call.",
534
- );
535
- }
536
-
537
- const ttlMs = options.cache?.ttlMs ?? 0;
538
- if (!Number.isInteger(ttlMs) || ttlMs < 0) {
539
- throw new Error(
540
- `[McpApp] cache.ttlMs must be a non-negative integer (got ${ttlMs}). ` +
541
- "The spec requires servers to provide ttlMs >= 0, and clients are told " +
542
- "to ignore a negative value — so a bad one would silently disable " +
543
- "caching instead of failing.",
544
- );
545
- }
546
- this.cacheTtlMs = ttlMs;
547
-
548
- this.taskStore = options.extensions?.[TASKS_EXTENSION_ID] !== undefined
549
- ? new TaskStore({
550
- onNotification: (task) => this.onTaskChanged(task),
551
- unrefTimer: (id) => unrefTimer(id as unknown as number),
552
- })
553
- : null;
554
-
555
- // Validate the shape of the MRTR key here rather than on first use. The
556
- // import itself is async so it stays lazy, but a typo in a 64-hex-character
557
- // secret should surface at boot, not on the first request that needs it —
558
- // by which point it is a runtime failure in production traffic.
559
- const mrtrKey = options.mrtr?.signingKey;
560
- if (mrtrKey !== undefined && !/^[0-9a-f]{64}$/.test(mrtrKey)) {
561
- throw new Error(
562
- "[McpApp] mrtr.signingKey must be 64 lowercase hex characters (32 bytes). " +
563
- "Generate one with: crypto.getRandomValues(new Uint8Array(32)) rendered as hex, " +
564
- "or the exported generateStateKey() + exportStateKey() helpers.",
565
- );
566
- }
567
- if (
568
- options.mrtr?.replayStore !== undefined && mrtrKey === undefined
569
- ) {
570
- throw new Error(
571
- "[McpApp] mrtr.replayStore requires mrtr.signingKey. " +
572
- "Only a verified token exposes a trusted nonce to consume.",
573
- );
574
- }
575
- this.mrtrReplayStore = mrtrKey === undefined
576
- ? null
577
- : options.mrtr?.replayStore ?? new MemoryMrtrReplayStore();
578
- if (mrtrKey !== undefined && options.mrtr?.replayStore === undefined) {
579
- (options.logger ?? console.error)(
580
- "[McpApp] WARNING: MRTR replay protection is process-local. " +
581
- "Load-balanced deployments must configure one shared atomic mrtr.replayStore.",
582
- );
583
- }
584
-
585
- // Create SDK MCP server
586
- this.mcpServer = new McpServer(
587
- {
588
- name: options.name,
589
- version: options.version,
590
- },
591
- {
592
- capabilities: {
593
- tools: {},
594
- ...(options.expectResources
595
- ? { resources: { listChanged: true } }
596
- : {}),
597
- },
598
- instructions: options.instructions,
599
- },
600
- );
601
-
602
- // Create request queue with concurrency control
603
- this.requestQueue = new RequestQueue({
604
- maxConcurrent: options.maxConcurrent ?? 10,
605
- strategy: options.backpressureStrategy ?? "sleep",
606
- sleepMs: options.backpressureSleepMs ?? 10,
607
- });
608
-
609
- // Optional rate limiting
610
- if (options.rateLimit) {
611
- this.rateLimiter = new RateLimiter({
612
- maxRequests: options.rateLimit.maxRequests,
613
- windowMs: options.rateLimit.windowMs,
614
- });
615
- }
616
-
617
- // Optional schema validation
618
- if (options.validateSchema) {
619
- this.schemaValidator = new SchemaValidator();
620
- }
621
-
622
- // Setup MCP protocol handlers
623
- this.setupHandlers();
624
-
625
- // Pre-declare resources capability so resources can be added after start()
626
- if (options.expectResources) {
627
- this.installResourceHandlers();
628
- }
629
- }
630
-
631
- /**
632
- * Pre-install the resources handlers on the low-level
633
- * SDK Server. This declares the `resources` capability BEFORE transport
634
- * connection, allowing dynamic resource registration after start().
635
- *
636
- * The handlers read from `this.resources` Map which is populated lazily
637
- * by registerResource() calls (e.g., after async MCP discovery).
638
- */
639
- private installResourceHandlers(): void {
640
- if (this.resourceHandlersInstalled) return;
641
- if (this.started) {
642
- throw new Error(
643
- "[McpApp] Cannot install resource handlers after the server starts. " +
644
- "Set expectResources: true or register resources before start().",
645
- );
646
- }
647
- const server = this.mcpServer.server;
648
-
649
- // Declare resources capability before transport connects
650
- server.registerCapabilities({ resources: { listChanged: true } });
651
-
652
- // resources/list — returns currently registered resources
653
- server.setRequestHandler(ListResourcesRequestSchema, () => {
654
- return {
655
- resources: Array.from(this.resources.values()).map((r) =>
656
- this.toResourceListing(r.resource)
657
- ),
658
- };
659
- });
660
-
661
- // resources/read — serve resource content by URI
662
- server.setRequestHandler(
663
- ReadResourceRequestSchema,
664
- async (request: ReadResourceRequest) => {
665
- const uri = request.params.uri;
666
- const info = this.resources.get(uri);
667
- if (!info) {
668
- throw new McpError(
669
- ErrorCode.InvalidParams,
670
- `Resource not found: ${uri}`,
671
- );
672
- }
673
-
674
- try {
675
- const finalContent = await this.readResourceForProtocol(
676
- uri,
677
- info.resource,
678
- info.handler,
679
- );
680
- return { contents: [finalContent] };
681
- } catch (error) {
682
- this.log(
683
- `[ERROR] Resource handler failed for ${uri}: ${
684
- error instanceof Error ? error.message : String(error)
685
- }`,
686
- );
687
- throw error;
688
- }
689
- },
690
- );
691
-
692
- // We currently expose concrete resources only. An explicit empty template
693
- // list is nevertheless required once the resources capability exists:
694
- // clients are entitled to ask which URI templates can be expanded.
695
- server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
696
- resourceTemplates: [],
697
- }));
698
-
699
- this.resourceHandlersInstalled = true;
700
- this.resourceLog("Resources capability installed");
701
- }
702
-
703
- /**
704
- * Setup MCP protocol request handlers
705
- */
706
- private setupHandlers(): void {
707
- const server = this.mcpServer.server;
708
-
709
- // Wire up "initialized" notification callback (post-handshake)
710
- server.oninitialized = () => {
711
- this.initializedCallback?.();
712
- };
713
-
714
- // tools/list handler
715
- server.setRequestHandler(ListToolsRequestSchema, () => {
716
- return { tools: this.buildToolListing() };
717
- });
718
-
719
- // tools/call handler (delegates to middleware pipeline)
720
- server.setRequestHandler(
721
- CallToolRequestSchema,
722
- async (request: CallToolRequest) => {
723
- const toolName = request.params.name;
724
- const args = request.params.arguments || {};
725
-
726
- // Per-request `_meta` is transport-independent. Trace context matters
727
- // here because a local server is exactly where a detached span is
728
- // hardest to correlate back to the host that caused it; `logLevel` is
729
- // read for the same reason it is on HTTP — the spec makes it
730
- // per-request, and a handler must stay silent without it.
731
- const meta = request.params._meta;
732
- const clientMeta: StatelessClientMeta | undefined = isRecord(meta)
733
- ? {
734
- ...readTraceContext(meta),
735
- ...(readLogLevel(meta) !== undefined
736
- ? { logLevel: readLogLevel(meta) }
737
- : {}),
738
- }
739
- : undefined;
740
-
741
- let result: unknown;
742
- try {
743
- result = await this.executeToolCall(
744
- toolName,
745
- args,
746
- undefined,
747
- undefined,
748
- undefined,
749
- clientMeta,
750
- );
751
- } catch (error) {
752
- return this.handleToolError(error, toolName);
753
- }
754
-
755
- // Serialization errors are framework bugs, not tool errors —
756
- // let them propagate
757
- return this.buildToolCallResult(toolName, result);
758
- },
759
- );
760
-
761
- // `server/discover` over stdio (spec 2026-07-28, SEP-2575).
762
- //
763
- // The spec makes this RPC a MUST for every server and names stdio as a
764
- // primary use: a client probes it for backward compatibility. That matters
765
- // here precisely because the SDK's stdio handshake still negotiates
766
- // 2025-11-25 — `server/discover` is then the only way for a peer to learn
767
- // this server also speaks 2026-07-28 over HTTP.
768
- //
769
- // Routed through `fallbackRequestHandler` rather than `setRequestHandler`
770
- // because the latter takes a Zod schema, and the method is absent from the
771
- // SDK's type surface. Adding a Zod dependency to declare one schema would
772
- // put a peer dependency in the public API for a single string comparison.
773
- // Every other unknown method keeps its previous answer: MethodNotFound.
774
- server.fallbackRequestHandler = (request: JSONRPCRequest) => {
775
- if (request.method !== "server/discover") {
776
- // Same text the SDK used for an unrouted method. It still reaches the
777
- // wire as "MCP error -32601: Method not found" — `McpError` prefixes
778
- // its own message and a handler cannot raise the code without it. The
779
- // code is unchanged, which is what a peer switches on; the string
780
- // difference is pinned by a test and noted in the changelog. Appending
781
- // the method name on top of that would have been a second, gratuitous
782
- // change to the same field.
783
- throw new McpError(ErrorCode.MethodNotFound, "Method not found");
784
- }
785
- return Promise.resolve(this.buildDiscoverResult());
786
- };
787
- }
788
-
789
- /**
790
- * The `server/discover` result (spec 2026-07-28, SEP-2575).
791
- *
792
- * Single source of truth for both transports. They used to be one inline
793
- * object on the HTTP path; a stdio copy would have been the second place to
794
- * forget `instructions` or a new capability.
795
- *
796
- * Always stamped as 2026-07-28 regardless of what the transport negotiated.
797
- * That is deliberate but not free: nothing gates the method, so a peer that
798
- * negotiated `2025-11-25` over stdio can call it and receive an envelope it
799
- * never agreed to. The alternative is worse — stamping the negotiated version
800
- * would make the probe answer "2025" to the client asking whether this server
801
- * speaks 2026, which is the one question it exists to answer. Treat
802
- * `server/discover` as a cross-version exception: its result describes what
803
- * the server supports, not what the current transport negotiated.
804
- */
805
- private buildDiscoverResult(): Record<string, unknown> {
806
- return this.stampResult(
807
- this.withCacheHints({
808
- supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
809
- capabilities: this.buildServerCapabilities(),
810
- serverInfo: {
811
- name: this.options.name,
812
- version: this.options.version,
813
- },
814
- ...(this.options.instructions
815
- ? { instructions: this.options.instructions }
816
- : {}),
817
- }, SPEC_2026_07_28),
818
- SPEC_2026_07_28,
819
- );
820
- }
821
-
822
- /**
823
- * Register tools with their handlers
824
- *
825
- * @param tools - Array of tool definitions (MCP format)
826
- * @param handlers - Map of tool name to handler function
827
- */
828
- registerTools(
829
- tools: MCPTool[],
830
- handlers: Map<string, ToolHandler>,
831
- ): void {
832
- if (this.started) {
833
- throw new Error(
834
- "[McpApp] Cannot register tools after server started. " +
835
- "Call registerTools() before start() or startHttp().",
836
- );
837
- }
838
- for (const tool of tools) {
839
- const handler = handlers.get(tool.name);
840
- if (!handler) {
841
- throw new Error(`No handler provided for tool: ${tool.name}`);
842
- }
843
-
844
- // Validate annotations BEFORE inserting: a throw must not leave the tool
845
- // half-registered. Registration is the right place to fail — a conforming
846
- // client drops the whole tool from `tools/list` over a malformed
847
- // annotation, so a typo would otherwise surface as a tool that silently
848
- // does not exist (AX: fast fail early).
849
- this.indexMirroredParams(tool);
850
-
851
- this.tools.set(tool.name, {
852
- ...tool,
853
- handler,
854
- });
855
-
856
- // Register schema for validation if enabled
857
- if (this.schemaValidator) {
858
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
859
- }
860
- }
861
-
862
- this.log(`Registered ${tools.length} tools`);
863
- }
864
-
865
- /**
866
- * Register a single tool
867
- *
868
- * @param tool - Tool definition
869
- * @param handler - Tool handler function
870
- */
871
- /**
872
- * Validate and index a tool's `x-mcp-header` annotations (spec 2026-07-28).
873
- *
874
- * Every registration path must go through here. Wiring it into `registerTools`
875
- * alone was a real bypass: a tool registered via `registerTool` or
876
- * `registerToolLive` carried annotations that clients would mirror into
877
- * `Mcp-Param-*` headers, while the server never required or checked them.
878
- *
879
- * Throws *before* the caller inserts the tool, so a rejected definition cannot
880
- * leave a half-registered tool behind.
881
- */
882
- private indexMirroredParams(tool: MCPTool): void {
883
- const invalid: string[] = [];
884
- const mirrored = collectMirroredParams(
885
- tool.inputSchema,
886
- (reason) => invalid.push(reason),
887
- );
888
- if (invalid.length > 0) {
889
- throw new Error(
890
- `[McpApp] Tool "${tool.name}" has invalid x-mcp-header annotations:\n` +
891
- invalid.map((r) => ` - ${r}`).join("\n"),
892
- );
893
- }
894
- // Replace wholesale: re-registering a tool without annotations must clear
895
- // whatever a previous definition left behind.
896
- if (mirrored.length > 0) this.mirroredParams.set(tool.name, mirrored);
897
- else this.mirroredParams.delete(tool.name);
898
- }
899
-
900
- registerTool(tool: MCPTool, handler: ToolHandler): void {
901
- if (this.started) {
902
- throw new Error(
903
- "[McpApp] Cannot register tools after server started. " +
904
- "Call registerTool() before start() or startHttp().",
905
- );
906
- }
907
- this.indexMirroredParams(tool);
908
- this.tools.set(tool.name, {
909
- ...tool,
910
- handler,
911
- });
912
-
913
- // Register schema for validation if enabled
914
- if (this.schemaValidator) {
915
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
916
- }
917
-
918
- this.log(`Registered tool: ${tool.name}`);
919
- }
920
-
921
- /**
922
- * Register a tool after the server has started (live registration).
923
- *
924
- * Unlike registerTool(), this can be called while the server is running.
925
- * The tool becomes immediately available for tools/list and tools/call.
926
- *
927
- * Use case: relay proxy where tools are registered dynamically
928
- * when remote owners connect/disconnect their tunnels.
929
- *
930
- * @param tool - Tool definition
931
- * @param handler - Tool handler function
932
- */
933
- registerToolLive(tool: MCPTool, handler: ToolHandler): void {
934
- this.indexMirroredParams(tool);
935
- this.tools.set(tool.name, {
936
- ...tool,
937
- handler,
938
- });
939
-
940
- if (this.schemaValidator) {
941
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
942
- }
943
-
944
- this.log(`Live-registered tool: ${tool.name} (total: ${this.tools.size})`);
945
- }
946
-
947
- /**
948
- * Register a tool that is only visible to the MCP App (UI layer),
949
- * not to the model via tools/list.
950
- *
951
- * Equivalent to registerTool() with _meta.ui.visibility: ["app"].
952
- * The tool is still callable via tools/call if the caller knows its name.
953
- *
954
- * @param tool - Tool definition
955
- * @param handler - Tool handler function
956
- */
957
- registerAppOnlyTool(tool: MCPTool, handler: ToolHandler): void {
958
- const merged: MCPTool = {
959
- ...tool,
960
- _meta: {
961
- ...tool._meta,
962
- ui: {
963
- ...tool._meta?.ui,
964
- visibility: ["app"],
965
- },
966
- } as MCPTool["_meta"],
967
- };
968
- this.registerTool(merged, handler);
969
- }
970
-
971
- /**
972
- * Unregister a tool (removes it from tools/list and tools/call).
973
- *
974
- * Can be called before or after start.
975
- * In-flight calls to this tool will complete normally.
976
- *
977
- * @param toolName - Name of the tool to remove
978
- * @returns true if the tool was found and removed
979
- */
980
- unregisterTool(toolName: string): boolean {
981
- const deleted = this.tools.delete(toolName);
982
- // Stale mirror metadata would make the server demand `Mcp-Param-*` headers
983
- // for a tool that no longer exists.
984
- this.mirroredParams.delete(toolName);
985
- if (deleted) {
986
- this.log(
987
- `Unregistered tool: ${toolName} (remaining: ${this.tools.size})`,
988
- );
989
- }
990
- return deleted;
991
- }
992
-
993
- // ============================================
994
- // Middleware Pipeline
995
- // ============================================
996
-
997
- /**
998
- * Add a custom middleware to the pipeline.
999
- * Must be called before start()/startHttp().
1000
- *
1001
- * Custom middlewares execute between rate-limit and validation:
1002
- * rate-limit → **custom middlewares** → validation → backpressure → handler
1003
- *
1004
- * @param middleware - Middleware function
1005
- * @returns this (for chaining)
1006
- *
1007
- * @example
1008
- * ```typescript
1009
- * server.use(async (ctx, next) => {
1010
- * console.log(`Calling ${ctx.toolName}`);
1011
- * const result = await next();
1012
- * console.log(`Done ${ctx.toolName}`);
1013
- * return result;
1014
- * });
1015
- * ```
1016
- */
1017
- use(middleware: Middleware): this {
1018
- if (this.started) {
1019
- throw new Error(
1020
- "[McpApp] Cannot add middleware after server started. " +
1021
- "Call use() before start() or startHttp().",
1022
- );
1023
- }
1024
- this.customMiddlewares.push(middleware);
1025
- this.middlewareRunner = null; // Invalidate cached runner
1026
- return this;
1027
- }
1028
-
1029
- /**
1030
- * Build the middleware pipeline from config + custom middlewares.
1031
- * Called once at start()/startHttp() time.
1032
- *
1033
- * Pipeline order:
1034
- * rate-limit → auth → custom middlewares → scope-check → validation → backpressure → handler
1035
- */
1036
- private buildPipeline(): void {
1037
- const pipeline: Middleware[] = [];
1038
-
1039
- // 1. Rate limiting (if configured)
1040
- if (this.rateLimiter && this.options.rateLimit) {
1041
- pipeline.push(
1042
- createRateLimitMiddleware(this.rateLimiter, this.options.rateLimit),
1043
- );
1044
- }
1045
-
1046
- // 2. Auth middleware (if auth provider is set)
1047
- if (this.authProvider) {
1048
- pipeline.push(createAuthMiddleware(this.authProvider));
1049
- }
1050
-
1051
- // 3. Custom middlewares (logging, tracing, etc.)
1052
- pipeline.push(...this.customMiddlewares);
1053
-
1054
- // 4. Scope enforcement (if any tool has requiredScopes)
1055
- const toolScopes = new Map<string, string[]>();
1056
- for (const [name, tool] of this.tools) {
1057
- if (tool.requiredScopes?.length) {
1058
- toolScopes.set(name, tool.requiredScopes);
1059
- }
1060
- }
1061
- if (toolScopes.size > 0) {
1062
- pipeline.push(createScopeMiddleware(toolScopes));
1063
- }
1064
-
1065
- // 5. Schema validation (if enabled)
1066
- if (this.schemaValidator) {
1067
- pipeline.push(createValidationMiddleware(this.schemaValidator));
1068
- }
1069
-
1070
- // 6. Backpressure (always)
1071
- pipeline.push(createBackpressureMiddleware(this.requestQueue));
1072
-
1073
- this.middlewareRunner = createMiddlewareRunner(pipeline, (ctx) => {
1074
- const tool = this.tools.get(ctx.toolName);
1075
- if (!tool) {
1076
- throw new Error(`Unknown tool: ${ctx.toolName}`);
1077
- }
1078
- return Promise.resolve(tool.handler(ctx.args, {
1079
- toolName: ctx.toolName,
1080
- ...(ctx.request ? { request: ctx.request } : {}),
1081
- ...(typeof ctx.sessionId === "string"
1082
- ? { sessionId: ctx.sessionId }
1083
- : {}),
1084
- ...(ctx.authInfo ? { authInfo: ctx.authInfo as AuthInfo } : {}),
1085
- ...(ctx.clientInfo !== undefined ? { clientInfo: ctx.clientInfo } : {}),
1086
- ...(ctx.clientCapabilities !== undefined
1087
- ? { clientCapabilities: ctx.clientCapabilities }
1088
- : {}),
1089
- ...(ctx.logLevel !== undefined ? { logLevel: ctx.logLevel } : {}),
1090
- ...(ctx.inputResponses !== undefined
1091
- ? { inputResponses: ctx.inputResponses }
1092
- : {}),
1093
- ...(ctx.retryVerified !== undefined
1094
- ? { retryVerified: ctx.retryVerified }
1095
- : {}),
1096
- }));
1097
- });
1098
- }
1099
-
1100
- /**
1101
- * Execute a tool call through the middleware pipeline.
1102
- * Unified entry point for both STDIO and HTTP transports.
1103
- *
1104
- * @param toolName - Name of the tool to call
1105
- * @param args - Tool arguments
1106
- * @param request - HTTP request (undefined for STDIO)
1107
- * @param sessionId - HTTP session ID (undefined for STDIO)
1108
- * @returns Tool execution result
1109
- */
1110
- private async executeToolCall(
1111
- toolName: string,
1112
- args: Record<string, unknown>,
1113
- request?: Request,
1114
- sessionId?: string,
1115
- preVerifiedAuthInfo?: AuthInfo,
1116
- clientMeta?: StatelessClientMeta,
1117
- mrtr?: {
1118
- inputResponses?: Record<string, unknown>;
1119
- retryVerified?: boolean;
1120
- },
1121
- ): Promise<MiddlewareResult> {
1122
- if (!this.middlewareRunner) {
1123
- throw new Error(
1124
- "[McpApp] Pipeline not built. Call start() or startHttp() first.",
1125
- );
1126
- }
1127
-
1128
- const ctx: MiddlewareContext = {
1129
- toolName,
1130
- args,
1131
- request,
1132
- sessionId,
1133
- // Pass pre-verified authInfo from the HTTP gate so the auth
1134
- // middleware skips the redundant verifyToken call (avoids JWKS
1135
- // race conditions on concurrent cold-cache requests).
1136
- authInfo: preVerifiedAuthInfo,
1137
- ...(clientMeta?.clientInfo !== undefined
1138
- ? { clientInfo: clientMeta.clientInfo }
1139
- : {}),
1140
- ...(clientMeta?.clientCapabilities !== undefined
1141
- ? { clientCapabilities: clientMeta.clientCapabilities }
1142
- : {}),
1143
- ...(clientMeta?.logLevel !== undefined
1144
- ? { logLevel: clientMeta.logLevel }
1145
- : {}),
1146
- ...(mrtr?.inputResponses !== undefined
1147
- ? { inputResponses: mrtr.inputResponses }
1148
- : {}),
1149
- ...(mrtr?.retryVerified !== undefined
1150
- ? { retryVerified: mrtr.retryVerified }
1151
- : {}),
1152
- };
1153
-
1154
- // OTel span + metrics
1155
- const span = startToolCallSpan(
1156
- toolName,
1157
- {
1158
- "mcp.tool.name": toolName,
1159
- "mcp.server.name": this.options.name,
1160
- "mcp.transport": request ? "http" : "stdio",
1161
- "mcp.session.id": sessionId,
1162
- },
1163
- clientMeta?.traceContext,
1164
- );
1165
-
1166
- // Update gauges before execution
1167
- const queueMetrics = this.requestQueue.getMetrics();
1168
- this.serverMetrics.setGauges({
1169
- activeRequests: queueMetrics.inFlight,
1170
- queuedRequests: queueMetrics.queued,
1171
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1172
- });
1173
-
1174
- const start = performance.now();
1175
- try {
1176
- const result = await this.middlewareRunner(ctx);
1177
- const durationMs = performance.now() - start;
1178
- this.serverMetrics.recordToolCall(toolName, true, durationMs);
1179
- endToolCallSpan(span, true, durationMs);
1180
- return result;
1181
- } catch (error) {
1182
- const durationMs = performance.now() - start;
1183
- const errorMsg = error instanceof Error ? error.message : String(error);
1184
- this.serverMetrics.recordToolCall(toolName, false, durationMs);
1185
- endToolCallSpan(span, false, durationMs, errorMsg);
1186
- throw error;
1187
- }
1188
- }
1189
-
1190
- // ============================================
1191
- // Resource Registration (MCP Apps SEP-1865)
1192
- // ============================================
1193
-
1194
- /**
1195
- * Apply CSP meta tag injection to HTML resource content (if configured).
1196
- * Only transforms text HTML content; blob responses pass through unchanged.
1197
- */
1198
- private applyResourceCsp(content: ResourceContent): ResourceContent {
1199
- if (!this.options.resourceCsp) return content;
1200
- const mediaType = content.mimeType.split(";", 1)[0].trim().toLowerCase();
1201
- if (
1202
- !this.isTextResourceContent(content) ||
1203
- mediaType !== "text/html"
1204
- ) {
1205
- return content;
1206
- }
1207
-
1208
- const cspValue = buildCspHeader(this.options.resourceCsp);
1209
- return {
1210
- ...content,
1211
- text: injectCspMetaTag(content.text, cspValue),
1212
- };
1213
- }
1214
-
1215
- private isTextResourceContent(
1216
- content: ResourceContent,
1217
- ): content is Extract<ResourceContent, { text: string }> {
1218
- return "text" in content;
1219
- }
1220
-
1221
- /** Standard padded base64 with zero pad bits, without whitespace or URL-safe substitutions. */
1222
- private isCanonicalBase64(blob: string): boolean {
1223
- try {
1224
- // `atob` accepts several equivalent spellings. Re-encoding is what
1225
- // rejects omitted padding, whitespace, URL-safe alphabets, and non-zero
1226
- // pad bits such as `/x==` (whose canonical form is `/w==`). Both APIs are
1227
- // Web-standard globals available in Deno and supported Node runtimes.
1228
- return btoa(atob(blob)) === blob;
1229
- } catch {
1230
- return false;
1231
- }
1232
- }
1233
-
1234
- /**
1235
- * Validate an untrusted handler result at the API boundary.
1236
- *
1237
- * TypeScript callers get the discriminated `ResourceContent` union at compile
1238
- * time. This check closes the equivalent JavaScript, `any`, and unchecked
1239
- * TypeScript paths before a malformed result reaches an MCP client.
1240
- */
1241
- private validateResourceContent(
1242
- requestedUri: string,
1243
- candidate: unknown,
1244
- resource: MCPResource,
1245
- ): ResourceContent {
1246
- if (!isRecord(candidate)) {
1247
- throw new Error("[McpApp] Resource handler must return an object");
1248
- }
1249
-
1250
- const hasText = Object.prototype.hasOwnProperty.call(candidate, "text");
1251
- const hasBlob = Object.prototype.hasOwnProperty.call(candidate, "blob");
1252
- if (hasText === hasBlob) {
1253
- throw new Error(
1254
- "[McpApp] Resource content must contain exactly one of text or blob",
1255
- );
1256
- }
1257
- if (candidate.uri !== requestedUri) {
1258
- throw new Error(
1259
- `[McpApp] Resource content URI must match requested URI: ${requestedUri}`,
1260
- );
1261
- }
1262
- if (Object.prototype.hasOwnProperty.call(candidate, "annotations")) {
1263
- throw new Error(
1264
- "[McpApp] Resource content annotations are not a ResourceContents field; put annotations on MCPResource metadata",
1265
- );
1266
- }
1267
- if (candidate._meta !== undefined && !isRecord(candidate._meta)) {
1268
- throw new Error(
1269
- "[McpApp] Resource content _meta must be an object when supplied",
1270
- );
1271
- }
1272
- if (
1273
- typeof candidate.mimeType !== "string" ||
1274
- candidate.mimeType.trim().length === 0
1275
- ) {
1276
- throw new Error(
1277
- "[McpApp] Resource content mimeType must be a non-empty string",
1278
- );
1279
- }
1280
- if (hasText && typeof candidate.text !== "string") {
1281
- throw new Error("[McpApp] Resource content text must be a string");
1282
- }
1283
- if (hasBlob) {
1284
- if (typeof candidate.blob !== "string") {
1285
- throw new Error("[McpApp] Resource content blob must be a string");
1286
- }
1287
- if (!this.isCanonicalBase64(candidate.blob)) {
1288
- throw new Error(
1289
- "[McpApp] Resource content blob must be canonical standard base64",
1290
- );
1291
- }
1292
- }
1293
-
1294
- if (
1295
- resource.mimeType !== undefined &&
1296
- candidate.mimeType !== resource.mimeType
1297
- ) {
1298
- throw new Error(
1299
- `[McpApp] Resource content mimeType must match registered metadata: ${resource.mimeType}`,
1300
- );
1301
- }
1302
- if (resource.size !== undefined) {
1303
- const actualSize = hasText
1304
- ? new TextEncoder().encode(candidate.text as string).byteLength
1305
- : atob(candidate.blob as string).length;
1306
- if (actualSize !== resource.size) {
1307
- throw new Error(
1308
- `[McpApp] Resource content size must match registered metadata: expected ${resource.size}, got ${actualSize}`,
1309
- );
1310
- }
1311
- }
1312
-
1313
- // Do not forward arbitrary JavaScript fields to the wire. In particular,
1314
- // annotations belong to Resource, not ResourceContents in the MCP schema.
1315
- return hasText
1316
- ? {
1317
- uri: requestedUri,
1318
- mimeType: candidate.mimeType,
1319
- text: candidate.text as string,
1320
- ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1321
- }
1322
- : {
1323
- uri: requestedUri,
1324
- mimeType: candidate.mimeType,
1325
- blob: candidate.blob as string,
1326
- ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1327
- };
1328
- }
1329
-
1330
- /** Run, validate, and CSP-harden a handler for a protocol response. */
1331
- private async readResourceForProtocol(
1332
- requestedUri: string,
1333
- resource: MCPResource,
1334
- handler: ResourceHandler,
1335
- ): Promise<ResourceContent> {
1336
- const content = this.validateResourceContent(
1337
- requestedUri,
1338
- await handler(new URL(requestedUri)),
1339
- resource,
1340
- );
1341
- // Size attests the bytes delivered to the client. CSP injection changes a
1342
- // text body, so validate the served representation too rather than only
1343
- // the handler's pre-injection value.
1344
- return this.validateResourceContent(
1345
- requestedUri,
1346
- this.applyResourceCsp(content),
1347
- resource,
1348
- );
1349
- }
1350
-
1351
- /** Convert public metadata into the exact wire listing shape. */
1352
- private toResourceListing(resource: MCPResource): Record<string, unknown> {
1353
- return {
1354
- uri: resource.uri,
1355
- name: resource.name,
1356
- ...(resource.title !== undefined ? { title: resource.title } : {}),
1357
- ...(resource.description !== undefined
1358
- ? { description: resource.description }
1359
- : {}),
1360
- ...(resource.mimeType !== undefined
1361
- ? { mimeType: resource.mimeType }
1362
- : {}),
1363
- ...(resource.size !== undefined ? { size: resource.size } : {}),
1364
- ...(resource.icons !== undefined ? { icons: resource.icons } : {}),
1365
- ...(resource.annotations !== undefined
1366
- ? { annotations: resource.annotations }
1367
- : {}),
1368
- ...(resource._meta !== undefined ? { _meta: resource._meta } : {}),
1369
- };
1370
- }
1371
-
1372
- /** Fail early rather than publishing a metadata value clients must ignore. */
1373
- private validateResourceMetadata(resource: MCPResource): void {
1374
- this.validateResourceUri(resource.uri);
1375
- if (typeof resource.name !== "string" || resource.name.length === 0) {
1376
- throw new Error("[McpApp] Resource name must be a non-empty string");
1377
- }
1378
- if (
1379
- resource.mimeType !== undefined &&
1380
- (typeof resource.mimeType !== "string" ||
1381
- resource.mimeType.trim().length === 0)
1382
- ) {
1383
- throw new Error(
1384
- "[McpApp] Resource mimeType must be a non-empty string when supplied",
1385
- );
1386
- }
1387
- if (
1388
- resource.size !== undefined &&
1389
- (!Number.isSafeInteger(resource.size) || resource.size < 0)
1390
- ) {
1391
- throw new Error(
1392
- `[McpApp] Resource size must be a non-negative safe integer (got ${resource.size})`,
1393
- );
1394
- }
1395
- }
1396
-
1397
- /**
1398
- * Resources are keyed by their wire URI, so accepting a spelling which URL
1399
- * canonicalisation changes would make list/read/handler identity ambiguous.
1400
- * Refuse it at registration instead of silently normalising a caller-owned
1401
- * identifier. Non-`ui:` schemes are valid MCP resources and remain allowed.
1402
- */
1403
- private validateResourceUri(uri: string): void {
1404
- if (typeof uri !== "string" || uri.length === 0) {
1405
- throw new Error("[McpApp] Resource URI must be a non-empty string");
1406
- }
1407
- let canonical: string;
1408
- try {
1409
- canonical = new URL(uri).toString();
1410
- } catch {
1411
- throw new Error(`[McpApp] Resource URI must be an absolute URI: ${uri}`);
1412
- }
1413
- if (canonical !== uri) {
1414
- throw new Error(
1415
- `[McpApp] Resource URI must be canonical: received ${uri}, canonical form is ${canonical}`,
1416
- );
1417
- }
1418
- }
1419
-
1420
- /** A consumer logger is observability, never a resource-commit dependency. */
1421
- private resourceLog(message: string): void {
1422
- try {
1423
- this.log(message);
1424
- } catch {
1425
- // Deliberately ignored: a throwing logger must not contradict a committed
1426
- // resource mutation or make a retry appear necessary.
1427
- }
1428
- }
1429
-
1430
- /**
1431
- * Publish the one post-commit list-changed projection for a mutation.
1432
- * It is best-effort by design: registry state is authoritative and callers
1433
- * must not receive a false failure after it changes.
1434
- */
1435
- private notifyResourceListChanged(): void {
1436
- if (!this.started) return;
1437
- try {
1438
- if (this.subscriptions !== null) {
1439
- this.sendNotification("notifications/resources/list_changed");
1440
- } else {
1441
- this.mcpServer.sendResourceListChanged();
1442
- }
1443
- } catch (error) {
1444
- this.resourceLog(
1445
- `[WARN] Resource list changed notification was not delivered: ${
1446
- error instanceof Error ? error.message : String(error)
1447
- }`,
1448
- );
1449
- }
1450
- }
1451
-
1452
- /**
1453
- * Register a single resource
1454
- *
1455
- * @param resource - Resource definition with uri, name, description
1456
- * @param handler - Callback that returns ResourceContent when resource is read
1457
- * @throws Error if resource with same URI already registered
1458
- *
1459
- * @example
1460
- * ```typescript
1461
- * server.registerResource(
1462
- * { uri: "ui://my-server/viewer", name: "Viewer", description: "Data viewer" },
1463
- * async (uri) => ({
1464
- * uri: uri.toString(),
1465
- * mimeType: MCP_APP_MIME_TYPE,
1466
- * text: "<html>...</html>"
1467
- * })
1468
- * );
1469
- * ```
1470
- */
1471
- registerResource(resource: MCPResource, handler: ResourceHandler): void {
1472
- this.validateResourceMetadata(resource);
1473
-
1474
- if (typeof handler !== "function") {
1475
- throw new Error("[McpApp] Resource handler must be a function");
1476
- }
1477
-
1478
- // Check for duplicate
1479
- if (this.resources.has(resource.uri)) {
1480
- throw new Error(
1481
- `[McpApp] Resource already registered: ${resource.uri}`,
1482
- );
1483
- }
1484
-
1485
- // Static registrations lazily install the single low-level handler set.
1486
- // Once a transport starts, handler installation would be too late, so a
1487
- // deployment that needs late discovery must opt in with expectResources.
1488
- if (!this.resourceHandlersInstalled) {
1489
- if (this.started) {
1490
- throw new Error(
1491
- "[McpApp] Cannot register a resource after start without expectResources: true.",
1492
- );
1493
- }
1494
- this.installResourceHandlers();
1495
- }
1496
-
1497
- // The Map is the only registry. It commits atomically and has no secondary
1498
- // SDK entry which could survive a failed rollback as a ghost resource.
1499
- this.resources.set(resource.uri, { resource, handler });
1500
- this.resourceLog(`Registered resource: ${resource.name} (${resource.uri})`);
1501
- this.notifyResourceListChanged();
1502
- }
1503
-
1504
- /**
1505
- * Remove a resource from this server.
1506
- *
1507
- * It is safe before or after either transport starts once resources are
1508
- * installed. Returns `false` when no such URI is present, so callers can make
1509
- * idempotent cleanup calls without catching an error.
1510
- */
1511
- unregisterResource(uri: string): boolean {
1512
- const info = this.resources.get(uri);
1513
- if (!info) return false;
1514
-
1515
- this.resources.delete(uri);
1516
- this.resourceLog(`Unregistered resource: ${uri}`);
1517
- this.notifyResourceListChanged();
1518
- return true;
1519
- }
1520
-
1521
- /**
1522
- * Register multiple resources
1523
- *
1524
- * @param resources - Array of resource definitions
1525
- * @param handlers - Map of URI to handler function
1526
- * @throws Error if any resource is missing a handler (fail-fast)
1527
- */
1528
- registerResources(
1529
- resources: MCPResource[],
1530
- handlers: Map<string, ResourceHandler>,
1531
- ): void {
1532
- // No mutation means no capability installation and no notification.
1533
- if (resources.length === 0) return;
1534
- // Validate all handlers exist BEFORE registering any (fail-fast)
1535
- const missingHandlers: string[] = [];
1536
- for (const resource of resources) {
1537
- if (!handlers.has(resource.uri)) {
1538
- missingHandlers.push(resource.uri);
1539
- }
1540
- }
1541
-
1542
- if (missingHandlers.length > 0) {
1543
- throw new Error(
1544
- `[McpApp] Missing handlers for resources:\n` +
1545
- missingHandlers.map((uri) => ` - ${uri}`).join("\n"),
1546
- );
1547
- }
1548
-
1549
- // Validate no duplicates exist BEFORE registering any (atomic behavior)
1550
- const duplicateUris: string[] = [];
1551
- for (const resource of resources) {
1552
- if (this.resources.has(resource.uri)) {
1553
- duplicateUris.push(resource.uri);
1554
- }
1555
- }
1556
-
1557
- if (duplicateUris.length > 0) {
1558
- throw new Error(
1559
- `[McpApp] Resources already registered:\n` +
1560
- duplicateUris.map((uri) => ` - ${uri}`).join("\n"),
1561
- );
1562
- }
1563
-
1564
- // A duplicate inside this batch would otherwise fail only when the second
1565
- // registration is attempted, after the first has been made visible.
1566
- const seenUris = new Set<string>();
1567
- const repeatedUris = resources
1568
- .map((resource) => resource.uri)
1569
- .filter((uri) => {
1570
- if (seenUris.has(uri)) return true;
1571
- seenUris.add(uri);
1572
- return false;
1573
- });
1574
- if (repeatedUris.length > 0) {
1575
- throw new Error(
1576
- `[McpApp] Resources are repeated in this batch:\n` +
1577
- repeatedUris.map((uri) => ` - ${uri}`).join("\n"),
1578
- );
1579
- }
1580
-
1581
- for (const resource of resources) {
1582
- this.validateResourceMetadata(resource);
1583
- if (typeof handlers.get(resource.uri) !== "function") {
1584
- throw new Error(
1585
- `[McpApp] Resource handler must be a function: ${resource.uri}`,
1586
- );
1587
- }
1588
- }
1589
- if (!this.resourceHandlersInstalled) {
1590
- if (this.started) {
1591
- throw new Error(
1592
- "[McpApp] Cannot register resources after start without expectResources: true.",
1593
- );
1594
- }
1595
- this.installResourceHandlers();
1596
- }
1597
- // All validation and the one possible handler-install side effect happened
1598
- // before this point. A Map update cannot partially fail, so the batch gets
1599
- // one commit and one notification (or neither on validation failure).
1600
- for (const resource of resources) {
1601
- this.resources.set(resource.uri, {
1602
- resource,
1603
- handler: handlers.get(resource.uri)!,
1604
- });
1605
- }
1606
- this.resourceLog(`Registered ${resources.length} resources`);
1607
- if (resources.length > 0) this.notifyResourceListChanged();
1608
- }
1609
-
1610
- /**
1611
- * Register MCP Apps viewers with automatic dist path resolution.
1612
- *
1613
- * Replaces the manual pattern of: enumerate viewers → resolve paths → register resources.
1614
- * Each viewer gets a `ui://{prefix}/{viewerName}` resource URI.
1615
- *
1616
- * Viewers whose dist is not found are skipped with a warning (not an error),
1617
- * so that the server can start in dev without building UIs first.
1618
- *
1619
- * @returns Summary of registered and skipped viewers
1620
- */
1621
- registerViewers(config: RegisterViewersConfig): RegisterViewersSummary {
1622
- if (!config.prefix) {
1623
- throw new Error(
1624
- "[McpApp] registerViewers: prefix is required",
1625
- );
1626
- }
1627
-
1628
- // Resolve viewer list: explicit or auto-discovered
1629
- let viewerNames: string[];
1630
- if (config.viewers) {
1631
- viewerNames = config.viewers;
1632
- } else if (config.discover) {
1633
- viewerNames = discoverViewers(config.discover.uiDir, config.discover);
1634
- } else {
1635
- viewerNames = [];
1636
- }
1637
-
1638
- const humanNameFn = config.humanName ?? defaultHumanName;
1639
- const registered: string[] = [];
1640
- const skipped: string[] = [];
1641
-
1642
- for (const viewerName of viewerNames) {
1643
- const distPath = resolveViewerDistPath(
1644
- config.moduleUrl,
1645
- viewerName,
1646
- config.exists,
1647
- );
1648
-
1649
- if (!distPath) {
1650
- this.log(
1651
- `Warning: UI not built for ui://${config.prefix}/${viewerName}. ` +
1652
- `Run the UI build step first.`,
1653
- );
1654
- skipped.push(viewerName);
1655
- continue;
1656
- }
1657
-
1658
- const resourceUri = `ui://${config.prefix}/${viewerName}`;
1659
- const readFile = config.readFile;
1660
- const currentDistPath = distPath;
1661
-
1662
- this.registerResource(
1663
- {
1664
- uri: resourceUri,
1665
- name: humanNameFn(viewerName),
1666
- description: `MCP App: ${viewerName}`,
1667
- mimeType: MCP_APP_MIME_TYPE,
1668
- },
1669
- async () => {
1670
- const html = await Promise.resolve(readFile(currentDistPath));
1671
- const content: ResourceContent = {
1672
- uri: resourceUri,
1673
- mimeType: MCP_APP_MIME_TYPE,
1674
- text: html,
1675
- };
1676
- if (config.csp) {
1677
- content._meta = {
1678
- ui: { csp: config.csp },
1679
- };
1680
- }
1681
- return content;
1682
- },
1683
- );
1684
-
1685
- registered.push(viewerName);
1686
- }
1687
-
1688
- if (registered.length > 0) {
1689
- this.log(
1690
- `Registered ${registered.length} viewer(s): ${registered.join(", ")}`,
1691
- );
1692
- }
1693
-
1694
- return { registered, skipped };
1695
- }
1696
-
1697
- /**
1698
- * Start the MCP server with stdio transport
1699
- */
1700
- async start(): Promise<void> {
1701
- // Guard FIRST. Resetting before the guard meant a concurrent start() during
1702
- // stop() cleared `stopping` and rebuilt the store on its way to failing with
1703
- // "already started" — after which a held request produced a live task on a
1704
- // stopped server. `startHttp()` had the order right; this did not.
1705
- if (this.started) {
1706
- throw new Error("Server already started");
1707
- }
1708
-
1709
- // Same reset as the HTTP path. Without it a stdio server that had been stopped
1710
- // kept `stopping` set and its store disposed, so it refused every task for the
1711
- // rest of its life — with nothing to say why.
1712
- this.prepareForStart();
1713
-
1714
- // Build middleware pipeline before connecting transport
1715
- this.buildPipeline();
1716
-
1717
- const transport = new StdioServerTransport();
1718
- await this.mcpServer.server.connect(transport);
1719
-
1720
- this.started = true;
1721
-
1722
- const rateLimitInfo = this.options.rateLimit
1723
- ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
1724
- : "";
1725
- const validationInfo = this.options.validateSchema
1726
- ? ", schema validation: on"
1727
- : "";
1728
-
1729
- this.log(
1730
- `Server started (max concurrent: ${
1731
- this.options.maxConcurrent ?? 10
1732
- }, strategy: ${
1733
- this.options.backpressureStrategy ?? "sleep"
1734
- }${rateLimitInfo}${validationInfo})`,
1735
- );
1736
- this.log(`Tools available: ${this.tools.size}`);
1737
- }
1738
-
1739
- /**
1740
- * Restore the invariants a running server relies on.
1741
- *
1742
- * Called by both transports' start paths. `stop()` disposes the task store and
1743
- * leaves it disposed — rebuilding it mid-teardown is what let an in-flight call
1744
- * spawn into a store nobody would drain — so coming back up is where a live one
1745
- * is created.
1746
- */
1747
- private prepareForStart(): void {
1748
- this.stopping = false;
1749
- if (
1750
- this.options.extensions?.[TASKS_EXTENSION_ID] !== undefined &&
1751
- (this.taskStore === null || this.taskStore.isDisposed)
1752
- ) {
1753
- this.taskStore = new TaskStore({
1754
- onNotification: (task) => this.onTaskChanged(task),
1755
- unrefTimer: (timerId) => unrefTimer(timerId as unknown as number),
1756
- });
1757
- }
1758
- }
1759
-
1760
- async stop(): Promise<void> {
1761
- // Synchronous, before any await: a handler settling during shutdown must see
1762
- // this immediately or it can still spawn a task.
1763
- this.stopping = true;
1764
-
1765
- // Release the subsystems whose timers exist from construction, BEFORE the
1766
- // `started` guard: they are created in the constructor, so a server that
1767
- // failed during startup still has them armed, and returning early left them
1768
- // running with no way to reach them again.
1769
- //
1770
- // Disposed and left disposed — NOT replaced. Replacing here opened a window
1771
- // where an in-flight call could spawn into a fresh store while the server was
1772
- // stopping, producing a task that outlived its server. `startHttp()` builds a
1773
- // new store instead, which keeps "a started server has a live store" true
1774
- // without inventing one mid-teardown.
1775
- if (this.taskStore) {
1776
- this.taskStore.drain();
1777
- this.taskStore.dispose();
1778
- }
1779
- if (this.subscriptions) {
1780
- this.subscriptions.shutdown();
1781
- this.subscriptions = null;
1782
- }
1783
-
1784
- if (!this.started) {
1785
- return;
1786
- }
1787
-
1788
- // Stop HTTP server if running
1789
- if (this.httpServer) {
1790
- await this.httpServer.shutdown();
1791
- this.httpServer = null;
1792
- }
1793
-
1794
- await this.mcpServer.server.close();
1795
- this.started = false;
1796
-
1797
- this.log("Server stopped");
1798
- }
1799
-
1800
- // ============================================
1801
- // HTTP Server Support
1802
- // ============================================
1803
-
1804
- private httpServer: ServeHandle | null = null;
1805
-
1806
- /**
1807
- * Start the MCP server with HTTP transport (Streamable HTTP compatible)
1808
- *
1809
- * This creates an HTTP server that handles MCP JSON-RPC requests.
1810
- * Supports tools/list, tools/call, resources/list, resources/read.
1811
- *
1812
- * @param options - HTTP server options
1813
- * @returns Server instance with shutdown method
1814
- *
1815
- * @example
1816
- * ```typescript
1817
- * const server = new McpApp({ name: "my-server", version: "1.0.0" });
1818
- * server.registerTools(tools, handlers);
1819
- * server.registerResource(resource, handler);
1820
- *
1821
- * const http = await server.startHttp({ port: 3000 });
1822
- * // Server running on http://localhost:3000
1823
- *
1824
- * // Later: await http.shutdown();
1825
- * ```
1826
- */
1827
- async startHttp(
1828
- options: HttpServerOptions,
1829
- ): Promise<
1830
- { shutdown: () => Promise<void>; addr: { hostname: string; port: number } }
1831
- > {
1832
- if (this.started) {
1833
- throw new Error("Server already started");
1834
- }
1835
-
1836
- // Configure auth provider:
1837
- // 1. Programmatic (options.auth.provider) takes priority
1838
- // 2. Otherwise, auto-load from YAML + env vars
1839
- if (this.options.auth?.provider) {
1840
- this.authProvider = this.options.auth.provider;
1841
- this.log(
1842
- `Auth configured: provider=${this.authProvider.constructor.name}`,
1843
- );
1844
- } else {
1845
- const authConfig = await loadAuthConfig();
1846
- if (authConfig) {
1847
- this.authProvider = createAuthProviderFromConfig(authConfig);
1848
- this.log(
1849
- `Auth auto-configured from config: provider=${authConfig.provider}`,
1850
- );
1851
- }
1852
- }
1853
-
1854
- const requireAuth = options.requireAuth ?? false;
1855
- if (requireAuth && !this.authProvider) {
1856
- throw new Error(
1857
- "[McpApp] HTTP auth is required (requireAuth=true) but no auth provider is configured.",
1858
- );
1859
- }
1860
- if (!this.authProvider && !requireAuth) {
1861
- this.log(
1862
- "[WARN] HTTP auth is disabled. Set requireAuth=true or configure auth for production deployments.",
1863
- );
1864
- }
1865
-
1866
- // Build middleware pipeline (includes auth if configured)
1867
- this.buildPipeline();
1868
-
1869
- const hostname = options.hostname ?? "0.0.0.0";
1870
- this.prepareForStart();
1871
-
1872
- if (this.subscriptions === null) {
1873
- this.subscriptions = new SubscriptionRegistry({
1874
- serverInfo: { name: this.options.name, version: this.options.version },
1875
- });
1876
- this.subscriptions.startKeepAlive(
1877
- setInterval,
1878
- (id) => unrefTimer(id as unknown as number),
1879
- );
1880
- }
1881
-
1882
- const enableCors = options.cors ?? true;
1883
- const corsOrigins = options.corsOrigins ?? "*";
1884
- const maxBodyBytes = options.maxBodyBytes === null
1885
- ? null
1886
- : (options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1887
- const httpRateLimit = options.ipRateLimit;
1888
- const httpRateLimiter = httpRateLimit
1889
- ? new RateLimiter({
1890
- maxRequests: httpRateLimit.maxRequests,
1891
- windowMs: httpRateLimit.windowMs,
1892
- })
1893
- : null;
1894
-
1895
- // Create Hono app
1896
- const app = new Hono();
1897
-
1898
- const isWildcardCors = corsOrigins === "*" ||
1899
- (Array.isArray(corsOrigins) && corsOrigins.includes("*"));
1900
- if (enableCors && isWildcardCors) {
1901
- this.log(
1902
- "[WARN] CORS wildcard origin ('*') is active. " +
1903
- "Use corsOrigins: ['https://your-app.example.com'] in production.",
1904
- );
1905
- }
1906
-
1907
- // CORS middleware
1908
- if (enableCors) {
1909
- app.use(
1910
- "*",
1911
- cors({
1912
- origin: corsOrigins,
1913
- allowMethods: ["GET", "POST", "DELETE", "OPTIONS"],
1914
- allowHeaders: [
1915
- "Content-Type",
1916
- "Accept",
1917
- "Authorization",
1918
- "mcp-protocol-version",
1919
- // Spec 2026-07-28 request-metadata headers. Omitting them broke
1920
- // browser clients outright: the preflight rejects the actual request
1921
- // before the server ever sees it, so a conforming client could not
1922
- // send the headers the server now requires.
1923
- "mcp-method",
1924
- "mcp-name",
1925
- // `Mcp-Param-*` names are defined by the tools themselves, so the
1926
- // allowlist is derived from the registered annotations rather than
1927
- // opened to `*` — which would also widen it for every other header.
1928
- //
1929
- // Known limitation: a tool registered via `registerToolLive` AFTER
1930
- // startHttp() is not reflected here. Register annotated tools before
1931
- // starting, or widen `corsOrigins`/headers deliberately.
1932
- ...[...this.mirroredParams.values()]
1933
- .flat()
1934
- .map((param) => `mcp-param-${param.headerName.toLowerCase()}`),
1935
- ],
1936
- exposeHeaders: [
1937
- "Content-Length",
1938
- "mcp-protocol-version",
1939
- ],
1940
- maxAge: 600,
1941
- }),
1942
- );
1943
- }
1944
-
1945
- // Health check endpoint
1946
- app.get(
1947
- "/health",
1948
- (c) =>
1949
- c.json({
1950
- status: "ok",
1951
- server: this.options.name,
1952
- version: this.options.version,
1953
- }),
1954
- );
1955
-
1956
- // Prometheus metrics endpoint
1957
- app.get("/metrics", (_c) => {
1958
- // Update gauges before serving
1959
- const qm = this.requestQueue.getMetrics();
1960
- this.serverMetrics.setGauges({
1961
- activeRequests: qm.inFlight,
1962
- queuedRequests: qm.queued,
1963
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1964
- });
1965
- return new Response(this.serverMetrics.toPrometheusFormat(), {
1966
- headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" },
1967
- });
1968
- });
1969
-
1970
- // RFC 9728 Protected Resource Metadata endpoint
1971
- app.get("/.well-known/oauth-protected-resource", (c) => {
1972
- if (!this.authProvider) {
1973
- return c.text("Not Found", 404);
1974
- }
1975
- return c.json(this.authProvider.getResourceMetadata());
1976
- });
1977
-
1978
- // Auth verification helper for HTTP endpoints.
1979
- // Returns an error Response if auth is required but token is missing/invalid.
1980
- // Returns null if auth passes or is not configured.
1981
- //
1982
- // 0.15.0+: provider's getResourceMetadata() always returns a valid
1983
- // absolute URL in resource_metadata_url (type-enforced). We used to
1984
- // derive this URL from `metadata.resource` by string concatenation
1985
- // (see `buildMetadataUrl` helper, removed 0.15.0), which produced a
1986
- // broken URL when `resource` was an opaque URI per RFC 9728 § 2
1987
- // (e.g., an OIDC project ID used as JWT audience).
1988
- // Auth verification for HTTP endpoints. Returns the verified AuthInfo
1989
- // on success, or an error Response if auth fails. The caller stores
1990
- // the AuthInfo so the middleware pipeline can skip re-verification.
1991
- const verifyHttpAuth = async (
1992
- request: Request,
1993
- ): Promise<{ authInfo: AuthInfo } | { denied: Response }> => {
1994
- if (!this.authProvider) return { authInfo: {} as AuthInfo };
1995
-
1996
- const token = extractBearerToken(request);
1997
- if (!token) {
1998
- const metadata = this.authProvider.getResourceMetadata();
1999
- return {
2000
- denied: createUnauthorizedResponse(
2001
- metadata.resource_metadata_url,
2002
- "missing_token",
2003
- "Authorization header with Bearer token required",
2004
- ),
2005
- };
2006
- }
2007
-
2008
- const authInfo = await this.authProvider.verifyToken(token);
2009
- if (!authInfo) {
2010
- const metadata = this.authProvider.getResourceMetadata();
2011
- return {
2012
- denied: createUnauthorizedResponse(
2013
- metadata.resource_metadata_url,
2014
- "invalid_token",
2015
- "Invalid or expired token",
2016
- ),
2017
- };
2018
- }
2019
-
2020
- return { authInfo: freezeAuthInfo(authInfo) };
2021
- };
2022
-
2023
- const checkHttpRateLimit = async (
2024
- request: Request,
2025
- sessionId?: string,
2026
- overrideHeaders?: Headers, // Track A: sanitized headers for stateless mode (no mcp-session-id)
2027
- ): Promise<{ allowed: boolean; retryAfterMs: number }> => {
2028
- if (!httpRateLimiter || !httpRateLimit) {
2029
- return { allowed: true, retryAfterMs: 0 };
2030
- }
2031
-
2032
- const ip = getClientIpFromHeaders(request.headers);
2033
- const context: HttpRateLimitContext = {
2034
- ip,
2035
- method: request.method,
2036
- path: new URL(request.url).pathname,
2037
- headers: overrideHeaders ?? request.headers,
2038
- sessionId,
2039
- };
2040
- const key = httpRateLimit.keyExtractor?.(context) ?? ip;
2041
- const behavior = httpRateLimit.onLimitExceeded ?? "reject";
2042
-
2043
- if (behavior === "wait") {
2044
- try {
2045
- await httpRateLimiter.waitForSlot(key);
2046
- return { allowed: true, retryAfterMs: 0 };
2047
- } catch {
2048
- return {
2049
- allowed: false,
2050
- retryAfterMs: Math.max(
2051
- httpRateLimiter.getTimeUntilSlot(key),
2052
- httpRateLimit.windowMs,
2053
- ),
2054
- };
2055
- }
2056
- }
2057
-
2058
- if (!httpRateLimiter.checkLimit(key)) {
2059
- return {
2060
- allowed: false,
2061
- retryAfterMs: httpRateLimiter.getTimeUntilSlot(key),
2062
- };
2063
- }
2064
-
2065
- return { allowed: true, retryAfterMs: 0 };
2066
- };
2067
-
2068
- // Custom routes (registered before MCP catch-all)
2069
- if (options.customRoutes) {
2070
- for (const route of options.customRoutes) {
2071
- app[route.method](route.path, (c) => route.handler(c.req.raw));
2072
- }
2073
- }
2074
-
2075
- // Legacy verbs from 2025-03-26..2025-11-25: GET opened a standalone SSE
2076
- // stream, DELETE terminated a session. Neither exists in this revision, and
2077
- // the spec says a server supporting only this revision SHOULD answer both
2078
- // with 405 — not 404, which an older client would read as "no MCP endpoint
2079
- // here" and use to fall back to the deprecated HTTP+SSE transport.
2080
- // Use subscriptions/listen for server-initiated notifications.
2081
- // deno-lint-ignore no-explicit-any
2082
- const methodNotAllowed = (c: any) => c.text("Method Not Allowed", 405);
2083
- app.get("/mcp", methodNotAllowed);
2084
- app.get("/", methodNotAllowed);
2085
- app.delete("/mcp", methodNotAllowed);
2086
- app.delete("/", methodNotAllowed);
2087
-
2088
- // MCP endpoint - POST handles JSON-RPC
2089
- const handleMcpPost = async (
2090
- c: {
2091
- req: {
2092
- json: () => Promise<unknown>;
2093
- raw: Request;
2094
- header: (name: string) => string | undefined;
2095
- };
2096
- json: (data: unknown, status?: number) => Response;
2097
- /** Accumulate a response header (Hono Context API — Track A: MCP-Protocol-Version) */
2098
- header: (name: string, value: string) => void;
2099
- },
2100
- ) => {
2101
- let requestId: string | number | null = null;
2102
- try {
2103
- // Strip mcp-session-id from headers passed to rate-limit context
2104
- // so a keyExtractor cannot use session IDs to bypass IP-level limits.
2105
- const rlHeaders = (() => {
2106
- const h = new Headers(c.req.raw.headers);
2107
- h.delete("mcp-session-id");
2108
- return h;
2109
- })();
2110
- const rateLimit = await checkHttpRateLimit(
2111
- c.req.raw,
2112
- undefined,
2113
- rlHeaders,
2114
- );
2115
- if (!rateLimit.allowed) {
2116
- const retryAfter = Math.max(
2117
- 1,
2118
- Math.ceil(rateLimit.retryAfterMs / 1000),
2119
- );
2120
- return jsonRpcResponse(
2121
- {
2122
- jsonrpc: "2.0",
2123
- id: null,
2124
- error: {
2125
- code: -32000,
2126
- message: `Rate limit exceeded. Retry after ${retryAfter}s`,
2127
- },
2128
- },
2129
- 429,
2130
- { "Retry-After": retryAfter.toString() },
2131
- );
2132
- }
2133
-
2134
- let body: {
2135
- id?: string | number;
2136
- method?: string;
2137
- params?: Record<string, unknown>;
2138
- };
2139
- try {
2140
- const bodyBytes = await readBodyWithLimit(c.req.raw, maxBodyBytes);
2141
- const bodyText = new TextDecoder().decode(bodyBytes);
2142
- const parsed = JSON.parse(bodyText);
2143
- if (!parsed || typeof parsed !== "object") {
2144
- throw new Error("Invalid JSON payload");
2145
- }
2146
- body = parsed as {
2147
- id?: string | number;
2148
- method?: string;
2149
- params?: Record<string, unknown>;
2150
- };
2151
- } catch (error) {
2152
- if (error instanceof BodyTooLargeError) {
2153
- return jsonRpcResponse({
2154
- jsonrpc: "2.0",
2155
- id: null,
2156
- error: { code: -32000, message: error.message },
2157
- }, 413);
2158
- }
2159
- throw error;
2160
- }
2161
-
2162
- const { id, method, params } = body;
2163
- requestId = id ?? null;
2164
-
2165
- // Auth gate: when requireAuth is configured, ALL requests (including
2166
- // initialize) must be authenticated per MCP spec 2025-06-18. The 401
2167
- // response with WWW-Authenticate triggers OAuth discovery in MCP
2168
- // clients (Claude.ai, Cursor). Without this, clients receive a 200 on
2169
- // initialize and never attempt the OAuth/DCR flow.
2170
- let httpAuthInfo: AuthInfo | undefined;
2171
- if (this.authProvider) {
2172
- const authResult = await verifyHttpAuth(c.req.raw);
2173
- if ("denied" in authResult) return authResult.denied;
2174
- httpAuthInfo = authResult.authInfo;
2175
- }
2176
-
2177
- // The `MCP-Protocol-Version` header is REQUIRED on every POST, and its
2178
- // absence is a header-validation failure — not a malformed body. The
2179
- // spec is explicit: "Validation failure conditions include: A required
2180
- // standard header (MCP-Protocol-Version, Mcp-Method, Mcp-Name) is
2181
- // missing", answered with 400 + -32020 (HeaderMismatch).
2182
- //
2183
- // This has to run BEFORE the `_meta` version check below, because a
2184
- // legacy client sends neither and would otherwise get -32602 for a
2185
- // missing body field when the primary violation is the missing header.
2186
- // A client reading -32602 looks for the wrong fix.
2187
- //
2188
- // Notifications are exempt: the revision leaves header requirements for
2189
- // notification POSTs undefined, so demanding one there invents a rule.
2190
- if (
2191
- id !== undefined && c.req.header("MCP-Protocol-Version") === undefined
2192
- ) {
2193
- return jsonRpcResponse(
2194
- {
2195
- jsonrpc: "2.0",
2196
- id,
2197
- error: {
2198
- code: MCP_HEADER_MISMATCH,
2199
- message:
2200
- "Missing required header 'MCP-Protocol-Version'. It must be present and match params._meta['io.modelcontextprotocol/protocolVersion'].",
2201
- data: {
2202
- problem: "missing_header",
2203
- header: "MCP-Protocol-Version",
2204
- recovery:
2205
- "Send MCP-Protocol-Version: 2026-07-28 and the matching _meta field.",
2206
- },
2207
- },
2208
- },
2209
- 400,
2210
- { "MCP-Protocol-Version": SPEC_2026_07_28 },
2211
- );
2212
- }
2213
-
2214
- // Per-request protocolVersion validation (spec 2026-07-28).
2215
- // Must run BEFORE any method dispatch so every call (not just initialize)
2216
- // is validated. Sets MCP-Protocol-Version header on all subsequent responses
2217
- // via Hono's c.header() accumulation.
2218
- // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
2219
- const clientVersion = isRecord(params) && isRecord(params["_meta"])
2220
- ? params["_meta"][STATELESS_PROTO_KEY]
2221
- : undefined;
2222
-
2223
- // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
2224
- // final spec (`clientInfo` is not — it is only SHOULD). A request
2225
- // missing a required field is malformed: -32602 + HTTP 400.
2226
- //
2227
- // Checked after the version so a client on an unsupported revision
2228
- // gets the clearer version error first.
2229
- // Must be an OBJECT, not merely present. `!== undefined` accepted
2230
- // `null`, a scalar or an array, which then reached the handler as a
2231
- // supposed ClientCapabilities and failed later as -32603 — an internal
2232
- // error for what is plainly a malformed request.
2233
- const capabilitiesValid = isRecord(params) &&
2234
- isRecord(params["_meta"]) &&
2235
- isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
2236
-
2237
- if (typeof clientVersion !== "string") {
2238
- // Header uses fallback version — no negotiated version available yet
2239
- return jsonRpcResponse(
2240
- {
2241
- jsonrpc: "2.0",
2242
- id,
2243
- error: {
2244
- code: JSONRPC_INVALID_PARAMS,
2245
- message: `Missing required field '${STATELESS_PROTO_KEY}'`,
2246
- },
2247
- },
2248
- 400,
2249
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2250
- );
2251
- }
2252
-
2253
- if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
2254
- // AX: data carries machine-readable supported/requested for agent recovery
2255
- return jsonRpcResponse(
2256
- {
2257
- jsonrpc: "2.0",
2258
- id,
2259
- error: {
2260
- code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
2261
- message: `Unsupported protocolVersion: "${clientVersion}"`,
2262
- data: {
2263
- supported: [...STATELESS_SUPPORTED_VERSIONS],
2264
- requested: clientVersion,
2265
- },
2266
- },
2267
- },
2268
- 400,
2269
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2270
- );
2271
- }
2272
-
2273
- if (!capabilitiesValid) {
2274
- return jsonRpcResponse(
2275
- {
2276
- jsonrpc: "2.0",
2277
- id,
2278
- error: {
2279
- code: JSONRPC_INVALID_PARAMS,
2280
- message:
2281
- `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
2282
- data: {
2283
- problem: "missing_field",
2284
- bodyField:
2285
- `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
2286
- recovery:
2287
- "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
2288
- },
2289
- },
2290
- },
2291
- 400,
2292
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2293
- );
2294
- }
2295
-
2296
- // Track C: request-metadata headers (SEP-2243).
2297
- //
2298
- // Notifications are exempt: the revision explicitly leaves header
2299
- // requirements for notification POSTs undefined, so a missing
2300
- // `Mcp-Method` there is not a violation to invent.
2301
- if (id !== undefined) {
2302
- const validation = validateRequestHeaders({
2303
- getHeader: (name) => c.req.header(name),
2304
- method: typeof method === "string" ? method : "",
2305
- params: isRecord(params) ? params : undefined,
2306
- bodyProtocolVersion: clientVersion,
2307
- mirroredParams: typeof params?.name === "string"
2308
- ? this.mirroredParams.get(params.name)
2309
- : undefined,
2310
- });
2311
- if (!validation.ok) {
2312
- return jsonRpcResponse(
2313
- {
2314
- jsonrpc: "2.0",
2315
- id,
2316
- error: {
2317
- code: MCP_HEADER_MISMATCH,
2318
- message: validation.message,
2319
- // AX: the caller has to fix the request, so what to fix
2320
- // travels as data. `problem` is an enum to switch on,
2321
- // `recovery` is one concrete action — neither requires
2322
- // parsing the English message.
2323
- data: validation.detail,
2324
- },
2325
- },
2326
- 400,
2327
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2328
- );
2329
- }
2330
- }
2331
-
2332
- const statelessVersion: string = clientVersion;
2333
- // Spec 2026-07-28: echo negotiated version in every response header.
2334
- // c.header() accumulates headers — all subsequent c.json() calls inherit it.
2335
- c.header("MCP-Protocol-Version", statelessVersion);
2336
-
2337
- if (method === "server/discover") {
2338
- return c.json({
2339
- jsonrpc: "2.0",
2340
- id,
2341
- result: this.buildDiscoverResult(),
2342
- });
2343
- }
2344
-
2345
- // Initialize — respond without creating a session or emitting Mcp-Session-Id.
2346
- // statelessVersion is guaranteed defined here (version check above returned early otherwise).
2347
- if (method === "initialize") {
2348
- return c.json({
2349
- jsonrpc: "2.0",
2350
- id,
2351
- result: this.stampResult({
2352
- protocolVersion: statelessVersion,
2353
- capabilities: this.buildServerCapabilities(),
2354
- serverInfo: {
2355
- name: this.options.name,
2356
- version: this.options.version,
2357
- },
2358
- ...(this.options.instructions
2359
- ? { instructions: this.options.instructions }
2360
- : {}),
2361
- }, statelessVersion),
2362
- });
2363
- // Note: c.json() inherits MCP-Protocol-Version header set above.
2364
- // No Mcp-Session-Id header emitted — stateless by design.
2365
- }
2366
-
2367
- // Tools call (delegates to middleware pipeline, which handles auth internally)
2368
- if (method === "tools/call") {
2369
- // Dispatch by method rather than the truthiness of `name`. An empty
2370
- // string can be represented faithfully by Mcp-Name, but it is not a
2371
- // usable tool name and must be InvalidParams rather than an apparent
2372
- // method that this server does not implement.
2373
- const toolParams = isRecord(params) ? params : undefined;
2374
- if (
2375
- toolParams === undefined ||
2376
- typeof toolParams["name"] !== "string" ||
2377
- toolParams["name"].length === 0
2378
- ) {
2379
- return jsonRpcResponse(
2380
- {
2381
- jsonrpc: "2.0",
2382
- id,
2383
- error: {
2384
- code: JSONRPC_INVALID_PARAMS,
2385
- message:
2386
- "tools/call requires a non-empty string 'name' parameter",
2387
- },
2388
- },
2389
- 400,
2390
- );
2391
- }
2392
- const toolName = toolParams["name"];
2393
- const args = (toolParams["arguments"] as Record<string, unknown>) ||
2394
- {};
2395
- const statelessClientMeta:
2396
- | StatelessClientMeta
2397
- | undefined = isRecord(params) && isRecord(params["_meta"])
2398
- ? {
2399
- clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
2400
- | Implementation
2401
- | undefined,
2402
- clientCapabilities: params["_meta"][
2403
- STATELESS_CLIENT_CAPABILITIES_KEY
2404
- ] as ClientCapabilities | undefined,
2405
- logLevel: readLogLevel(params["_meta"]),
2406
- ...readTraceContext(params["_meta"]),
2407
- }
2408
- : undefined;
2409
-
2410
- // MRTR retry fields live in `params` directly — siblings of `_meta`,
2411
- // not members of it, unlike every other per-request field. Reading them
2412
- // from `_meta` yields a silent undefined even when the client sent them.
2413
- //
2414
- // MRTR is always enabled on 2026-07-28 (the only supported version).
2415
- const mrtrEnabled = true;
2416
-
2417
- // Digest of the arguments AS RECEIVED, taken before the middleware
2418
- // pipeline runs. Re-deriving it at seal time would hash whatever the
2419
- // pipeline left in `args` — validation coercion, defaults, redaction —
2420
- // so a client replaying the request byte-for-byte would fail
2421
- // `wrong_params` through no fault of its own.
2422
- const ingressDigest = mrtrEnabled
2423
- ? await paramsDigest({ arguments: args, name: toolName })
2424
- : "";
2425
- // A scalar or array `inputResponses` was silently dropped, so a client
2426
- // sending the wrong shape saw its answers ignored and the same
2427
- // InputRequiredResult come back, with nothing to indicate why.
2428
- const rawResponses = mrtrEnabled && isRecord(params)
2429
- ? params["inputResponses"]
2430
- : undefined;
2431
- if (rawResponses !== undefined && !isRecord(rawResponses)) {
2432
- return jsonRpcResponse(
2433
- {
2434
- jsonrpc: "2.0",
2435
- id,
2436
- error: {
2437
- code: JSONRPC_INVALID_PARAMS,
2438
- message:
2439
- "inputResponses must be an object keyed by the ids from inputRequests",
2440
- data: {
2441
- problem: "malformed_field",
2442
- bodyField: "params.inputResponses",
2443
- recovery:
2444
- "Send an object whose keys match the inputRequests keys the server issued.",
2445
- },
2446
- },
2447
- },
2448
- 400,
2449
- {
2450
- "MCP-Protocol-Version": statelessVersion,
2451
- },
2452
- );
2453
- }
2454
- const echoedResponses = isRecord(rawResponses)
2455
- ? rawResponses
2456
- : undefined;
2457
- const echoedState = mrtrEnabled && isRecord(params) &&
2458
- typeof params["requestState"] === "string"
2459
- ? params["requestState"]
2460
- : undefined;
2461
-
2462
- let retryVerified: boolean | undefined;
2463
-
2464
- // A retry carrying answers but no token cannot be verified, and the
2465
- // server always issues a token when it has a key. So this combination
2466
- // is either a confused client or an attempt to inject answers past the
2467
- // verification gate — refuse it rather than forwarding unverified
2468
- // responses to the handler.
2469
- // Resolved only when MRTR is actually in play. Resolving on every 2026
2470
- // tools/call meant a transient key-import failure also broke ordinary
2471
- // tools that never touch MRTR.
2472
- const needsKey = mrtrEnabled &&
2473
- (echoedResponses !== undefined || echoedState !== undefined);
2474
- const guardKey = needsKey
2475
- ? await this.getMrtrKeySafe(
2476
- id,
2477
- statelessVersion,
2478
- )
2479
- : { key: null as CryptoKey | null };
2480
- if ("error" in guardKey) return guardKey.error;
2481
- if (
2482
- echoedResponses !== undefined && echoedState === undefined &&
2483
- guardKey.key !== null
2484
- ) {
2485
- return jsonRpcResponse(
2486
- {
2487
- jsonrpc: "2.0",
2488
- id,
2489
- error: {
2490
- code: JSONRPC_INVALID_PARAMS,
2491
- message:
2492
- "inputResponses supplied without the requestState issued with them",
2493
- data: {
2494
- problem: "missing_request_state",
2495
- recovery:
2496
- "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
2497
- },
2498
- },
2499
- },
2500
- 400,
2501
- {
2502
- "MCP-Protocol-Version": statelessVersion,
2503
- },
2504
- );
2505
- }
2506
-
2507
- if (echoedState !== undefined) {
2508
- const key = guardKey.key;
2509
- if (key === null) {
2510
- // Unprotected mode: nothing to verify, and the handler is told so
2511
- // rather than being handed a false assurance.
2512
- retryVerified = false;
2513
- } else {
2514
- // On an authenticated server this binds the token to one user, so
2515
- // a token minted for A cannot be spent by B. On an UNAUTHENTICATED
2516
- // server every caller is "anonymous", and the binding protects
2517
- // nothing — correctly so: without auth there is no user boundary to
2518
- // cross, and any caller could invoke the tool directly anyway. The
2519
- // method and argument bindings still apply in both cases.
2520
- const principal = callerPrincipal(httpAuthInfo);
2521
- if (principal === null) {
2522
- return noPrincipalError(
2523
- id,
2524
- statelessVersion,
2525
- );
2526
- }
2527
- const verdict = await verifyRequestState(echoedState, key, {
2528
- principal,
2529
- method: "tools/call",
2530
- paramsDigest: ingressDigest,
2531
- });
2532
- if (!verdict.ok) {
2533
- // Attacker-controlled input that failed its integrity or binding
2534
- // checks. Rejected before the handler runs, and the reason is
2535
- // returned so a legitimate client can recover (e.g. re-elicit
2536
- // after an expiry) rather than guessing.
2537
- return jsonRpcResponse(
2538
- {
2539
- jsonrpc: "2.0",
2540
- id,
2541
- error: {
2542
- code: JSONRPC_INVALID_PARAMS,
2543
- message: `Invalid requestState: ${verdict.reason}`,
2544
- data: { reason: verdict.reason },
2545
- },
2546
- },
2547
- 400,
2548
- );
2549
- }
2550
-
2551
- const replayStore = this.mrtrReplayStore;
2552
- if (replayStore === null) {
2553
- return jsonRpcResponse(
2554
- {
2555
- jsonrpc: "2.0",
2556
- id,
2557
- error: {
2558
- code: ErrorCode.InternalError,
2559
- message: "MRTR replay protection is unavailable",
2560
- data: {
2561
- problem: "mrtr_replay_store_unavailable",
2562
- recovery:
2563
- "Configure mrtr.signingKey with a working replay store and retry the full interaction.",
2564
- },
2565
- },
2566
- },
2567
- 500,
2568
- { "MCP-Protocol-Version": statelessVersion },
2569
- );
2570
- }
2571
-
2572
- let consumed: boolean;
2573
- try {
2574
- const storeResult = await replayStore.consume(
2575
- verdict.payload.nonce,
2576
- verdict.payload.exp,
2577
- );
2578
- if (storeResult !== true && storeResult !== false) {
2579
- throw new Error(
2580
- "mrtr.replayStore.consume() must return a boolean",
2581
- );
2582
- }
2583
- consumed = storeResult;
2584
- } catch {
2585
- this.log(
2586
- "[WARN] MRTR replay store unavailable; retry rejected before handler",
2587
- );
2588
- return jsonRpcResponse(
2589
- {
2590
- jsonrpc: "2.0",
2591
- id,
2592
- error: {
2593
- code: ErrorCode.InternalError,
2594
- message: "MRTR replay protection is unavailable",
2595
- data: {
2596
- problem: "mrtr_replay_store_unavailable",
2597
- recovery:
2598
- "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2599
- },
2600
- },
2601
- },
2602
- 500,
2603
- { "MCP-Protocol-Version": statelessVersion },
2604
- );
2605
- }
2606
- if (!consumed) {
2607
- return jsonRpcResponse(
2608
- {
2609
- jsonrpc: "2.0",
2610
- id,
2611
- error: {
2612
- code: JSONRPC_INVALID_PARAMS,
2613
- message: "Invalid requestState: replayed",
2614
- data: { reason: "replayed" },
2615
- },
2616
- },
2617
- 400,
2618
- { "MCP-Protocol-Version": statelessVersion },
2619
- );
2620
- }
2621
- retryVerified = true;
2622
- }
2623
- }
2624
-
2625
- try {
2626
- const result = await this.executeToolCall(
2627
- toolName,
2628
- args,
2629
- c.req.raw,
2630
- undefined,
2631
- httpAuthInfo,
2632
- statelessClientMeta,
2633
- {
2634
- ...(echoedResponses !== undefined
2635
- ? { inputResponses: echoedResponses }
2636
- : {}),
2637
- ...(retryVerified !== undefined ? { retryVerified } : {}),
2638
- },
2639
- );
2640
- // MRTR: the handler is asking the client for input rather than
2641
- // returning a result. Checked BEFORE the task branch and before
2642
- // stampResult, which would overwrite resultType with "complete".
2643
- if (
2644
- mrtrEnabled && isRecord(result) &&
2645
- result["resultType"] === "input_required"
2646
- ) {
2647
- const sealPrincipal = callerPrincipal(httpAuthInfo);
2648
- if (sealPrincipal === null) {
2649
- return noPrincipalError(
2650
- id,
2651
- statelessVersion,
2652
- );
2653
- }
2654
- const built = await this.buildInputRequiredResult(
2655
- result as unknown as InputRequiredSignal,
2656
- {
2657
- clientCapabilities: statelessClientMeta?.clientCapabilities,
2658
- principal: sealPrincipal,
2659
- method: "tools/call",
2660
- paramsDigest: ingressDigest,
2661
- },
2662
- );
2663
- if (!built.ok) {
2664
- return jsonRpcResponse(
2665
- {
2666
- jsonrpc: "2.0",
2667
- id,
2668
- error: {
2669
- code: built.code,
2670
- message: built.message,
2671
- ...(built.data !== undefined ? { data: built.data } : {}),
2672
- },
2673
- },
2674
- // Status follows the code: an InternalError is a server fault
2675
- // (500), a capability or shape problem is the caller's (400).
2676
- // Flattening both to 400 told a client to fix a request that a
2677
- // misconfigured signing key had broken — and the sibling ingress
2678
- // path already answered 500 for exactly that.
2679
- built.code === ErrorCode.InternalError ? 500 : 400,
2680
- {
2681
- "MCP-Protocol-Version": statelessVersion,
2682
- },
2683
- );
2684
- }
2685
- return c.json({ jsonrpc: "2.0", id, result: built.result });
2686
- }
2687
-
2688
- // Tasks extension: the handler asked for a task handle instead of
2689
- // a synchronous result.
2690
- if (isAsyncTaskDescriptor(result)) {
2691
- const guard = this.requireTasksCapability(
2692
- statelessClientMeta?.clientCapabilities,
2693
- id,
2694
- );
2695
- if (guard) return guard;
2696
-
2697
- // Owner binding: the spec requires an authorization check on every
2698
- // task-related request, and a task id alone is only one line of
2699
- // defence.
2700
- if (this.stopping || this.taskStore === null) {
2701
- return jsonRpcResponse(
2702
- {
2703
- jsonrpc: "2.0",
2704
- id,
2705
- error: {
2706
- code: ErrorCode.InternalError,
2707
- message:
2708
- "Server is shutting down; no new tasks are accepted.",
2709
- data: {
2710
- problem: "server_stopping",
2711
- recovery: "Retry against a running instance.",
2712
- },
2713
- },
2714
- },
2715
- 503,
2716
- {
2717
- "MCP-Protocol-Version": statelessVersion,
2718
- },
2719
- );
2720
- }
2721
- const ownerPrincipal = callerPrincipal(httpAuthInfo);
2722
- if (ownerPrincipal === null) {
2723
- return noPrincipalError(
2724
- id,
2725
- statelessVersion,
2726
- );
2727
- }
2728
- const owner = await taskOwnerKeyFor(
2729
- this.options,
2730
- httpAuthInfo,
2731
- c.req.raw,
2732
- ownerPrincipal,
2733
- );
2734
- if (owner === null) {
2735
- return noOwnerKeyError(
2736
- id,
2737
- statelessVersion,
2738
- );
2739
- }
2740
- // Re-checked, and wrapped: the guard above sits before two awaits
2741
- // (the principal lookup and the async owner hook), so shutdown can
2742
- // begin in between. Without this, spawn()'s post-disposal throw
2743
- // would escape to the POST-level catch and be reported as -32700
2744
- // "Parse error".
2745
- let task;
2746
- try {
2747
- task = this.taskStore.spawn(
2748
- result,
2749
- owner,
2750
- // Same conversion the synchronous path uses, so a handler's
2751
- // return value produces an identical result either way.
2752
- (raw) => this.buildToolCallResult(toolName, raw),
2753
- );
2754
- } catch (spawnError) {
2755
- // Narrowed to the actual shutdown condition. A blanket catch
2756
- // reported a legitimate throw from the handler's own task setup as
2757
- // "server is shutting down" — a diagnosis that sends the reader to
2758
- // look at the wrong thing entirely, on a perfectly healthy server.
2759
- if (this.stopping || this.taskStore.isDisposed) {
2760
- return jsonRpcResponse(
2761
- {
2762
- jsonrpc: "2.0",
2763
- id,
2764
- error: {
2765
- code: ErrorCode.InternalError,
2766
- message:
2767
- "Server is shutting down; no new tasks are accepted.",
2768
- data: {
2769
- problem: "server_stopping",
2770
- recovery: "Retry against a running instance.",
2771
- },
2772
- },
2773
- },
2774
- 503,
2775
- {
2776
- "MCP-Protocol-Version": statelessVersion,
2777
- },
2778
- );
2779
- }
2780
- // A real failure: let the tool error path report it as such.
2781
- throw spawnError;
2782
- }
2783
- return c.json({
2784
- jsonrpc: "2.0",
2785
- id,
2786
- // NOT stampResult(): that writes resultType "complete", and a
2787
- // CreateTaskResult carries "task". Its fields are flat on the
2788
- // result, not nested under a `task` key.
2789
- //
2790
- // Note the asymmetry with tasks/get below, which DOES carry
2791
- // "complete" — that is an ordinary RPC response which happens to
2792
- // describe a task. The spec states this distinction three times;
2793
- // conflating them is the likeliest mistake here.
2794
- result: this.stampResult(
2795
- { ...task },
2796
- statelessVersion,
2797
- "task",
2798
- ),
2799
- });
2800
- }
2801
-
2802
- return c.json({
2803
- jsonrpc: "2.0",
2804
- id,
2805
- result: this.stampResult(
2806
- this.buildToolCallResult(toolName, result),
2807
- statelessVersion,
2808
- ),
2809
- });
2810
- } catch (error) {
2811
- // Handle AuthError with proper HTTP status codes
2812
- if (error instanceof AuthError) {
2813
- if (
2814
- error.code === "missing_token" || error.code === "invalid_token"
2815
- ) {
2816
- return createUnauthorizedResponse(
2817
- error.resourceMetadataUrl,
2818
- error.code,
2819
- error.message,
2820
- );
2821
- }
2822
- if (error.code === "insufficient_scope") {
2823
- return createForbiddenResponse(
2824
- error.requiredScopes ?? [],
2825
- error.resourceMetadataUrl,
2826
- );
2827
- }
2828
- }
2829
-
2830
- // Delegate to centralized error handler
2831
- try {
2832
- const isErrorResult = this.handleToolError(error, toolName);
2833
- return c.json({
2834
- jsonrpc: "2.0",
2835
- id,
2836
- // An `isError: true` tool result is still a completed JSON-RPC
2837
- // result, so it carries `resultType: "complete"`. Only MRTR
2838
- // interim results (Track B) use `"input_required"`.
2839
- result: this.stampResult(
2840
- isErrorResult as Record<string, unknown>,
2841
- statelessVersion,
2842
- ),
2843
- });
2844
- } catch (rethrown) {
2845
- this.log(
2846
- `Error executing tool ${toolName}: ${
2847
- rethrown instanceof Error
2848
- ? rethrown.message
2849
- : String(rethrown)
2850
- }`,
2851
- );
2852
- const errorMessage = rethrown instanceof Error
2853
- ? rethrown.message
2854
- : "Tool execution failed";
2855
- const errorCode = errorMessage.startsWith("Unknown tool")
2856
- ? -32602
2857
- : errorMessage.startsWith("Rate limit")
2858
- ? -32000
2859
- : -32603;
2860
- return c.json({
2861
- jsonrpc: "2.0",
2862
- id,
2863
- error: { code: errorCode, message: errorMessage },
2864
- });
2865
- }
2866
- }
2867
- }
2868
-
2869
- // Auth gate already applied above (covers all methods including tools/call, tools/list, etc.)
2870
- // Note: tools/call also runs auth again in the middleware pipeline (createAuthMiddleware),
2871
- // which provides per-tool scope enforcement. The top-level check above is the gate
2872
- // that triggers OAuth discovery (401 with WWW-Authenticate).
2873
-
2874
- // Tools list
2875
- if (method === "tools/list") {
2876
- return c.json({
2877
- jsonrpc: "2.0",
2878
- id,
2879
- result: this.stampResult(
2880
- this.withCacheHints(
2881
- { tools: this.buildToolListing() },
2882
- statelessVersion,
2883
- ),
2884
- statelessVersion,
2885
- ),
2886
- });
2887
- }
2888
-
2889
- // Resources list
2890
- if (method === "resources/list") {
2891
- return c.json({
2892
- jsonrpc: "2.0",
2893
- id,
2894
- result: this.stampResult(
2895
- this.withCacheHints({
2896
- resources: Array.from(this.resources.values()).map((r) =>
2897
- this.toResourceListing(r.resource)
2898
- ),
2899
- }, statelessVersion),
2900
- statelessVersion,
2901
- ),
2902
- });
2903
- }
2904
-
2905
- // Concrete resources only for now. Keep this endpoint explicit rather
2906
- // than falling through to MethodNotFound once resources are advertised.
2907
- if (method === "resources/templates/list") {
2908
- return c.json({
2909
- jsonrpc: "2.0",
2910
- id,
2911
- result: this.stampResult(
2912
- this.withCacheHints({ resourceTemplates: [] }, statelessVersion),
2913
- statelessVersion,
2914
- ),
2915
- });
2916
- }
2917
-
2918
- // Resources read
2919
- if (method === "resources/read") {
2920
- // Dispatch by method, not the truthiness of its routing parameter.
2921
- // `uri: ""` has a valid empty Mcp-Name header representation, but it
2922
- // is not a usable resource URI. Letting it skip this branch turned a
2923
- // malformed resources/read into a misleading -32601 method-not-found.
2924
- const uri = isRecord(params) && typeof params["uri"] === "string" &&
2925
- params["uri"].length > 0
2926
- ? params["uri"]
2927
- : undefined;
2928
- if (uri === undefined) {
2929
- return jsonRpcResponse(
2930
- {
2931
- jsonrpc: "2.0",
2932
- id,
2933
- error: {
2934
- code: JSONRPC_INVALID_PARAMS,
2935
- message:
2936
- "resources/read requires a non-empty string 'uri' parameter",
2937
- },
2938
- },
2939
- 400,
2940
- );
2941
- }
2942
- const resourceInfo = this.resources.get(uri);
2943
-
2944
- if (!resourceInfo) {
2945
- return c.json({
2946
- jsonrpc: "2.0",
2947
- id,
2948
- error: { code: -32602, message: `Resource not found: ${uri}` },
2949
- });
2950
- }
2951
-
2952
- try {
2953
- const finalContent = await this.readResourceForProtocol(
2954
- uri,
2955
- resourceInfo.resource,
2956
- resourceInfo.handler,
2957
- );
2958
- return c.json({
2959
- jsonrpc: "2.0",
2960
- id,
2961
- result: this.stampResult(
2962
- this.withCacheHints(
2963
- { contents: [finalContent] },
2964
- statelessVersion,
2965
- {
2966
- // resources/read is the only cacheable method an MRTR retry
2967
- // can target, so it is the only one that needs this guard.
2968
- isMrtrRetry: isRecord(params) &&
2969
- (params["requestState"] !== undefined ||
2970
- params["inputResponses"] !== undefined),
2971
- },
2972
- ),
2973
- statelessVersion,
2974
- ),
2975
- });
2976
- } catch (error) {
2977
- this.log(
2978
- `Error reading resource ${uri}: ${
2979
- error instanceof Error ? error.message : String(error)
2980
- }`,
2981
- );
2982
- return c.json({
2983
- jsonrpc: "2.0",
2984
- id,
2985
- error: {
2986
- code: -32603,
2987
- message: error instanceof Error
2988
- ? error.message
2989
- : "Resource read failed",
2990
- },
2991
- });
2992
- }
2993
- }
2994
-
2995
- // ── subscriptions/listen (SEP-2575) ──────────────────────────────
2996
- //
2997
- // Replaces the removed HTTP GET stream and resources/subscribe. The
2998
- // response IS the stream: a long-lived SSE body carrying only the
2999
- // notification types the client opted into.
3000
- if (method === "subscriptions/listen" && this.subscriptions !== null) {
3001
- const registry = this.subscriptions;
3002
-
3003
- // A notification-shaped listen makes no sense: the response IS the
3004
- // stream, and the subscription id IS this request's id — with no id
3005
- // there is nothing to correlate notifications to.
3006
- if (id === undefined) {
3007
- return jsonRpcResponse(
3008
- {
3009
- jsonrpc: "2.0",
3010
- id: null,
3011
- error: {
3012
- code: JSONRPC_INVALID_PARAMS,
3013
- message:
3014
- "subscriptions/listen requires a JSON-RPC id: the response is the notification stream, and the id identifies the subscription",
3015
- },
3016
- },
3017
- 400,
3018
- );
3019
- }
3020
- const subscriptionId: string | number = id as string | number;
3021
- // A missing or non-object filter is malformed, not "subscribe to
3022
- // nothing": a client that meant to subscribe would otherwise get a
3023
- // 200 stream that stays silent forever, with no way to tell why.
3024
- if (!isRecord(params) || !isRecord(params["notifications"])) {
3025
- return jsonRpcResponse(
3026
- {
3027
- jsonrpc: "2.0",
3028
- id,
3029
- error: {
3030
- code: JSONRPC_INVALID_PARAMS,
3031
- message:
3032
- "subscriptions/listen requires a 'notifications' object naming the types to receive",
3033
- data: {
3034
- problem: "missing_field",
3035
- bodyField: "params.notifications",
3036
- recovery:
3037
- 'Send params.notifications, e.g. { toolsListChanged: true } or { resourceSubscriptions: ["ui://x"] }.',
3038
- },
3039
- },
3040
- },
3041
- 400,
3042
- );
3043
- }
3044
- const filter = validateSubscriptionFilter(
3045
- params["notifications"] as Record<string, unknown>,
3046
- );
3047
- if (!filter.ok) {
3048
- return jsonRpcResponse(
3049
- {
3050
- jsonrpc: "2.0",
3051
- id,
3052
- error: {
3053
- code: JSONRPC_INVALID_PARAMS,
3054
- message: filter.message,
3055
- data: {
3056
- problem: "malformed_field",
3057
- bodyField: filter.bodyField,
3058
- recovery: filter.recovery,
3059
- },
3060
- },
3061
- },
3062
- 400,
3063
- );
3064
- }
3065
- const requested = filter.filter;
3066
-
3067
- // Recognising `taskIds` is mandatory even though pushing task updates is
3068
- // not: a client that asks for task notifications without declaring the
3069
- // Tasks extension MUST be refused. Accepting it would open a stream that
3070
- // can never deliver, with nothing to say why.
3071
- if (
3072
- Array.isArray(requested.taskIds) && requested.taskIds.length > 0
3073
- ) {
3074
- const guard = this.requireTasksCapability(
3075
- isRecord(params["_meta"])
3076
- ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3077
- | ClientCapabilities
3078
- | undefined
3079
- : undefined,
3080
- id,
3081
- );
3082
- if (guard) return guard;
3083
- }
3084
-
3085
- // Computed ONCE by the registry and reused for both the
3086
- // acknowledgement and the registration. Deriving it independently here
3087
- // is how a client ends up told it subscribed to a set the registry does
3088
- // not actually enforce.
3089
- const agreed = registry.computeAgreedFilter(requested);
3090
-
3091
- let internalKey: string | null = null;
3092
- const stream = new ReadableStream<Uint8Array>({
3093
- start: (controller) => {
3094
- let closed = false;
3095
- const sink: SubscriptionSink = {
3096
- enqueue(chunk) {
3097
- // The cancel() callback fires before unregister(), so a write
3098
- // can race a closed controller on every client disconnect.
3099
- if (closed) return;
3100
- try {
3101
- controller.enqueue(chunk);
3102
- } catch {
3103
- closed = true;
3104
- }
3105
- },
3106
- close() {
3107
- if (closed) return;
3108
- closed = true;
3109
- try {
3110
- controller.close();
3111
- } catch { /* already closed */ }
3112
- },
3113
- get isClosed() {
3114
- return closed;
3115
- },
3116
- };
3117
-
3118
- // The acknowledgement MUST be the first message on the stream, so
3119
- // it is enqueued BEFORE registering — otherwise a fan-out landing
3120
- // in between would precede it.
3121
- sink.enqueue(
3122
- encodeSSEEvent(
3123
- buildAcknowledgedMessage(subscriptionId, agreed),
3124
- ),
3125
- );
3126
- internalKey = registry.register(subscriptionId, agreed, sink);
3127
- },
3128
- cancel: () => {
3129
- // Client closed the stream: that IS the cancellation signal on
3130
- // HTTP, and the server must send nothing further.
3131
- if (internalKey !== null) {
3132
- registry.unregister(internalKey, "client");
3133
- }
3134
- },
3135
- });
3136
-
3137
- return new Response(stream, {
3138
- status: 200,
3139
- headers: {
3140
- "Content-Type": "text/event-stream",
3141
- "Cache-Control": "no-cache",
3142
- Connection: "keep-alive",
3143
- // Tells nginx and friends not to buffer, without which events sit
3144
- // in a proxy until the buffer fills.
3145
- "X-Accel-Buffering": "no",
3146
- "MCP-Protocol-Version": statelessVersion,
3147
- },
3148
- });
3149
- }
3150
-
3151
- // ── Tasks extension (io.modelcontextprotocol/tasks) ──────────────
3152
- //
3153
- // The capability guard repeats on every one of these, not just at task
3154
- // creation: the spec requires the missing-capability error for a
3155
- // non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
3156
- // Guarding creation alone would still let such a client poll and cancel
3157
- // tasks it could never have been handed.
3158
- // Capability-gated: a non-declaring client must not reach tasks/*.
3159
- // The version gate (STATELESS_SUPPORTED_VERSIONS) upstream of this block
3160
- // already rejects any peer running a pre-2026 protocol version.
3161
- if (
3162
- this.taskStore !== null &&
3163
- (method === "tasks/get" || method === "tasks/update" ||
3164
- method === "tasks/cancel")
3165
- ) {
3166
- // These are requests, never notifications. Without an id they would
3167
- // otherwise slip past header validation — which exempts notifications —
3168
- // then mutate task state and answer with an id-less, malformed
3169
- // JSON-RPC response.
3170
- if (id === undefined) {
3171
- return jsonRpcResponse(
3172
- {
3173
- jsonrpc: "2.0",
3174
- id: null,
3175
- error: {
3176
- code: JSONRPC_INVALID_PARAMS,
3177
- message: `${method} is a request and requires a JSON-RPC id`,
3178
- data: {
3179
- problem: "missing_field",
3180
- bodyField: "id",
3181
- recovery:
3182
- "Send the call as a JSON-RPC request with an id, not as a notification.",
3183
- },
3184
- },
3185
- },
3186
- 400,
3187
- );
3188
- }
3189
- const store = this.taskStore;
3190
- const guard = this.requireTasksCapability(
3191
- isRecord(params) && isRecord(params["_meta"])
3192
- ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3193
- | ClientCapabilities
3194
- | undefined
3195
- : undefined,
3196
- id,
3197
- );
3198
- if (guard) return guard;
3199
-
3200
- const taskId =
3201
- isRecord(params) && typeof params["taskId"] === "string"
3202
- ? params["taskId"]
3203
- : undefined;
3204
- if (taskId === undefined) {
3205
- return jsonRpcResponse(
3206
- {
3207
- jsonrpc: "2.0",
3208
- id,
3209
- error: {
3210
- code: JSONRPC_INVALID_PARAMS,
3211
- message: `${method} requires a string 'taskId' parameter`,
3212
- },
3213
- },
3214
- 400,
3215
- );
3216
- }
3217
-
3218
- const callerBase = callerPrincipal(httpAuthInfo);
3219
- if (callerBase === null) {
3220
- return noPrincipalError(
3221
- id,
3222
- statelessVersion,
3223
- );
3224
- }
3225
- const caller = await taskOwnerKeyFor(
3226
- this.options,
3227
- httpAuthInfo,
3228
- c.req.raw,
3229
- callerBase,
3230
- );
3231
- if (caller === null) {
3232
- return noOwnerKeyError(
3233
- id,
3234
- statelessVersion,
3235
- );
3236
- }
3237
-
3238
- if (method === "tasks/get") {
3239
- const task = store.get(taskId, caller);
3240
- if (task === null) {
3241
- return c.json({
3242
- jsonrpc: "2.0",
3243
- id,
3244
- error: {
3245
- code: JSONRPC_INVALID_PARAMS,
3246
- message: `Unknown taskId: ${taskId}`,
3247
- },
3248
- });
3249
- }
3250
- // "complete", not "task" — see the note at task creation.
3251
- return c.json({
3252
- jsonrpc: "2.0",
3253
- id,
3254
- result: this.stampResult({ ...task }, statelessVersion),
3255
- });
3256
- }
3257
-
3258
- if (method === "tasks/update") {
3259
- // Spec field name is `inputResponses`, matching MRTR's vocabulary.
3260
- const responses = isRecord(params) &&
3261
- isRecord(params["inputResponses"])
3262
- ? params["inputResponses"]
3263
- : undefined;
3264
- if (responses === undefined) {
3265
- return jsonRpcResponse(
3266
- {
3267
- jsonrpc: "2.0",
3268
- id,
3269
- error: {
3270
- code: JSONRPC_INVALID_PARAMS,
3271
- message: "tasks/update requires an 'inputResponses' object",
3272
- },
3273
- },
3274
- 400,
3275
- );
3276
- }
3277
- if (!store.update(taskId, responses, caller)) {
3278
- // SHOULD be an error for an unknown id — and an id belonging to
3279
- // another caller is reported identically, so the response never
3280
- // confirms that someone else's task exists.
3281
- return c.json({
3282
- jsonrpc: "2.0",
3283
- id,
3284
- error: {
3285
- code: JSONRPC_INVALID_PARAMS,
3286
- message: `Unknown taskId: ${taskId}`,
3287
- },
3288
- });
3289
- }
3290
- // MUST be an EMPTY acknowledgement (beyond the resultType envelope).
3291
- // Returning the task state instead would look helpful and be
3292
- // non-conformant — and the spec calls the ack eventually consistent,
3293
- // so any state returned here could already be stale.
3294
- return c.json({
3295
- jsonrpc: "2.0",
3296
- id,
3297
- result: this.stampResult({}, statelessVersion),
3298
- });
3299
- }
3300
-
3301
- // tasks/cancel — likewise an empty ack. Cancellation is cooperative:
3302
- // the server acknowledges intent, and the task may still finish or
3303
- // reach a different terminal status.
3304
- if (!store.cancel(taskId, caller)) {
3305
- return c.json({
3306
- jsonrpc: "2.0",
3307
- id,
3308
- error: {
3309
- code: JSONRPC_INVALID_PARAMS,
3310
- message: `Unknown taskId: ${taskId}`,
3311
- },
3312
- });
3313
- }
3314
- return c.json({
3315
- jsonrpc: "2.0",
3316
- id,
3317
- result: this.stampResult({}, statelessVersion),
3318
- });
3319
- }
3320
-
3321
- // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28.
3322
- // They fall through to method-not-found below (404 + -32601), which is
3323
- // how a client distinguishes a modern server from a legacy HTTP+SSE one.
3324
- if (method === "prompts/list") {
3325
- return c.json({
3326
- jsonrpc: "2.0",
3327
- id,
3328
- result: this.stampResult(
3329
- this.withCacheHints({ prompts: [] }, statelessVersion),
3330
- statelessVersion,
3331
- ),
3332
- });
3333
- }
3334
- if (method === "completion/complete") {
3335
- return c.json({
3336
- jsonrpc: "2.0",
3337
- id,
3338
- result: this.stampResult(
3339
- { completion: { values: [] } },
3340
- statelessVersion,
3341
- ),
3342
- });
3343
- }
3344
-
3345
- // Handle notifications: a method and NO id (JSON-RPC 2.0).
3346
- //
3347
- // `!id` was wrong: `0` is a valid id and is falsy, so a request with
3348
- // `id: 0` was answered 202-with-no-body as though it were a
3349
- // notification. The spec only forbids `null`.
3350
- if (method && id === undefined) {
3351
- return new Response(null, { status: 202 });
3352
- }
3353
-
3354
- // Malformed request: no method at all
3355
- if (!method) {
3356
- return c.json({
3357
- jsonrpc: "2.0",
3358
- id: id ?? null,
3359
- error: {
3360
- code: -32600,
3361
- message: "Invalid Request: missing 'method' field",
3362
- },
3363
- });
3364
- }
3365
-
3366
- // Method not found.
3367
- //
3368
- // Spec 2026-07-28 requires HTTP **404** here, not 200: "If the server
3369
- // does not implement the requested RPC method, it MUST respond with
3370
- // 404 Not Found and a JSON-RPC error with code -32601". The status is
3371
- // load-bearing — a client probing an unknown URL uses exactly this
3372
- // response to tell a modern MCP endpoint from a legacy HTTP+SSE server.
3373
- //
3374
- // This also covers the removed methods (`ping`, `logging/setLevel`).
3375
- return jsonRpcResponse(
3376
- {
3377
- jsonrpc: "2.0",
3378
- id,
3379
- error: { code: -32601, message: `Method not found: ${method}` },
3380
- },
3381
- 404,
3382
- );
3383
- } catch (error) {
3384
- this.log(
3385
- `HTTP request error: ${
3386
- error instanceof Error ? error.message : String(error)
3387
- }`,
3388
- );
3389
- return c.json({
3390
- jsonrpc: "2.0",
3391
- id: requestId,
3392
- error: { code: -32700, message: "Parse error" },
3393
- });
3394
- }
3395
- };
3396
-
3397
- // deno-lint-ignore no-explicit-any
3398
- app.post("/mcp", handleMcpPost as any);
3399
- // deno-lint-ignore no-explicit-any
3400
- app.post("/", handleMcpPost as any);
3401
-
3402
- // Embedded mode: skip serve(), surface the Hono fetch handler to the
3403
- // caller and let them mount it inside their own framework (Fresh, Hono,
3404
- // Express, etc.).
3405
- if (options.embedded) {
3406
- if (!options.embeddedHandlerCallback) {
3407
- throw new Error(
3408
- "[McpApp] embedded=true requires embeddedHandlerCallback",
3409
- );
3410
- }
3411
- // deno-lint-ignore no-explicit-any
3412
- options.embeddedHandlerCallback(app.fetch as any);
3413
- this.started = true;
3414
- this.log(
3415
- `HTTP handler ready (embedded mode — no port bound, max concurrent: ${
3416
- this.options.maxConcurrent ?? 10
3417
- })`,
3418
- );
3419
- return {
3420
- shutdown: async () => {
3421
- await this.stop();
3422
- },
3423
- addr: { hostname: "embedded", port: 0 },
3424
- };
3425
- }
3426
-
3427
- // Start server
3428
- this.httpServer = serve(
3429
- {
3430
- port: options.port,
3431
- hostname,
3432
- maxBodyBytes,
3433
- onListen: options.onListen ?? ((info) => {
3434
- this.log(
3435
- `HTTP server started on http://${info.hostname}:${info.port}`,
3436
- );
3437
- }),
3438
- },
3439
- app.fetch,
3440
- );
3441
-
3442
- this.started = true;
3443
-
3444
- const rateLimitInfo = this.options.rateLimit
3445
- ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
3446
- : "";
3447
- const validationInfo = this.options.validateSchema
3448
- ? ", schema validation: on"
3449
- : "";
3450
-
3451
- this.log(
3452
- `Server started HTTP mode (max concurrent: ${
3453
- this.options.maxConcurrent ?? 10
3454
- }, strategy: ${
3455
- this.options.backpressureStrategy ?? "sleep"
3456
- }${rateLimitInfo}${validationInfo})`,
3457
- );
3458
- this.log(
3459
- `Tools available: ${this.tools.size}, Resources: ${this.resources.size}`,
3460
- );
3461
-
3462
- return {
3463
- shutdown: async () => {
3464
- await this.stop();
3465
- },
3466
- addr: { hostname, port: options.port },
3467
- };
3468
- }
3469
-
3470
- /**
3471
- * Build the HTTP middleware stack and return its fetch handler without
3472
- * binding a port. Use this when you want to mount the MCP HTTP layer
3473
- * inside another HTTP framework on Deno (Fresh, Hono, `Deno.serve`) or
3474
- * Node (Express, Hono-on-Node) instead of giving up port ownership to
3475
- * {@link startHttp}.
3476
- *
3477
- * **Runtime targets:** `@casys/mcp-server` is Deno-first — the canonical
3478
- * deployment path is Deno 2.x on Deno Deploy or self-hosted Deno, with
3479
- * a Node 20+ distribution via `scripts/build-node.sh` as a secondary
3480
- * target. Cloudflare Workers, workerd, and browser runtimes are not
3481
- * supported — if you target those, use
3482
- * [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server)
3483
- * directly instead.
3484
- *
3485
- * The returned handler accepts a Web Standard {@link Request} and returns
3486
- * a Web Standard {@link Response}. It exposes the same routes as
3487
- * {@link startHttp}: `POST /mcp`, `GET /health`, `GET /metrics`, and
3488
- * `GET /.well-known/oauth-protected-resource`. `GET /mcp` returns 405.
3489
- *
3490
- * Auth, multi-tenant middleware, scope checks, and rate limiting are all
3491
- * applied identically. OTel hooks are started, so the server is fully
3492
- * live after this returns — just without its own listening socket.
3493
- *
3494
- * Multi-tenant SaaS pattern: cache one `McpApp` per tenant
3495
- * and call `getFetchHandler()` once per server, then dispatch each
3496
- * inbound request to the right cached handler from your framework's
3497
- * routing layer.
3498
- *
3499
- * @example
3500
- * ```typescript
3501
- * // In a Fresh route at routes/mcp/[...path].tsx
3502
- * const server = new McpApp({ name: "my-mcp", version: "1.0.0" });
3503
- * server.registerTools(tools, handlers);
3504
- * const handler = await server.getFetchHandler({
3505
- * requireAuth: true,
3506
- * auth: { provider: myAuthProvider },
3507
- * });
3508
- * // Later, in your route handler:
3509
- * return await handler(ctx.req);
3510
- * ```
3511
- *
3512
- * @param options - Same as {@link startHttp}, minus `port`/`hostname`/`onListen`.
3513
- * @returns A Web Standard fetch handler.
3514
- */
3515
- async getFetchHandler(
3516
- options: Omit<HttpServerOptions, "port" | "hostname" | "onListen"> = {},
3517
- ): Promise<FetchHandler> {
3518
- let captured: FetchHandler | null = null;
3519
- await this.startHttp({
3520
- // port/hostname are unused in embedded mode but the type requires them.
3521
- // Pass sentinel values that would never bind even if used.
3522
- port: 0,
3523
- ...options,
3524
- embedded: true,
3525
- embeddedHandlerCallback: (handler) => {
3526
- captured = handler;
3527
- },
3528
- });
3529
- if (!captured) {
3530
- // Defensive: startHttp should always invoke the callback synchronously
3531
- // before returning. If it didn't, something is structurally wrong.
3532
- throw new Error(
3533
- "[McpApp] getFetchHandler: embedded callback was not invoked",
3534
- );
3535
- }
3536
- return captured;
3537
- }
3538
-
3539
- /**
3540
- * Read the MCP Apps capability advertised by the connected client.
3541
- *
3542
- * Returns the capability object (possibly empty `{}`) when the client
3543
- * advertised support for MCP Apps via its `extensions` capability,
3544
- * or `undefined` when:
3545
- * - the client did not send capabilities yet (called before initialize)
3546
- * - the client did not advertise the MCP Apps extension at all
3547
- * - the client sent a malformed extension value
3548
- *
3549
- * Use this from a tool handler to decide whether to return a UI
3550
- * resource (`_meta.ui`) or a text-only fallback. Hosts that don't
3551
- * support MCP Apps will silently drop the `_meta.ui` field, but
3552
- * checking explicitly lets you serve a richer text response when
3553
- * the UI path isn't available.
3554
- *
3555
- * @returns MCP Apps capability or `undefined` if not supported.
3556
- *
3557
- * @example
3558
- * ```typescript
3559
- * const cap = app.getClientMcpAppsCapability();
3560
- * if (cap?.mimeTypes?.includes(MCP_APP_MIME_TYPE)) {
3561
- * return {
3562
- * content: [{ type: "text", text: summary }],
3563
- * _meta: { ui: { resourceUri: "ui://my-app/dashboard" } },
3564
- * };
3565
- * }
3566
- * return { content: [{ type: "text", text: detailedTextFallback }] };
3567
- * ```
3568
- *
3569
- * @see {@link getMcpAppsCapability} for the standalone reader
3570
- * @see {@link MCP_APPS_EXTENSION_ID} for the extension key
3571
- */
3572
- getClientMcpAppsCapability(): McpAppsClientCapability | undefined {
3573
- return getMcpAppsCapability(this.mcpServer.server.getClientCapabilities());
3574
- }
3575
-
3576
- /**
3577
- * Get queue metrics for monitoring
3578
- */
3579
- getMetrics(): QueueMetrics {
3580
- return this.requestQueue.getMetrics();
3581
- }
3582
-
3583
- /**
3584
- * Get full server metrics (counters, histograms, gauges)
3585
- */
3586
- getServerMetrics(): import("./observability/metrics.js").ServerMetricsSnapshot {
3587
- const qm = this.requestQueue.getMetrics();
3588
- this.serverMetrics.setGauges({
3589
- activeRequests: qm.inFlight,
3590
- queuedRequests: qm.queued,
3591
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
3592
- });
3593
- return this.serverMetrics.getSnapshot();
3594
- }
3595
-
3596
- /**
3597
- * Get Prometheus text format metrics
3598
- */
3599
- getPrometheusMetrics(): string {
3600
- return this.serverMetrics.toPrometheusFormat();
3601
- }
3602
-
3603
- /**
3604
- * Get rate limiter metrics (if rate limiting is enabled)
3605
- */
3606
- getRateLimitMetrics(): { keys: number; totalRequests: number } | null {
3607
- return this.rateLimiter?.getMetrics() ?? null;
3608
- }
3609
-
3610
- /**
3611
- * Get rate limiter instance (for advanced use cases)
3612
- */
3613
- getRateLimiter(): RateLimiter | null {
3614
- return this.rateLimiter;
3615
- }
3616
-
3617
- /**
3618
- * Get schema validator instance (for advanced use cases)
3619
- */
3620
- getSchemaValidator(): SchemaValidator | null {
3621
- return this.schemaValidator;
3622
- }
3623
-
3624
- /**
3625
- * Check if server is started
3626
- */
3627
- isStarted(): boolean {
3628
- return this.started;
3629
- }
3630
-
3631
- /**
3632
- * Get number of registered tools
3633
- */
3634
- getToolCount(): number {
3635
- return this.tools.size;
3636
- }
3637
-
3638
- /**
3639
- * Get tool names
3640
- */
3641
- getToolNames(): string[] {
3642
- return Array.from(this.tools.keys());
3643
- }
3644
-
3645
- // ============================================
3646
- // Resource Introspection (MCP Apps)
3647
- // ============================================
3648
-
3649
- /**
3650
- * Get number of registered resources
3651
- */
3652
- getResourceCount(): number {
3653
- return this.resources.size;
3654
- }
3655
-
3656
- /**
3657
- * Get registered resource URIs
3658
- */
3659
- getResourceUris(): string[] {
3660
- return Array.from(this.resources.keys());
3661
- }
3662
-
3663
- /**
3664
- * Check if a resource is registered
3665
- */
3666
- hasResource(uri: string): boolean {
3667
- return this.resources.has(uri);
3668
- }
3669
-
3670
- /**
3671
- * Get resource info by URI (for testing/debugging)
3672
- */
3673
- getResourceInfo(uri: string): MCPResource | undefined {
3674
- return this.resources.get(uri)?.resource;
3675
- }
3676
-
3677
- /**
3678
- * Read resource content by URI.
3679
- * Invokes the registered handler directly (no MCP protocol round-trip).
3680
- * Returns null if the resource is not registered.
3681
- */
3682
- async readResourceContent(uri: string): Promise<ResourceContent | null> {
3683
- const entry = this.resources.get(uri);
3684
- if (!entry) return null;
3685
- return this.validateResourceContent(
3686
- uri,
3687
- await entry.handler(new URL(uri)),
3688
- entry.resource,
3689
- );
3690
- }
3691
-
3692
- /**
3693
- * Send a JSON-RPC notification to the connected transport.
3694
- *
3695
- * Routing depends on the transport:
3696
- * - **HTTP**: fanned out to `subscriptions/listen` streams, only to
3697
- * subscribers that opted into that notification type.
3698
- * - **stdio**: written to stdout via the SDK transport.
3699
- *
3700
- * @param method - Notification method (e.g. "notifications/tools/list_changed")
3701
- * @param params - Notification parameters
3702
- */
3703
- sendNotification(
3704
- method: string,
3705
- params?: Record<string, unknown>,
3706
- ): void {
3707
- if (!this.started) return;
3708
-
3709
- // Route through the subscription registry (subscriptions/listen streams).
3710
- if (this.subscriptions !== null) {
3711
- switch (method) {
3712
- case "notifications/tools/list_changed":
3713
- this.subscriptions.fanOut("toolsListChanged");
3714
- return;
3715
- case "notifications/prompts/list_changed":
3716
- this.subscriptions.fanOut("promptsListChanged");
3717
- return;
3718
- case "notifications/resources/list_changed":
3719
- this.subscriptions.fanOut("resourcesListChanged");
3720
- return;
3721
- case "notifications/resources/updated": {
3722
- const uri = isRecord(params) && typeof params["uri"] === "string"
3723
- ? params["uri"]
3724
- : undefined;
3725
- if (uri === undefined) {
3726
- this.log(
3727
- "[WARN] notifications/resources/updated requires a string 'uri' param; dropped",
3728
- );
3729
- return;
3730
- }
3731
- this.subscriptions.fanOutResourceUpdated(uri);
3732
- return;
3733
- }
3734
- default:
3735
- // subscriptions/listen carries only the four change types a client can
3736
- // opt into. Anything else — a request-scoped progress or log message —
3737
- // belongs on the response stream of the request it relates to, which is
3738
- // not something this method can reach. Say so rather than drop silently.
3739
- this.log(
3740
- `[WARN] sendNotification("${method}") has no delivery channel in stateless mode: ` +
3741
- "only the four subscriptions/listen change types can be pushed. " +
3742
- "Request-scoped notifications must travel on their own request's response stream.",
3743
- );
3744
- return;
3745
- }
3746
- }
3747
-
3748
- // For stdio mode, send via SDK transport
3749
- try {
3750
- this.mcpServer.server.notification({ method, params });
3751
- } catch {
3752
- // Transport may not support notifications yet (pre-initialized)
3753
- }
3754
- }
3755
-
3756
- /**
3757
- * Register a callback for the "initialized" notification.
3758
- * Called after client sends "initialized" (post-handshake).
3759
- */
3760
- onInitialized(callback: () => void): void {
3761
- this.initializedCallback = callback;
3762
- }
3763
-
3764
- private initializedCallback: (() => void) | null = null;
3765
-
3766
- /**
3767
- * Check if a handler result is a pre-formatted MCP result.
3768
- * Pre-formatted results have a `content` array and are passed through
3769
- * without re-wrapping. This supports proxy/gateway patterns.
3770
- */
3771
- private isPreformattedResult(
3772
- result: unknown,
3773
- ): result is {
3774
- content: Array<{ type: string; text: string }>;
3775
- _meta?: Record<string, unknown>;
3776
- } {
3777
- if (!result || typeof result !== "object") return false;
3778
- const obj = result as Record<string, unknown>;
3779
- return Array.isArray(obj.content) &&
3780
- obj.content.length > 0 &&
3781
- typeof obj.content[0] === "object" &&
3782
- obj.content[0] !== null &&
3783
- "type" in obj.content[0] &&
3784
- "text" in obj.content[0];
3785
- }
3786
-
3787
- /**
3788
- * Apply the spec-2026-07-28 result envelope when — and only when — the peer
3789
- * negotiated that revision.
3790
- *
3791
- * Always applies on the stateless transport, which only accepts 2026-07-28.
3792
- * Stdio mode passes `undefined` and stays on the legacy shape.
3793
- *
3794
- * Omitting the envelope for a genuinely legacy peer is safe in the other
3795
- * direction too: the spec instructs clients to read a missing `resultType` as
3796
- * `"complete"`.
3797
- *
3798
- * Every HTTP result path funnels through here. Adding a new one without it is
3799
- * the failure mode to watch for — hence the conformance test that walks the
3800
- * method table rather than asserting one endpoint at a time.
3801
- *
3802
- * @param negotiatedVersion Version from the request's `_meta`, or `undefined`
3803
- * where no per-request negotiation happens.
3804
- */
3805
- private stampResult(
3806
- result: Record<string, unknown>,
3807
- negotiatedVersion?: string,
3808
- resultType: "complete" | "task" = "complete",
3809
- ): Record<string, unknown> {
3810
- if (negotiatedVersion !== SPEC_2026_07_28) return result;
3811
- return {
3812
- ...completeResult(result, {
3813
- name: this.options.name,
3814
- version: this.options.version,
3815
- }),
3816
- resultType,
3817
- };
3818
- }
3819
-
3820
- /**
3821
- * Resolve the MRTR signing key once, warning if a deployment has none.
3822
- *
3823
- * A missing key is not an error: the spec permits unprotected `requestState`
3824
- * when tampering can cause nothing worse than the request failing. It is a
3825
- * loud warning because that condition is easy to believe and hard to verify.
3826
- */
3827
- /**
3828
- * Key lookup that reports failure instead of throwing.
3829
- *
3830
- * The `tools/call` call sites sit outside the tool try/catch, so a throw would
3831
- * reach the POST-level catch and surface as -32700 "Parse error" — the same trap
3832
- * the earlier throwing principal guard fell into. Returns a ready response
3833
- * instead.
3834
- */
3835
- private async getMrtrKeySafe(
3836
- id: unknown,
3837
- version: string,
3838
- ): Promise<{ key: CryptoKey | null } | { error: Response }> {
3839
- try {
3840
- return { key: await this.getMrtrKey() };
3841
- } catch (error) {
3842
- return {
3843
- error: jsonRpcResponse(
3844
- {
3845
- jsonrpc: "2.0",
3846
- id,
3847
- error: {
3848
- code: ErrorCode.InternalError,
3849
- message: "MRTR signing key is unavailable",
3850
- data: {
3851
- problem: "mrtr_key_unavailable",
3852
- detail: error instanceof Error ? error.message : String(error),
3853
- recovery:
3854
- "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
3855
- },
3856
- },
3857
- },
3858
- 500,
3859
- { "MCP-Protocol-Version": version },
3860
- ),
3861
- };
3862
- }
3863
- }
3864
-
3865
- private getMrtrKey(): Promise<CryptoKey | null> {
3866
- // Assigned synchronously, so two concurrent callers share one import rather
3867
- // than one of them observing a half-initialised state.
3868
- //
3869
- // A REJECTED import is un-memoised in the catch below: caching the rejection
3870
- // poisoned the instance permanently, and every later retry surfaced it through
3871
- // the POST-level catch as -32700 "Parse error" — wrong code, and no second
3872
- // attempt ever made. A transient WebCrypto failure should not be terminal.
3873
- this.mrtrKeyPromise ??= (async () => {
3874
- const hex = this.options.mrtr?.signingKey;
3875
- if (hex === undefined) {
3876
- this.log(
3877
- "[WARN] MRTR requestState is unprotected: no mrtr.signingKey configured. " +
3878
- "A client can tamper with it. Only acceptable when requestState " +
3879
- "influences nothing beyond whether the request succeeds.",
3880
- );
3881
- return null;
3882
- }
3883
- try {
3884
- return await importStateKey(hex);
3885
- } catch (error) {
3886
- // Drop the memoised rejection so a later request retries the import.
3887
- this.mrtrKeyPromise = null;
3888
- throw new Error(
3889
- `[McpApp] mrtr.signingKey could not be imported: ${
3890
- error instanceof Error ? error.message : String(error)
3891
- }`,
3892
- );
3893
- }
3894
- })();
3895
- return this.mrtrKeyPromise;
3896
- }
3897
-
3898
- /**
3899
- * Turn a handler's `InputRequiredSignal` into the wire result.
3900
- *
3901
- * Validates what the spec puts on the server rather than the client:
3902
- * - at least one of `inputRequests` / `requestState` must be present;
3903
- * - no input request may name a capability the client did not declare.
3904
- *
3905
- * A violation is the server author's bug, so it surfaces as `-32603` rather
3906
- * than being emitted as an invalid MRTR result for the client to puzzle over.
3907
- */
3908
- private async buildInputRequiredResult(
3909
- signal: InputRequiredSignal,
3910
- context: {
3911
- clientCapabilities: ClientCapabilities | undefined;
3912
- principal: string;
3913
- method: string;
3914
- /** Digest of the arguments as received, taken before the pipeline ran. */
3915
- paramsDigest: string;
3916
- },
3917
- ): Promise<
3918
- { ok: true; result: Record<string, unknown> } | {
3919
- ok: false;
3920
- message: string;
3921
- code: number;
3922
- data?: Record<string, unknown>;
3923
- }
3924
- > {
3925
- const requests = signal.inputRequests;
3926
-
3927
- // `Object.keys(null)` throws, and `inputRequests: null` survives JSON — so an
3928
- // unchecked map reached the generic tool-error path as a 200 instead of being
3929
- // classified as the malformed server output it is. Validated before enumerating.
3930
- if (requests !== undefined && !isRecord(requests)) {
3931
- return {
3932
- ok: false,
3933
- code: ErrorCode.InternalError,
3934
- message: "Malformed inputRequest: inputRequests must be an object",
3935
- };
3936
- }
3937
-
3938
- const hasRequests = requests !== undefined &&
3939
- Object.keys(requests).length > 0;
3940
-
3941
- if (!hasRequests && signal.requestState === undefined) {
3942
- return {
3943
- ok: false,
3944
- code: ErrorCode.InternalError,
3945
- message:
3946
- "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
3947
- };
3948
- }
3949
-
3950
- let canonicalRequests: Record<string, unknown> | undefined;
3951
- if (hasRequests) {
3952
- const check = checkInputRequestCapabilities(
3953
- requests as Record<string, InputRequestEntry>,
3954
- context.clientCapabilities as Record<string, unknown> | undefined,
3955
- );
3956
- if (!check.ok) {
3957
- // A structurally invalid input request is the SERVER's bug. Reporting it
3958
- // as -32021 told the client to declare a capability it already had, and
3959
- // hid the real fault behind a client-facing error.
3960
- if (check.kind === "malformed") {
3961
- return {
3962
- ok: false,
3963
- code: ErrorCode.InternalError,
3964
- message: `Malformed inputRequest: ${
3965
- check.missingCapabilities.join(", ")
3966
- }`,
3967
- };
3968
- }
3969
- // Spec rule 7 is a MUST NOT on the server: never ask for input the
3970
- // client cannot provide. Emitting it anyway would strand the request.
3971
- return {
3972
- ok: false,
3973
- code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
3974
- message:
3975
- `Cannot request input for capabilities the client did not declare: ${
3976
- check.missingCapabilities.join(", ")
3977
- }`,
3978
- // ClientCapabilities-shaped so a typed client can read it directly and
3979
- // learn which capability to declare.
3980
- data: {
3981
- // The check supplies a nested shape for sub-capabilities; otherwise
3982
- // the names are top-level keys.
3983
- requiredCapabilities: check.requiredCapabilities ??
3984
- Object.fromEntries(
3985
- check.missingCapabilities.map((cap) => [cap, {}]),
3986
- ),
3987
- },
3988
- };
3989
- }
3990
- canonicalRequests = check.canonicalRequests;
3991
- }
3992
-
3993
- // Seal the token so the retry can be proven legitimate. The payload holds
3994
- // only bindings — principal, method, argument digest, expiry, nonce — not
3995
- // application state: since the digest guarantees identical arguments, a
3996
- // handler rebuilds its context from those.
3997
- //
3998
- // The principal binding is only meaningful when auth is configured; see the
3999
- // verification site. Sealing happens AFTER the capability check on purpose —
4000
- // no point minting a token for a result that will be refused.
4001
- // Resolved here regardless of `needsKey` at ingress: a FIRST leg carries
4002
- // neither MRTR field and still needs a sealed token. A rejected import is
4003
- // reported as what it is rather than surfacing as a tool failure — the
4004
- // handler did nothing wrong.
4005
- let key: CryptoKey | null;
4006
- try {
4007
- key = await this.getMrtrKey();
4008
- } catch (error) {
4009
- return {
4010
- ok: false,
4011
- code: ErrorCode.InternalError,
4012
- message: "MRTR signing key is unavailable",
4013
- data: {
4014
- problem: "mrtr_key_unavailable",
4015
- detail: error instanceof Error ? error.message : String(error),
4016
- recovery:
4017
- "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
4018
- },
4019
- };
4020
- }
4021
- let requestState = signal.requestState;
4022
- if (key !== null) {
4023
- const ttl = this.options.mrtr?.defaultTtlSecs ?? 300;
4024
- requestState = await sealRequestState({
4025
- sub: context.principal,
4026
- method: context.method,
4027
- paramsDigest: context.paramsDigest,
4028
- exp: Math.floor(Date.now() / 1000) + ttl,
4029
- nonce: bytesToHexLocal(crypto.getRandomValues(new Uint8Array(16))),
4030
- }, key);
4031
- }
4032
-
4033
- // No `?? requests` fallback. Falling back to the handler's object would
4034
- // silently restore the very bypass this closes — a fallback that reopens a
4035
- // security hole is worse than a failure. If the invariant ever breaks, say so.
4036
- if (hasRequests && canonicalRequests === undefined) {
4037
- return {
4038
- ok: false,
4039
- code: ErrorCode.InternalError,
4040
- message:
4041
- "Internal invariant violated: inputRequests were not canonicalised before emission",
4042
- };
4043
- }
4044
-
4045
- // Serialisation can EMPTY the map: JSON drops keys whose value is `undefined`,
4046
- // so `{ ask: undefined }` canonicalises to `{}`. The at-least-one rule was
4047
- // checked against the original, so that emitted an InputRequiredResult with an
4048
- // empty map and — where no key is configured — no requestState either, leaving
4049
- // the client nothing to answer and no reason to retry.
4050
- const canonicalCount = canonicalRequests === undefined
4051
- ? 0
4052
- : Object.keys(canonicalRequests).length;
4053
- if (hasRequests && canonicalCount === 0) {
4054
- return {
4055
- ok: false,
4056
- code: ErrorCode.InternalError,
4057
- message:
4058
- "inputRequests contained no serialisable entries (keys with an undefined value are dropped by JSON)",
4059
- };
4060
- }
4061
- if (canonicalCount === 0 && requestState === undefined) {
4062
- return {
4063
- ok: false,
4064
- code: ErrorCode.InternalError,
4065
- message:
4066
- "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
4067
- };
4068
- }
4069
-
4070
- return {
4071
- ok: true,
4072
- result: {
4073
- resultType: "input_required",
4074
- // This path deliberately cannot use stampResult(): that would replace
4075
- // its `input_required` discriminator with `complete`. It is still a
4076
- // 2026 Result, though, so carry the same server identity envelope as
4077
- // every other response.
4078
- _meta: {
4079
- [STATELESS_SERVER_INFO_KEY]: {
4080
- name: this.options.name,
4081
- version: this.options.version,
4082
- },
4083
- },
4084
- // The clone the check inspected, NOT the handler's object. Serialising the
4085
- // original a second time lets a stateful `toJSON()` return a different
4086
- // value for the response than the gate approved.
4087
- ...(canonicalRequests !== undefined
4088
- ? { inputRequests: canonicalRequests }
4089
- : {}),
4090
- ...(requestState !== undefined ? { requestState } : {}),
4091
- },
4092
- };
4093
- }
4094
-
4095
- /**
4096
- * Reject a Tasks request from a client that did not declare the extension.
4097
- *
4098
- * Returns a ready 400 response to return, or `null` when the client is
4099
- * entitled to proceed. Two distinct spec rules converge here: a server
4100
- * **MUST NOT** hand a task to a non-declaring client, and **MUST** answer the
4101
- * missing-capability error when one calls `tasks/*`.
4102
- *
4103
- * `-32021` (`MissingRequiredClientCapability`) is the code, and
4104
- * `data.requiredCapabilities` is required to list what was missing — a client
4105
- * that gets this back needs to know which capability to add, not just that
4106
- * something was absent.
4107
- */
4108
- private requireTasksCapability(
4109
- clientCapabilities: ClientCapabilities | undefined,
4110
- id: unknown,
4111
- ): Response | null {
4112
- if (this.taskStore === null) {
4113
- return jsonRpcResponse(
4114
- {
4115
- jsonrpc: "2.0",
4116
- id,
4117
- error: {
4118
- code: ErrorCode.MethodNotFound,
4119
- message:
4120
- `Tasks extension is not enabled on this server (declare "${TASKS_EXTENSION_ID}" in McpAppOptions.extensions)`,
4121
- },
4122
- },
4123
- 404,
4124
- );
4125
- }
4126
-
4127
- const extensions = clientCapabilities?.extensions;
4128
- const declared = isRecord(extensions) &&
4129
- extensions[TASKS_EXTENSION_ID] !== undefined;
4130
- if (declared) return null;
4131
-
4132
- return jsonRpcResponse(
4133
- {
4134
- jsonrpc: "2.0",
4135
- id,
4136
- error: {
4137
- code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
4138
- message:
4139
- `Client did not declare the "${TASKS_EXTENSION_ID}" extension`,
4140
- // ClientCapabilities-shaped, per the schema: capability keys mapping
4141
- // to their settings object. An array of names would not deserialise
4142
- // into `ClientCapabilities` on a typed client.
4143
- data: {
4144
- requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } },
4145
- },
4146
- },
4147
- },
4148
- 400,
4149
- );
4150
- }
4151
-
4152
- /**
4153
- * Task status transitions, for pushing to subscribers.
4154
- *
4155
- * The spec's notification method is `notifications/tasks` — not a
4156
- * `tasks/`-prefixed name, which would collide with the request methods.
4157
- *
4158
- * Delivery goes out over `subscriptions/listen` once that route is wired
4159
- * (Track G); the registry exists but the transport does not yet open streams.
4160
- * Until then this is intentionally a no-op beyond the log: polling via
4161
- * `tasks/get` is the spec's default and works without it.
4162
- */
4163
- private onTaskChanged(task: DetailedTask): void {
4164
- this.log(`task ${task.taskId} → ${task.status}`);
4165
- }
4166
-
4167
- /**
4168
- * Add the required `CacheableResult` fields (spec 2026-07-28, SEP-2549).
4169
- *
4170
- * Applies to `tools/list`, `prompts/list`, `resources/list`, `resources/read`
4171
- * and `resources/templates/list`, where the final spec makes both fields
4172
- * required rather than optional. Same version gate as {@link stampResult}:
4173
- * neither field exists in an earlier revision.
4174
- *
4175
- * Both are hints — a client that ignores them stays correct, it just polls
4176
- * more often.
4177
- */
4178
- private withCacheHints(
4179
- result: Record<string, unknown>,
4180
- negotiatedVersion?: string,
4181
- request?: { readonly isMrtrRetry?: boolean },
4182
- ): Record<string, unknown> {
4183
- if (negotiatedVersion !== SPEC_2026_07_28) return result;
4184
-
4185
- // A result produced by an MRTR retry MUST NOT be cached: it depends on
4186
- // `inputResponses` / `requestState`, which are not part of the cache key, so
4187
- // a cache would serve it for a later request that supplied different input.
4188
- // Emitting no hints is how a server declines to make the result cacheable —
4189
- // clients read an absent ttlMs as 0.
4190
- if (request?.isMrtrRetry) return result;
4191
-
4192
- return {
4193
- ...result,
4194
- ttlMs: this.cacheTtlMs,
4195
- cacheScope: this.options.cache?.scope ?? "private",
4196
- };
4197
- }
4198
-
4199
- /**
4200
- * Capabilities advertised on `server/discover` and `initialize`.
4201
- *
4202
- * Single source of truth: these two responses used to build the same object
4203
- * independently, which is how they drift.
4204
- *
4205
- * `extensions` (spec 2026-07-28) is the declaration point for opt-in
4206
- * extensions such as `io.modelcontextprotocol/tasks`. It is emitted only when
4207
- * the consumer actually declares one — an empty `extensions: {}` would read as
4208
- * "this server supports no extensions", which is a stronger claim than we can
4209
- * make while MCP Apps support is de-facto (via `ui://` resources) rather than
4210
- * declared. Wire it up here once the Apps extension identifier is pinned.
4211
- */
4212
- private buildServerCapabilities(): Record<string, unknown> {
4213
- const { extensions } = this.options;
4214
- // The declaration in options is the single source of truth: `taskStore` is
4215
- // created from it, so advertising and behaviour cannot drift apart.
4216
- return {
4217
- tools: {},
4218
- // Capability lifetime is defined by installed handlers, not the current
4219
- // Map size. A dynamic registry may correctly be empty at initialize and
4220
- // gain resources later; `listChanged` tells clients to refresh then.
4221
- resources: this.resourceHandlersInstalled
4222
- ? { listChanged: true }
4223
- : undefined,
4224
- ...(extensions && Object.keys(extensions).length > 0
4225
- ? { extensions }
4226
- : {}),
4227
- };
4228
- }
4229
-
4230
- /**
4231
- * Build the tools/list response, filtering out app-only tools
4232
- * and passing through outputSchema/annotations when defined.
4233
- */
4234
- private buildToolListing(): Array<Record<string, unknown>> {
4235
- return Array.from(this.tools.values())
4236
- .filter((t) => {
4237
- const vis = (t._meta?.ui as { visibility?: unknown } | undefined)
4238
- ?.visibility;
4239
- if (Array.isArray(vis) && !vis.includes("model")) return false;
4240
- return true;
4241
- })
4242
- .map((t) => {
4243
- const entry: Record<string, unknown> = {
4244
- name: t.name,
4245
- description: t.description,
4246
- inputSchema: t.inputSchema,
4247
- _meta: t._meta,
4248
- };
4249
- if (t.outputSchema !== undefined) entry.outputSchema = t.outputSchema;
4250
- if (t.annotations !== undefined) entry.annotations = t.annotations;
4251
- return entry;
4252
- })
4253
- // Spec 2026-07-28 (minor change 3): return tools in a deterministic order.
4254
- // It lets clients cache the list and improves LLM prompt-cache hit rates.
4255
- //
4256
- // Map iteration is already insertion-ordered, so this only matters where
4257
- // registration order itself is unstable — which it is for the relay/proxy
4258
- // case, where tools are registered as child servers are discovered
4259
- // asynchronously. Sorting by name makes the output independent of who
4260
- // answered first.
4261
- //
4262
- // Deliberately not `localeCompare`: that orders differently per host
4263
- // locale, reintroducing the very non-determinism being removed here.
4264
- .sort((a, b) =>
4265
- (a.name as string) < (b.name as string)
4266
- ? -1
4267
- : (a.name as string) > (b.name as string)
4268
- ? 1
4269
- : 0
4270
- );
4271
- }
4272
-
4273
- /**
4274
- * Check if a handler result is a StructuredToolResult
4275
- * (has content as string + structuredContent as object).
4276
- */
4277
- private isStructuredToolResult(
4278
- result: unknown,
4279
- ): result is StructuredToolResult {
4280
- if (!result || typeof result !== "object") return false;
4281
- const obj = result as Record<string, unknown>;
4282
- return (
4283
- typeof obj.content === "string" &&
4284
- obj.structuredContent !== null &&
4285
- obj.structuredContent !== undefined &&
4286
- typeof obj.structuredContent === "object" &&
4287
- !Array.isArray(obj.structuredContent)
4288
- );
4289
- }
4290
-
4291
- /**
4292
- * Build a CallToolResult from the handler's return value.
4293
- * Priority: preformatted > structuredToolResult > plain value.
4294
- */
4295
- private buildToolCallResult(
4296
- toolName: string,
4297
- result: unknown,
4298
- ): Record<string, unknown> {
4299
- // Proxy/gateway pattern — pass through as-is
4300
- if (this.isPreformattedResult(result)) {
4301
- return canonicaliseWireResult(result as Record<string, unknown>);
4302
- }
4303
-
4304
- const tool = this.tools.get(toolName);
4305
-
4306
- // StructuredToolResult: separate content (for LLM) and structuredContent (for viewer)
4307
- if (this.isStructuredToolResult(result)) {
4308
- const r: Record<string, unknown> = {
4309
- content: [{ type: "text", text: result.content }],
4310
- structuredContent: result.structuredContent,
4311
- };
4312
- if (tool?._meta) r._meta = tool._meta;
4313
- return canonicaliseWireResult(r);
4314
- }
4315
-
4316
- // Plain value: JSON-stringify into content[0].text
4317
- const r: Record<string, unknown> = {
4318
- content: [{
4319
- type: "text",
4320
- text: typeof result === "string"
4321
- ? result
4322
- : JSON.stringify(result, null, 2),
4323
- }],
4324
- };
4325
- if (tool?._meta) r._meta = tool._meta;
4326
- return canonicaliseWireResult(r);
4327
- }
4328
-
4329
- /**
4330
- * Handle a tool execution error using the configured toolErrorMapper.
4331
- * Returns an isError result if the mapper handles it, otherwise rethrows.
4332
- */
4333
- private handleToolError(
4334
- error: unknown,
4335
- toolName: string,
4336
- ): Record<string, unknown> {
4337
- const mapper = this.options.toolErrorMapper;
4338
- if (mapper) {
4339
- let msg: string | null;
4340
- try {
4341
- msg = mapper(error, toolName);
4342
- } catch (mapperError) {
4343
- this.log(
4344
- `toolErrorMapper threw for tool ${toolName}: ${
4345
- mapperError instanceof Error
4346
- ? mapperError.message
4347
- : String(mapperError)
4348
- } (original error: ${
4349
- error instanceof Error ? error.message : String(error)
4350
- })`,
4351
- );
4352
- // Fall through to rethrow original error
4353
- msg = null;
4354
- }
4355
- if (msg !== null) {
4356
- this.log(`Tool ${toolName} returned business error: ${msg}`);
4357
- return {
4358
- content: [{ type: "text", text: msg }],
4359
- isError: true,
4360
- };
4361
- }
4362
- }
4363
- // No mapper or mapper returned null → rethrow
4364
- this.log(
4365
- `Error executing tool ${toolName}: ${
4366
- error instanceof Error ? error.message : String(error)
4367
- }`,
4368
- );
4369
- throw error;
4370
- }
4371
-
4372
- /**
4373
- * Log message using custom logger or stderr
4374
- */
4375
- private log(msg: string): void {
4376
- if (this.options.logger) {
4377
- this.options.logger(msg);
4378
- } else {
4379
- console.error(`[${this.options.name}] ${msg}`);
4380
- }
4381
- }
4382
- }
4383
-
4384
- // ── registerViewers types ──────────────────────────────────────────
4385
-
4386
- /** Configuration for registerViewers() */
4387
- export interface RegisterViewersConfig {
4388
- /** URI prefix — viewers get `ui://{prefix}/{viewerName}` */
4389
- prefix: string;
4390
- /** import.meta.url of the consumer's server.ts (for resolving dist paths) */
4391
- moduleUrl: string;
4392
- /** Check if a path or URL exists. Receives a filesystem path for local
4393
- * modules (file://) or an HTTPS URL for remote modules (JSR, CDN). */
4394
- exists: (path: string) => boolean;
4395
- /** Read a file and return its content as string */
4396
- readFile: (path: string) => string | Promise<string>;
4397
- /** Explicit list of viewer names. If omitted, use `discover`. */
4398
- viewers?: string[];
4399
- /** Auto-discover viewers by scanning a directory */
4400
- discover?: {
4401
- uiDir: string;
4402
- } & DiscoverViewersFS;
4403
- /** Custom function to generate human-readable names. Default: kebab-to-Title. */
4404
- humanName?: (viewerName: string) => string;
4405
- /** MCP Apps CSP — declares external domains the viewer needs (tiles, APIs, CDNs).
4406
- * Uses McpUiCsp from @casys/mcp-compose (resourceDomains, connectDomains). */
4407
- csp?: {
4408
- resourceDomains?: string[];
4409
- connectDomains?: string[];
4410
- frameDomains?: string[];
4411
- };
4412
- }
4413
-
4414
- /** Summary returned by registerViewers() */
4415
- export interface RegisterViewersSummary {
4416
- registered: string[];
4417
- skipped: string[];
4418
- }
4419
-
4420
- /** Default: "invoice-viewer" → "Invoice Viewer" */
4421
- function defaultHumanName(name: string): string {
4422
- return name
4423
- .split("-")
4424
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
4425
- .join(" ");
4426
- }