Repository navigation
fix: expose response decoding details - #379
jeanmatthieu merged 5 commits into
Conversation
varun06
left a comment
There was a problem hiding this comment.
Thanks, this is a big improvement over the empty TypeMismatchError. A few points, starting with two outside the diff.
The #220 case still goes around the fix through tasks. Client.taskResult(_:) (Sources/MCP/Client/ClientTasks.swift:111) gets the payload as Value and then calls CallTool.Result(decoding: payload) itself, so a malformed tools/call result delivered through tasks/result still throws a bare DecodingError without the raw payload. Callers following the new docs ("catch ResponseDecodingError") miss it. callToolResult in TaskTypes.swift drops it with try?. Could the "decode Value as T, or throw ResponseDecodingError" step live in one shared helper that both AnyPendingRequest and these task paths call?
It isn't an MCPError. An undecodable response envelope throws MCPError.internalError("The server sent an invalid response"), but an undecodable result now throws ResponseDecodingError, so catch let e as MCPError handles one and not the other. This was already true of TypeMismatchError, so it's not a regression. But since this PR makes the type public, it's worth deciding on deliberately and saying so in the docs.
|
|
||
| /// Error thrown when a type mismatch occurs during response handling | ||
| /// A server response could not be decoded as the result type of a request. | ||
| public struct ResponseDecodingError: Swift.Error, Sendable { |
There was a problem hiding this comment.
Could this conform to LocalizedError (or CustomStringConvertible) with a short description, such as "Could not decode the result as \(expectedType): \(underlyingError)", that leaves out rawResult?
On the server side, Server.swift (around lines 580, 1387 and 2156) wraps unknown errors as MCPError.internalError(error.localizedDescription). As written, a malformed createMessage/elicit result reaches the peer as "The operation couldn't be completed. (MCP.ResponseDecodingError error 1.)", which is as opaque as the error this PR replaces. Going the other way, "\(error)" in a log line dumps the whole rawResult, which can be large tool output or sensitive content.
| public struct ResponseDecodingError: Swift.Error, Sendable { | ||
| /// The result type the request expected. | ||
| public let expectedType: String | ||
| /// The result received from the server. |
There was a problem hiding this comment.
AnyPendingRequest is also used by Server for server-to-client requests (sampling, elicitation, roots), so a malformed client result now throws this error on the server too. The doc comments ("A server response…", "received from the server"), the CHANGELOG bullet and the migration row describe only client results. Could they say "peer" and cover the server-side behavior change?
| return deliver(.success(decoded)) | ||
| if let value = value as? Value { | ||
| do { | ||
| let data = try JSONEncoder().encode(value) |
There was a problem hiding this comment.
Nit: this repeats the Value → T round-trip that Decodable.init(decoding:preservingStrings:) in MultiRoundTrip.swift already does. return deliver(.success(try T(decoding: value))) inside the do keeps a single implementation, so the two can't drift apart, and it fits with the shared-helper suggestion in the review summary.
|
Thanks @varun06 , I addressed these. Direct replies and both task result paths now share the same decoder, so malformed task results keep the raw value and decoding error. I kept TaskSnapshot.callToolResult optional for compatibility. The printed error leaves out the raw result, and the docs clarify that this is a local error separate from MCPError, including on server-to-client requests. Tests were made with AI assistance. The full suite and both conformance legs pass locally. |
The struct relied on the synthesized memberwise initializer, which is internal, so callers could not build the error, for example in a test double or a custom transport. Its peers (TaskCancelledError, HTTPStatusError, SkillVerificationError, OAuthAuthorizationError) declare a documented public init; this one now matches them. Made with AI assistance.
The description named only the expected type, so a malformed result sent back as internalError(localizedDescription) by the server, or logged by a caller, did not say what was wrong with it. It now adds the decoding error: a DecodingError as its coding path and debug description (`content[0].text: Expected to decode String but found a number instead.`), any other error as it prints. The raw result stays out of the description. Made with AI assistance.
jeanmatthieu
left a comment
There was a problem hiding this comment.
Thanks @EhsanAzish80 for working through the feedback. The shared decoder for direct and task results, and the docs on how this error relates to MCPError, both look good.
I pushed two small commits on top to finish the last review thread:
ResponseDecodingErrornow has a documentedpublic init(expectedType:rawResult:underlyingError:), like its peers (TaskCancelledError,HTTPStatusError), so callers can build one, for example in tests.- The description now says why decoding failed. A
DecodingErrorprints as its coding path and reason, such asCould not decode the result as CallTool.Result: content[0].text: Expected to decode String but found a number instead., and the raw result is still left out. This also makes theinternalErrorthe server sends back for a malformed sampling or elicitation result readable.
Both commits come with tests, and the full suite passes (1,412 tests). Approving, thanks again!
9d88352
into
modelcontextprotocol:rel/1.0.0
Motivation and Context
When a peer result does not decode as the expected type, the SDK currently throws an empty internal error. Task results can also lose the decoding detail. This makes it hard to see what the peer sent or why decoding failed.
This adds a public
ResponseDecodingErrorwithexpectedType: String,rawResult: Value, andunderlyingError: any Error. Client requests, server-to-client requests, and task results use the sameValuedecoder. The error's printed description does not include the raw result. It is a local decoding error, separate fromMCPError. The wire response does not change.Fixes #220. This supersedes #292.
How Has This Been Tested?
InMemoryTransportcover an undecodable method result and malformed task results at both 2025-11-25 and 2026-07-28. They check the raw value, underlying error, and safe printed description.swift buildandswift testpassed (1,410 tests).swift scripts/weave.swift --check,swift scripts/doc-coverage.swift, and DocC with--warnings-as-errorspassed.Tests were made with AI assistance.
Breaking Changes
An undecodable result, including a task result, now throws
ResponseDecodingErrorinstead of the empty internalTypeMismatchErroror a bareDecodingError.TaskSnapshot.callToolResultkeeps its optional behavior. The migration guide and changelog cover this.Types of changes
Checklist
Additional context
Callers can catch
ResponseDecodingErrorto inspect a malformed response, or use aMethodwithResult == Valuefor raw access.