Skip to content

fix: expose response decoding details - #379

Merged
jeanmatthieu merged 5 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:fix/response-decoding-detail
Nov 27, 2026
Merged

jeanmatthieu merged 5 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:fix/response-decoding-detail

Conversation

@EhsanAzish80

@EhsanAzish80 EhsanAzish80 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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 ResponseDecodingError with expectedType: String, rawResult: Value, and underlyingError: any Error. Client requests, server-to-client requests, and task results use the same Value decoder. The error's printed description does not include the raw result. It is a local decoding error, separate from MCPError. The wire response does not change.

Fixes #220. This supersedes #292.

How Has This Been Tested?

  • Real client and server tests over InMemoryTransport cover 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 build and swift test passed (1,410 tests).
  • Conformance passed for 2025-11-25 (84 server checks) and 2026-07-28 (152 server checks) on this revision.
  • swift scripts/weave.swift --check, swift scripts/doc-coverage.swift, and DocC with --warnings-as-errors passed.

Tests were made with AI assistance.

Breaking Changes

An undecodable result, including a task result, now throws ResponseDecodingError instead of the empty internal TypeMismatchError or a bare DecodingError. TaskSnapshot.callToolResult keeps its optional behavior. The migration guide and changelog cover this.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Callers can catch ResponseDecodingError to inspect a malformed response, or use a Method with Result == Value for raw access.

@EhsanAzish80
EhsanAzish80 requested a review from a team as a code owner November 26, 2026 19:45

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread Sources/MCP/Base/PendingRequest.swift Outdated

/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread Sources/MCP/Base/PendingRequest.swift Outdated
public struct ResponseDecodingError: Swift.Error, Sendable {
/// The result type the request expected.
public let expectedType: String
/// The result received from the server.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread Sources/MCP/Base/PendingRequest.swift Outdated
return deliver(.success(decoded))
if let value = value as? Value {
do {
let data = try JSONEncoder().encode(value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

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
jeanmatthieu previously approved these changes Nov 27, 2026

@jeanmatthieu jeanmatthieu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • ResponseDecodingError now has a documented public 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 DecodingError prints as its coding path and reason, such as Could 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 the internalError the 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!

@jeanmatthieu
jeanmatthieu merged commit 9d88352 into modelcontextprotocol:rel/1.0.0 Nov 27, 2026
13 of 14 checks passed
@EhsanAzish80
EhsanAzish80 deleted the fix/response-decoding-detail branch November 27, 2026 10:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants