Skip to content

fix: preserve data in malformed URL elicitation errors - #382

Merged
jeanmatthieu merged 3 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:fix/url-elicitation-error-data
Nov 27, 2026
Merged

jeanmatthieu merged 3 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:fix/url-elicitation-error-data

Conversation

@EhsanAzish80

@EhsanAzish80 EhsanAzish80 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Motivation and Context

A -32042 error can carry data that urlElicitationRequired cannot represent. Undecodable items and extra fields can disappear when the decoded error is sent again.

This uses urlElicitationRequired only when the entire data can round-trip through that case. Otherwise it decodes as serverError(code:message:data:) and keeps the data. The clean URL elicitation case still works as before. There is no new MCPError case or public API shape change.

Fixes #381. This follows up the data-preservation discussion in #229.

How Has This Been Tested?

  • Tests cover absent or wrong-type elicitations, all-invalid and partly-invalid arrays, extra fields beside and inside valid elicitations, the clean typed case, and wire round trips.
  • swift build and swift test passed (1,411 tests).
  • Conformance passed for 2025-11-25 (84 checks) and 2026-07-28 (152 checks).
  • swift scripts/weave.swift --check, swift scripts/doc-coverage.swift, and DocC with --warnings-as-errors passed.

AI assisted with this fix and its tests. I reviewed both and ran the checks.

Breaking Changes

A -32042 error with data the typed case cannot represent now decodes as serverError with its data instead of urlElicitationRequired with missing fields or items. 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

This is a narrow follow-up to the closed #229 PR. It preserves unexpected JSON-RPC error data without adding a payment error case.

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

@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 for picking up #381. The direction is right, but the fallback only fires when elicitations isn't an array, so the data loss from the issue still happens in a couple of common shapes (inline comments below).

One more outside the diff: the MCPError doc comment (Sources/MCP/Base/Error.swift:31) says "An error whose code has no case of its own … is a serverError(code:message:data:)". After this change that's no longer true for -32042 (and already wasn't for -32021). A reader would match only case .urlElicitationRequired and miss the fallback. Could the type doc and the urlElicitationRequired case doc say that a -32042 whose payload can't be decoded arrives as serverError with its data intact? (AGENTS.md: "A stale comment is a bug.")

Comment thread Sources/MCP/Base/Error.swift Outdated
URLElicitationInfo.self, from: JSONEncoder().encode(item))
{
elicitations.append(info)
if let items = fields?["elicitations"]?.arrayValue {

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.

Any array here counts as readable, even when none of its items decode. Example:

{"code":-32042,"message":"Sign in","data":{"elicitations":[{"elicitationId":"e1","url":"https://x"}],"challenges":{"scheme":"Bearer"}}}

The item has no mode, so try? drops it and the result is .urlElicitationRequired(message: "Sign in", elicitations: []). challenges is gone, which is the loss #381 reports. The -32021 path falls back when the payload can't be decoded. To match it, this should also fall back to serverError(code:message:data: serverData) when items is non-empty but elicitations ends up empty, and arguably whenever any item fails to decode.

elicitations.append(info)
}
}
self = .urlElicitationRequired(message: message, elicitations: elicitations)

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.

Even with a valid elicitations array, every other key in data is dropped, because urlElicitationRequired has nowhere to store it and .data rebuilds only {"elicitations": [...]}. With {"elicitations":[<valid>],"challenges":{...}} the client can't reach challenges, and a proxy that relays the decoded error removes it from the wire. Should the typed case be used only when data holds nothing but elicitations, or should the case keep the remaining keys somehow?

elicitations: [.init(elicitationId: "e1", url: "https://example.com", message: "m")])
#expect(try decode(MCPError.self, json(error)) == error)

let empty = try decode(

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.

This test locks in empty array → urlElicitationRequired(elicitations: []), but nothing covers the cases where data is still lost:

  • an array whose items are all undecodable, e.g. {"elicitations":[42]} or [{}]
  • a valid array alongside other keys, e.g. {"elicitations":[<valid>],"challenges":{...}}

Both decode to urlElicitationRequired and drop data today, and neither would fail CI. Could you add cases for them, each with a round-trip expectWire check like the malformed case below?

Keep -32042 data in serverError when the typed case would drop an item or extra field. Cover the 2025-11-25 URL elicitation error shape with wire tests.
@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

@varun06 Thanks, good catches. I changed the -32042 decoder so it only uses urlElicitationRequired when the full data can round-trip without losing fields or items. Otherwise it keeps the data in serverError.

I added wire tests for invalid items, extra challenges, and extra fields inside an item. I also updated the MCPError comments and guides. The local build, 1,411 tests, both conformance versions, and doc checks pass. I’ll watch CI on the updated branch.

The second commit of this change made -32042 decode as urlElicitationRequired only when data holds nothing but an elicitations array whose items round-trip exactly, but design.md still described the first rule (fall back only when the array is missing).

Assisted-by: Optimus (Claude)

@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 for addressing the previous feedback, @EhsanAzish80! I pushed one small commit (e00e6e7) that only updates docs: design/design.md still described the original -32042 fallback rule (only a missing elicitations array falls back), so I updated it to match the stricter round-trip check from your second commit. No code changes.

@jeanmatthieu
jeanmatthieu merged commit 55daebd into modelcontextprotocol:rel/1.0.0 Nov 27, 2026
13 of 14 checks passed
@EhsanAzish80
EhsanAzish80 deleted the fix/url-elicitation-error-data branch November 27, 2026 10:14

@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 for the update. The exact-match check fixes both data-loss cases from my last review (undecodable items, and extra keys next to elicitations), and the doc comments now describe the fallback. Two inline comments on the new version.

One more outside the diff, carried over from my earlier review: the guide snippet in Examples/Snippets/Client/Features.swift (around line 123, shown in docs/client.md) and describe() in Notifications.swift still match only MCPError.urlElicitationRequired. Since the docs now say a -32042 can arrive as serverError with its data available, the sample should show that path too, for example catch let error as MCPError where error.errorCode == MCPError.Code.urlElicitationRequired and then reading error.data. Otherwise code copied from the guide lets these errors escape.

}
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
if let fields, fields.count == 1,

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.

I think this is now stricter than the spec. ElicitRequestURLParams items may carry _meta (and task), and the SDK's own Elicitation.URLParameters has _meta, but URLElicitationInfo has only mode/elicitationId/url/message. So:

{"code":-32042,"message":"Sign in","data":{"elicitations":[{"mode":"url","elicitationId":"e1","url":"https://x","message":"m","_meta":{}}]}}

The _meta key is dropped on re-encode, roundTrip != original, and a conformant server's error becomes .serverError(-32042, …). catch MCPError.urlElicitationRequired no longer fires and recoverySuggestion is nil. The same happens with _meta at the data level, because of fields.count == 1.

Two options: compare ignoring keys the spec allows but the type doesn't model, or give URLElicitationInfo an optional _meta. A test for an item with _meta would pin the behavior either way.

Two smaller points on the same check:

  • mode isn't checked to be "url", so {"mode":"form",…} round-trips and becomes urlElicitationRequired.
  • Building let typed = MCPError.urlElicitationRequired(...) and keeping it only if typed.data == data would reuse the case's own encode rule, so decode and encode can't drift apart, and it would avoid the extra sorted-keys encoder.

case internalError(String?)

/// An error with an implementation-defined or unrecognized code.
/// An implementation-defined error, or a received error whose data cannot

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.

This wording, and the new rows in protocol.src.md / client.src.md and the rough-edges note, now read as a general rule: any received error whose data doesn't fit its typed case becomes serverError. Only -32042 does that. -32022 with {"supported":[1,"2025-11-25"],"x":1} still decodes as unsupportedProtocolVersion(supported: ["2025-11-25"]) and drops 1 and x. -32602 with uri plus extra keys drops the extras as resourceNotFound. The standard codes drop everything except detail.

Either scope the docs to -32042, or apply the same fits-or-fall-back check to every typed case. I'd lean toward the latter as a follow-up, but the docs shouldn't promise it before the code does it.

@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

Thanks, these are good catches. I checked the merged decoder: _meta makes a valid URL elicitation fall back to serverError so its data is preserved, but the examples don’t handle that path. The mode check and the broader docs wording also need correction. I’ll put the tests, mode check, examples, and docs correction in a small follow-up PR. I’d keep the lossless fallback for now and discuss adding metadata to the typed public API separately.

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