@classytic/arc 2.47.0 → 2.49.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 (216) hide show
  1. package/dist/{EventTransport-BHKy4_Bi.mjs → EventTransport-DbHZK230.mjs} +2 -2
  2. package/dist/{HookSystem-CAIDVoKC.mjs → HookSystem-DMoeJ6Do.mjs} +2 -2
  3. package/dist/{QueryCache-DdvrGG8Q.d.mts → QueryCache-BE47tmlO.d.mts} +36 -1
  4. package/dist/{ResourceRegistry-23Ml6FNe.mjs → ResourceRegistry-CP-iTcKy.mjs} +2 -2
  5. package/dist/{acquire-DoFX06fm.mjs → acquire-CB0va87C.mjs} +1 -1
  6. package/dist/audit/index.d.mts +1 -1
  7. package/dist/audit/index.mjs +4 -4
  8. package/dist/auth/audit.mjs +1 -1
  9. package/dist/auth/index.d.mts +2 -2
  10. package/dist/auth/index.mjs +53 -15
  11. package/dist/auth/redis-session.mjs +1 -1
  12. package/dist/{authorizationDecision-DYiubkYw.mjs → authorizationDecision-DHO94aV2.mjs} +4 -4
  13. package/dist/{boundedMap-CtdzpJ3X.mjs → boundedMap-C51EUUOm.mjs} +1 -1
  14. package/dist/{buildHandler-CARdmPNo.mjs → buildHandler-9DuwEKvr.mjs} +23 -16
  15. package/dist/cache/index.d.mts +2 -2
  16. package/dist/cache/index.mjs +4 -4
  17. package/dist/{caching-QRiryDLs.mjs → caching-COTX3sDa.mjs} +3 -6
  18. package/dist/{claimed-BLecr1j3.mjs → claimed-C7T1nHlo.mjs} +1 -1
  19. package/dist/cleanup/index.d.mts +2 -2
  20. package/dist/cleanup/index.mjs +4 -4
  21. package/dist/cli/commands/describe.d.mts +1 -1
  22. package/dist/cli/commands/describe.mjs +3 -3
  23. package/dist/cli/commands/docs.mjs +3 -3
  24. package/dist/cli/commands/doctor.mjs +1 -1
  25. package/dist/cli/commands/generate.mjs +2 -2
  26. package/dist/cli/commands/init.mjs +2 -2
  27. package/dist/cli/commands/introspect.mjs +2 -2
  28. package/dist/cli/index.mjs +3 -3
  29. package/dist/{constants-Cx7BcnHT.mjs → constants-DOnfMd7i.mjs} +1 -1
  30. package/dist/context/index.mjs +5 -5
  31. package/dist/core/index.d.mts +3 -3
  32. package/dist/core/index.mjs +7 -7
  33. package/dist/{core-0WyMuo0f.mjs → core-BoEdFDDw.mjs} +3 -3
  34. package/dist/{createActionRouter-mLAGbpDV.mjs → createActionRouter-CpTn15dm.mjs} +54 -18
  35. package/dist/{createAggregationRouter-BEAjn3dA.mjs → createAggregationRouter-CD_Hydp0.mjs} +13 -11
  36. package/dist/{createApp-QDP4vYWH.mjs → createApp-Be6XTGD9.mjs} +332 -40
  37. package/dist/{createMcpServer-DzXHX0SO.d.mts → createMcpServer-CS2KOVP6.d.mts} +9 -10
  38. package/dist/{defineAggregation-CFNfvz-C.mjs → defineAggregation-BI5pRb8c.mjs} +1 -1
  39. package/dist/{defineResource-BROJmhzJ.mjs → defineResource-BAzNu5Um.mjs} +8 -8
  40. package/dist/discovery/index.mjs +1 -1
  41. package/dist/docs/index.d.mts +1 -1
  42. package/dist/docs/index.mjs +3 -3
  43. package/dist/{elevation-DrXeEWWk.mjs → elevation-DupGuM41.mjs} +6 -9
  44. package/dist/encryption/index.mjs +3 -3
  45. package/dist/{errorHandler-BiBXtxj4.mjs → errorHandler-DA03vRqp.mjs} +4 -7
  46. package/dist/{errors-DnrUChAy.mjs → errors-BpYV859Y.mjs} +1 -1
  47. package/dist/{eventPlugin-BhKLUe7H.mjs → eventPlugin-D7LYtYzL.mjs} +9 -13
  48. package/dist/{eventTypes-CCIRGakw.mjs → eventTypes-BqA-N-Uz.mjs} +2 -2
  49. package/dist/events/index.d.mts +18 -5
  50. package/dist/events/index.mjs +8 -8
  51. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  52. package/dist/events/transports/redis.d.mts +35 -0
  53. package/dist/events/transports/redis.mjs +87 -11
  54. package/dist/factory/index.d.mts +4 -4
  55. package/dist/factory/index.mjs +6 -6
  56. package/dist/{fastify-augmentation-bzkWPt1f.d.mts → fastify-augmentation-baQc3MaO.d.mts} +2 -2
  57. package/dist/fieldTypes-EFWxCkZ5.mjs +80 -0
  58. package/dist/{fields-CYdpcV73.mjs → fields-CT1Erg7o.mjs} +1 -1
  59. package/dist/{filter-merge-6kasezRH.mjs → filter-merge-B1eJ1pMx.mjs} +1 -1
  60. package/dist/{generate-DUkcbc4r.mjs → generate-Cr0ULavs.mjs} +2 -2
  61. package/dist/{headers-KxhrKevA.mjs → headers-D4bncIOf.mjs} +2 -2
  62. package/dist/{health-jkYNdobJ.mjs → health-BoFxrkJE.mjs} +1 -1
  63. package/dist/{health-CRJg3IIq.mjs → health-DN_pUVMX.mjs} +1 -1
  64. package/dist/hooks/index.d.mts +1 -1
  65. package/dist/hooks/index.mjs +2 -2
  66. package/dist/http-cache/index.d.mts +2 -2
  67. package/dist/http-cache/index.mjs +4 -4
  68. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  69. package/dist/http-cache/purgers/fastly.mjs +2 -2
  70. package/dist/http-cache/testing/index.mjs +1 -1
  71. package/dist/idempotency/index.d.mts +1 -1
  72. package/dist/idempotency/index.mjs +10 -8
  73. package/dist/idempotency/redis.mjs +2 -2
  74. package/dist/{index-B5i9-vuP.d.mts → index-CMNpMBtW.d.mts} +1 -1
  75. package/dist/{index-BxZS-8So.d.mts → index-DKM2p5w5.d.mts} +48 -23
  76. package/dist/{index-Cy2-QffW.d.mts → index-DLCcLUQT.d.mts} +69 -6
  77. package/dist/{index-DFCCQ9AE.d.mts → index-DexdFs1a.d.mts} +1 -1
  78. package/dist/{index-D1X_C_qz.d.mts → index-Dhrks-hM.d.mts} +60 -10
  79. package/dist/index.d.mts +4 -4
  80. package/dist/index.mjs +11 -11
  81. package/dist/{init-CACwpktI.mjs → init-C4a24wD2.mjs} +1 -1
  82. package/dist/integrations/event-gateway.mjs +2 -2
  83. package/dist/integrations/index.d.mts +2 -2
  84. package/dist/integrations/index.mjs +1 -1
  85. package/dist/integrations/jobs/index.mjs +3 -3
  86. package/dist/integrations/mcp/index.d.mts +6 -38
  87. package/dist/integrations/mcp/index.mjs +2 -2
  88. package/dist/integrations/mcp/testing.d.mts +11 -15
  89. package/dist/integrations/mcp/testing.mjs +22 -42
  90. package/dist/integrations/streamline.mjs +3 -3
  91. package/dist/integrations/webhooks.d.mts +1 -1
  92. package/dist/integrations/webhooks.mjs +4 -4
  93. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  94. package/dist/integrations/websocket-redis.mjs +1 -1
  95. package/dist/integrations/websocket.mjs +2 -2
  96. package/dist/{jsonBody-CzDBkCme.mjs → jsonBody-DoTt5BS6.mjs} +2 -2
  97. package/dist/{keys-Cbwf6r1B.mjs → keys--l9n7aOC.mjs} +1 -1
  98. package/dist/{loadResources-Kr6vuljv.mjs → loadResources-rygByIQA.mjs} +3 -3
  99. package/dist/{loadResourcesFromEntry-D2e0qoDR.mjs → loadResourcesFromEntry-ItNBIQ5w.mjs} +2 -2
  100. package/dist/logger/index.mjs +2 -2
  101. package/dist/{logger-C110X5Yz.mjs → logger-UbknHqHy.mjs} +1 -1
  102. package/dist/{mcpPlugin-4lIPr9OJ.mjs → mcpPlugin-CTkk4RP8.mjs} +218 -378
  103. package/dist/{memory-D9qkhXiB.mjs → memory-C47xVsjX.mjs} +3 -3
  104. package/dist/{metrics-B-qrrWfI.mjs → metrics-TJyAb1Xk.mjs} +4 -7
  105. package/dist/middleware/index.d.mts +1 -1
  106. package/dist/middleware/index.mjs +3 -3
  107. package/dist/migrations/index.mjs +2 -2
  108. package/dist/{module-BD8xHgrz.mjs → module-CWiqsXnh.mjs} +1 -1
  109. package/dist/{multiTenant-KZj8j1uJ.d.mts → multiTenant-QtDzxx_K.d.mts} +1 -1
  110. package/dist/{multipartBody-qU7KCn1l.mjs → multipartBody-BdG1qbn1.mjs} +1 -1
  111. package/dist/{observeSend-BnPtTotW.mjs → observeSend-DrA3ADFN.mjs} +1 -1
  112. package/dist/{openapi-DoVa5SVP.mjs → openapi-D6MAbYpv.mjs} +7 -7
  113. package/dist/outbox-admin/index.d.mts +1 -1
  114. package/dist/outbox-admin/index.mjs +5 -5
  115. package/dist/{outbox-module-DyITEIop.mjs → outbox-module-D5QABFQW.mjs} +197 -28
  116. package/dist/{outbox-module-5Mnwcycy.d.mts → outbox-module-DzW6zwWJ.d.mts} +103 -10
  117. package/dist/permissions/index.d.mts +2 -2
  118. package/dist/permissions/index.mjs +7 -7
  119. package/dist/{permissions-BBy4bOGi.mjs → permissions-CFsmdYUt.mjs} +9 -9
  120. package/dist/{pipe-BOm2o4UA.mjs → pipe-B_05AgGt.mjs} +2 -2
  121. package/dist/pipeline/index.d.mts +1 -1
  122. package/dist/pipeline/index.mjs +2 -2
  123. package/dist/{plan-DDIGwuxr.mjs → plan-BnlNJhrj.mjs} +1 -1
  124. package/dist/{plugin-Bn4D_0XK.mjs → plugin-CrMPYbdj.mjs} +94 -50
  125. package/dist/plugins/index.d.mts +6 -5
  126. package/dist/plugins/index.mjs +19 -18
  127. package/dist/plugins/response-cache.mjs +4 -4
  128. package/dist/plugins/tracing-entry.mjs +2 -2
  129. package/dist/{pluralize-ClEjcKlG.mjs → pluralize-oVIxJ4CY.mjs} +1 -1
  130. package/dist/presets/filesUpload.d.mts +1 -1
  131. package/dist/presets/filesUpload.mjs +5 -5
  132. package/dist/presets/index.d.mts +2 -2
  133. package/dist/presets/index.mjs +2 -2
  134. package/dist/presets/multiTenant.d.mts +1 -1
  135. package/dist/presets/multiTenant.mjs +5 -5
  136. package/dist/presets/search.d.mts +1 -1
  137. package/dist/presets/search.mjs +2 -2
  138. package/dist/{presets-DK2jh5YR.mjs → presets-CUd3L7v6.mjs} +4 -4
  139. package/dist/{projection-BHH-sXyS.mjs → projection-DowJlIto.mjs} +2 -2
  140. package/dist/{purger.types-2wNJK_89.mjs → purger.types-BjKy8869.mjs} +1 -1
  141. package/dist/{queryCachePlugin-Ckqe98AM.mjs → queryCachePlugin-BvB3k_Fh.mjs} +114 -14
  142. package/dist/{queryCachePlugin-DYQUyeJ9.d.mts → queryCachePlugin-DrQNnGws.d.mts} +1 -1
  143. package/dist/{rateLimitKey-CWAjlqcN.mjs → rateLimitKey-56nH1cWN.mjs} +1 -1
  144. package/dist/{realtime-BIJi9USY.mjs → realtime-DXGBPtYK.mjs} +19 -22
  145. package/dist/registry/index.d.mts +2 -2
  146. package/dist/registry/index.mjs +3 -3
  147. package/dist/{registry-y9ZA-R_J.mjs → registry-Biz-6sEZ.mjs} +2 -2
  148. package/dist/{relay-BNrC1CEP.mjs → relay-DEIoMntZ.mjs} +200 -99
  149. package/dist/{renewingLease-CS43br5E.mjs → renewingLease-BCJpW9-u.mjs} +1 -1
  150. package/dist/{replyHelpers-oZDzakGb.mjs → replyHelpers-DliJNb0-.mjs} +2 -2
  151. package/dist/{requestContext-fWb_YaV2.mjs → requestContext-tUgLt9Ky.mjs} +1 -1
  152. package/dist/{requirement--2hWyyHi.mjs → requirement-0l2DApiQ.mjs} +1 -1
  153. package/dist/{resourceRateLimit-DCWglD7V.d.mts → resourceRateLimit-BPiESPtG.d.mts} +4 -0
  154. package/dist/{resourceRateLimit-1WbcyMZY.mjs → resourceRateLimit-iSXF8rLH.mjs} +19 -4
  155. package/dist/{rolldown-runtime-yH2lHMo_.mjs → rolldown-runtime-gKJR3o-6.mjs} +1 -1
  156. package/dist/{routeValidator-BSlRIA5c.mjs → routeValidator-xNYA4rr1.mjs} +47 -5
  157. package/dist/{runtimeCapabilities-CYCEtU1W.mjs → runtimeCapabilities-BQK-GrYe.mjs} +1 -1
  158. package/dist/{schedules-B5WGlYIT.mjs → schedules-D9iMVFhF.mjs} +6 -9
  159. package/dist/{schemaConverter-DtNvts-6.mjs → schemaConverter-cIh4oX9a.mjs} +2 -2
  160. package/dist/{actionPermissions-DXrlWHHK.mjs → schemaIR-BsY4y9VP.mjs} +184 -16
  161. package/dist/schemas/index.mjs +1 -1
  162. package/dist/scim/index.mjs +2 -2
  163. package/dist/scope/index.d.mts +1 -1
  164. package/dist/scope/index.mjs +5 -5
  165. package/dist/{scope-BwVLSyNG.mjs → scope-QyhM9w8z.mjs} +4 -4
  166. package/dist/{shutdown-BJiJN7FT.mjs → shutdown-BM7Q0h4B.mjs} +1 -1
  167. package/dist/{sse-B_50llZu.mjs → sse-ofvlcTQQ.mjs} +9 -35
  168. package/dist/sseStats-DQqNN385.d.mts +112 -0
  169. package/dist/sseStream-BxQW7hPq.mjs +166 -0
  170. package/dist/{store-helpers-D-n5cwy5.mjs → store-helpers-_FRhHDyv.mjs} +1 -1
  171. package/dist/{simpleEqualityMatcher-DGRLq-1k.mjs → streamFrames-B3ZJfI02.mjs} +19 -2
  172. package/dist/{streaming-Dcgqa-hH.mjs → streaming-HZr63UiM.mjs} +1 -1
  173. package/dist/{subscriberIdentity-C9KhIXTF.mjs → subscriberIdentity-DSgnoT_D.mjs} +1 -1
  174. package/dist/{tenancy-COrhjPRZ.mjs → tenancy-_ukT0oBt.mjs} +2 -2
  175. package/dist/{tenantPreparation-BElWHytd.mjs → tenantPreparation-DSlQI53c.mjs} +4 -4
  176. package/dist/testing/cleanupStoreContract.mjs +1 -1
  177. package/dist/testing/index.d.mts +4 -4
  178. package/dist/testing/index.mjs +324 -17
  179. package/dist/testing/outboxStoreContract.mjs +2 -2
  180. package/dist/testing/requiredPorts.mjs +2 -2
  181. package/dist/testing/storageContract.mjs +1 -1
  182. package/dist/{timing-CaxKbRk_.mjs → timing-Z8p-Zlw1.mjs} +1 -1
  183. package/dist/{transactionContext-8qKON0Nk.mjs → transactionContext-DBbSTfY3.mjs} +1 -1
  184. package/dist/{typeGuards-DVjVSsXO.mjs → typeGuards-_6nNQqgq.mjs} +1 -1
  185. package/dist/types/index.d.mts +1 -1
  186. package/dist/types/index.mjs +1 -1
  187. package/dist/types/storage.mjs +1 -1
  188. package/dist/{types-DeLiuaNv.d.mts → types-B4E0sc6D.d.mts} +20 -31
  189. package/dist/{types-DZHqOuJE.mjs → types-CrOlZ4rY.mjs} +4 -4
  190. package/dist/usage/index.d.mts +1 -1
  191. package/dist/usage/index.mjs +7 -7
  192. package/dist/{userHelpers-_eGj6kf0.mjs → userHelpers-CBKx3XJN.mjs} +1 -1
  193. package/dist/utils/index.d.mts +239 -34
  194. package/dist/utils/index.mjs +13 -13
  195. package/dist/{utils-Dd6MWpye.mjs → utils--HE8R8sH.mjs} +761 -8
  196. package/dist/{validate-BaF5wd0x.mjs → validate-BUeE2MLR.mjs} +3 -3
  197. package/dist/{versioning-S18y2-0C.d.mts → versioning-B07RgD27.d.mts} +2 -13
  198. package/dist/{versioning-DyV7mwtK.mjs → versioning-qYgqwOhL.mjs} +4 -7
  199. package/dist/{workScope-CmCBUmPR.mjs → workScope-C-1QHNmV.mjs} +2 -2
  200. package/llms.txt +2 -2
  201. package/package.json +42 -50
  202. package/skills/arc/references/api-reference.md +2 -2
  203. package/skills/arc/references/auth-better-auth.md +1 -0
  204. package/skills/arc/references/events-outbox.md +7 -4
  205. package/skills/arc/references/events.md +2 -2
  206. package/skills/arc/references/mcp-custom-tools.md +1 -1
  207. package/skills/arc/references/mcp-setup.md +11 -10
  208. package/skills/arc/references/mcp-testing.md +3 -3
  209. package/skills/arc/references/production-api.md +4 -0
  210. package/skills/arc/references/production-boot.md +2 -0
  211. package/skills/arc/references/production-idempotency.md +1 -1
  212. package/skills/arc/references/production-realtime.md +28 -2
  213. package/skills/arc/references/validation.md +4 -0
  214. package/skills/arc/references/writes-hooks-errors.md +1 -0
  215. package/dist/schemaIR-uS_RHqa3.mjs +0 -108
  216. package/dist/sseStream-BjSo9Ult.mjs +0 -57
@@ -1,25 +1,24 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { t as arcLog } from "./logger-C110X5Yz.mjs";
3
- import { i as NotFoundError, p as isArcError, t as ArcError } from "./errors-DnrUChAy.mjs";
4
- import { f as BaseController, n as normalizeActionsToRouterConfig, r as resolveActionTargetFence } from "./plugin-Bn4D_0XK.mjs";
5
- import { n as requireSingleHeaderValue } from "./headers-KxhrKevA.mjs";
6
- import { b as isElevated, c as getOrgId, g as getUserId, x as isMember } from "./types-DZHqOuJE.mjs";
7
- import { a as resolveEffectiveRoles, t as applyFieldReadPermissions } from "./fields-CYdpcV73.mjs";
8
- import { o as toJsonSchema } from "./schemaConverter-DtNvts-6.mjs";
9
- import { t as buildRequestScopeProjection } from "./projection-BHH-sXyS.mjs";
10
- import { l as resolvePipelineSteps, t as resolveActionPermission } from "./actionPermissions-DXrlWHHK.mjs";
11
- import { a as withoutTenantInjection, r as prepareTenantContext } from "./tenantPreparation-BElWHytd.mjs";
12
- import { r as evaluatePermissionDecision } from "./authorizationDecision-DYiubkYw.mjs";
13
- import { n as declareRuntimeCapability } from "./runtimeCapabilities-CYCEtU1W.mjs";
14
- import { t as executePipeline } from "./pipe-BOm2o4UA.mjs";
15
- import { a as resourceRateLimitWindowMs, i as resolveResourceRateLimiter, t as createMemoryResourceRateLimiter } from "./resourceRateLimit-1WbcyMZY.mjs";
16
- import { n as evictToSize, r as touch, t as assertCapacity } from "./boundedMap-CtdzpJ3X.mjs";
17
- import { t as pluralize } from "./pluralize-ClEjcKlG.mjs";
18
- import { n as createIdempotencyResult, r as operationIdentity, t as resolveIdempotencyTiming } from "./timing-CaxKbRk_.mjs";
19
- import { n as acquireIdempotencyKey, r as releaseIdempotencyLock } from "./acquire-DoFX06fm.mjs";
20
- import { r as shouldRejectAdditionalProperties, t as normalizeSchemaIR } from "./schemaIR-uS_RHqa3.mjs";
21
- import { n as validateAggregations } from "./validate-BaF5wd0x.mjs";
22
- import { n as executeAggregation } from "./buildHandler-CARdmPNo.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { a as resourceRateLimitWindowMs, i as resolveResourceRateLimiter, t as createMemoryResourceRateLimiter } from "./resourceRateLimit-iSXF8rLH.mjs";
3
+ import { n as declareRuntimeCapability } from "./runtimeCapabilities-BQK-GrYe.mjs";
4
+ import { n as evictToSize, r as touch, t as assertCapacity } from "./boundedMap-C51EUUOm.mjs";
5
+ import { i as NotFoundError, p as isArcError, t as ArcError } from "./errors-BpYV859Y.mjs";
6
+ import { a as resolveActionPermission, i as shouldRejectAdditionalProperties, n as normalizeSchemaIR, p as resolvePipelineSteps, t as actionSchemaIR } from "./schemaIR-BsY4y9VP.mjs";
7
+ import { n as fieldTypesFromOpenApiSchemas } from "./fieldTypes-EFWxCkZ5.mjs";
8
+ import { f as BaseController, n as normalizeActionsToRouterConfig, r as resolveActionTargetFence } from "./plugin-CrMPYbdj.mjs";
9
+ import { a as withoutTenantInjection, r as prepareTenantContext } from "./tenantPreparation-DSlQI53c.mjs";
10
+ import { b as isElevated, c as getOrgId, g as getUserId, x as isMember } from "./types-CrOlZ4rY.mjs";
11
+ import { t as pluralize } from "./pluralize-oVIxJ4CY.mjs";
12
+ import { t as buildRequestScopeProjection } from "./projection-DowJlIto.mjs";
13
+ import { n as acquireIdempotencyKey, r as releaseIdempotencyLock } from "./acquire-CB0va87C.mjs";
14
+ import { n as createIdempotencyResult, r as operationIdentity, t as resolveIdempotencyTiming } from "./timing-Z8p-Zlw1.mjs";
15
+ import { t as arcLog } from "./logger-UbknHqHy.mjs";
16
+ import { r as evaluatePermissionDecision } from "./authorizationDecision-DHO94aV2.mjs";
17
+ import { a as resolveEffectiveRoles, t as applyFieldReadPermissions } from "./fields-CT1Erg7o.mjs";
18
+ import { n as executeAggregation } from "./buildHandler-9DuwEKvr.mjs";
19
+ import { n as validateAggregations } from "./validate-BUeE2MLR.mjs";
20
+ import { o as toJsonSchema } from "./schemaConverter-cIh4oX9a.mjs";
21
+ import { t as executePipeline } from "./pipe-B_05AgGt.mjs";
23
22
  import { ARC_ERROR_CODES, isHttpError, toErrorContract } from "@classytic/repo-core/errors";
24
23
  import { createHash, randomUUID } from "node:crypto";
25
24
  import fp from "fastify-plugin";
@@ -27,45 +26,20 @@ import { IdempotencyError, fingerprintRequest } from "@classytic/repo-core/idemp
27
26
  import { z } from "zod";
28
27
  // src/integrations/mcp/createMcpServer.ts
29
28
  /**
30
- * @classytic/arc — createMcpServer()
31
- *
32
- * Level 2 — Declarative MCP server factory.
33
- * Uses `server.registerTool()` / `server.registerPrompt()` (official SDK API)
34
- * with flat inputSchema shapes — no z.object() wrapping, no Zod version hacks.
35
- *
36
- * @example
37
- * ```typescript
38
- * import { createMcpServer, defineTool } from '@classytic/arc/mcp';
39
- * import { z } from 'zod';
40
- *
41
- * const server = await createMcpServer({
42
- * name: 'my-api',
43
- * version: '1.0.0',
44
- * tools: [
45
- * defineTool('greet', {
46
- * description: 'Say hello',
47
- * input: { name: z.string() },
48
- * handler: async ({ name }) => ({ content: [{ type: 'text', text: `Hello ${name}` }] }),
49
- * }),
50
- * ],
51
- * });
52
- * ```
53
- */
54
- /**
55
29
  * Create a configured MCP server from declarative config.
56
30
  *
57
31
  * @param config - Server name, version, tools, prompts
58
32
  * @returns McpServer instance (not yet connected to a transport)
59
33
  */
60
34
  async function createMcpServer(config, authRef) {
61
- const { McpServer } = await import("@modelcontextprotocol/server");
62
- const server = new McpServer({
35
+ const { McpServer: McpServerCtor } = await import("@modelcontextprotocol/server");
36
+ const server = new McpServerCtor({
63
37
  name: config.name,
64
38
  version: config.version ?? "1.0.0"
65
39
  }, config.instructions ? { instructions: config.instructions } : void 0);
66
40
  if (config.tools) {
67
41
  const resolved = resolveToolCollisions(config.tools);
68
- for (const tool of resolved) registerTool(server, tool, authRef);
42
+ for (const tool of resolved) registerTool(server, tool, authRef, config.logger);
69
43
  }
70
44
  if (config.prompts) for (const prompt of config.prompts) registerPrompt(server, prompt);
71
45
  return server;
@@ -127,62 +101,69 @@ function resolveToolCollisions(tools) {
127
101
  return out;
128
102
  }
129
103
  /**
104
+ * Flat shape → `z.object()`. A whole schema (anything carrying
105
+ * `~standard`, e.g. `z.strictObject(...)`) is registered as-is. The SDK still
106
+ * accepts a raw shape, but only through overloads marked deprecated.
107
+ */
108
+ function toObjectSchema(schema) {
109
+ if (schema === void 0) return void 0;
110
+ if ("~standard" in schema) return schema;
111
+ return z.object(schema);
112
+ }
113
+ /**
130
114
  * Register a ToolDefinition using `server.registerTool()`.
131
115
  *
132
- * The inputSchema is passed as a flat Zod shape `{ field: z.string() }` —
133
- * the SDK wraps it in z.object() internally. This avoids the Zod v3/v4-mini
134
- * version mismatch entirely.
116
+ * A tool WITHOUT an input schema is registered with a one-argument callback:
117
+ * the SDK calls such handlers as `(ctx)`, not `(args, ctx)`. Registering the
118
+ * two-argument form there handed the SDK context to the tool as its input and
119
+ * left `ctx.extra` / `ctx.log` unbound.
135
120
  */
136
- function registerTool(server, tool, authRef) {
137
- const srv = server;
138
- const config = {};
139
- if (tool.title) config.title = tool.title;
140
- if (tool.description) config.description = tool.description;
121
+ function registerTool(server, tool, authRef, logger) {
141
122
  /**
142
- * Flat SHAPES are passed straight through. v2's `registerTool` carries a
143
- * `ZodRawShape` overload and auto-wraps it in `z.object()` itself, so arc's
144
- * host-facing ergonomic (`{ name: z.string() }`) needs no adaptation layer.
145
- *
146
- * arc's own MIGRATION-V2 notes claimed v2 "requires z.object(), raw shapes no
147
- * longer accepted" and a wrap was written here on that basis. That was true of
148
- * the PRE-ALPHA and is not true of 2.0.0 — checked against the shipped
149
- * overloads. Wrapping anyway would have been arc maintaining an adapter for a
150
- * conversion the SDK already owns.
123
+ * Server-side, not `ctx.mcpReq.log`: protocol 2026-07-28 deprecates logging
124
+ * to the client (SEP-2577 — "migrate to stderr or OpenTelemetry"), and the
125
+ * SDK drops those lines anyway unless the server declares `logging` and the
126
+ * request carries a `logLevel` envelope key.
151
127
  */
152
- if (tool.inputSchema) config.inputSchema = tool.inputSchema;
153
- if (tool.outputSchema) config.outputSchema = tool.outputSchema;
154
- if (tool.annotations) config.annotations = tool.annotations;
155
- srv.registerTool(tool.name, config, (input, mcpCtx) => {
128
+ const log = async (level, message) => {
129
+ logger?.[level === "warning" ? "warn" : level]({ mcpTool: tool.name }, message);
130
+ };
131
+ const run = (input, mcpCtx) => {
156
132
  const ctx = {
157
133
  session: authRef?.current ?? null,
158
- /**
159
- * v2 exposes logging as `ctx.mcpReq.log(level, message)` — the SDK builds
160
- * the `notifications/message` envelope and correlates it to the in-flight
161
- * request. v1 handed over a raw `sendNotification` that arc had to frame
162
- * itself; that hand-framed envelope carried no request id, so a log line
163
- * from a tool arrived uncorrelated.
164
- *
165
- * Still best-effort: a transport that has already closed must not turn a
166
- * successful tool call into a failed one.
167
- */
168
- log: async (level, message) => {
169
- try {
170
- await (mcpCtx?.mcpReq)?.log?.(level, message);
171
- } catch {}
172
- },
134
+ log,
173
135
  extra: mcpCtx
174
136
  };
175
137
  return tool.handler(input, ctx);
176
- });
138
+ };
139
+ const inputSchema = toObjectSchema(tool.inputSchema);
140
+ const config = {
141
+ ...tool.title ? { title: tool.title } : {},
142
+ ...tool.description ? { description: tool.description } : {},
143
+ ...tool.outputSchema ? { outputSchema: z.object(tool.outputSchema) } : {},
144
+ ...tool.annotations ? { annotations: tool.annotations } : {}
145
+ };
146
+ if (inputSchema) server.registerTool(tool.name, {
147
+ ...config,
148
+ inputSchema
149
+ }, (input, mcpCtx) => run(input, mcpCtx));
150
+ else server.registerTool(tool.name, config, (mcpCtx) => run({}, mcpCtx));
177
151
  }
178
- /** Register a PromptDefinition using `server.registerPrompt()` */
152
+ /**
153
+ * Register a PromptDefinition using `server.registerPrompt()`. Same arity rule
154
+ * as tools: an args-less prompt's callback receives only the SDK context.
155
+ */
179
156
  function registerPrompt(server, prompt) {
180
- const srv = server;
181
- const config = {};
182
- if (prompt.title) config.title = prompt.title;
183
- if (prompt.description) config.description = prompt.description;
184
- if (prompt.argsSchema) config.argsSchema = prompt.argsSchema;
185
- srv.registerPrompt(prompt.name, config, (args) => prompt.handler(args));
157
+ const config = {
158
+ ...prompt.title ? { title: prompt.title } : {},
159
+ ...prompt.description ? { description: prompt.description } : {}
160
+ };
161
+ const render = (args) => prompt.handler(args);
162
+ if (prompt.argsSchema) server.registerPrompt(prompt.name, {
163
+ ...config,
164
+ argsSchema: z.object(prompt.argsSchema)
165
+ }, (args) => render(args));
166
+ else server.registerPrompt(prompt.name, config, () => render({}));
186
167
  }
187
168
  // src/integrations/mcp/buildRequestContext.ts
188
169
  /**
@@ -867,20 +848,65 @@ const ALL_CRUD_OPS = [
867
848
  "update",
868
849
  "delete"
869
850
  ];
851
+ /**
852
+ * CRUD tool hints. `openWorldHint: false` because a CRUD tool reaches only the
853
+ * resource's own repository. Every hint is explicit: the spec defaults are
854
+ * the cautious ones (`destructiveHint` and `openWorldHint` default TRUE), so an
855
+ * omitted hint reads as "may destroy, may reach the internet".
856
+ */
870
857
  const CRUD_ANNOTATIONS = {
871
- list: { readOnlyHint: true },
872
- get: { readOnlyHint: true },
873
- create: { destructiveHint: false },
858
+ list: {
859
+ readOnlyHint: true,
860
+ openWorldHint: false
861
+ },
862
+ get: {
863
+ readOnlyHint: true,
864
+ openWorldHint: false
865
+ },
866
+ create: {
867
+ readOnlyHint: false,
868
+ destructiveHint: false,
869
+ idempotentHint: false,
870
+ openWorldHint: false
871
+ },
874
872
  update: {
873
+ readOnlyHint: false,
875
874
  destructiveHint: true,
876
- idempotentHint: true
875
+ idempotentHint: true,
876
+ openWorldHint: false
877
877
  },
878
878
  delete: {
879
+ readOnlyHint: false,
879
880
  destructiveHint: true,
880
- idempotentHint: true
881
+ idempotentHint: true,
882
+ openWorldHint: false
881
883
  }
882
884
  };
883
885
  /**
886
+ * Hints for a custom route, from its HTTP method's RFC 9110 semantics: GET /
887
+ * HEAD / OPTIONS are safe (read-only), PUT and DELETE idempotent, DELETE / PUT /
888
+ * PATCH / POST may overwrite or remove. `openWorldHint` is left unset — a
889
+ * route handler may call anything, so the spec's cautious default stands.
890
+ */
891
+ function routeAnnotations(method) {
892
+ switch (method.toUpperCase()) {
893
+ case "GET":
894
+ case "HEAD":
895
+ case "OPTIONS": return { readOnlyHint: true };
896
+ case "PUT":
897
+ case "DELETE": return {
898
+ readOnlyHint: false,
899
+ destructiveHint: true,
900
+ idempotentHint: true
901
+ };
902
+ default: return {
903
+ readOnlyHint: false,
904
+ destructiveHint: true,
905
+ idempotentHint: false
906
+ };
907
+ }
908
+ }
909
+ /**
884
910
  * Build a handler that dispatches to the controller method for `op` via
885
911
  * the shared {@link invokeController} pipeline. Permission check + context
886
912
  * build + envelope/error conversion all live in one place — this factory
@@ -1208,6 +1234,37 @@ function extractAuthCacheKey(headers) {
1208
1234
  function hashForCache(value) {
1209
1235
  return createHash("sha256").update(value).digest("hex").slice(0, 32);
1210
1236
  }
1237
+ /** Key under `AuthInfo.extra` carrying arc's resolved identity. */
1238
+ const ARC_AUTH_KEY = "arcAuth";
1239
+ /**
1240
+ * Arc identity → the SDK's `AuthInfo`, the pass-through `createMcpHandler`
1241
+ * hands to the server factory and to tools as `ctx.http.authInfo`. The full
1242
+ * arc result rides in `extra` so the factory recovers it without a lossy
1243
+ * round-trip through the OAuth-shaped fields.
1244
+ */
1245
+ function toSdkAuthInfo(auth, headers) {
1246
+ return {
1247
+ token: /^Bearer\s+(.+)$/i.exec(headers.authorization ?? "")?.[1] ?? "",
1248
+ clientId: auth.clientId ?? "",
1249
+ scopes: [...auth.scopes ?? []],
1250
+ extra: { [ARC_AUTH_KEY]: auth }
1251
+ };
1252
+ }
1253
+ /** Inverse of {@link toSdkAuthInfo}; `null` when the request carried no arc identity. */
1254
+ function fromSdkAuthInfo(authInfo) {
1255
+ const auth = authInfo?.extra?.[ARC_AUTH_KEY];
1256
+ return auth && typeof auth === "object" ? auth : null;
1257
+ }
1258
+ /**
1259
+ * `WWW-Authenticate` for a 401 under Better Auth: MCP's authorization spec has
1260
+ * the server point clients at its RFC 9728 protected-resource metadata, which
1261
+ * {@link registerOAuthDiscovery} serves. Custom resolvers get none — they are
1262
+ * often API-key gates, and a Bearer challenge would send clients into OAuth.
1263
+ */
1264
+ function oauthChallengeHeader(auth, req) {
1265
+ if (!auth || !isBetterAuth(auth)) return void 0;
1266
+ return `Bearer resource_metadata="${req.protocol}://${req.host}/.well-known/oauth-protected-resource"`;
1267
+ }
1211
1268
  /**
1212
1269
  * Register OAuth 2.1 discovery endpoints for MCP clients.
1213
1270
  * Only relevant when using Better Auth — custom auth doesn't need these.
@@ -1301,7 +1358,7 @@ function jsonSchemaPropToZod(schema) {
1301
1358
  * format can't express strict mode natively — see [./types.ts]).
1302
1359
  */
1303
1360
  function convertActionSchemaToZod(raw) {
1304
- return schemaIRToZodShape(normalizeSchemaIR(raw));
1361
+ return schemaIRToZodShape(actionSchemaIR(raw));
1305
1362
  }
1306
1363
  /**
1307
1364
  * Build an MCP tool handler for a declarative action.
@@ -1333,7 +1390,7 @@ function createActionToolHandler(actionName, handler, permissions, resourceName,
1333
1390
  log: wiring.log
1334
1391
  }
1335
1392
  } : { tenantMiddlewares: extras?.tenantMiddlewares };
1336
- const ir = rawSchema ? normalizeSchemaIR(rawSchema) : void 0;
1393
+ const ir = rawSchema ? actionSchemaIR(rawSchema) : void 0;
1337
1394
  const strict = ir ? shouldRejectAdditionalProperties(ir) : false;
1338
1395
  const allowedBaseKeys = [...idLess ? [] : ["id"], ...parity?.keyRequired ? ["_idempotencyKey"] : []];
1339
1396
  const allowedKeys = strict && ir ? /* @__PURE__ */ new Set([...allowedBaseKeys, ...Object.keys(ir.properties)]) : void 0;
@@ -1442,7 +1499,8 @@ function buildAggregationTools(args) {
1442
1499
  const description = buildAggregationToolDescription(norm, mcpCfg?.description);
1443
1500
  const annotations = mcpCfg?.annotations ? { ...mcpCfg.annotations } : {
1444
1501
  readOnlyHint: true,
1445
- idempotentHint: true
1502
+ idempotentHint: true,
1503
+ openWorldHint: false
1446
1504
  };
1447
1505
  const toolName = prefix ? `${prefix}_aggregation_${norm.name}_${resourceName}` : `aggregation_${norm.name}_${resourceName}`;
1448
1506
  tools.push({
@@ -1457,7 +1515,8 @@ function buildAggregationTools(args) {
1457
1515
  repo,
1458
1516
  buildOptionsFromSession,
1459
1517
  fields,
1460
- tenantMiddlewares: args.tenantMiddlewares
1518
+ tenantMiddlewares: args.tenantMiddlewares,
1519
+ fieldTypes: args.fieldTypes
1461
1520
  })
1462
1521
  });
1463
1522
  }
@@ -1522,7 +1581,8 @@ function createAggregationToolHandler(args) {
1522
1581
  };
1523
1582
  const result = await executeAggregation(normalized, {
1524
1583
  repo,
1525
- buildOptions: () => tenantOptions
1584
+ buildOptions: () => tenantOptions,
1585
+ ...args.fieldTypes ? { fieldTypes: args.fieldTypes } : {}
1526
1586
  }, {
1527
1587
  query: filterInput,
1528
1588
  tenantOptions,
@@ -2165,7 +2225,7 @@ function resourceToTools(resource, config = {}) {
2165
2225
  const hasId = route.path.includes(":id");
2166
2226
  const mcpConfig = typeof route.mcp === "object" && route.mcp !== null ? route.mcp : void 0;
2167
2227
  const toolDescription = mcpConfig?.description ?? route.summary ?? route.description ?? `${opName} on ${resource.displayName}`;
2168
- const toolAnnotations = mcpConfig?.annotations ? { ...mcpConfig.annotations } : route.method.toUpperCase() === "GET" ? { readOnlyHint: true } : { openWorldHint: true };
2228
+ const toolAnnotations = mcpConfig?.annotations ? { ...mcpConfig.annotations } : routeAnnotations(route.method);
2169
2229
  const inputShape = buildRouteInputSchema(route, hasId);
2170
2230
  const toolName = prefix ? `${prefix}_${opName}_${resource.name}` : `${opName}_${resource.name}`;
2171
2231
  const routeSource = route._presetSource ? `preset:${route._presetSource}:${resource.name}:${opName}` : `route:${resource.name}:${route.method} ${route.path}`;
@@ -2283,7 +2343,8 @@ function resourceToTools(resource, config = {}) {
2283
2343
  buildOptionsFromSession,
2284
2344
  tenantMiddlewares: resource.middlewares?.aggregations,
2285
2345
  prefix,
2286
- fields: resource.fields
2346
+ fields: resource.fields,
2347
+ fieldTypes: fieldTypesFromOpenApiSchemas(resource._registryMeta?.openApiSchemas)
2287
2348
  }));
2288
2349
  }
2289
2350
  return tools;
@@ -2357,126 +2418,14 @@ function getOps(r, override) {
2357
2418
  if (override) ops = ops.filter((op) => override.includes(op));
2358
2419
  return ops;
2359
2420
  }
2360
- // src/integrations/mcp/sessionCache.ts
2361
- const DEFAULT_TTL_MS = 18e5;
2362
- const DEFAULT_MAX_SESSIONS = 1e3;
2363
- var McpSessionCache = class {
2364
- sessions = /* @__PURE__ */ new Map();
2365
- ttlMs;
2366
- maxSessions;
2367
- cleanupTimer = null;
2368
- constructor(opts = {}) {
2369
- this.ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
2370
- this.maxSessions = opts.maxSessions ?? DEFAULT_MAX_SESSIONS;
2371
- if (this.ttlMs > 0) {
2372
- this.cleanupTimer = setInterval(() => this.cleanup(), Math.max(this.ttlMs / 2, 5e3));
2373
- if (this.cleanupTimer.unref) this.cleanupTimer.unref();
2374
- }
2375
- }
2376
- /** Get an existing session by ID */
2377
- get(sessionId) {
2378
- const entry = this.sessions.get(sessionId);
2379
- if (!entry) return void 0;
2380
- if (Date.now() - entry.lastAccessed > this.ttlMs) {
2381
- this.remove(sessionId);
2382
- return;
2383
- }
2384
- return entry;
2385
- }
2386
- /** Store a new session */
2387
- set(sessionId, entry) {
2388
- if (this.sessions.size >= this.maxSessions && !this.sessions.has(sessionId)) this.evictOldest();
2389
- entry.lastAccessed = Date.now();
2390
- this.sessions.set(sessionId, entry);
2391
- }
2392
- /** Refresh the TTL on a session */
2393
- touch(sessionId) {
2394
- const entry = this.sessions.get(sessionId);
2395
- if (entry) entry.lastAccessed = Date.now();
2396
- }
2397
- /** Remove and close a session */
2398
- remove(sessionId) {
2399
- const entry = this.sessions.get(sessionId);
2400
- if (entry) {
2401
- this.closeTransport(entry);
2402
- this.sessions.delete(sessionId);
2403
- }
2404
- }
2405
- /** Remove all expired sessions */
2406
- cleanup() {
2407
- const now = Date.now();
2408
- for (const [id, entry] of this.sessions) if (now - entry.lastAccessed > this.ttlMs) {
2409
- this.closeTransport(entry);
2410
- this.sessions.delete(id);
2411
- }
2412
- }
2413
- /** Close all sessions and stop cleanup timer */
2414
- close() {
2415
- if (this.cleanupTimer) {
2416
- clearInterval(this.cleanupTimer);
2417
- this.cleanupTimer = null;
2418
- }
2419
- for (const [id, entry] of this.sessions) {
2420
- this.closeTransport(entry);
2421
- this.sessions.delete(id);
2422
- }
2423
- }
2424
- /** Current session count */
2425
- get size() {
2426
- return this.sessions.size;
2427
- }
2428
- /** Evict the oldest (least recently accessed) session */
2429
- evictOldest() {
2430
- let oldestId = null;
2431
- let oldestTime = Infinity;
2432
- for (const [id, entry] of this.sessions) if (entry.lastAccessed < oldestTime) {
2433
- oldestTime = entry.lastAccessed;
2434
- oldestId = id;
2435
- }
2436
- if (oldestId) this.remove(oldestId);
2437
- }
2438
- /** Safely close a transport */
2439
- closeTransport(entry) {
2440
- try {
2441
- const transport = entry.transport;
2442
- if (transport && typeof transport.close === "function") Promise.resolve(transport.close()).catch(() => {});
2443
- } catch {}
2444
- }
2445
- };
2446
2421
  // src/integrations/mcp/mcpPlugin.ts
2447
- /**
2448
- * @classytic/arc — MCP Plugin (Level 1)
2449
- *
2450
- * Fastify plugin that auto-generates MCP tools from Arc resources.
2451
- *
2452
- * Two transport modes:
2453
- * - **Stateless** (default) — fresh server per request, no session tracking.
2454
- * Best for production, horizontal scaling, serverless, edge.
2455
- * - **Stateful** — sessions cached with TTL, reused across requests.
2456
- * Use when you need server-initiated notifications or long-lived connections.
2457
- *
2458
- * Auth is NOT enforced — the plugin respects whatever auth mode you choose:
2459
- * - `auth: false` — no auth, anonymous access (dev/testing/stdio)
2460
- * - `auth: betterAuthInstance` — OAuth 2.1 via Better Auth's mcp() plugin
2461
- * - `auth: async (headers) => {...}` — custom function (API key, JWT, gateway, etc.)
2462
- *
2463
- * @example
2464
- * ```typescript
2465
- * // Stateless (default) — production, scalable
2466
- * await app.register(mcpPlugin, { resources, auth: false });
2467
- *
2468
- * // Stateful — when you need session persistence
2469
- * await app.register(mcpPlugin, { resources, stateful: true, sessionTtlMs: 600000 });
2470
- *
2471
- * // Multiple MCP endpoints scoped to different resource groups
2472
- * await app.register(mcpPlugin, { resources: catalogResources, prefix: '/mcp/catalog' });
2473
- * await app.register(mcpPlugin, { resources: orderResources, prefix: '/mcp/orders' });
2474
- * ```
2475
- */
2422
+ /** The one MCP protocol revision arc's endpoint speaks. */
2423
+ const MCP_PROTOCOL_VERSION = "2026-07-28";
2476
2424
  const mcpPluginImpl = async (fastify, options) => {
2477
- let StreamableHTTPServerTransport;
2425
+ if (options.stateful === true) throw new Error(`mcpPlugin: \`stateful: true\` was removed — MCP ${MCP_PROTOCOL_VERSION} has no sessions, so every request is served statelessly. Delete \`stateful\`, \`sessionTtlMs\` and \`maxSessions\`.`);
2426
+ let nodeSdk;
2478
2427
  try {
2479
- StreamableHTTPServerTransport = (await import("@modelcontextprotocol/node")).NodeStreamableHTTPServerTransport;
2428
+ nodeSdk = await import("@modelcontextprotocol/node");
2480
2429
  } catch {
2481
2430
  throw new Error("@modelcontextprotocol/server and @modelcontextprotocol/node are required for MCP support. Install them: npm install @modelcontextprotocol/server @modelcontextprotocol/node");
2482
2431
  }
@@ -2536,18 +2485,14 @@ const mcpPluginImpl = async (fastify, options) => {
2536
2485
  fastify.log.info(`mcpPlugin: ${allTools.length} tools from ${enabledResources.length} resources`);
2537
2486
  const overrideOpsMap = {};
2538
2487
  for (const [name, cfg] of Object.entries(overrides)) overrideOpsMap[name] = { operations: cfg.operations };
2539
- const stateful = options.stateful === true;
2540
- const cache = stateful ? new McpSessionCache({
2541
- ttlMs: options.sessionTtlMs,
2542
- maxSessions: options.maxSessions
2543
- }) : null;
2544
2488
  async function createServerInstance(authRef) {
2545
2489
  const server = await createMcpServer({
2546
2490
  name: options.serverName ?? "arc-mcp",
2547
2491
  version: options.serverVersion ?? "1.0.0",
2548
2492
  instructions: options.instructions,
2549
2493
  tools: allTools,
2550
- prompts: options.extraPrompts
2494
+ prompts: options.extraPrompts,
2495
+ logger: fastify.log
2551
2496
  }, authRef);
2552
2497
  registerSchemaResources(server, enabledResources, overrideOpsMap);
2553
2498
  return server;
@@ -2592,7 +2537,7 @@ const mcpPluginImpl = async (fastify, options) => {
2592
2537
  fastify.get(`${prefix}/health`, async (request, reply) => {
2593
2538
  const liveness = {
2594
2539
  status: "ok",
2595
- mode: stateful ? "stateful" : "stateless"
2540
+ protocolVersion: MCP_PROTOCOL_VERSION
2596
2541
  };
2597
2542
  if (options.auth) {
2598
2543
  if (!await resolveMcpAuth(request.headers, options.auth)) return reply.send(liveness);
@@ -2601,23 +2546,14 @@ const mcpPluginImpl = async (fastify, options) => {
2601
2546
  ...liveness,
2602
2547
  tools: allTools.length,
2603
2548
  resources: enabledResources.length,
2604
- toolNames: allTools.map((t) => t.name),
2605
- sessions: cache?.size ?? null
2549
+ toolNames: allTools.map((t) => t.name)
2606
2550
  });
2607
2551
  });
2608
- if (stateful) {
2609
- if (!cache) throw new Error("[Arc/MCP] Stateful session cache missing in stateful registration");
2610
- registerStatefulRoutes(fastify, prefix, options, cache, createServerInstance, StreamableHTTPServerTransport);
2611
- } else {
2612
- const authCache = options.auth && options.authCacheTtlMs !== 0 ? new McpAuthCache({ ttlMs: options.authCacheTtlMs }) : void 0;
2613
- registerStatelessRoutes(fastify, prefix, options, createServerInstance, StreamableHTTPServerTransport, authCache);
2614
- }
2615
- if (cache) fastify.addHook("onClose", async () => cache.close());
2552
+ const authCache = options.auth && options.authCacheTtlMs !== 0 ? new McpAuthCache({ ttlMs: options.authCacheTtlMs }) : void 0;
2553
+ await registerRoutes(fastify, prefix, options, createServerInstance, nodeSdk.toNodeHandler, authCache);
2616
2554
  const registration = {
2617
- sessions: cache,
2618
2555
  toolNames: allTools.map((t) => t.name),
2619
- resourceNames: enabledResources.map((r) => r.name),
2620
- stateful
2556
+ resourceNames: enabledResources.map((r) => r.name)
2621
2557
  };
2622
2558
  if (!fastify.hasDecorator("mcp")) {
2623
2559
  const registrations = /* @__PURE__ */ new Map();
@@ -2628,17 +2564,11 @@ const mcpPluginImpl = async (fastify, options) => {
2628
2564
  get(p) {
2629
2565
  return registrations.get(p);
2630
2566
  },
2631
- get sessions() {
2632
- return first()?.sessions ?? null;
2633
- },
2634
2567
  get toolNames() {
2635
2568
  return first()?.toolNames ?? [];
2636
2569
  },
2637
2570
  get resourceNames() {
2638
2571
  return first()?.resourceNames ?? [];
2639
- },
2640
- get stateful() {
2641
- return first()?.stateful ?? false;
2642
2572
  }
2643
2573
  };
2644
2574
  fastify.decorate("mcp", decorator);
@@ -2650,138 +2580,48 @@ const mcpPluginImpl = async (fastify, options) => {
2650
2580
  }
2651
2581
  }
2652
2582
  };
2653
- function registerStatelessRoutes(fastify, prefix, options, createServer, Transport, authCache) {
2654
- fastify.post(prefix, async (request, reply) => {
2655
- const authResult = await resolveMcpAuth(request.headers, options.auth ?? false, authCache);
2656
- if (!authResult && options.auth) {
2657
- fastify.log.warn({
2658
- msg: "mcpPlugin: auth failed",
2659
- status: 401
2660
- });
2661
- return reply.code(401).send({
2662
- jsonrpc: "2.0",
2663
- error: {
2664
- code: -32e3,
2665
- message: "Unauthorized"
2666
- }
2667
- });
2668
- }
2669
- const authRef = { current: authResult };
2670
- const transport = new Transport({ sessionIdGenerator: void 0 });
2671
- await (await createServer(authRef)).connect(transport);
2672
- await transport.handleRequest(request.raw, reply.raw, request.body);
2583
+ async function registerRoutes(fastify, prefix, options, createServer, toNodeHandler, authCache) {
2584
+ const { createMcpHandler } = await import("@modelcontextprotocol/server");
2585
+ const onerror = (err) => fastify.log.error({ err }, "mcpPlugin: MCP request failed");
2586
+ const handler = createMcpHandler(({ authInfo }) => createServer({ current: fromSdkAuthInfo(authInfo) }), {
2587
+ legacy: "reject",
2588
+ onerror
2673
2589
  });
2674
- fastify.get(prefix, async (_request, reply) => {
2675
- reply.code(405).send({
2676
- jsonrpc: "2.0",
2677
- error: {
2678
- code: -32e3,
2679
- message: "SSE not available in stateless mode. Use stateful: true for server-initiated messages."
2680
- }
2681
- });
2682
- });
2683
- fastify.delete(prefix, async (_request, reply) => {
2684
- reply.code(200).send();
2685
- });
2686
- }
2687
- function registerStatefulRoutes(fastify, prefix, options, cache, createServer, Transport) {
2688
- /**
2689
- * Check if the requesting principal owns the session. FAIL-CLOSED:
2690
- *
2691
- * - `authResult === null` (failed/absent credentials) NEVER owns a
2692
- * session — pre-2.20 this returned `true`, so an unauthenticated
2693
- * caller with a leaked `Mcp-Session-Id` could attach to the victim's
2694
- * SSE stream, terminate the session, and (via the auth-snapshot
2695
- * refresh) wipe `entry.auth` to null — after which ANY principal
2696
- * passed ownership and took over the session.
2697
- * - `entry.auth === null` under configured auth is equally a deny:
2698
- * POST 401s before creating a session, so an auth-mode session always
2699
- * has an owner snapshot; a missing one means corrupted state.
2700
- */
2701
- function isSessionOwner(entry, authResult) {
2702
- if (!options.auth) return true;
2703
- if (!authResult || !entry.auth) return false;
2704
- const prev = entry.auth;
2705
- return prev.userId === authResult.userId && prev.organizationId === authResult.organizationId && prev.clientId === authResult.clientId;
2706
- }
2590
+ const serve = toNodeHandler(handler, { onerror });
2591
+ fastify.addHook("onClose", async () => handler.close());
2707
2592
  fastify.post(prefix, async (request, reply) => {
2708
- const authResult = await resolveMcpAuth(request.headers, options.auth ?? false);
2709
- if (!authResult && options.auth) {
2710
- fastify.log.warn({
2711
- msg: "mcpPlugin: auth failed",
2712
- status: 401
2713
- });
2714
- return reply.code(401).send({
2715
- jsonrpc: "2.0",
2716
- error: {
2717
- code: -32e3,
2718
- message: "Unauthorized"
2719
- }
2720
- });
2721
- }
2722
- const sessionId = requireSingleHeaderValue(request.headers, "mcp-session-id");
2723
- if (sessionId) {
2724
- const entry = cache.get(sessionId);
2725
- if (entry) {
2726
- if (!isSessionOwner(entry, authResult)) return reply.code(403).send({
2727
- jsonrpc: "2.0",
2728
- error: {
2729
- code: -32e3,
2730
- message: "Session ownership mismatch"
2731
- }
2732
- });
2733
- cache.touch(sessionId);
2734
- entry.auth = authResult;
2735
- entry.authRef.current = authResult;
2736
- await entry.transport.handleRequest(request.raw, reply.raw, request.body);
2737
- return;
2738
- }
2739
- }
2740
- const authRef = { current: authResult };
2741
- const transport = new Transport({
2742
- sessionIdGenerator: () => randomUUID(),
2743
- onsessioninitialized: (newSessionId) => {
2744
- cache.set(newSessionId, {
2745
- transport,
2746
- lastAccessed: Date.now(),
2747
- organizationId: authResult?.organizationId ?? "",
2748
- auth: authResult,
2749
- authRef
2750
- });
2751
- }
2752
- });
2753
- await (await createServer(authRef)).connect(transport);
2754
- await transport.handleRequest(request.raw, reply.raw, request.body);
2593
+ const headers = request.headers;
2594
+ const authResult = await resolveMcpAuth(headers, options.auth ?? false, authCache);
2595
+ if (!authResult && options.auth) return sendUnauthorized(fastify, options, request, reply);
2596
+ const raw = authResult ? Object.assign(request.raw, { auth: toSdkAuthInfo(authResult, headers) }) : request.raw;
2597
+ await serve(raw, reply.raw, request.body);
2755
2598
  });
2756
- fastify.get(prefix, async (request, reply) => {
2757
- const sessionId = requireSingleHeaderValue(request.headers, "mcp-session-id");
2758
- if (!sessionId) return reply.code(400).send({ error: "Missing Mcp-Session-Id header" });
2759
- const entry = cache.get(sessionId);
2760
- if (!entry) return reply.code(403).send({ error: "Unauthorized" });
2761
- if (options.auth) {
2762
- const authResult = await resolveMcpAuth(request.headers, options.auth);
2763
- if (!authResult) return reply.code(401).send({ error: "Unauthorized" });
2764
- if (!isSessionOwner(entry, authResult)) return reply.code(403).send({ error: "Unauthorized" });
2765
- entry.auth = authResult;
2766
- entry.authRef.current = authResult;
2767
- }
2768
- cache.touch(sessionId);
2769
- await entry.transport.handleRequest(request.raw, reply.raw);
2599
+ const methodNotAllowed = async (_request, reply) => reply.code(405).header("allow", "POST").send({
2600
+ jsonrpc: "2.0",
2601
+ error: {
2602
+ code: -32e3,
2603
+ message: `Method not allowed: MCP ${MCP_PROTOCOL_VERSION} is served over POST only.`
2604
+ },
2605
+ id: null
2770
2606
  });
2771
- fastify.delete(prefix, async (request, reply) => {
2772
- const sessionId = requireSingleHeaderValue(request.headers, "mcp-session-id");
2773
- if (!sessionId) return reply.code(400).send({ error: "Missing Mcp-Session-Id header" });
2774
- const entry = cache.get(sessionId);
2775
- if (!entry) return reply.code(204).send();
2776
- if (options.auth) {
2777
- const authResult = await resolveMcpAuth(request.headers, options.auth);
2778
- if (!authResult) return reply.code(401).send({ error: "Unauthorized" });
2779
- if (!isSessionOwner(entry, authResult)) return reply.code(403).send({ error: "Unauthorized" });
2780
- entry.auth = authResult;
2781
- entry.authRef.current = authResult;
2782
- }
2783
- cache.remove(sessionId);
2784
- reply.code(204).send();
2607
+ fastify.get(prefix, methodNotAllowed);
2608
+ fastify.delete(prefix, methodNotAllowed);
2609
+ }
2610
+ /** 401 in the JSON-RPC envelope; Better Auth adds the RFC 9728 challenge. */
2611
+ function sendUnauthorized(fastify, options, request, reply) {
2612
+ fastify.log.warn({
2613
+ msg: "mcpPlugin: auth failed",
2614
+ status: 401
2615
+ });
2616
+ const challenge = oauthChallengeHeader(options.auth, request);
2617
+ if (challenge) reply.header("www-authenticate", challenge);
2618
+ return reply.code(401).send({
2619
+ jsonrpc: "2.0",
2620
+ error: {
2621
+ code: -32e3,
2622
+ message: "Unauthorized"
2623
+ },
2624
+ id: null
2785
2625
  });
2786
2626
  }
2787
2627
  /**
@@ -2821,4 +2661,4 @@ const mcpPlugin = fp(mcpPluginImpl, {
2821
2661
  name: "arc-mcp",
2822
2662
  fastify: "5.x"
2823
2663
  });
2824
- export { resolveToolCollisions as _, toolInputShape as a, resolveCrudDescription as c, permissionDeniedResult as d, toCallToolError as f, createMcpServer as g, buildRequestContext as h, isZodTypeSchema as i, invokeController as l, toCallToolSuccess as m, mcpPlugin as n, fieldRulesToZod as o, toCallToolResult as p, resourceToTools as r, defaultCrudDescription as s, filterResourcesForMcp as t, mcpHandlerAdapter as u };
2664
+ export { createMcpServer as _, isZodTypeSchema as a, defaultCrudDescription as c, mcpHandlerAdapter as d, permissionDeniedResult as f, buildRequestContext as g, toCallToolSuccess as h, resourceToTools as i, resolveCrudDescription as l, toCallToolResult as m, filterResourcesForMcp as n, toolInputShape as o, toCallToolError as p, mcpPlugin as r, fieldRulesToZod as s, MCP_PROTOCOL_VERSION as t, invokeController as u, resolveToolCollisions as v };