effect 4.1.6 → 4.1.7

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 (173) hide show
  1. package/dist/Config.d.ts +1 -1
  2. package/dist/Config.d.ts.map +1 -1
  3. package/dist/Config.js +5 -3
  4. package/dist/Config.js.map +1 -1
  5. package/dist/Context.d.ts.map +1 -1
  6. package/dist/Context.js +79 -31
  7. package/dist/Context.js.map +1 -1
  8. package/dist/Cron.d.ts.map +1 -1
  9. package/dist/Cron.js +10 -9
  10. package/dist/Cron.js.map +1 -1
  11. package/dist/Equal.d.ts.map +1 -1
  12. package/dist/Equal.js +2 -3
  13. package/dist/Equal.js.map +1 -1
  14. package/dist/Formatter.js +4 -4
  15. package/dist/Formatter.js.map +1 -1
  16. package/dist/Hash.d.ts.map +1 -1
  17. package/dist/Hash.js +13 -27
  18. package/dist/Hash.js.map +1 -1
  19. package/dist/Metric.d.ts.map +1 -1
  20. package/dist/Metric.js +3 -4
  21. package/dist/Metric.js.map +1 -1
  22. package/dist/Pool.d.ts.map +1 -1
  23. package/dist/Pool.js +49 -21
  24. package/dist/Pool.js.map +1 -1
  25. package/dist/Predicate.d.ts.map +1 -1
  26. package/dist/Predicate.js +2 -1
  27. package/dist/Predicate.js.map +1 -1
  28. package/dist/Scheduler.d.ts.map +1 -1
  29. package/dist/Scheduler.js +15 -9
  30. package/dist/Scheduler.js.map +1 -1
  31. package/dist/SchemaAST.d.ts +2 -2
  32. package/dist/SchemaAST.d.ts.map +1 -1
  33. package/dist/SchemaAST.js +199 -95
  34. package/dist/SchemaAST.js.map +1 -1
  35. package/dist/SchemaParser.d.ts.map +1 -1
  36. package/dist/SchemaParser.js +29 -50
  37. package/dist/SchemaParser.js.map +1 -1
  38. package/dist/Tracer.d.ts.map +1 -1
  39. package/dist/Tracer.js +1 -4
  40. package/dist/Tracer.js.map +1 -1
  41. package/dist/ai/McpClient.d.ts +68 -4
  42. package/dist/ai/McpClient.d.ts.map +1 -1
  43. package/dist/ai/McpClient.js +100 -17
  44. package/dist/ai/McpClient.js.map +1 -1
  45. package/dist/ai/McpClientError.d.ts +46 -4
  46. package/dist/ai/McpClientError.d.ts.map +1 -1
  47. package/dist/ai/McpClientError.js +38 -3
  48. package/dist/ai/McpClientError.js.map +1 -1
  49. package/dist/ai/McpSchema.d.ts +88 -88
  50. package/dist/ai/McpSchema.d.ts.map +1 -1
  51. package/dist/ai/McpServer.d.ts +6 -5
  52. package/dist/ai/McpServer.d.ts.map +1 -1
  53. package/dist/ai/McpServer.js +95 -47
  54. package/dist/ai/McpServer.js.map +1 -1
  55. package/dist/ai/internal/mcpProtocol/v2024_11_05.js +9 -7
  56. package/dist/ai/internal/mcpProtocol/v2024_11_05.js.map +1 -1
  57. package/dist/ai/internal/mcpProtocol/v2025_03_26.js +12 -11
  58. package/dist/ai/internal/mcpProtocol/v2025_03_26.js.map +1 -1
  59. package/dist/ai/internal/mcpProtocol/v2025_06_18.js +18 -17
  60. package/dist/ai/internal/mcpProtocol/v2025_06_18.js.map +1 -1
  61. package/dist/ai/internal/mcpProtocol/v2025_11_25.js +19 -18
  62. package/dist/ai/internal/mcpProtocol/v2025_11_25.js.map +1 -1
  63. package/dist/ai/internal/mcpProtocol/v2026_07_28.js +1 -1
  64. package/dist/ai/internal/mcpProtocol/v2026_07_28.js.map +1 -1
  65. package/dist/ai/internal/mcpProtocol.js +11 -0
  66. package/dist/ai/internal/mcpProtocol.js.map +1 -1
  67. package/dist/ai/internal/mcpRuntime.js +29 -17
  68. package/dist/ai/internal/mcpRuntime.js.map +1 -1
  69. package/dist/ai/internal/mcpSchema/v2024_11_05.js +2 -1
  70. package/dist/ai/internal/mcpSchema/v2024_11_05.js.map +1 -1
  71. package/dist/ai/internal/mcpSchema/v2025_03_26.js +1 -8
  72. package/dist/ai/internal/mcpSchema/v2025_03_26.js.map +1 -1
  73. package/dist/ai/internal/mcpSchema/v2025_06_18.js +5 -9
  74. package/dist/ai/internal/mcpSchema/v2025_06_18.js.map +1 -1
  75. package/dist/ai/internal/mcpSchema/v2025_11_25.js +1 -8
  76. package/dist/ai/internal/mcpSchema/v2025_11_25.js.map +1 -1
  77. package/dist/ai/internal/mcpSchema/v2026_07_28.js +4 -3
  78. package/dist/ai/internal/mcpSchema/v2026_07_28.js.map +1 -1
  79. package/dist/cluster/ClusterCron.d.ts +5 -20
  80. package/dist/cluster/ClusterCron.d.ts.map +1 -1
  81. package/dist/cluster/ClusterCron.js +16 -4
  82. package/dist/cluster/ClusterCron.js.map +1 -1
  83. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  84. package/dist/cluster/SqlMessageStorage.js +3 -1
  85. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  86. package/dist/encoding/Hex.js +7 -5
  87. package/dist/encoding/Hex.js.map +1 -1
  88. package/dist/http/HttpEffect.d.ts.map +1 -1
  89. package/dist/http/HttpEffect.js +31 -2
  90. package/dist/http/HttpEffect.js.map +1 -1
  91. package/dist/http/HttpServerError.d.ts +1 -1
  92. package/dist/http/HttpServerError.js +1 -1
  93. package/dist/internal/core.js +60 -43
  94. package/dist/internal/core.js.map +1 -1
  95. package/dist/internal/effect.js +51 -51
  96. package/dist/internal/effect.js.map +1 -1
  97. package/dist/internal/equal.js +30 -0
  98. package/dist/internal/equal.js.map +1 -1
  99. package/dist/internal/fiberCachedKeys.d.ts +2 -0
  100. package/dist/internal/fiberCachedKeys.d.ts.map +1 -0
  101. package/dist/internal/fiberCachedKeys.js +48 -0
  102. package/dist/internal/fiberCachedKeys.js.map +1 -0
  103. package/dist/internal/hashMap.js +1 -1
  104. package/dist/internal/hashMap.js.map +1 -1
  105. package/dist/internal/predicate.d.ts +2 -0
  106. package/dist/internal/predicate.d.ts.map +1 -0
  107. package/dist/internal/predicate.js +10 -0
  108. package/dist/internal/predicate.js.map +1 -0
  109. package/dist/internal/references.js +8 -11
  110. package/dist/internal/references.js.map +1 -1
  111. package/dist/internal/version.js +1 -1
  112. package/dist/sql/Statement.d.ts +23 -0
  113. package/dist/sql/Statement.d.ts.map +1 -1
  114. package/dist/sql/Statement.js +30 -5
  115. package/dist/sql/Statement.js.map +1 -1
  116. package/dist/workers/Worker.d.ts +21 -0
  117. package/dist/workers/Worker.d.ts.map +1 -1
  118. package/dist/workers/Worker.js +23 -0
  119. package/dist/workers/Worker.js.map +1 -1
  120. package/package.json +1 -1
  121. package/src/Config.ts +6 -3
  122. package/src/Context.ts +108 -50
  123. package/src/Cron.ts +11 -10
  124. package/src/Equal.ts +10 -3
  125. package/src/Formatter.ts +4 -4
  126. package/src/Hash.ts +24 -31
  127. package/src/Metric.ts +4 -4
  128. package/src/Pool.ts +62 -33
  129. package/src/Predicate.ts +2 -5
  130. package/src/Scheduler.ts +27 -10
  131. package/src/SchemaAST.ts +231 -156
  132. package/src/SchemaParser.ts +40 -57
  133. package/src/Tracer.ts +1 -2
  134. package/src/ai/McpClient.ts +157 -15
  135. package/src/ai/McpClientError.ts +55 -4
  136. package/src/ai/McpServer.ts +157 -87
  137. package/src/ai/internal/mcpProtocol/v2024_11_05.ts +8 -13
  138. package/src/ai/internal/mcpProtocol/v2025_03_26.ts +13 -15
  139. package/src/ai/internal/mcpProtocol/v2025_06_18.ts +21 -23
  140. package/src/ai/internal/mcpProtocol/v2025_11_25.ts +22 -24
  141. package/src/ai/internal/mcpProtocol/v2026_07_28.ts +1 -1
  142. package/src/ai/internal/mcpProtocol.ts +15 -0
  143. package/src/ai/internal/mcpRuntime.ts +36 -13
  144. package/src/ai/internal/mcpSchema/v2024_11_05.ts +2 -1
  145. package/src/ai/internal/mcpSchema/v2025_03_26.ts +1 -9
  146. package/src/ai/internal/mcpSchema/v2025_06_18.ts +3 -10
  147. package/src/ai/internal/mcpSchema/v2025_11_25.ts +1 -9
  148. package/src/ai/internal/mcpSchema/v2026_07_28.ts +6 -8
  149. package/src/cluster/ClusterCron.ts +31 -20
  150. package/src/cluster/SqlMessageStorage.ts +7 -2
  151. package/src/encoding/Hex.ts +5 -5
  152. package/src/http/HttpEffect.ts +23 -3
  153. package/src/http/HttpServerError.ts +1 -1
  154. package/src/internal/core.ts +80 -44
  155. package/src/internal/effect.ts +84 -55
  156. package/src/internal/equal.ts +36 -0
  157. package/src/internal/fiberCachedKeys.ts +81 -0
  158. package/src/internal/hashMap.ts +1 -1
  159. package/src/internal/predicate.ts +10 -0
  160. package/src/internal/references.ts +21 -14
  161. package/src/internal/version.ts +1 -1
  162. package/src/sql/Statement.ts +48 -12
  163. package/src/workers/Worker.ts +25 -0
  164. package/dist/internal/hash.d.ts +0 -2
  165. package/dist/internal/hash.d.ts.map +0 -1
  166. package/dist/internal/hash.js +0 -14
  167. package/dist/internal/hash.js.map +0 -1
  168. package/dist/internal/metric.d.ts +0 -2
  169. package/dist/internal/metric.d.ts.map +0 -1
  170. package/dist/internal/metric.js +0 -3
  171. package/dist/internal/metric.js.map +0 -1
  172. package/src/internal/hash.ts +0 -15
  173. package/src/internal/metric.ts +0 -2
@@ -1102,6 +1102,7 @@ export class McpServer extends Context.Service<McpServer, {
1102
1102
  */
1103
1103
  static readonly make = Effect.gen(function*() {
1104
1104
  const internalCore = yield* McpCore.make
1105
+ const toolIndex = new Map<string, number>()
1105
1106
  const tools = Arr.empty<{
1106
1107
  readonly tool: McpTool
1107
1108
  readonly annotations: Context.Context<never>
@@ -1245,18 +1246,20 @@ export class McpServer extends Context.Service<McpServer, {
1245
1246
  return tools
1246
1247
  },
1247
1248
  addTool: Effect.fnUntraced(function*(options) {
1248
- const existingIndex = tools.findIndex(({ tool }) => tool.name === options.tool.name)
1249
- if (existingIndex === -1) {
1249
+ const existingIndex = toolIndex.get(options.tool.name)
1250
+ if (existingIndex === undefined) {
1251
+ toolIndex.set(options.tool.name, tools.length)
1250
1252
  tools.push(options)
1251
1253
  } else {
1252
1254
  tools[existingIndex] = options
1253
1255
  }
1254
1256
  const { invoke, visible } = makeInvoke(options.services, globalMiddleware)
1257
+ const title = options.tool.title ?? options.tool.annotations?.title
1255
1258
  yield* internalCore.tools.register({
1256
- descriptor: new McpTool({
1257
- ...options.tool,
1258
- title: options.tool.title ?? options.tool.annotations?.title
1259
- }),
1259
+ // Reuse a validated descriptor whose title is already resolved.
1260
+ descriptor: options.tool instanceof McpTool && title === options.tool.title
1261
+ ? options.tool
1262
+ : new McpTool({ ...options.tool, title }),
1260
1263
  visible: visible("tools/list", options.tool.name),
1261
1264
  isVisible: isEnabled(options.annotations),
1262
1265
  handle: (call, invocation, beforeHandle) =>
@@ -1538,6 +1541,7 @@ const requestSpanOptions = (
1538
1541
  readonly networkTransport: string | undefined
1539
1542
  readonly sessionId: string | undefined
1540
1543
  readonly recordToolArguments: boolean
1544
+ readonly server: McpServer["Service"]
1541
1545
  }
1542
1546
  ): Tracer.SpanOptionsNoTrace & { readonly name: string } => {
1543
1547
  const params = Predicate.isReadonlyObject(request.payload)
@@ -1554,18 +1558,20 @@ const requestSpanOptions = (
1554
1558
  switch (method) {
1555
1559
  case "tools/call": {
1556
1560
  attributes["gen_ai.operation.name"] = "execute_tool"
1557
- if (typeof params?.name === "string") {
1558
- target = params.name
1561
+ const registered = options.server.tools.find(({ tool }) => tool.name === params?.name)
1562
+ if (registered !== undefined) {
1563
+ target = registered.tool.name
1559
1564
  attributes["gen_ai.tool.name"] = target
1560
- }
1561
- if (options.recordToolArguments && params?.arguments !== undefined) {
1562
- attributes["gen_ai.tool.call.arguments"] = Toolkit.stringifyToolArguments(params.arguments)
1565
+ if (options.recordToolArguments && params?.arguments !== undefined) {
1566
+ attributes["gen_ai.tool.call.arguments"] = Toolkit.stringifyToolArguments(params.arguments)
1567
+ }
1563
1568
  }
1564
1569
  break
1565
1570
  }
1566
1571
  case "prompts/get": {
1567
- if (typeof params?.name === "string") {
1568
- target = params.name
1572
+ const registered = options.server.prompts.find(({ prompt }) => prompt.name === params?.name)
1573
+ if (registered !== undefined) {
1574
+ target = registered.prompt.name
1569
1575
  attributes["gen_ai.prompt.name"] = target
1570
1576
  }
1571
1577
  break
@@ -1573,8 +1579,9 @@ const requestSpanOptions = (
1573
1579
  case "resources/read":
1574
1580
  case "resources/subscribe":
1575
1581
  case "resources/unsubscribe": {
1576
- // Resource URIs can be unbounded and sensitive, so they stay out of the span name.
1577
- if (typeof params?.uri === "string") attributes["mcp.resource.uri"] = params.uri
1582
+ // Resource URIs stay out of span names; only registered static URIs are bounded enough to record.
1583
+ const registered = options.server.resources.find(({ resource }) => resource.uri === params?.uri)
1584
+ if (registered !== undefined) attributes["mcp.resource.uri"] = registered.resource.uri
1578
1585
  break
1579
1586
  }
1580
1587
  }
@@ -1723,11 +1730,12 @@ const normalizeCacheHints = (
1723
1730
  *
1724
1731
  * Each request handled by the server runs in a server span that follows the
1725
1732
  * OpenTelemetry MCP semantic conventions. Spans are named after the JSON-RPC
1726
- * method, with the tool or prompt name appended for `tools/call` and
1727
- * `prompts/get` (for example `tools/call get_weather`). A W3C `traceparent` in
1728
- * `params._meta` becomes the span's parent, and the transport span (such as
1729
- * the HTTP server span) is linked. Tool arguments are recorded only when
1730
- * `Toolkit.RecordToolArguments` is `true`.
1733
+ * method, with the tool or prompt name appended for registered `tools/call`
1734
+ * and `prompts/get` targets (for example `tools/call get_weather`).
1735
+ * `mcp.resource.uri` is recorded only for registered static resources. A W3C
1736
+ * `traceparent` in `params._meta` becomes the span's parent, and the transport
1737
+ * span (such as the HTTP server span) is linked. Tool arguments are recorded
1738
+ * only for registered tools when `Toolkit.RecordToolArguments` is `true`.
1731
1739
  *
1732
1740
  * @stability unstable
1733
1741
  * @category running
@@ -1806,7 +1814,8 @@ const runWithRuntime = Effect.fnUntraced(function*(
1806
1814
  sessionId: isHttp
1807
1815
  ? Context.getOrUndefined(fiber.context, HttpServerRequest.HttpServerRequest)?.headers[MCP_SESSION_ID_HEADER]
1808
1816
  : undefined,
1809
- recordToolArguments: fiber.getRef(Toolkit.RecordToolArguments)
1817
+ recordToolArguments: fiber.getRef(Toolkit.RecordToolArguments),
1818
+ server
1810
1819
  })
1811
1820
  const ambientParent = Context.getOrUndefined(fiber.context, Tracer.ParentSpan)
1812
1821
  return Effect.flatMap(
@@ -3005,12 +3014,19 @@ const addMcpHttpRoutes = Effect.fnUntraced(function*(
3005
3014
  const router = yield* HttpRouter.HttpRouter
3006
3015
  const allowSessionTermination = options.allowSessionTermination === true &&
3007
3016
  runtime.protocols.some((protocol) => protocol.runtime._tag === "Stateful")
3008
- const forbidden = Effect.succeed(HttpServerResponse.empty({ status: 403 }))
3009
- const withAllowedOrigin = (
3010
- handler: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse>
3017
+ const unsupportedContentType = Effect.succeed(mcpTransportRejection(415, "Content-Type must be application/json"))
3018
+ const notAcceptable = Effect.succeed(
3019
+ mcpTransportRejection(406, "Accept header must include both application/json and text/event-stream")
3020
+ )
3021
+ const withAllowedOrigin = <R>(
3022
+ handler: (
3023
+ request: HttpServerRequest.HttpServerRequest
3024
+ ) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, R>
3011
3025
  ) =>
3012
3026
  (request: HttpServerRequest.HttpServerRequest) =>
3013
- isAllowedMcpOrigin(request, options.allowedOrigins) ? handler(request) : forbidden
3027
+ isAllowedMcpOrigin(request, options.allowedOrigins)
3028
+ ? handler(request)
3029
+ : Effect.succeed(mcpTransportRejection(403, `Origin '${request.headers["origin"]}' is not allowed`))
3014
3030
  const methodNotAllowedResponse = Effect.succeed(HttpServerResponse.empty({
3015
3031
  status: 405,
3016
3032
  headers: { allow: allowSessionTermination ? "POST, DELETE" : "POST" }
@@ -3026,51 +3042,52 @@ const addMcpHttpRoutes = Effect.fnUntraced(function*(
3026
3042
  ? withAllowedOrigin((request) => runtime.terminateHttpSession(request.headers))
3027
3043
  : methodNotAllowed
3028
3044
  )
3029
- yield* router.add("POST", options.path, (request) => {
3030
- if (!isAllowedMcpOrigin(request, options.allowedOrigins)) {
3031
- return Effect.succeed(HttpServerResponse.empty({ status: 403 }))
3032
- }
3033
- if (mcpMediaTypes(request.headers["content-type"])[0] !== "application/json") {
3034
- return Effect.succeed(HttpServerResponse.empty({ status: 415 }))
3035
- }
3036
- const accepted = mcpMediaTypes(request.headers["accept"])
3037
- if (!accepted.includes("application/json") || !accepted.includes("text/event-stream")) {
3038
- return Effect.succeed(HttpServerResponse.empty({ status: 406 }))
3039
- }
3040
- return Effect.gen(function*() {
3041
- const parsed = yield* Effect.result(
3042
- Effect.flatMap(request.text, Schema.decodeEffect(Schema.UnknownFromJsonString))
3043
- )
3044
- const admission = runtime.admitHttp(request.headers, parsed)
3045
- if (admission._tag === "Rejected") {
3046
- return admission.response
3045
+ yield* router.add(
3046
+ "POST",
3047
+ options.path,
3048
+ withAllowedOrigin((request) => {
3049
+ if (mcpMediaTypes(request.headers["content-type"])[0] !== "application/json") {
3050
+ return unsupportedContentType
3047
3051
  }
3048
- const toResponse = (response: HttpServerResponse.HttpServerResponse) => {
3049
- // Completed responses may already contain notifications followed by the result.
3050
- const hasMultipleMessages = response.body._tag === "Uint8Array" &&
3051
- response.body.body.subarray(0, -1).includes(10)
3052
- return admission.isSubscription || response.body._tag === "Stream" || hasMultipleMessages
3053
- ? toServerSentEvents(response, admission.isSubscription)
3054
- : response
3052
+ const accepted = mcpMediaTypes(request.headers["accept"])
3053
+ if (!accepted.includes("application/json") || !accepted.includes("text/event-stream")) {
3054
+ return notAcceptable
3055
3055
  }
3056
- if (admission.acknowledge) {
3057
- return yield* Effect.catchCause(
3058
- Effect.map(httpEffect, toResponse),
3059
- () => Effect.succeed(HttpServerResponse.empty({ status: 202 }))
3056
+ return Effect.gen(function*() {
3057
+ const parsed = yield* Effect.result(
3058
+ Effect.flatMap(request.text, Schema.decodeEffect(Schema.UnknownFromJsonString))
3060
3059
  )
3061
- }
3062
- return yield* Effect.flatMap(httpEffect, (response) => {
3063
- if (response.body._tag !== "Uint8Array" || response.body.body.length > 0) {
3064
- return Effect.succeed(toResponse(response))
3060
+ const admission = runtime.admitHttp(request.headers, parsed)
3061
+ if (admission._tag === "Rejected") {
3062
+ return admission.response
3065
3063
  }
3066
- // Only fully cancelled request POSTs may return an empty SSE response.
3067
- // https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
3068
- return httpPostResponses.get(request)?.expected === 0
3069
- ? Effect.succeed(HttpServerResponse.stream(Stream.empty, { contentType: "text/event-stream" }))
3070
- : Effect.die(new Error("MCP request ended without writing its response"))
3064
+ const toResponse = (response: HttpServerResponse.HttpServerResponse) => {
3065
+ // Completed responses may already contain notifications followed by the result.
3066
+ const hasMultipleMessages = response.body._tag === "Uint8Array" &&
3067
+ response.body.body.subarray(0, -1).includes(10)
3068
+ return admission.isSubscription || response.body._tag === "Stream" || hasMultipleMessages
3069
+ ? toServerSentEvents(response, admission.isSubscription)
3070
+ : response
3071
+ }
3072
+ if (admission.acknowledge) {
3073
+ return yield* Effect.catchCause(
3074
+ Effect.map(httpEffect, toResponse),
3075
+ () => Effect.succeed(HttpServerResponse.empty({ status: 202 }))
3076
+ )
3077
+ }
3078
+ return yield* Effect.flatMap(httpEffect, (response) => {
3079
+ if (response.body._tag !== "Uint8Array" || response.body.body.length > 0) {
3080
+ return Effect.succeed(toResponse(response))
3081
+ }
3082
+ // Only fully cancelled request POSTs may return an empty SSE response.
3083
+ // https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
3084
+ return httpPostResponses.get(request)?.expected === 0
3085
+ ? Effect.succeed(HttpServerResponse.stream(Stream.empty, { contentType: "text/event-stream" }))
3086
+ : Effect.die(new Error("MCP request ended without writing its response"))
3087
+ })
3071
3088
  })
3072
3089
  })
3073
- })
3090
+ )
3074
3091
  })
3075
3092
 
3076
3093
  const mcpHttpSerialization: RpcSerialization.RpcSerialization["Service"] = (() => {
@@ -3193,6 +3210,9 @@ const isAllowedMcpOrigin = (
3193
3210
  return origin === undefined || (allowedOrigins ?? []).includes(origin)
3194
3211
  }
3195
3212
 
3213
+ const mcpTransportRejection = (status: 403 | 406 | 415, message: string): HttpServerResponse.HttpServerResponse =>
3214
+ McpRuntime.jsonRpcError(status, { code: McpSchema.INVALID_REQUEST_ERROR_CODE, message })
3215
+
3196
3216
  const mcpMediaTypes = (header: string | undefined): ReadonlyArray<string> =>
3197
3217
  header === undefined
3198
3218
  ? []
@@ -3423,6 +3443,9 @@ export const registerToolkit: <Tools extends Record<string, Tool.Any>, Names ext
3423
3443
  if (origin === "parameters" && isParameterValidationError(error)) {
3424
3444
  return Effect.fail(new InvalidParams({ message: error.reason.message }))
3425
3445
  }
3446
+ if (origin === "handler" && isInvalidParams(error)) {
3447
+ return Effect.fail(error)
3448
+ }
3426
3449
  if (origin === "handler" && isDeclaredFailure(error)) {
3427
3450
  return Effect.catchCause(declaredFailureResult(error), internalToolError)
3428
3451
  }
@@ -3431,40 +3454,48 @@ export const registerToolkit: <Tools extends Record<string, Tool.Any>, Names ext
3431
3454
  }
3432
3455
  const content = options?.content
3433
3456
  const mapper = content && Object.hasOwn(content, tool.name) ? content[tool.name as Names] : undefined
3434
- const outputSchema = mapper ? undefined : yield* Schema.decodeUnknownEffect(McpSchema.ToolOutputJson)(
3435
- toolJsonSchema(tool.successSchema, false)
3436
- ).pipe(Effect.orDie)
3437
- const inputSchema = yield* Schema.decodeUnknownEffect(ToolJson)(
3438
- rawJsonSchema ?? toolJsonSchema(tool.parametersSchema, strict)
3439
- ).pipe(
3440
- Effect.catchTag("SchemaError", (error) =>
3457
+ // Decoding copies a caller-owned raw schema, so later mutation does not change the descriptor.
3458
+ const inputSchema = rawJsonSchema === undefined
3459
+ ? toolJsonSchema(tool.parametersSchema, strict)
3460
+ : yield* Effect.catch(Schema.decodeUnknownEffect(ToolJson)(rawJsonSchema), (cause) =>
3441
3461
  Effect.die(
3442
- rawJsonSchema !== undefined
3443
- ? `McpServer cannot register tool '${tool.name}': its raw JSON Schema must have an object root ` +
3444
- `(type: "object").\n\n${error.message}`
3445
- : `McpServer cannot register tool '${tool.name}': its parameters must encode to a JSON Schema with an ` +
3446
- `object root (type: "object"), such as a Schema.Struct. Use Tool.EmptyParams for a tool without ` +
3447
- `parameters.\n\n${error.message}`
3462
+ `McpServer cannot register tool '${tool.name}': its raw JSON Schema must have an object root ` +
3463
+ `(type: "object").\n\n${cause.message}`
3448
3464
  ))
3449
- )
3465
+ const title = Context.getOrUndefined(tool.annotations, Tool.Title)
3450
3466
  const readOnlyHint = Context.get(tool.annotations, Tool.Readonly)
3451
- const mcpTool = new McpTool({
3467
+ const fields = {
3452
3468
  name: tool.name,
3469
+ title,
3453
3470
  description: Tool.getDescription(tool),
3454
- inputSchema,
3455
- outputSchema,
3471
+ inputSchema: inputSchema as McpSchema.ToolJson,
3472
+ outputSchema: mapper ? undefined : toolJsonSchema(tool.successSchema, false),
3456
3473
  annotations: {
3457
- ...(Context.getOption(tool.annotations, Tool.Title).pipe(
3458
- Option.map((title) => ({ title })),
3459
- Option.getOrUndefined
3460
- )),
3474
+ ...(title !== undefined ? { title } : undefined),
3461
3475
  readOnlyHint,
3462
3476
  destructiveHint: Context.getOrUndefined(tool.annotations, Tool.Destructive) ?? !readOnlyHint,
3463
3477
  idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
3464
3478
  openWorldHint: Context.get(tool.annotations, Tool.OpenWorld)
3465
3479
  },
3466
- _meta: toolMeta
3467
- })
3480
+ _meta: Predicate.isReadonlyObject(toolMeta) ? { ...toolMeta } : toolMeta
3481
+ }
3482
+ let mcpTool: McpTool
3483
+ if (isValidTool(fields)) {
3484
+ mcpTool = Schema.makeClassTrusted(McpTool, fields)
3485
+ } else {
3486
+ try {
3487
+ mcpTool = new McpTool(fields)
3488
+ } catch (error) {
3489
+ // Name the tool when the input schema lacks an object root; rethrow anything else.
3490
+ yield* Effect.catch(Schema.decodeUnknownEffect(ToolJson)(inputSchema), (cause) =>
3491
+ Effect.die(
3492
+ `McpServer cannot register tool '${tool.name}': its parameters must encode to a JSON Schema with an ` +
3493
+ `object root (type: "object"), such as a Schema.Struct. Use Tool.EmptyParams for a tool without ` +
3494
+ `parameters.\n\n${cause.message}`
3495
+ ))
3496
+ throw error
3497
+ }
3498
+ }
3468
3499
  registrations.push({
3469
3500
  tool: mcpTool,
3470
3501
  annotations,
@@ -3528,11 +3559,50 @@ export const registerToolkit: <Tools extends Record<string, Tool.Any>, Names ext
3528
3559
  }
3529
3560
  })
3530
3561
 
3562
+ const isInvalidParams = Schema.is(InvalidParams)
3563
+
3531
3564
  const isParameterValidationError = (
3532
3565
  error: unknown
3533
3566
  ): error is AiError.AiError & { readonly reason: AiError.ToolParameterValidationError } =>
3534
3567
  AiError.isAiError(error) && error.reason._tag === "ToolParameterValidationError"
3535
3568
 
3569
+ // Shallow check of the `McpTool` fields `registerToolkit` sets. Passing descriptors
3570
+ // skip schema validation; the rest go through the checked constructor.
3571
+ const isValidTool = (fields: {
3572
+ readonly name: unknown
3573
+ readonly title: unknown
3574
+ readonly description: unknown
3575
+ readonly inputSchema: unknown
3576
+ readonly outputSchema: unknown
3577
+ readonly annotations: { readonly [x: string]: unknown }
3578
+ readonly _meta: unknown
3579
+ }): boolean => {
3580
+ const { annotations, inputSchema } = fields
3581
+ if (!Predicate.isReadonlyObject(inputSchema)) return false
3582
+ const { properties, required } = inputSchema
3583
+ return typeof fields.name === "string" &&
3584
+ (fields.title === undefined || typeof fields.title === "string") &&
3585
+ (fields.description === undefined || typeof fields.description === "string") &&
3586
+ inputSchema.type === "object" &&
3587
+ (properties === undefined || (Predicate.isReadonlyObject(properties) &&
3588
+ Object.values(properties).every((value) => typeof value === "boolean" || Predicate.isReadonlyObject(value)))) &&
3589
+ (required === undefined || (Array.isArray(required) && isStringArray(required))) &&
3590
+ (fields.outputSchema === undefined || Predicate.isReadonlyObject(fields.outputSchema)) &&
3591
+ typeof annotations.readOnlyHint === "boolean" &&
3592
+ typeof annotations.destructiveHint === "boolean" &&
3593
+ typeof annotations.idempotentHint === "boolean" &&
3594
+ typeof annotations.openWorldHint === "boolean" &&
3595
+ (fields._meta === undefined || Predicate.isReadonlyObject(fields._meta))
3596
+ }
3597
+
3598
+ // Unlike `Array.prototype.every`, this also rejects holes in sparse arrays.
3599
+ const isStringArray = (array: ReadonlyArray<unknown>): boolean => {
3600
+ for (let i = 0; i < array.length; i++) {
3601
+ if (typeof array[i] !== "string") return false
3602
+ }
3603
+ return true
3604
+ }
3605
+
3536
3606
  // MCP requires an object root. A non-recursive root is compiled inline rather
3537
3607
  // than as a definition; a recursive root keeps its definition and the top-level
3538
3608
  // `$ref` is inlined.
@@ -18,6 +18,12 @@ const ClientRpcs = ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs)
18
18
 
19
19
  const AdapterRpcs = ClientRpcs.omit("ping")
20
20
 
21
+ const projectTool = McpProtocol.makeToolProjector(McpSchema.Tool, (tool) => ({
22
+ name: tool.name,
23
+ description: tool.description,
24
+ inputSchema: McpProtocol.projectLegacyToolInputSchema(tool.inputSchema)
25
+ }))
26
+
21
27
  const profileFromInitialize = (
22
28
  initialize: typeof McpSchema.Initialize.payloadSchema.Type
23
29
  ): McpCore.NegotiatedProtocolProfile => ({
@@ -246,19 +252,8 @@ export const protocol = McpProtocol.make({
246
252
  })
247
253
  }),
248
254
  "tools/list": Effect.fnUntraced(function*(pageRequest) {
249
- return yield* McpProtocol.listForClient(core.tools.list, pageRequest?.cursor).pipe(
250
- Effect.map((tools) =>
251
- McpSchema.ListToolsResult.make({
252
- tools: tools.map((tool) =>
253
- McpSchema.Tool.make({
254
- name: tool.name,
255
- description: tool.description,
256
- inputSchema: McpProtocol.projectLegacyToolInputSchema(tool.inputSchema)
257
- })
258
- )
259
- })
260
- )
261
- )
255
+ const tools = yield* McpProtocol.listForClient(core.tools.list, pageRequest?.cursor)
256
+ return { tools: yield* Effect.orDie(Effect.forEach(tools, projectTool)) }
262
257
  }),
263
258
  "tools/call": Effect.fnUntraced(function*(call) {
264
259
  const request = yield* PublicMcpSchema.McpServerClient
@@ -18,6 +18,18 @@ const ClientRpcs = ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs)
18
18
 
19
19
  const AdapterRpcs = ClientRpcs.omit("ping")
20
20
 
21
+ const projectTool = McpProtocol.makeToolProjector(McpSchema.Tool, (tool) => ({
22
+ name: tool.name,
23
+ description: tool.description,
24
+ inputSchema: McpProtocol.projectLegacyToolInputSchema(tool.inputSchema),
25
+ annotations: tool.title === undefined && tool.annotations === undefined
26
+ ? undefined
27
+ : {
28
+ ...tool.annotations,
29
+ title: tool.title
30
+ }
31
+ }))
32
+
21
33
  const profileFromInitialize = (
22
34
  initialize: typeof McpSchema.Initialize.payloadSchema.Type
23
35
  ): McpCore.NegotiatedProtocolProfile => ({
@@ -270,21 +282,7 @@ export const protocol = McpProtocol.make({
270
282
  }),
271
283
  "tools/list": Effect.fnUntraced(function*(pageRequest) {
272
284
  const tools = yield* McpProtocol.listForClient(core.tools.list, pageRequest?.cursor)
273
- return McpSchema.ListToolsResult.make({
274
- tools: tools.map((tool) =>
275
- McpSchema.Tool.make({
276
- name: tool.name,
277
- description: tool.description,
278
- inputSchema: McpProtocol.projectLegacyToolInputSchema(tool.inputSchema),
279
- annotations: tool.title === undefined && tool.annotations === undefined
280
- ? undefined
281
- : McpSchema.ToolAnnotations.make({
282
- ...tool.annotations,
283
- title: tool.title
284
- })
285
- })
286
- )
287
- })
285
+ return { tools: yield* Effect.orDie(Effect.forEach(tools, projectTool)) }
288
286
  }),
289
287
  "tools/call": Effect.fnUntraced(function*(call) {
290
288
  const request = yield* PublicMcpSchema.McpServerClient
@@ -35,6 +35,26 @@ const isToolOutputSchema = (
35
35
  return isPropertiesSupported && isRequiredDefined
36
36
  }
37
37
 
38
+ const projectTool = McpProtocol.makeToolProjector(McpSchema.Tool, (tool) => ({
39
+ name: tool.name,
40
+ title: tool.title,
41
+ description: tool.description,
42
+ inputSchema: tool.inputSchema,
43
+ outputSchema: isToolOutputSchema(tool.outputSchema)
44
+ ? tool.outputSchema
45
+ : undefined,
46
+ annotations: tool.annotations === undefined
47
+ ? undefined
48
+ : {
49
+ title: tool.annotations.title,
50
+ readOnlyHint: tool.annotations.readOnlyHint,
51
+ destructiveHint: tool.annotations.destructiveHint,
52
+ idempotentHint: tool.annotations.idempotentHint,
53
+ openWorldHint: tool.annotations.openWorldHint
54
+ },
55
+ _meta: tool._meta
56
+ }))
57
+
38
58
  const profileFromInitialize = (
39
59
  initialize: typeof McpSchema.Initialize.payloadSchema.Type
40
60
  ): McpCore.NegotiatedProtocolProfile => ({
@@ -263,29 +283,7 @@ export const protocol = McpProtocol.make({
263
283
  }),
264
284
  "tools/list": Effect.fnUntraced(function*(pageRequest) {
265
285
  const tools = yield* McpProtocol.listForClient(core.tools.list, pageRequest?.cursor)
266
- return McpSchema.ListToolsResult.make({
267
- tools: tools.map((tool) =>
268
- McpSchema.Tool.make({
269
- name: tool.name,
270
- title: tool.title,
271
- description: tool.description,
272
- inputSchema: tool.inputSchema,
273
- outputSchema: isToolOutputSchema(tool.outputSchema)
274
- ? tool.outputSchema
275
- : undefined,
276
- annotations: tool.annotations === undefined
277
- ? undefined
278
- : McpSchema.ToolAnnotations.make({
279
- title: tool.annotations.title,
280
- readOnlyHint: tool.annotations.readOnlyHint,
281
- destructiveHint: tool.annotations.destructiveHint,
282
- idempotentHint: tool.annotations.idempotentHint,
283
- openWorldHint: tool.annotations.openWorldHint
284
- }),
285
- _meta: tool._meta
286
- })
287
- )
288
- })
286
+ return { tools: yield* Effect.orDie(Effect.forEach(tools, projectTool)) }
289
287
  }),
290
288
  "tools/call": Effect.fnUntraced(function*(call) {
291
289
  const request = yield* PublicMcpSchema.McpServerClient
@@ -34,6 +34,27 @@ const isToolOutputSchema = (
34
34
  return isPropertiesSupported && isRequiredDefined
35
35
  }
36
36
 
37
+ const projectTool = McpProtocol.makeToolProjector(McpSchema.Tool, (tool) => ({
38
+ name: tool.name,
39
+ title: tool.title,
40
+ description: tool.description,
41
+ inputSchema: tool.inputSchema,
42
+ outputSchema: isToolOutputSchema(tool.outputSchema)
43
+ ? tool.outputSchema
44
+ : undefined,
45
+ icons: tool.icons,
46
+ annotations: tool.annotations === undefined
47
+ ? undefined
48
+ : {
49
+ title: tool.annotations.title,
50
+ readOnlyHint: tool.annotations.readOnlyHint,
51
+ destructiveHint: tool.annotations.destructiveHint,
52
+ idempotentHint: tool.annotations.idempotentHint,
53
+ openWorldHint: tool.annotations.openWorldHint
54
+ },
55
+ _meta: tool._meta
56
+ }))
57
+
37
58
  const unsupported = (
38
59
  operation: PublicMcpSchema.McpReverseOperationUnsupported["operation"],
39
60
  reason: string
@@ -286,30 +307,7 @@ export const protocol = McpProtocol.make({
286
307
  }),
287
308
  "tools/list": Effect.fnUntraced(function*(pageRequest) {
288
309
  const tools = yield* McpProtocol.listForClient(core.tools.list, pageRequest?.cursor)
289
- return McpSchema.ListToolsResult.make({
290
- tools: tools.map((tool) =>
291
- McpSchema.Tool.make({
292
- name: tool.name,
293
- title: tool.title,
294
- description: tool.description,
295
- inputSchema: tool.inputSchema,
296
- outputSchema: isToolOutputSchema(tool.outputSchema)
297
- ? tool.outputSchema
298
- : undefined,
299
- icons: tool.icons,
300
- annotations: tool.annotations === undefined
301
- ? undefined
302
- : McpSchema.ToolAnnotations.make({
303
- title: tool.annotations.title,
304
- readOnlyHint: tool.annotations.readOnlyHint,
305
- destructiveHint: tool.annotations.destructiveHint,
306
- idempotentHint: tool.annotations.idempotentHint,
307
- openWorldHint: tool.annotations.openWorldHint
308
- }),
309
- _meta: tool._meta
310
- })
311
- )
312
- })
310
+ return { tools: yield* Effect.orDie(Effect.forEach(tools, projectTool)) }
313
311
  }),
314
312
  "tools/call": Effect.fnUntraced(function*(call) {
315
313
  const request = yield* PublicMcpSchema.McpServerClient
@@ -209,7 +209,7 @@ const projectResourceTemplate = (resourceTemplate: PublicMcpSchema.ResourceTempl
209
209
 
210
210
  const projectPrompt = (prompt: PublicMcpSchema.Prompt) => Schema.encodeEffect(McpSchema.Prompt)(prompt)
211
211
 
212
- const projectTool = (tool: PublicMcpSchema.Tool) => McpProtocol.transcode(PublicMcpSchema.Tool, McpSchema.Tool, tool)
212
+ const projectTool = McpProtocol.makeToolProjector(McpSchema.Tool, (tool) => tool)
213
213
 
214
214
  const privateStaleCache = {
215
215
  ttlMs: 0,
@@ -1,6 +1,7 @@
1
1
  import * as Data from "../../Data.ts"
2
2
  import * as Effect from "../../Effect.ts"
3
3
  import * as Base64 from "../../encoding/Base64.ts"
4
+ import { memoize } from "../../Function.ts"
4
5
  import type * as Headers from "../../http/Headers.ts"
5
6
  import type * as LogLevel from "../../LogLevel.ts"
6
7
  import * as Match from "../../Match.ts"
@@ -357,6 +358,20 @@ export const transcodeStrict = <
357
358
  Effect.flatMap(Schema.decodeUnknownEffect(to, { onExcessProperty: "error" }))
358
359
  )
359
360
 
361
+ /**
362
+ * Encodes each tool descriptor instance to its JSON wire form once. A
363
+ * replaced tool is a new instance, so it is encoded afresh.
364
+ *
365
+ * @internal
366
+ */
367
+ export const makeToolProjector = <A>(
368
+ schema: Schema.Codec<A, unknown>,
369
+ project: (tool: PublicMcpSchema.Tool) => A
370
+ ) => {
371
+ const encode = Schema.encodeExit(Schema.toCodecJson(schema))
372
+ return memoize((tool: PublicMcpSchema.Tool) => encode(project(tool)))
373
+ }
374
+
360
375
  /**
361
376
  * @internal
362
377
  */