Skip to content

Commit 6bccdd5

Browse files
Marve10seffect-bot
andauthored
Fix McpServer declared tool failures that are not JSON returning an internal error (#10243)
Co-authored-by: Effect Bot <[email protected]>
1 parent d7b3b6b commit 6bccdd5

4 files changed

Lines changed: 59 additions & 32 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Encode declared `McpServer` tool failures with their JSON codec, so values such as `bigint`, `Map` and `Option` no longer cause an internal error or lossy output

‎packages/effect/MCP.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,9 @@ other registrations and passed to the server.
253253

254254
A tool result is sent to the client in its JSON encoding, the same encoding its advertised
255255
`outputSchema` describes. For example, a `Schema.Date` field is sent as an ISO string and a
256-
`Schema.Void` field as `null`.
256+
`Schema.Void` field as `null`. Declared failures are sent as text in the JSON encoding of their
257+
`failure` schema. In the default `"error"` failure mode, a declared `Error` with a non-empty
258+
`message` is sent as that message instead.
257259

258260
## Request-level dependencies
259261

‎packages/effect/src/ai/McpServer.ts‎

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3106,40 +3106,40 @@ export const registerToolkit: <Tools extends Record<string, Tool.Any>>(
31063106
const annotations = tool.annotations
31073107
const toolMeta = Context.getOrUndefined(annotations, Tool.Meta)
31083108
const isDeclaredFailure = Schema.is(tool.failureSchema)
3109-
const encodeFailure = Schema.encodeUnknownEffect(tool.failureSchema) as (
3110-
error: unknown
3111-
) => Effect.Effect<unknown, Schema.SchemaError, Tool.HandlerServices<Tools[keyof Tools]>>
3112-
const declaredFailureResult = (error: unknown) =>
3113-
error instanceof Error && error.message !== ""
3114-
? Effect.succeed(toolErrorResult(error.message))
3115-
: Effect.map(encodeFailure(error), (encoded) =>
3116-
new CallToolResult({ isError: true, content: toolResultContent(encoded) }))
3117-
// `structuredContent` must be JSON and match the advertised `outputSchema`, which is derived from the JSON codec.
3118-
// The Toolkit has already encoded the result, so only the JSON conversion of its encoded form runs here.
3119-
const encodeStructured = Schema.encodeUnknownEffect(Schema.toCodecJson(Schema.toEncoded(tool.successSchema))) as (
3120-
result: unknown
3121-
) => Effect.Effect<unknown, Schema.SchemaError, Tool.HandlerServices<Tools[keyof Tools]>>
3122-
const successResult = (result: unknown) =>
3123-
encodeStructured(result).pipe(
3124-
Effect.mapError((cause) =>
3109+
// MCP content is JSON, so results and declared failures go through their JSON codec.
3110+
const encodeJson = (schema: Schema.Constraint) => {
3111+
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema)) as (
3112+
value: unknown
3113+
) => Effect.Effect<unknown, Schema.SchemaError, Tool.HandlerServices<Tools[keyof Tools]>>
3114+
return (toolResult: unknown) =>
3115+
Effect.mapError(encode(toolResult), (cause) =>
31253116
AiError.make({
31263117
module: "McpServer",
31273118
method: "registerToolkit",
31283119
reason: new AiError.ToolResultEncodingError({
31293120
toolName: tool.name,
3130-
toolResult: result,
3121+
toolResult,
31313122
description: cause.message
31323123
})
3133-
})
3134-
),
3135-
Effect.map((structuredContent) =>
3136-
new CallToolResult({
3137-
isError: false,
3138-
structuredContent,
3139-
content: toolResultContent(structuredContent)
3140-
})
3141-
)
3142-
)
3124+
}))
3125+
}
3126+
const encodeFailure = encodeJson(tool.failureSchema)
3127+
// Successes and "return"-mode failures arrive already encoded by the Toolkit; only their JSON conversion runs here.
3128+
const encodeReturnedFailure = encodeJson(Schema.toEncoded(tool.failureSchema))
3129+
const encodeStructured = encodeJson(Schema.toEncoded(tool.successSchema))
3130+
const failureResult = (encoded: unknown) =>
3131+
new CallToolResult({ isError: true, content: toolResultContent(encoded) })
3132+
const declaredFailureResult = (error: unknown) =>
3133+
error instanceof Error && error.message !== ""
3134+
? Effect.succeed(toolErrorResult(error.message))
3135+
: Effect.map(encodeFailure(error), failureResult)
3136+
const successResult = (result: unknown) =>
3137+
Effect.map(encodeStructured(result), (structuredContent) =>
3138+
new CallToolResult({
3139+
isError: false,
3140+
structuredContent,
3141+
content: toolResultContent(structuredContent)
3142+
}))
31433143
const handleCause = (cause: Cause.Cause<unknown>) => {
31443144
const failure = Cause.findFail(cause)
31453145
if (Result.isSuccess(failure)) {
@@ -3208,9 +3208,7 @@ export const registerToolkit: <Tools extends Record<string, Tool.Any>>(
32083208
}
32093209
// Declared failures return their encoded payload; anything else is classified by origin.
32103210
return result.failureOrigin === "handler"
3211-
? Effect.succeed(
3212-
new CallToolResult({ isError: true, content: toolResultContent(result.encodedResult) })
3213-
)
3211+
? Effect.map(encodeReturnedFailure(result.encodedResult), failureResult)
32143212
: Effect.failCause(Cause.annotate(
32153213
Cause.fail(result.result),
32163214
Context.make(Toolkit.FailureOrigin, result.failureOrigin ?? "result")

‎packages/effect/test/ai/McpServer/McpServer.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2195,11 +2195,33 @@ describe("McpServer", () => {
21952195
assert.isUndefined(result.structuredContent)
21962196
assert.deepStrictEqual(result.content, [{ type: "text", text: INTERNAL_TOOL_ERROR_MESSAGE }])
21972197
assert.lengthOf(reported, 1)
2198-
assert.instanceOf(Cause.squash(reported[0]), TypeError)
2198+
const error = Cause.squash(reported[0])
2199+
assertTrue(AiError.isAiError(error))
2200+
assert.strictEqual(error.reason._tag, "ToolResultEncodingError")
21992201
assert.lengthOf(logged, 1)
22002202
assert.strictEqual(Cause.squash(logged[0]), Cause.squash(reported[0]))
22012203
}))
22022204

2205+
for (const failureMode of ["error", "return"] as const) {
2206+
it.effect(`encodes declared failures with their JSON codec in ${failureMode} mode`, () =>
2207+
Effect.gen(function*() {
2208+
const toolkit = Toolkit.make(Tool.make("Charge", {
2209+
failure: Schema.Struct({ missingCents: Schema.BigInt, retryAfter: Schema.FiniteFromString }),
2210+
failureMode
2211+
}))
2212+
const client = yield* McpTest.makeClient(
2213+
Layer.effectDiscard(McpServer.registerToolkit(toolkit)).pipe(
2214+
Layer.provide(toolkit.toLayer({ Charge: () => Effect.fail({ missingCents: 250n, retryAfter: 5 }) }))
2215+
),
2216+
{ protocols: [McpProtocol.v2025_06_18] }
2217+
)
2218+
const result = yield* client.callTool({ name: "Charge" })
2219+
2220+
assert.isTrue(result.isError)
2221+
assert.strictEqual(toolResultText(result), JSON.stringify({ missingCents: "250", retryAfter: "5" }))
2222+
}))
2223+
}
2224+
22032225
for (
22042226
const [origin, failureMode] of [
22052227
["handler", "error"],

0 commit comments

Comments
 (0)