@classytic/arc 2.47.0 → 2.48.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 (160) hide show
  1. package/dist/{EventTransport-BHKy4_Bi.mjs → EventTransport-BWwg5YAU.mjs} +2 -2
  2. package/dist/{HookSystem-CAIDVoKC.mjs → HookSystem-B9x-Y_k7.mjs} +2 -2
  3. package/dist/{ResourceRegistry-23Ml6FNe.mjs → ResourceRegistry-BcvEJoZd.mjs} +2 -2
  4. package/dist/{acquire-DoFX06fm.mjs → acquire-D2yj6Zzl.mjs} +1 -1
  5. package/dist/{actionPermissions-DXrlWHHK.mjs → actionPermissions-Dha8sAz2.mjs} +13 -13
  6. package/dist/audit/index.mjs +4 -4
  7. package/dist/auth/audit.mjs +1 -1
  8. package/dist/auth/index.mjs +7 -7
  9. package/dist/auth/redis-session.mjs +1 -1
  10. package/dist/{authorizationDecision-DYiubkYw.mjs → authorizationDecision-BZSJcPNE.mjs} +4 -4
  11. package/dist/{boundedMap-CtdzpJ3X.mjs → boundedMap-o2KZDCWy.mjs} +1 -1
  12. package/dist/{buildHandler-CARdmPNo.mjs → buildHandler-G3k59KY2.mjs} +4 -4
  13. package/dist/cache/index.mjs +4 -4
  14. package/dist/{caching-QRiryDLs.mjs → caching-CJIDPZOv.mjs} +2 -2
  15. package/dist/{claimed-BLecr1j3.mjs → claimed-D0A43wjT.mjs} +1 -1
  16. package/dist/cleanup/index.mjs +4 -4
  17. package/dist/cli/commands/describe.mjs +3 -3
  18. package/dist/cli/commands/docs.mjs +3 -3
  19. package/dist/cli/commands/doctor.mjs +1 -1
  20. package/dist/cli/commands/generate.mjs +2 -2
  21. package/dist/cli/commands/init.mjs +2 -2
  22. package/dist/cli/commands/introspect.mjs +2 -2
  23. package/dist/cli/index.mjs +3 -3
  24. package/dist/{constants-Cx7BcnHT.mjs → constants-D-faL5SX.mjs} +1 -1
  25. package/dist/context/index.mjs +5 -5
  26. package/dist/core/index.mjs +7 -7
  27. package/dist/{core-0WyMuo0f.mjs → core-NSu1peyq.mjs} +3 -3
  28. package/dist/{createActionRouter-mLAGbpDV.mjs → createActionRouter-DTSVv1VK.mjs} +6 -6
  29. package/dist/{createAggregationRouter-BEAjn3dA.mjs → createAggregationRouter-zEasm-ax.mjs} +7 -7
  30. package/dist/{createApp-QDP4vYWH.mjs → createApp-CjqhkX1x.mjs} +29 -29
  31. package/dist/{createMcpServer-DzXHX0SO.d.mts → createMcpServer-hSFeqRUb.d.mts} +9 -10
  32. package/dist/{defineAggregation-CFNfvz-C.mjs → defineAggregation-DH2L6_v9.mjs} +1 -1
  33. package/dist/{defineResource-BROJmhzJ.mjs → defineResource-zYCrhNaN.mjs} +8 -8
  34. package/dist/discovery/index.mjs +1 -1
  35. package/dist/docs/index.mjs +3 -3
  36. package/dist/{elevation-DrXeEWWk.mjs → elevation-z--rFcZ5.mjs} +5 -5
  37. package/dist/encryption/index.mjs +3 -3
  38. package/dist/{errorHandler-BiBXtxj4.mjs → errorHandler-3_3oN-Uc.mjs} +3 -3
  39. package/dist/{errors-DnrUChAy.mjs → errors-DyY48oRi.mjs} +1 -1
  40. package/dist/{eventPlugin-BhKLUe7H.mjs → eventPlugin-Co9sABCg.mjs} +8 -8
  41. package/dist/{eventTypes-CCIRGakw.mjs → eventTypes-HmAFyJmJ.mjs} +2 -2
  42. package/dist/events/index.mjs +8 -8
  43. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  44. package/dist/events/transports/redis.mjs +2 -2
  45. package/dist/factory/index.mjs +6 -6
  46. package/dist/{fields-CYdpcV73.mjs → fields-rfsl26Ov.mjs} +1 -1
  47. package/dist/{filter-merge-6kasezRH.mjs → filter-merge-8glLr7Dk.mjs} +1 -1
  48. package/dist/{generate-DUkcbc4r.mjs → generate-BOfBueRt.mjs} +2 -2
  49. package/dist/{headers-KxhrKevA.mjs → headers-CHSOqpcY.mjs} +2 -2
  50. package/dist/{health-CRJg3IIq.mjs → health-DHvAIVmM.mjs} +1 -1
  51. package/dist/{health-jkYNdobJ.mjs → health-ezwTHQh2.mjs} +1 -1
  52. package/dist/hooks/index.mjs +2 -2
  53. package/dist/http-cache/index.mjs +4 -4
  54. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  55. package/dist/http-cache/purgers/fastly.mjs +2 -2
  56. package/dist/http-cache/testing/index.mjs +1 -1
  57. package/dist/idempotency/index.mjs +7 -7
  58. package/dist/idempotency/redis.mjs +2 -2
  59. package/dist/index.mjs +11 -11
  60. package/dist/{init-CACwpktI.mjs → init-MoE3eZNR.mjs} +1 -1
  61. package/dist/integrations/event-gateway.mjs +2 -2
  62. package/dist/integrations/index.d.mts +1 -1
  63. package/dist/integrations/index.mjs +1 -1
  64. package/dist/integrations/jobs/index.mjs +3 -3
  65. package/dist/integrations/mcp/index.d.mts +3 -35
  66. package/dist/integrations/mcp/index.mjs +2 -2
  67. package/dist/integrations/mcp/testing.d.mts +11 -15
  68. package/dist/integrations/mcp/testing.mjs +22 -42
  69. package/dist/integrations/streamline.mjs +3 -3
  70. package/dist/integrations/webhooks.mjs +4 -4
  71. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  72. package/dist/integrations/websocket-redis.mjs +1 -1
  73. package/dist/integrations/websocket.mjs +2 -2
  74. package/dist/{jsonBody-CzDBkCme.mjs → jsonBody-DZGiCawf.mjs} +2 -2
  75. package/dist/{keys-Cbwf6r1B.mjs → keys-CrMOZuk6.mjs} +1 -1
  76. package/dist/{loadResources-Kr6vuljv.mjs → loadResources-CVQvYUhN.mjs} +3 -3
  77. package/dist/{loadResourcesFromEntry-D2e0qoDR.mjs → loadResourcesFromEntry-D0naccV2.mjs} +2 -2
  78. package/dist/logger/index.mjs +2 -2
  79. package/dist/{logger-C110X5Yz.mjs → logger-VyMcSmVG.mjs} +1 -1
  80. package/dist/{mcpPlugin-4lIPr9OJ.mjs → mcpPlugin-DQACaqVu.mjs} +210 -373
  81. package/dist/{memory-D9qkhXiB.mjs → memory-Lpfu8Hga.mjs} +3 -3
  82. package/dist/{metrics-B-qrrWfI.mjs → metrics-DjVj1sg5.mjs} +3 -3
  83. package/dist/middleware/index.mjs +3 -3
  84. package/dist/migrations/index.mjs +2 -2
  85. package/dist/{module-BD8xHgrz.mjs → module-BqPJpZ_L.mjs} +1 -1
  86. package/dist/{multipartBody-qU7KCn1l.mjs → multipartBody-BNgNv7r0.mjs} +1 -1
  87. package/dist/{observeSend-BnPtTotW.mjs → observeSend-BKJHibJz.mjs} +1 -1
  88. package/dist/{openapi-DoVa5SVP.mjs → openapi-T90KrPR6.mjs} +6 -6
  89. package/dist/outbox-admin/index.mjs +5 -5
  90. package/dist/{outbox-module-DyITEIop.mjs → outbox-module-C874VgBr.mjs} +7 -7
  91. package/dist/permissions/index.mjs +7 -7
  92. package/dist/{permissions-BBy4bOGi.mjs → permissions-R9T2G1PH.mjs} +9 -9
  93. package/dist/{pipe-BOm2o4UA.mjs → pipe-DzqbsZy-.mjs} +2 -2
  94. package/dist/pipeline/index.mjs +2 -2
  95. package/dist/{plan-DDIGwuxr.mjs → plan-C0gkeABY.mjs} +1 -1
  96. package/dist/{plugin-Bn4D_0XK.mjs → plugin-BJcVOX5r.mjs} +22 -22
  97. package/dist/plugins/index.mjs +17 -17
  98. package/dist/plugins/response-cache.mjs +4 -4
  99. package/dist/plugins/tracing-entry.mjs +2 -2
  100. package/dist/{pluralize-ClEjcKlG.mjs → pluralize-CrCpyoZs.mjs} +1 -1
  101. package/dist/presets/filesUpload.mjs +5 -5
  102. package/dist/presets/index.mjs +2 -2
  103. package/dist/presets/multiTenant.mjs +5 -5
  104. package/dist/presets/search.mjs +2 -2
  105. package/dist/{presets-DK2jh5YR.mjs → presets-CNDvNYsz.mjs} +4 -4
  106. package/dist/{projection-BHH-sXyS.mjs → projection-CIUe8b59.mjs} +2 -2
  107. package/dist/{purger.types-2wNJK_89.mjs → purger.types-f83fTzGy.mjs} +1 -1
  108. package/dist/{queryCachePlugin-Ckqe98AM.mjs → queryCachePlugin-B2jpwFcv.mjs} +6 -6
  109. package/dist/{rateLimitKey-CWAjlqcN.mjs → rateLimitKey-BWx-qep0.mjs} +1 -1
  110. package/dist/{realtime-BIJi9USY.mjs → realtime-D2tqi3d2.mjs} +11 -11
  111. package/dist/registry/index.mjs +3 -3
  112. package/dist/{registry-y9ZA-R_J.mjs → registry-Dl0k6UXy.mjs} +2 -2
  113. package/dist/{relay-BNrC1CEP.mjs → relay-ZYvS4xyW.mjs} +4 -4
  114. package/dist/{renewingLease-CS43br5E.mjs → renewingLease-DT4yLb29.mjs} +1 -1
  115. package/dist/{replyHelpers-oZDzakGb.mjs → replyHelpers-BJFN5AW7.mjs} +2 -2
  116. package/dist/{requestContext-fWb_YaV2.mjs → requestContext-Ct5la-SA.mjs} +1 -1
  117. package/dist/{requirement--2hWyyHi.mjs → requirement-CxDxjB6V.mjs} +1 -1
  118. package/dist/{resourceRateLimit-1WbcyMZY.mjs → resourceRateLimit-D1oH2obv.mjs} +2 -2
  119. package/dist/{rolldown-runtime-yH2lHMo_.mjs → rolldown-runtime-BdTN42uL.mjs} +1 -1
  120. package/dist/{routeValidator-BSlRIA5c.mjs → routeValidator-DclDl5WJ.mjs} +1 -1
  121. package/dist/{runtimeCapabilities-CYCEtU1W.mjs → runtimeCapabilities-ClWr60El.mjs} +1 -1
  122. package/dist/{schedules-B5WGlYIT.mjs → schedules-gVkRcs-9.mjs} +5 -5
  123. package/dist/{schemaConverter-DtNvts-6.mjs → schemaConverter-CIwB5wPO.mjs} +2 -2
  124. package/dist/{schemaIR-uS_RHqa3.mjs → schemaIR-A0IoD05P.mjs} +2 -2
  125. package/dist/schemas/index.mjs +1 -1
  126. package/dist/scim/index.mjs +2 -2
  127. package/dist/scope/index.mjs +5 -5
  128. package/dist/{scope-BwVLSyNG.mjs → scope-VMZhdkbT.mjs} +4 -4
  129. package/dist/{shutdown-BJiJN7FT.mjs → shutdown-Bi19vH0z.mjs} +1 -1
  130. package/dist/{simpleEqualityMatcher-DGRLq-1k.mjs → simpleEqualityMatcher-CaCS09fh.mjs} +1 -1
  131. package/dist/{sse-B_50llZu.mjs → sse-BqM359f1.mjs} +7 -7
  132. package/dist/{sseStream-BjSo9Ult.mjs → sseStream-qSa-F2Qm.mjs} +2 -2
  133. package/dist/{store-helpers-D-n5cwy5.mjs → store-helpers-rx-F2ZGR.mjs} +1 -1
  134. package/dist/{streaming-Dcgqa-hH.mjs → streaming-CPChx3A7.mjs} +1 -1
  135. package/dist/{subscriberIdentity-C9KhIXTF.mjs → subscriberIdentity-CYNYw8p_.mjs} +1 -1
  136. package/dist/{tenancy-COrhjPRZ.mjs → tenancy-BoWImS3K.mjs} +2 -2
  137. package/dist/{tenantPreparation-BElWHytd.mjs → tenantPreparation-oqKCZQZM.mjs} +4 -4
  138. package/dist/testing/cleanupStoreContract.mjs +1 -1
  139. package/dist/testing/index.mjs +11 -11
  140. package/dist/testing/outboxStoreContract.mjs +2 -2
  141. package/dist/testing/requiredPorts.mjs +2 -2
  142. package/dist/testing/storageContract.mjs +1 -1
  143. package/dist/{timing-CaxKbRk_.mjs → timing-Dsteq59c.mjs} +1 -1
  144. package/dist/{transactionContext-8qKON0Nk.mjs → transactionContext-C1OgH-hW.mjs} +1 -1
  145. package/dist/{typeGuards-DVjVSsXO.mjs → typeGuards-DNlpASzd.mjs} +1 -1
  146. package/dist/types/index.mjs +1 -1
  147. package/dist/types/storage.mjs +1 -1
  148. package/dist/{types-DeLiuaNv.d.mts → types-DduBiYaI.d.mts} +18 -29
  149. package/dist/{types-DZHqOuJE.mjs → types-HFFSwF_K.mjs} +4 -4
  150. package/dist/usage/index.mjs +4 -4
  151. package/dist/{userHelpers-_eGj6kf0.mjs → userHelpers-N-k-8dNF.mjs} +1 -1
  152. package/dist/utils/index.mjs +12 -12
  153. package/dist/{utils-Dd6MWpye.mjs → utils-C7w_RVlx.mjs} +5 -5
  154. package/dist/{validate-BaF5wd0x.mjs → validate-Brr4b_fH.mjs} +3 -3
  155. package/dist/{versioning-DyV7mwtK.mjs → versioning-CE5kdWOY.mjs} +3 -3
  156. package/dist/{workScope-CmCBUmPR.mjs → workScope-A3XBpYTa.mjs} +2 -2
  157. package/package.json +15 -23
  158. package/skills/arc/references/mcp-custom-tools.md +1 -1
  159. package/skills/arc/references/mcp-setup.md +11 -10
  160. package/skills/arc/references/mcp-testing.md +3 -3
@@ -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.48.0 | MIT | https://classytic.com */
2
+ import { t as arcLog } from "./logger-VyMcSmVG.mjs";
3
+ import { i as NotFoundError, p as isArcError, t as ArcError } from "./errors-DyY48oRi.mjs";
4
+ import { f as BaseController, n as normalizeActionsToRouterConfig, r as resolveActionTargetFence } from "./plugin-BJcVOX5r.mjs";
5
+ import { b as isElevated, c as getOrgId, g as getUserId, x as isMember } from "./types-HFFSwF_K.mjs";
6
+ import { a as resolveEffectiveRoles, t as applyFieldReadPermissions } from "./fields-rfsl26Ov.mjs";
7
+ import { o as toJsonSchema } from "./schemaConverter-CIwB5wPO.mjs";
8
+ import { t as buildRequestScopeProjection } from "./projection-CIUe8b59.mjs";
9
+ import { l as resolvePipelineSteps, t as resolveActionPermission } from "./actionPermissions-Dha8sAz2.mjs";
10
+ import { a as withoutTenantInjection, r as prepareTenantContext } from "./tenantPreparation-oqKCZQZM.mjs";
11
+ import { r as evaluatePermissionDecision } from "./authorizationDecision-BZSJcPNE.mjs";
12
+ import { n as declareRuntimeCapability } from "./runtimeCapabilities-ClWr60El.mjs";
13
+ import { t as executePipeline } from "./pipe-DzqbsZy-.mjs";
14
+ import { a as resourceRateLimitWindowMs, i as resolveResourceRateLimiter, t as createMemoryResourceRateLimiter } from "./resourceRateLimit-D1oH2obv.mjs";
15
+ import { n as evictToSize, r as touch, t as assertCapacity } from "./boundedMap-o2KZDCWy.mjs";
16
+ import { t as pluralize } from "./pluralize-CrCpyoZs.mjs";
17
+ import { n as createIdempotencyResult, r as operationIdentity, t as resolveIdempotencyTiming } from "./timing-Dsteq59c.mjs";
18
+ import { n as acquireIdempotencyKey, r as releaseIdempotencyLock } from "./acquire-D2yj6Zzl.mjs";
19
+ import { r as shouldRejectAdditionalProperties, t as normalizeSchemaIR } from "./schemaIR-A0IoD05P.mjs";
20
+ import { n as validateAggregations } from "./validate-Brr4b_fH.mjs";
21
+ import { n as executeAggregation } from "./buildHandler-G3k59KY2.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.
@@ -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({
@@ -2165,7 +2223,7 @@ function resourceToTools(resource, config = {}) {
2165
2223
  const hasId = route.path.includes(":id");
2166
2224
  const mcpConfig = typeof route.mcp === "object" && route.mcp !== null ? route.mcp : void 0;
2167
2225
  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 };
2226
+ const toolAnnotations = mcpConfig?.annotations ? { ...mcpConfig.annotations } : routeAnnotations(route.method);
2169
2227
  const inputShape = buildRouteInputSchema(route, hasId);
2170
2228
  const toolName = prefix ? `${prefix}_${opName}_${resource.name}` : `${opName}_${resource.name}`;
2171
2229
  const routeSource = route._presetSource ? `preset:${route._presetSource}:${resource.name}:${opName}` : `route:${resource.name}:${route.method} ${route.path}`;
@@ -2357,126 +2415,14 @@ function getOps(r, override) {
2357
2415
  if (override) ops = ops.filter((op) => override.includes(op));
2358
2416
  return ops;
2359
2417
  }
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
2418
  // 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
- */
2419
+ /** The one MCP protocol revision arc's endpoint speaks. */
2420
+ const MCP_PROTOCOL_VERSION = "2026-07-28";
2476
2421
  const mcpPluginImpl = async (fastify, options) => {
2477
- let StreamableHTTPServerTransport;
2422
+ 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\`.`);
2423
+ let nodeSdk;
2478
2424
  try {
2479
- StreamableHTTPServerTransport = (await import("@modelcontextprotocol/node")).NodeStreamableHTTPServerTransport;
2425
+ nodeSdk = await import("@modelcontextprotocol/node");
2480
2426
  } catch {
2481
2427
  throw new Error("@modelcontextprotocol/server and @modelcontextprotocol/node are required for MCP support. Install them: npm install @modelcontextprotocol/server @modelcontextprotocol/node");
2482
2428
  }
@@ -2536,18 +2482,14 @@ const mcpPluginImpl = async (fastify, options) => {
2536
2482
  fastify.log.info(`mcpPlugin: ${allTools.length} tools from ${enabledResources.length} resources`);
2537
2483
  const overrideOpsMap = {};
2538
2484
  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
2485
  async function createServerInstance(authRef) {
2545
2486
  const server = await createMcpServer({
2546
2487
  name: options.serverName ?? "arc-mcp",
2547
2488
  version: options.serverVersion ?? "1.0.0",
2548
2489
  instructions: options.instructions,
2549
2490
  tools: allTools,
2550
- prompts: options.extraPrompts
2491
+ prompts: options.extraPrompts,
2492
+ logger: fastify.log
2551
2493
  }, authRef);
2552
2494
  registerSchemaResources(server, enabledResources, overrideOpsMap);
2553
2495
  return server;
@@ -2592,7 +2534,7 @@ const mcpPluginImpl = async (fastify, options) => {
2592
2534
  fastify.get(`${prefix}/health`, async (request, reply) => {
2593
2535
  const liveness = {
2594
2536
  status: "ok",
2595
- mode: stateful ? "stateful" : "stateless"
2537
+ protocolVersion: MCP_PROTOCOL_VERSION
2596
2538
  };
2597
2539
  if (options.auth) {
2598
2540
  if (!await resolveMcpAuth(request.headers, options.auth)) return reply.send(liveness);
@@ -2601,23 +2543,14 @@ const mcpPluginImpl = async (fastify, options) => {
2601
2543
  ...liveness,
2602
2544
  tools: allTools.length,
2603
2545
  resources: enabledResources.length,
2604
- toolNames: allTools.map((t) => t.name),
2605
- sessions: cache?.size ?? null
2546
+ toolNames: allTools.map((t) => t.name)
2606
2547
  });
2607
2548
  });
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());
2549
+ const authCache = options.auth && options.authCacheTtlMs !== 0 ? new McpAuthCache({ ttlMs: options.authCacheTtlMs }) : void 0;
2550
+ await registerRoutes(fastify, prefix, options, createServerInstance, nodeSdk.toNodeHandler, authCache);
2616
2551
  const registration = {
2617
- sessions: cache,
2618
2552
  toolNames: allTools.map((t) => t.name),
2619
- resourceNames: enabledResources.map((r) => r.name),
2620
- stateful
2553
+ resourceNames: enabledResources.map((r) => r.name)
2621
2554
  };
2622
2555
  if (!fastify.hasDecorator("mcp")) {
2623
2556
  const registrations = /* @__PURE__ */ new Map();
@@ -2628,17 +2561,11 @@ const mcpPluginImpl = async (fastify, options) => {
2628
2561
  get(p) {
2629
2562
  return registrations.get(p);
2630
2563
  },
2631
- get sessions() {
2632
- return first()?.sessions ?? null;
2633
- },
2634
2564
  get toolNames() {
2635
2565
  return first()?.toolNames ?? [];
2636
2566
  },
2637
2567
  get resourceNames() {
2638
2568
  return first()?.resourceNames ?? [];
2639
- },
2640
- get stateful() {
2641
- return first()?.stateful ?? false;
2642
2569
  }
2643
2570
  };
2644
2571
  fastify.decorate("mcp", decorator);
@@ -2650,138 +2577,48 @@ const mcpPluginImpl = async (fastify, options) => {
2650
2577
  }
2651
2578
  }
2652
2579
  };
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);
2580
+ async function registerRoutes(fastify, prefix, options, createServer, toNodeHandler, authCache) {
2581
+ const { createMcpHandler } = await import("@modelcontextprotocol/server");
2582
+ const onerror = (err) => fastify.log.error({ err }, "mcpPlugin: MCP request failed");
2583
+ const handler = createMcpHandler(({ authInfo }) => createServer({ current: fromSdkAuthInfo(authInfo) }), {
2584
+ legacy: "reject",
2585
+ onerror
2673
2586
  });
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
- }
2587
+ const serve = toNodeHandler(handler, { onerror });
2588
+ fastify.addHook("onClose", async () => handler.close());
2707
2589
  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);
2590
+ const headers = request.headers;
2591
+ const authResult = await resolveMcpAuth(headers, options.auth ?? false, authCache);
2592
+ if (!authResult && options.auth) return sendUnauthorized(fastify, options, request, reply);
2593
+ const raw = authResult ? Object.assign(request.raw, { auth: toSdkAuthInfo(authResult, headers) }) : request.raw;
2594
+ await serve(raw, reply.raw, request.body);
2755
2595
  });
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);
2596
+ const methodNotAllowed = async (_request, reply) => reply.code(405).header("allow", "POST").send({
2597
+ jsonrpc: "2.0",
2598
+ error: {
2599
+ code: -32e3,
2600
+ message: `Method not allowed: MCP ${MCP_PROTOCOL_VERSION} is served over POST only.`
2601
+ },
2602
+ id: null
2770
2603
  });
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();
2604
+ fastify.get(prefix, methodNotAllowed);
2605
+ fastify.delete(prefix, methodNotAllowed);
2606
+ }
2607
+ /** 401 in the JSON-RPC envelope; Better Auth adds the RFC 9728 challenge. */
2608
+ function sendUnauthorized(fastify, options, request, reply) {
2609
+ fastify.log.warn({
2610
+ msg: "mcpPlugin: auth failed",
2611
+ status: 401
2612
+ });
2613
+ const challenge = oauthChallengeHeader(options.auth, request);
2614
+ if (challenge) reply.header("www-authenticate", challenge);
2615
+ return reply.code(401).send({
2616
+ jsonrpc: "2.0",
2617
+ error: {
2618
+ code: -32e3,
2619
+ message: "Unauthorized"
2620
+ },
2621
+ id: null
2785
2622
  });
2786
2623
  }
2787
2624
  /**
@@ -2821,4 +2658,4 @@ const mcpPlugin = fp(mcpPluginImpl, {
2821
2658
  name: "arc-mcp",
2822
2659
  fastify: "5.x"
2823
2660
  });
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 };
2661
+ 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 };