@casys/mcp-server 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/CHANGELOG.md +1779 -0
  2. package/LICENSE +21 -0
  3. package/README.md +19 -5
  4. package/esm/_dnt.polyfills.d.ts +12 -0
  5. package/esm/_dnt.polyfills.d.ts.map +1 -0
  6. package/esm/_dnt.polyfills.js +15 -0
  7. package/esm/_dnt.shims.d.ts +2 -0
  8. package/esm/_dnt.shims.d.ts.map +1 -0
  9. package/esm/_dnt.shims.js +57 -0
  10. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
  11. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
  12. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
  13. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
  14. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
  15. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
  16. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
  17. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
  18. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
  19. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
  20. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
  21. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
  22. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
  23. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
  24. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
  25. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
  26. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
  27. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
  28. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
  29. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
  30. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
  31. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
  32. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
  33. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
  34. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
  35. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
  36. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
  37. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
  38. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
  39. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
  40. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
  41. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
  42. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
  43. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
  44. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
  45. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
  46. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
  47. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
  48. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
  49. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
  50. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
  51. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
  52. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
  53. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
  54. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
  55. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
  56. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
  57. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
  58. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
  59. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
  60. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
  61. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
  62. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
  63. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
  64. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
  65. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
  66. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
  67. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
  68. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
  69. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
  70. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
  71. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
  72. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
  73. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
  74. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
  75. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
  76. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
  77. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
  78. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
  79. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
  80. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
  81. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
  82. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
  83. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
  84. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
  85. package/esm/mod.d.ts +102 -0
  86. package/esm/mod.d.ts.map +1 -0
  87. package/esm/mod.js +103 -0
  88. package/esm/package.json +3 -0
  89. package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
  90. package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
  91. package/esm/src/auth/as-metadata-proxy.js +171 -0
  92. package/esm/src/auth/config.d.ts +117 -0
  93. package/esm/src/auth/config.d.ts.map +1 -0
  94. package/esm/src/auth/config.js +219 -0
  95. package/esm/src/auth/jwt-provider.d.ts +157 -0
  96. package/esm/src/auth/jwt-provider.d.ts.map +1 -0
  97. package/esm/src/auth/jwt-provider.js +187 -0
  98. package/esm/src/auth/middleware.d.ts +61 -0
  99. package/esm/src/auth/middleware.d.ts.map +1 -0
  100. package/esm/src/auth/middleware.js +209 -0
  101. package/esm/src/auth/mod.d.ts +23 -0
  102. package/esm/src/auth/mod.d.ts.map +1 -0
  103. package/esm/src/auth/mod.js +27 -0
  104. package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
  105. package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
  106. package/esm/src/auth/multi-tenant-middleware.js +128 -0
  107. package/esm/src/auth/presets.d.ts +231 -0
  108. package/esm/src/auth/presets.d.ts.map +1 -0
  109. package/esm/src/auth/presets.js +223 -0
  110. package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
  111. package/esm/src/auth/provider.d.ts.map +1 -0
  112. package/esm/src/auth/provider.js +34 -0
  113. package/esm/src/auth/scope-middleware.d.ts +30 -0
  114. package/esm/src/auth/scope-middleware.d.ts.map +1 -0
  115. package/esm/src/auth/scope-middleware.js +48 -0
  116. package/esm/src/auth/static-token-provider.d.ts +155 -0
  117. package/esm/src/auth/static-token-provider.d.ts.map +1 -0
  118. package/esm/src/auth/static-token-provider.js +256 -0
  119. package/esm/src/auth/types.d.ts +151 -0
  120. package/esm/src/auth/types.d.ts.map +1 -0
  121. package/esm/src/auth/types.js +64 -0
  122. package/esm/src/client-auth/callback-server.d.ts +34 -0
  123. package/esm/src/client-auth/callback-server.d.ts.map +1 -0
  124. package/esm/src/client-auth/callback-server.js +141 -0
  125. package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
  126. package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
  127. package/esm/src/client-auth/client-id-metadata.js +149 -0
  128. package/esm/src/client-auth/connect.d.ts +32 -0
  129. package/esm/src/client-auth/connect.d.ts.map +1 -0
  130. package/esm/src/client-auth/connect.js +47 -0
  131. package/esm/src/client-auth/mod.d.ts +19 -0
  132. package/esm/src/client-auth/mod.d.ts.map +1 -0
  133. package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
  134. package/esm/src/client-auth/provider.d.ts +78 -0
  135. package/esm/src/client-auth/provider.d.ts.map +1 -0
  136. package/esm/src/client-auth/provider.js +246 -0
  137. package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
  138. package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
  139. package/esm/src/client-auth/token-store/file-store.js +62 -0
  140. package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
  141. package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
  142. package/esm/src/client-auth/token-store/memory-store.js +25 -0
  143. package/esm/src/client-auth/types.d.ts +89 -0
  144. package/esm/src/client-auth/types.d.ts.map +1 -0
  145. package/esm/src/client-auth/types.js +10 -0
  146. package/esm/src/concurrency/rate-limiter.d.ts +87 -0
  147. package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
  148. package/esm/src/concurrency/rate-limiter.js +165 -0
  149. package/esm/src/concurrency/request-queue.d.ts +71 -0
  150. package/esm/src/concurrency/request-queue.d.ts.map +1 -0
  151. package/esm/src/concurrency/request-queue.js +128 -0
  152. package/esm/src/http/body.d.ts +20 -0
  153. package/esm/src/http/body.d.ts.map +1 -0
  154. package/esm/src/http/body.js +63 -0
  155. package/esm/src/http/request-guards.d.ts +54 -0
  156. package/esm/src/http/request-guards.d.ts.map +1 -0
  157. package/esm/src/http/request-guards.js +114 -0
  158. package/esm/src/http/wire.d.ts +26 -0
  159. package/esm/src/http/wire.d.ts.map +1 -0
  160. package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
  161. package/esm/src/inspector/launcher.d.ts +48 -0
  162. package/esm/src/inspector/launcher.d.ts.map +1 -0
  163. package/esm/src/inspector/launcher.js +100 -0
  164. package/esm/src/mcp-app.d.ts +728 -0
  165. package/esm/src/mcp-app.d.ts.map +1 -0
  166. package/esm/src/mcp-app.js +3530 -0
  167. package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
  168. package/esm/src/middleware/backpressure.d.ts.map +1 -0
  169. package/esm/src/middleware/backpressure.js +31 -0
  170. package/esm/src/middleware/mod.d.ts +11 -0
  171. package/esm/src/middleware/mod.d.ts.map +1 -0
  172. package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
  173. package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
  174. package/esm/src/middleware/rate-limit.d.ts.map +1 -0
  175. package/esm/src/middleware/rate-limit.js +33 -0
  176. package/esm/src/middleware/runner.d.ts +32 -0
  177. package/esm/src/middleware/runner.d.ts.map +1 -0
  178. package/esm/src/middleware/runner.js +49 -0
  179. package/esm/src/middleware/types.d.ts +76 -0
  180. package/esm/src/middleware/types.d.ts.map +1 -0
  181. package/esm/src/middleware/types.js +9 -0
  182. package/esm/src/middleware/validation.d.ts +24 -0
  183. package/esm/src/middleware/validation.d.ts.map +1 -0
  184. package/esm/src/middleware/validation.js +30 -0
  185. package/esm/src/mrtr/capability-check.d.ts +75 -0
  186. package/esm/src/mrtr/capability-check.d.ts.map +1 -0
  187. package/esm/src/mrtr/capability-check.js +233 -0
  188. package/esm/src/mrtr/mod.d.ts +18 -0
  189. package/esm/src/mrtr/mod.d.ts.map +1 -0
  190. package/esm/src/mrtr/mod.js +12 -0
  191. package/esm/src/mrtr/replay-store.d.ts +50 -0
  192. package/esm/src/mrtr/replay-store.d.ts.map +1 -0
  193. package/esm/src/mrtr/replay-store.js +61 -0
  194. package/esm/src/mrtr/request-state.d.ts +181 -0
  195. package/esm/src/mrtr/request-state.d.ts.map +1 -0
  196. package/esm/src/mrtr/request-state.js +313 -0
  197. package/esm/src/mrtr/retry-guard.d.ts +61 -0
  198. package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
  199. package/esm/src/mrtr/retry-guard.js +53 -0
  200. package/esm/src/mrtr/types.d.ts +99 -0
  201. package/esm/src/mrtr/types.d.ts.map +1 -0
  202. package/esm/src/mrtr/types.js +14 -0
  203. package/esm/src/observability/metrics.d.ts +104 -0
  204. package/esm/src/observability/metrics.d.ts.map +1 -0
  205. package/esm/src/observability/metrics.js +207 -0
  206. package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
  207. package/esm/src/observability/mod.d.ts.map +1 -0
  208. package/esm/src/observability/mod.js +11 -0
  209. package/esm/src/observability/otel.d.ts +73 -0
  210. package/esm/src/observability/otel.d.ts.map +1 -0
  211. package/esm/src/observability/otel.js +260 -0
  212. package/esm/src/runtime/runtime.d.ts +10 -0
  213. package/esm/src/runtime/runtime.d.ts.map +1 -0
  214. package/esm/src/runtime/runtime.deno.d.ts +50 -0
  215. package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
  216. package/esm/src/runtime/runtime.deno.js +120 -0
  217. package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
  218. package/esm/src/runtime/runtime.node.d.ts +51 -0
  219. package/esm/src/runtime/runtime.node.d.ts.map +1 -0
  220. package/esm/src/runtime/runtime.node.js +268 -0
  221. package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
  222. package/esm/src/runtime/types.d.ts.map +1 -0
  223. package/esm/src/runtime/types.js +12 -0
  224. package/esm/src/security/channel-hmac.d.ts +43 -0
  225. package/esm/src/security/channel-hmac.d.ts.map +1 -0
  226. package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
  227. package/esm/src/security/csp.d.ts +50 -0
  228. package/esm/src/security/csp.d.ts.map +1 -0
  229. package/esm/src/security/csp.js +63 -0
  230. package/esm/src/security/message-signer.d.ts +88 -0
  231. package/esm/src/security/message-signer.d.ts.map +1 -0
  232. package/esm/src/security/message-signer.js +166 -0
  233. package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
  234. package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
  235. package/esm/src/subscriptions/subscription-registry.js +406 -0
  236. package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
  237. package/esm/src/tasks/mod.d.ts.map +1 -0
  238. package/esm/src/tasks/mod.js +11 -0
  239. package/esm/src/tasks/task-store.d.ts +342 -0
  240. package/esm/src/tasks/task-store.d.ts.map +1 -0
  241. package/esm/src/tasks/task-store.js +649 -0
  242. package/esm/src/transport/request-headers.d.ts +145 -0
  243. package/esm/src/transport/request-headers.d.ts.map +1 -0
  244. package/esm/src/transport/request-headers.js +525 -0
  245. package/esm/src/types.d.ts +776 -0
  246. package/esm/src/types.d.ts.map +1 -0
  247. package/esm/src/types.js +92 -0
  248. package/esm/src/ui/viewer-utils.d.ts +45 -0
  249. package/esm/src/ui/viewer-utils.d.ts.map +1 -0
  250. package/esm/src/ui/viewer-utils.js +97 -0
  251. package/esm/src/validation/schema-validator.d.ts +115 -0
  252. package/esm/src/validation/schema-validator.d.ts.map +1 -0
  253. package/esm/src/validation/schema-validator.js +249 -0
  254. package/package.json +35 -23
  255. package/mod.ts +0 -302
  256. package/src/auth/as-metadata-proxy.ts +0 -288
  257. package/src/auth/config.ts +0 -368
  258. package/src/auth/jwt-provider.ts +0 -327
  259. package/src/auth/middleware.ts +0 -257
  260. package/src/auth/mod.ts +0 -89
  261. package/src/auth/multi-tenant-middleware.ts +0 -236
  262. package/src/auth/presets.ts +0 -351
  263. package/src/auth/scope-middleware.ts +0 -59
  264. package/src/auth/static-token-provider.ts +0 -197
  265. package/src/auth/types.ts +0 -207
  266. package/src/client-auth/callback-server.ts +0 -166
  267. package/src/client-auth/client-id-metadata.ts +0 -260
  268. package/src/client-auth/connect.ts +0 -72
  269. package/src/client-auth/provider.ts +0 -300
  270. package/src/client-auth/token-store/file-store.ts +0 -73
  271. package/src/client-auth/token-store/memory-store.ts +0 -32
  272. package/src/client-auth/types.ts +0 -95
  273. package/src/concurrency/rate-limiter.ts +0 -190
  274. package/src/concurrency/request-queue.ts +0 -140
  275. package/src/http/body.ts +0 -72
  276. package/src/http/request-guards.ts +0 -137
  277. package/src/inspector/launcher.ts +0 -131
  278. package/src/mcp-app.ts +0 -4426
  279. package/src/middleware/runner.ts +0 -63
  280. package/src/middleware/types.ts +0 -104
  281. package/src/middleware/validation.ts +0 -28
  282. package/src/mrtr/capability-check.ts +0 -303
  283. package/src/mrtr/mod.ts +0 -46
  284. package/src/mrtr/replay-store.ts +0 -103
  285. package/src/mrtr/request-state.ts +0 -435
  286. package/src/mrtr/types.ts +0 -107
  287. package/src/observability/metrics.ts +0 -336
  288. package/src/observability/otel.ts +0 -330
  289. package/src/runtime/runtime.deno.ts +0 -149
  290. package/src/runtime/runtime.node.ts +0 -324
  291. package/src/security/csp.ts +0 -89
  292. package/src/security/message-signer.ts +0 -223
  293. package/src/subscriptions/subscription-registry.ts +0 -558
  294. package/src/tasks/task-store.ts +0 -1014
  295. package/src/testdata/stdio-e2e-server.ts +0 -110
  296. package/src/transport/request-headers.ts +0 -661
  297. package/src/types.ts +0 -907
  298. package/src/ui/viewer-utils.ts +0 -117
  299. package/src/validation/schema-validator.ts +0 -307
@@ -0,0 +1,112 @@
1
+ /**
2
+ * AS Metadata Proxy for DCR compatibility discovery.
3
+ *
4
+ * Creates a Web Standard request handler that serves an RFC 8414
5
+ * Authorization Server Metadata document enriched with
6
+ * `registration_endpoint` (RFC 7591). This is a compatibility path for
7
+ * MCP clients and IdPs that still rely on Dynamic Client Registration
8
+ * (DCR), which is now optional (`MAY`) in the 2025-11-25 MCP spec.
9
+ *
10
+ * For new OAuth client integrations, prefer the spec-preferred Client ID
11
+ * Metadata Documents (CIMD) on the client side. See
12
+ * `src/client-auth/client-id-metadata.ts`.
13
+ *
14
+ * **Issuer field note (RFC 8414 §3.2)**:
15
+ * The `issuer` field in the served metadata will be the upstream IdP's
16
+ * issuer, not the URL where this handler is served. This intentionally
17
+ * violates RFC 8414 §3.2 (`issuer` MUST match the AS URL) because
18
+ * overriding `issuer` would cause JWT `iss` claim mismatches — the IdP
19
+ * still issues tokens with its own `iss`, and clients verify
20
+ * `token.iss === metadata.issuer`. The metadata-URL mismatch is the
21
+ * lesser evil for this compatibility path and is not needed when clients
22
+ * use CIMD or the upstream IdP ships native registration discovery.
23
+ *
24
+ * @module lib/server/auth/as-metadata-proxy
25
+ */
26
+ /**
27
+ * Options for {@link createAsMetadataHandler}.
28
+ *
29
+ * Provide exactly one of:
30
+ * - `upstreamMetadataUrl` — full URL of the upstream metadata document
31
+ * - `upstreamIssuer` — OIDC issuer (derives `/.well-known/openid-configuration`)
32
+ *
33
+ * Providing both or neither throws at construction time.
34
+ */
35
+ export interface AsMetadataProxyOptions {
36
+ /**
37
+ * Full URL of the upstream AS metadata document to proxy.
38
+ *
39
+ * IdP-agnostic — pass the appropriate discovery endpoint:
40
+ * - OIDC providers: `https://idp.example.com/.well-known/openid-configuration`
41
+ * - RFC 8414 AS: `https://as.example.com/.well-known/oauth-authorization-server`
42
+ * - Custom paths: any URL that returns a JSON metadata document
43
+ *
44
+ * Mutually exclusive with `upstreamIssuer`.
45
+ */
46
+ upstreamMetadataUrl?: string;
47
+ /**
48
+ * OIDC issuer URL (e.g., `https://my-tenant.zitadel.cloud`).
49
+ * Convenience shorthand — derives `{upstreamIssuer}/.well-known/openid-configuration`.
50
+ *
51
+ * Mutually exclusive with `upstreamMetadataUrl`.
52
+ */
53
+ upstreamIssuer?: string;
54
+ /**
55
+ * Absolute HTTPS URL of the RFC 7591 DCR endpoint that the MCP server
56
+ * exposes (implemented separately by the consumer — outside lib scope).
57
+ * Injected as `registration_endpoint` in the enriched metadata.
58
+ *
59
+ * Must be a valid absolute HTTP(S) URL (validated at construction time).
60
+ */
61
+ registrationEndpoint: string;
62
+ /**
63
+ * TTL for the upstream metadata cache in milliseconds.
64
+ * @default 86_400_000 (24 hours)
65
+ *
66
+ * Uses stale-while-revalidate: serves cached metadata even after
67
+ * expiry while refreshing in the background.
68
+ */
69
+ cacheTtlMs?: number;
70
+ /**
71
+ * Additional RFC 8414 fields to inject or override in the metadata
72
+ * (beyond `registration_endpoint`). Useful for overriding
73
+ * `scopes_supported`, adding `code_challenge_methods_supported`, etc.
74
+ *
75
+ * **Warning**: avoid overriding `issuer` — see module-level JSDoc
76
+ * for why this causes JWT validation failures.
77
+ */
78
+ extraFields?: Record<string, unknown>;
79
+ /**
80
+ * Custom `fetch` implementation. Defaults to `globalThis.fetch`.
81
+ *
82
+ * Use for dependency injection in tests, or for advanced scenarios
83
+ * like mTLS, custom headers, or retry wrappers.
84
+ */
85
+ fetch?: typeof globalThis.fetch;
86
+ }
87
+ /**
88
+ * Creates a Web Standard request handler that serves an RFC 8414
89
+ * Authorization Server Metadata document enriched with
90
+ * `registration_endpoint`.
91
+ *
92
+ * The handler is framework-agnostic — mount it in Fresh, Hono, Express
93
+ * (via adapter), or any framework that accepts `(Request) => Response`.
94
+ *
95
+ * @example Explicit metadata URL (any AS)
96
+ * ```typescript
97
+ * const handler = createAsMetadataHandler({
98
+ * upstreamMetadataUrl: "https://as.example.com/.well-known/oauth-authorization-server",
99
+ * registrationEndpoint: "https://my-app.example.com/oauth/register",
100
+ * });
101
+ * ```
102
+ *
103
+ * @example OIDC issuer shorthand
104
+ * ```typescript
105
+ * const handler = createAsMetadataHandler({
106
+ * upstreamIssuer: "https://my-tenant.zitadel.cloud",
107
+ * registrationEndpoint: "https://my-app.example.com/oauth/register",
108
+ * });
109
+ * ```
110
+ */
111
+ export declare function createAsMetadataHandler(options: AsMetadataProxyOptions): (req: Request) => Promise<Response>;
112
+ //# sourceMappingURL=as-metadata-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"as-metadata-proxy.d.ts","sourceRoot":"","sources":["../../../src/src/auth/as-metadata-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAIH;;;;;;;;GAQG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;OASG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;;;;OAMG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAE7B;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEtC;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AA0DD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,sBAAsB,GAC9B,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CA8GrC"}
@@ -0,0 +1,171 @@
1
+ /**
2
+ * AS Metadata Proxy for DCR compatibility discovery.
3
+ *
4
+ * Creates a Web Standard request handler that serves an RFC 8414
5
+ * Authorization Server Metadata document enriched with
6
+ * `registration_endpoint` (RFC 7591). This is a compatibility path for
7
+ * MCP clients and IdPs that still rely on Dynamic Client Registration
8
+ * (DCR), which is now optional (`MAY`) in the 2025-11-25 MCP spec.
9
+ *
10
+ * For new OAuth client integrations, prefer the spec-preferred Client ID
11
+ * Metadata Documents (CIMD) on the client side. See
12
+ * `src/client-auth/client-id-metadata.ts`.
13
+ *
14
+ * **Issuer field note (RFC 8414 §3.2)**:
15
+ * The `issuer` field in the served metadata will be the upstream IdP's
16
+ * issuer, not the URL where this handler is served. This intentionally
17
+ * violates RFC 8414 §3.2 (`issuer` MUST match the AS URL) because
18
+ * overriding `issuer` would cause JWT `iss` claim mismatches — the IdP
19
+ * still issues tokens with its own `iss`, and clients verify
20
+ * `token.iss === metadata.issuer`. The metadata-URL mismatch is the
21
+ * lesser evil for this compatibility path and is not needed when clients
22
+ * use CIMD or the upstream IdP ships native registration discovery.
23
+ *
24
+ * @module lib/server/auth/as-metadata-proxy
25
+ */
26
+ // ─── Implementation ──────────────────────────────────────────────────
27
+ function stripTrailingSlash(url) {
28
+ return url.endsWith("/") ? url.slice(0, -1) : url;
29
+ }
30
+ /**
31
+ * Validates that a string is a parseable absolute HTTP(S) URL.
32
+ * Throws at construction time for fast failure.
33
+ */
34
+ function validateUrl(value, label) {
35
+ try {
36
+ const parsed = new URL(value);
37
+ if (!parsed.protocol.startsWith("http")) {
38
+ throw new Error(`expected http(s) scheme`);
39
+ }
40
+ }
41
+ catch (cause) {
42
+ throw new Error(`AsMetadataProxyOptions.${label} is not a valid HTTP(S) URL: "${value}"`, { cause });
43
+ }
44
+ }
45
+ /**
46
+ * Resolves the upstream metadata URL from the flat options.
47
+ * Enforces mutual exclusivity: exactly one of upstreamMetadataUrl
48
+ * or upstreamIssuer must be provided.
49
+ */
50
+ function resolveMetadataUrl(options) {
51
+ const { upstreamMetadataUrl, upstreamIssuer } = options;
52
+ const hasUrl = upstreamMetadataUrl !== undefined;
53
+ const hasIssuer = upstreamIssuer !== undefined;
54
+ if (hasUrl && hasIssuer) {
55
+ throw new Error("AsMetadataProxyOptions: provide either upstreamMetadataUrl or upstreamIssuer, not both");
56
+ }
57
+ if (!hasUrl && !hasIssuer) {
58
+ throw new Error("AsMetadataProxyOptions: one of upstreamMetadataUrl or upstreamIssuer is required");
59
+ }
60
+ if (hasUrl) {
61
+ validateUrl(upstreamMetadataUrl, "upstreamMetadataUrl");
62
+ return upstreamMetadataUrl;
63
+ }
64
+ validateUrl(upstreamIssuer, "upstreamIssuer");
65
+ return `${stripTrailingSlash(upstreamIssuer)}/.well-known/openid-configuration`;
66
+ }
67
+ /**
68
+ * Creates a Web Standard request handler that serves an RFC 8414
69
+ * Authorization Server Metadata document enriched with
70
+ * `registration_endpoint`.
71
+ *
72
+ * The handler is framework-agnostic — mount it in Fresh, Hono, Express
73
+ * (via adapter), or any framework that accepts `(Request) => Response`.
74
+ *
75
+ * @example Explicit metadata URL (any AS)
76
+ * ```typescript
77
+ * const handler = createAsMetadataHandler({
78
+ * upstreamMetadataUrl: "https://as.example.com/.well-known/oauth-authorization-server",
79
+ * registrationEndpoint: "https://my-app.example.com/oauth/register",
80
+ * });
81
+ * ```
82
+ *
83
+ * @example OIDC issuer shorthand
84
+ * ```typescript
85
+ * const handler = createAsMetadataHandler({
86
+ * upstreamIssuer: "https://my-tenant.zitadel.cloud",
87
+ * registrationEndpoint: "https://my-app.example.com/oauth/register",
88
+ * });
89
+ * ```
90
+ */
91
+ export function createAsMetadataHandler(options) {
92
+ // ── Fail-fast validation at construction time ──
93
+ const metadataUrl = resolveMetadataUrl(options);
94
+ validateUrl(options.registrationEndpoint, "registrationEndpoint");
95
+ if (options.cacheTtlMs !== undefined &&
96
+ (options.cacheTtlMs < 0 || !Number.isFinite(options.cacheTtlMs))) {
97
+ throw new Error("AsMetadataProxyOptions.cacheTtlMs must be a non-negative finite number");
98
+ }
99
+ const { registrationEndpoint, cacheTtlMs = 24 * 60 * 60 * 1000, extraFields, fetch: fetchFn = globalThis.fetch, } = options;
100
+ let cached = null;
101
+ let refreshing = false;
102
+ async function fetchUpstream() {
103
+ const res = await fetchFn(metadataUrl, {
104
+ signal: AbortSignal.timeout(10_000),
105
+ });
106
+ if (!res.ok) {
107
+ throw new Error(`AS metadata fetch failed: ${res.status} from ${metadataUrl}`);
108
+ }
109
+ const body = await res.json();
110
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
111
+ throw new Error(`AS metadata from ${metadataUrl} is not a JSON object (got ${Array.isArray(body) ? "array" : typeof body})`);
112
+ }
113
+ if (typeof body.issuer !== "string") {
114
+ throw new Error(`AS metadata from ${metadataUrl} is missing required 'issuer' field`);
115
+ }
116
+ return body;
117
+ }
118
+ async function getMetadata() {
119
+ const now = Date.now();
120
+ // Fresh cache hit
121
+ if (cached && now - cached.fetchedAt < cacheTtlMs) {
122
+ return cached.metadata;
123
+ }
124
+ // Stale-while-revalidate: serve stale, refresh in background
125
+ if (cached) {
126
+ if (!refreshing) {
127
+ refreshing = true;
128
+ fetchUpstream()
129
+ .then((m) => {
130
+ cached = { metadata: m, fetchedAt: Date.now() };
131
+ })
132
+ .catch((e) => console.error("[as-metadata-proxy] background refresh failed:", e))
133
+ .finally(() => {
134
+ refreshing = false;
135
+ });
136
+ }
137
+ return cached.metadata;
138
+ }
139
+ // Cold start: must await
140
+ const metadata = await fetchUpstream();
141
+ cached = { metadata, fetchedAt: now };
142
+ return metadata;
143
+ }
144
+ return async (req) => {
145
+ if (req.method !== "GET" && req.method !== "HEAD") {
146
+ return new Response(null, {
147
+ status: 405,
148
+ headers: { "Allow": "GET, HEAD" },
149
+ });
150
+ }
151
+ try {
152
+ const upstream = await getMetadata();
153
+ const enriched = {
154
+ ...upstream,
155
+ ...extraFields,
156
+ registration_endpoint: registrationEndpoint,
157
+ };
158
+ return new Response(JSON.stringify(enriched), {
159
+ headers: {
160
+ "Content-Type": "application/json",
161
+ "Cache-Control": "public, max-age=3600",
162
+ },
163
+ });
164
+ }
165
+ catch (err) {
166
+ console.error("[as-metadata-proxy] upstream fetch failed:", err);
167
+ const msg = err instanceof Error ? err.message : String(err);
168
+ return new Response(JSON.stringify({ error: "as_metadata_unavailable", message: msg }), { status: 502, headers: { "Content-Type": "application/json" } });
169
+ }
170
+ };
171
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Auth configuration loader.
3
+ *
4
+ * Loads auth config from YAML file with env var overrides.
5
+ * Priority: env vars > YAML > (nothing = no auth)
6
+ *
7
+ * @module lib/server/auth/config
8
+ */
9
+ import type { AuthProvider } from "./provider.js";
10
+ /** Supported auth provider names */
11
+ export type AuthProviderName = "github" | "google" | "auth0" | "oidc";
12
+ /**
13
+ * Fields shared by all {@link AuthConfig} variants.
14
+ */
15
+ interface AuthConfigBase {
16
+ /** JWT audience (aud claim) */
17
+ audience: string;
18
+ /** RFC 9728 § 2 resource identifier (HTTP(S) URL or opaque URI) */
19
+ resource: string;
20
+ /** Scopes supported by this server */
21
+ scopesSupported?: string[];
22
+ /**
23
+ * Absolute HTTP(S) URL where the `/.well-known/oauth-protected-resource`
24
+ * metadata document is served publicly (RFC 9728 § 3).
25
+ *
26
+ * Required when `resource` is an opaque URI (e.g., an OIDC project ID used
27
+ * as JWT audience per RFC 9728 § 2) — otherwise preset factories will
28
+ * throw at construction. When `resource` is itself an HTTP(S) URL, this
29
+ * field is optional and auto-derived by the preset bridge layer. Mirrors
30
+ * `JwtAuthProviderOptions.resourceMetadataUrl`.
31
+ */
32
+ resourceMetadataUrl?: string;
33
+ }
34
+ /** Auth config for GitHub Actions OIDC (no provider-specific fields). */
35
+ export interface GitHubAuthConfig extends AuthConfigBase {
36
+ provider: "github";
37
+ }
38
+ /** Auth config for Google OIDC (no provider-specific fields). */
39
+ export interface GoogleAuthConfig extends AuthConfigBase {
40
+ provider: "google";
41
+ }
42
+ /** Auth config for Auth0 — `domain` is REQUIRED at the type level. */
43
+ export interface Auth0AuthConfig extends AuthConfigBase {
44
+ provider: "auth0";
45
+ /** Auth0 tenant domain (e.g., `"my-tenant.auth0.com"`). */
46
+ domain: string;
47
+ }
48
+ /** Auth config for generic OIDC — `issuer` is REQUIRED at the type level. */
49
+ export interface OIDCAuthConfig extends AuthConfigBase {
50
+ provider: "oidc";
51
+ /** OIDC issuer URL (used as both JWT `iss` and JWKS discovery root). */
52
+ issuer: string;
53
+ /** JWKS URI, optional — derived from `issuer` if absent. */
54
+ jwksUri?: string;
55
+ }
56
+ /**
57
+ * Parsed auth configuration (after YAML + env merge).
58
+ *
59
+ * 0.17.0: discriminated union on `provider` tag. Each variant encodes
60
+ * its provider-specific required fields at the type level:
61
+ * - `"github"` / `"google"`: base only
62
+ * - `"auth0"`: base + required `domain`
63
+ * - `"oidc"`: base + required `issuer`, optional `jwksUri`
64
+ *
65
+ * TypeScript narrows on `config.provider`, so `createAuthProviderFromConfig`
66
+ * no longer needs non-null assertions (`config.domain!`) — the required
67
+ * fields are typed correctly in each branch.
68
+ *
69
+ * The runtime checks in `loadAuthConfig()` stay as defense-in-depth for
70
+ * YAML/env input (untyped), but TS callers constructing `AuthConfig` literals
71
+ * directly now get compile-time safety.
72
+ *
73
+ * BREAKING from 0.16.x: callers who constructed `AuthConfig` literals with
74
+ * optional `domain`/`issuer` and relied on runtime validation now get a
75
+ * compile error if they don't match a variant's required fields. Migration:
76
+ * ensure the literal satisfies the discriminated variant (e.g.,
77
+ * `provider: "auth0"` requires `domain`). See
78
+ * `Casys-AI/mcp-server#11`.
79
+ */
80
+ export type AuthConfig = GitHubAuthConfig | GoogleAuthConfig | Auth0AuthConfig | OIDCAuthConfig;
81
+ /**
82
+ * Load auth configuration from YAML file + env var overrides.
83
+ *
84
+ * 1. Reads YAML file (if it exists)
85
+ * 2. Overlays env vars (MCP_AUTH_* take precedence)
86
+ * 3. Validates the merged config
87
+ * 4. Returns null if no auth is configured
88
+ *
89
+ * Env var mapping:
90
+ * - MCP_AUTH_PROVIDER → auth.provider
91
+ * - MCP_AUTH_AUDIENCE → auth.audience
92
+ * - MCP_AUTH_RESOURCE → auth.resource
93
+ * - MCP_AUTH_DOMAIN → auth.domain
94
+ * - MCP_AUTH_ISSUER → auth.issuer
95
+ * - MCP_AUTH_JWKS_URI → auth.jwksUri
96
+ * - MCP_AUTH_SCOPES → auth.scopesSupported (space-separated)
97
+ * - MCP_AUTH_RESOURCE_METADATA_URL → auth.resourceMetadataUrl
98
+ *
99
+ * @param configPath - Path to YAML config file. Defaults to "mcp-server.yaml" in cwd.
100
+ * @returns AuthConfig or null if no auth configured
101
+ * @throws Error if config is invalid (fail-fast)
102
+ */
103
+ export declare function loadAuthConfig(configPath?: string): Promise<AuthConfig | null>;
104
+ /**
105
+ * Create an AuthProvider from a loaded AuthConfig.
106
+ *
107
+ * 0.17.0: `config` is a discriminated union on `provider`, so TypeScript
108
+ * narrows `config.domain`/`config.issuer` as required (non-optional) in
109
+ * their respective branches. No more non-null assertions (`config.domain!`)
110
+ * or defensive runtime checks here — the type system guarantees them.
111
+ *
112
+ * @param config - Validated auth config
113
+ * @returns AuthProvider instance
114
+ */
115
+ export declare function createAuthProviderFromConfig(config: AuthConfig): AuthProvider;
116
+ export {};
117
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/src/auth/config.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAQlD,oCAAoC;AACpC,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,CAAC;AAStE;;GAEG;AACH,UAAU,cAAc;IACtB,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;IACjB,sCAAsC;IACtC,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B;;;;;;;;;OASG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,yEAAyE;AACzE,MAAM,WAAW,gBAAiB,SAAQ,cAAc;IACtD,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED,iEAAiE;AACjE,MAAM,WAAW,gBAAiB,SAAQ,cAAc;IACtD,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED,sEAAsE;AACtE,MAAM,WAAW,eAAgB,SAAQ,cAAc;IACrD,QAAQ,EAAE,OAAO,CAAC;IAClB,2DAA2D;IAC3D,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,6EAA6E;AAC7E,MAAM,WAAW,cAAe,SAAQ,cAAc;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,MAAM,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,MAAM,UAAU,GAClB,gBAAgB,GAChB,gBAAgB,GAChB,eAAe,GACf,cAAc,CAAC;AAkBnB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,cAAc,CAClC,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CA+H5B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,YAAY,CAkC7E"}
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Auth configuration loader.
3
+ *
4
+ * Loads auth config from YAML file with env var overrides.
5
+ * Priority: env vars > YAML > (nothing = no auth)
6
+ *
7
+ * @module lib/server/auth/config
8
+ */
9
+ import { parse as parseYaml } from "../../deps/jsr.io/@std/yaml/1.2.0/mod.js";
10
+ import { env, readTextFile } from "../runtime/runtime.js";
11
+ import { createAuth0AuthProvider, createGitHubAuthProvider, createGoogleAuthProvider, createOIDCAuthProvider, } from "./presets.js";
12
+ const VALID_PROVIDERS = [
13
+ "github",
14
+ "google",
15
+ "auth0",
16
+ "oidc",
17
+ ];
18
+ /**
19
+ * Load auth configuration from YAML file + env var overrides.
20
+ *
21
+ * 1. Reads YAML file (if it exists)
22
+ * 2. Overlays env vars (MCP_AUTH_* take precedence)
23
+ * 3. Validates the merged config
24
+ * 4. Returns null if no auth is configured
25
+ *
26
+ * Env var mapping:
27
+ * - MCP_AUTH_PROVIDER → auth.provider
28
+ * - MCP_AUTH_AUDIENCE → auth.audience
29
+ * - MCP_AUTH_RESOURCE → auth.resource
30
+ * - MCP_AUTH_DOMAIN → auth.domain
31
+ * - MCP_AUTH_ISSUER → auth.issuer
32
+ * - MCP_AUTH_JWKS_URI → auth.jwksUri
33
+ * - MCP_AUTH_SCOPES → auth.scopesSupported (space-separated)
34
+ * - MCP_AUTH_RESOURCE_METADATA_URL → auth.resourceMetadataUrl
35
+ *
36
+ * @param configPath - Path to YAML config file. Defaults to "mcp-server.yaml" in cwd.
37
+ * @returns AuthConfig or null if no auth configured
38
+ * @throws Error if config is invalid (fail-fast)
39
+ */
40
+ export async function loadAuthConfig(configPath) {
41
+ // 1. Load YAML (optional - file may not exist)
42
+ const yamlAuth = await loadYamlAuth(configPath ?? "mcp-server.yaml");
43
+ // 2. Read env vars
44
+ const envProvider = env("MCP_AUTH_PROVIDER");
45
+ const envAudience = env("MCP_AUTH_AUDIENCE");
46
+ const envResource = env("MCP_AUTH_RESOURCE");
47
+ const envDomain = env("MCP_AUTH_DOMAIN");
48
+ const envIssuer = env("MCP_AUTH_ISSUER");
49
+ const envJwksUri = env("MCP_AUTH_JWKS_URI");
50
+ const envScopes = env("MCP_AUTH_SCOPES");
51
+ const envResourceMetadataUrl = env("MCP_AUTH_RESOURCE_METADATA_URL");
52
+ // 3. Merge: env overrides YAML
53
+ const providerRaw = envProvider ?? yamlAuth?.provider;
54
+ // No provider configured anywhere → no auth
55
+ if (!providerRaw)
56
+ return null;
57
+ // Validate provider name — untyped YAML/env input requires a runtime check
58
+ // even after 0.17.0's compile-time DU. This is the defense-in-depth layer.
59
+ if (!VALID_PROVIDERS.includes(providerRaw)) {
60
+ throw new Error(`[AuthConfig] Unknown auth provider: "${providerRaw}". ` +
61
+ `Valid values: ${VALID_PROVIDERS.join(", ")}`);
62
+ }
63
+ const provider = providerRaw;
64
+ const audience = envAudience ?? yamlAuth?.audience;
65
+ const resource = envResource ?? yamlAuth?.resource;
66
+ if (!audience) {
67
+ throw new Error(`[AuthConfig] "audience" is required when provider="${provider}". ` +
68
+ "Set auth.audience in YAML or MCP_AUTH_AUDIENCE env var.");
69
+ }
70
+ if (!resource) {
71
+ throw new Error(`[AuthConfig] "resource" is required when provider="${provider}". ` +
72
+ "Set auth.resource in YAML or MCP_AUTH_RESOURCE env var.");
73
+ }
74
+ const base = {
75
+ audience,
76
+ resource,
77
+ scopesSupported: envScopes
78
+ ? envScopes.split(" ").filter(Boolean)
79
+ : yamlAuth?.scopesSupported,
80
+ resourceMetadataUrl: envResourceMetadataUrl ??
81
+ yamlAuth?.resourceMetadataUrl,
82
+ };
83
+ // 4. Construct the correct DU variant, enforcing provider-specific
84
+ // required fields at runtime. The runtime checks mirror the type-level
85
+ // constraints in the DU variants (Auth0AuthConfig.domain, OIDCAuthConfig.issuer).
86
+ //
87
+ // The `issuer` / `domain` fields are URL-shaped at runtime even though the
88
+ // DU variants type them as `string`. 0.17.0 runs them through `new URL()`
89
+ // here (at the YAML/env boundary) to catch typos like
90
+ // `MCP_AUTH_ISSUER=not-a-url` with a clear error naming the offending field,
91
+ // instead of surfacing a confusing `authorizationServers[0]` error deep
92
+ // inside the preset bridge later (pre-existing issue caught during 0.17.0
93
+ // review, code-reviewer finding).
94
+ switch (provider) {
95
+ case "github":
96
+ return { provider: "github", ...base };
97
+ case "google":
98
+ return { provider: "google", ...base };
99
+ case "auth0": {
100
+ const domain = envDomain ?? yamlAuth?.domain;
101
+ if (!domain) {
102
+ throw new Error('[AuthConfig] "domain" is required for auth0 provider. ' +
103
+ "Set auth.domain in YAML or MCP_AUTH_DOMAIN env var.");
104
+ }
105
+ return { provider: "auth0", ...base, domain };
106
+ }
107
+ case "oidc": {
108
+ const issuer = envIssuer ?? yamlAuth?.issuer;
109
+ if (!issuer) {
110
+ throw new Error('[AuthConfig] "issuer" is required for oidc provider. ' +
111
+ "Set auth.issuer in YAML or MCP_AUTH_ISSUER env var.");
112
+ }
113
+ try {
114
+ const parsed = new URL(issuer);
115
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
116
+ throw new Error(`[AuthConfig] "issuer" for oidc provider must use http(s):// ` +
117
+ `scheme, got ${JSON.stringify(parsed.protocol)} in ` +
118
+ `${JSON.stringify(issuer)}.`);
119
+ }
120
+ }
121
+ catch (err) {
122
+ // If new URL() threw, re-wrap with AuthConfig-labelled error.
123
+ // If our explicit scheme check threw, re-throw as-is (already labelled).
124
+ if (err instanceof Error && err.message.startsWith("[AuthConfig]")) {
125
+ throw err;
126
+ }
127
+ throw new Error(`[AuthConfig] "issuer" for oidc provider is not a valid URL: ` +
128
+ `${JSON.stringify(issuer)}. Set auth.issuer in YAML or ` +
129
+ `MCP_AUTH_ISSUER env var to an absolute http(s)://... URL.`);
130
+ }
131
+ const jwksUri = envJwksUri ?? yamlAuth?.jwksUri;
132
+ return { provider: "oidc", ...base, issuer, jwksUri };
133
+ }
134
+ default: {
135
+ // Exhaustiveness guard: future provider additions land here as a TS
136
+ // error at this function. Runtime throw is belt-and-suspenders — the
137
+ // earlier `VALID_PROVIDERS.includes` check at line ~130 already
138
+ // eliminates unknown provider strings.
139
+ const _exhaustive = provider;
140
+ throw new Error(`[AuthConfig] Unreachable — unhandled provider ${JSON.stringify(_exhaustive)}`);
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * Create an AuthProvider from a loaded AuthConfig.
146
+ *
147
+ * 0.17.0: `config` is a discriminated union on `provider`, so TypeScript
148
+ * narrows `config.domain`/`config.issuer` as required (non-optional) in
149
+ * their respective branches. No more non-null assertions (`config.domain!`)
150
+ * or defensive runtime checks here — the type system guarantees them.
151
+ *
152
+ * @param config - Validated auth config
153
+ * @returns AuthProvider instance
154
+ */
155
+ export function createAuthProviderFromConfig(config) {
156
+ const base = {
157
+ audience: config.audience,
158
+ resource: config.resource,
159
+ scopesSupported: config.scopesSupported,
160
+ resourceMetadataUrl: config.resourceMetadataUrl,
161
+ };
162
+ switch (config.provider) {
163
+ case "github":
164
+ return createGitHubAuthProvider(base);
165
+ case "google":
166
+ return createGoogleAuthProvider(base);
167
+ case "auth0":
168
+ return createAuth0AuthProvider({ ...base, domain: config.domain });
169
+ case "oidc":
170
+ return createOIDCAuthProvider({
171
+ ...base,
172
+ issuer: config.issuer,
173
+ jwksUri: config.jwksUri,
174
+ authorizationServers: [config.issuer],
175
+ });
176
+ default: {
177
+ // Exhaustiveness guard matching the one in loadAuthConfig — when a
178
+ // 5th variant is added to AuthConfig, TS flags this function as
179
+ // incomplete before any caller is affected.
180
+ const _exhaustive = config;
181
+ throw new Error(`[AuthConfig] Unreachable — unhandled variant ${JSON.stringify(_exhaustive)}`);
182
+ }
183
+ }
184
+ }
185
+ /**
186
+ * Load the auth section from a YAML config file.
187
+ * Returns null if file doesn't exist (not an error).
188
+ */
189
+ async function loadYamlAuth(path) {
190
+ // readTextFile returns null if file doesn't exist
191
+ const text = await readTextFile(path);
192
+ if (text === null)
193
+ return null;
194
+ const parsed = parseYaml(text);
195
+ // Validate parsed YAML is an object (not string, array, null, etc.)
196
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
197
+ return null;
198
+ }
199
+ const configFile = parsed;
200
+ if (!configFile.auth || typeof configFile.auth !== "object" ||
201
+ Array.isArray(configFile.auth)) {
202
+ return null;
203
+ }
204
+ const auth = configFile.auth;
205
+ return {
206
+ provider: typeof auth.provider === "string" ? auth.provider : undefined,
207
+ audience: typeof auth.audience === "string" ? auth.audience : undefined,
208
+ resource: typeof auth.resource === "string" ? auth.resource : undefined,
209
+ domain: typeof auth.domain === "string" ? auth.domain : undefined,
210
+ issuer: typeof auth.issuer === "string" ? auth.issuer : undefined,
211
+ jwksUri: typeof auth.jwksUri === "string" ? auth.jwksUri : undefined,
212
+ scopesSupported: Array.isArray(auth.scopesSupported)
213
+ ? auth.scopesSupported.filter((s) => typeof s === "string")
214
+ : undefined,
215
+ resourceMetadataUrl: typeof auth.resourceMetadataUrl === "string"
216
+ ? auth.resourceMetadataUrl
217
+ : undefined,
218
+ };
219
+ }