Repository navigation
fix: preserve data in malformed URL elicitation errors - #382
jeanmatthieu merged 3 commits into
Conversation
varun06
left a comment
There was a problem hiding this comment.
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.")
| URLElicitationInfo.self, from: JSONEncoder().encode(item)) | ||
| { | ||
| elicitations.append(info) | ||
| if let items = fields?["elicitations"]?.arrayValue { |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
|
@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
left a comment
There was a problem hiding this comment.
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.
55daebd
into
modelcontextprotocol:rel/1.0.0
varun06
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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:
modeisn't checked to be"url", so{"mode":"form",…}round-trips and becomesurlElicitationRequired.- Building
let typed = MCPError.urlElicitationRequired(...)and keeping it only iftyped.data == datawould 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 |
There was a problem hiding this comment.
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.
|
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. |
Motivation and Context
A -32042 error can carry data that
urlElicitationRequiredcannot represent. Undecodable items and extra fields can disappear when the decoded error is sent again.This uses
urlElicitationRequiredonly when the entiredatacan round-trip through that case. Otherwise it decodes asserverError(code:message:data:)and keeps the data. The clean URL elicitation case still works as before. There is no newMCPErrorcase or public API shape change.Fixes #381. This follows up the data-preservation discussion in #229.
How Has This Been Tested?
elicitations, all-invalid and partly-invalid arrays, extra fields beside and inside valid elicitations, the clean typed case, and wire round trips.swift buildandswift testpassed (1,411 tests).swift scripts/weave.swift --check,swift scripts/doc-coverage.swift, and DocC with--warnings-as-errorspassed.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
serverErrorwith its data instead ofurlElicitationRequiredwith missing fields or items. The migration guide and changelog cover this.Types of changes
Checklist
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.