Skip to content

Commit 55daebd

Browse files
authored
fix: preserve data in malformed URL elicitation errors (#382)
fix: preserve data in malformed URL elicitation errors
2 parents 528a11f + e00e6e7 commit 55daebd

12 files changed

Lines changed: 116 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ fixes merged to `main` after it (up to `234e412`), with before and after code:
3636

3737
Behavior that can break working code ([docs/migration.md](docs/migration.md#behavior-changes)):
3838

39+
- A -32042 error whose data cannot be represented by `urlElicitationRequired` now decodes as
40+
`serverError` and keeps its data, including other keys and undecodable elicitation items.
3941
- `MCPError` decoding: -32000 and -32001 decode as `serverError`, -32602 with `data.uri` as
4042
`resourceNotFound`, and the standard cases without `data.detail` drop their own message text
4143
([details](docs/migration.md#mcperror-decoding)).

‎Sources/MCP/Base/Error.swift‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,10 @@ public struct URLElicitationInfo: Codable, Hashable, Sendable {
2929
/// A model context protocol error.
3030
///
3131
/// The cases are frozen for 1.x. An error whose code has no case of its own,
32-
/// including a code a later revision adds, is a ``serverError(code:message:data:)``;
33-
/// ``errorCode`` and the constants of ``Code`` identify it.
32+
/// including a code a later revision adds, is a ``serverError(code:message:data:)``.
33+
/// A received -32042 also uses `serverError` when its data cannot be represented
34+
/// by ``urlElicitationRequired(message:elicitations:)``; ``errorCode`` and the
35+
/// constants of ``Code`` identify it.
3436
public enum MCPError: Swift.Error, Sendable {
3537
// Standard JSON-RPC 2.0 errors (-32700 to -32603). The string, if any,
3638
// is sent as `data.detail`.
@@ -46,7 +48,8 @@ public enum MCPError: Swift.Error, Sendable {
4648
/// The receiver failed to handle the request: -32603.
4749
case internalError(String?)
4850

49-
/// An error with an implementation-defined or unrecognized code.
51+
/// An implementation-defined error, or a received error whose data cannot
52+
/// be represented by its typed case.
5053
case serverError(code: Int, message: String, data: Value? = nil)
5154

5255
// MCP specific errors
@@ -60,6 +63,8 @@ public enum MCPError: Swift.Error, Sendable {
6063
/// The server does not serve the requested protocol version: -32022.
6164
case unsupportedProtocolVersion(supported: [String], requested: String? = nil)
6265
/// The server needs the user to complete URL elicitations first: -32042.
66+
/// A received -32042 with unrepresentable data decodes as `serverError`
67+
/// with its data available.
6368
case urlElicitationRequired(message: String, elicitations: [URLElicitationInfo])
6469

6570
// Transport specific errors
@@ -384,15 +389,20 @@ extension MCPError: Codable {
384389
self = .unsupportedProtocolVersion(
385390
supported: supported, requested: fields?["requested"]?.stringValue)
386391
case -32042:
387-
var elicitations: [URLElicitationInfo] = []
388-
for item in fields?["elicitations"]?.arrayValue ?? [] {
389-
if let info = try? JSONDecoder().decode(
390-
URLElicitationInfo.self, from: JSONEncoder().encode(item))
391-
{
392-
elicitations.append(info)
393-
}
392+
let encoder = JSONEncoder()
393+
encoder.outputFormatting = .sortedKeys
394+
if let fields, fields.count == 1,
395+
let items = fields["elicitations"]?.arrayValue,
396+
let original = try? encoder.encode(items),
397+
let elicitations = try? JSONDecoder().decode(
398+
[URLElicitationInfo].self, from: original),
399+
let roundTrip = try? encoder.encode(elicitations),
400+
roundTrip == original
401+
{
402+
self = .urlElicitationRequired(message: message, elicitations: elicitations)
403+
} else {
404+
self = .serverError(code: code, message: message, data: serverData)
394405
}
395-
self = .urlElicitationRequired(message: message, elicitations: elicitations)
396406
default:
397407
// -32000 and -32001 are used by the SDK for local transport errors
398408
// only; on the wire they are implementation-defined server errors.

‎Tests/MCPTests/ProtocolFoundationsTests.swift‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,77 @@ struct MCPErrorWireTests {
124124
message: "Sign in",
125125
elicitations: [.init(elicitationId: "e1", url: "https://example.com", message: "m")])
126126
#expect(try decode(MCPError.self, json(error)) == error)
127+
128+
let empty = try decode(
129+
MCPError.self, ["code": -32042, "message": "Sign in", "data": ["elicitations": [Any]()]])
130+
#expect(empty == .urlElicitationRequired(message: "Sign in", elicitations: []))
131+
}
132+
133+
@Test("-32042 without an elicitations array keeps its data")
134+
func testURLElicitationWithoutArray() throws {
135+
let bare = try decode(MCPError.self, ["code": -32042, "message": "Sign in"])
136+
#expect(bare == .serverError(code: -32042, message: "Sign in"))
137+
138+
let challenges: Value = ["challenges": ["scheme": "Bearer"]]
139+
let withoutElicitations = try decode(
140+
MCPError.self,
141+
["code": -32042, "message": "Sign in", "data": ["challenges": ["scheme": "Bearer"]]])
142+
#expect(withoutElicitations == .serverError(
143+
code: -32042, message: "Sign in", data: challenges))
144+
145+
let invalidArray: Value = ["elicitations": "unexpected", "challenges": ["scheme": "Bearer"]]
146+
let malformed = try decode(
147+
MCPError.self,
148+
["code": -32042, "message": "Sign in",
149+
"data": ["elicitations": "unexpected", "challenges": ["scheme": "Bearer"]]])
150+
#expect(malformed == .serverError(code: -32042, message: "Sign in", data: invalidArray))
151+
152+
let encoded = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(malformed))
153+
expectWire(encoded, matches: [
154+
"code": -32042, "message": "Sign in", "data": invalidArray,
155+
])
156+
}
157+
158+
@Test("-32042 with an undecodable elicitation keeps its data")
159+
func testURLElicitationWithInvalidItem() throws {
160+
let valid: Value = ["mode": "url", "elicitationId": "e1",
161+
"url": "https://example.com", "message": "Continue"]
162+
let invalid: Value = ["elicitationId": "e2", "url": "https://example.com"]
163+
for items in [[Value.int(42)], [valid, invalid]] {
164+
let data: Value = ["elicitations": .array(items)]
165+
let error = try decode(MCPError.self, [
166+
"code": -32042, "message": "Sign in", "data": try json(data),
167+
])
168+
#expect(error == .serverError(code: -32042, message: "Sign in", data: data))
169+
let encoded = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(error))
170+
expectWire(encoded, matches: ["code": -32042, "message": "Sign in", "data": data])
171+
}
172+
}
173+
174+
@Test("-32042 with other data beside valid elicitations keeps its data")
175+
func testURLElicitationWithAdditionalData() throws {
176+
let item: Value = ["mode": "url", "elicitationId": "e1",
177+
"url": "https://example.com", "message": "Continue"]
178+
let data: Value = ["elicitations": .array([item]), "challenges": ["scheme": "Bearer"]]
179+
let error = try decode(MCPError.self, [
180+
"code": -32042, "message": "Sign in", "data": try json(data),
181+
])
182+
#expect(error == .serverError(code: -32042, message: "Sign in", data: data))
183+
let encoded = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(error))
184+
expectWire(encoded, matches: ["code": -32042, "message": "Sign in", "data": data])
185+
}
186+
187+
@Test("-32042 with an extra elicitation field keeps its data")
188+
func testURLElicitationWithAdditionalItemField() throws {
189+
let item: Value = ["mode": "url", "elicitationId": "e1", "url": "https://example.com",
190+
"message": "Continue", "extra": "value"]
191+
let data: Value = ["elicitations": .array([item])]
192+
let error = try decode(MCPError.self, [
193+
"code": -32042, "message": "Sign in", "data": try json(data),
194+
])
195+
#expect(error == .serverError(code: -32042, message: "Sign in", data: data))
196+
let encoded = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(error))
197+
expectWire(encoded, matches: ["code": -32042, "message": "Sign in", "data": data])
127198
}
128199

129200
@Test(

‎design/design.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,10 @@ Decoding rules:
442442
- Standard cases read `data.detail`, else the message.
443443
- -32602 with `data.uri` and no `data.detail` decodes as `resourceNotFound`. So does -32002 with
444444
`data.uri`, the code earlier servers used.
445+
- -32042 decodes as `urlElicitationRequired` only when `data` has no key but `elicitations`, and
446+
every item decodes as a `URLElicitationInfo` that re-encodes to the same JSON. Otherwise (no
447+
array, other `data` keys, an undecodable item or an item with extra fields) it decodes as
448+
`serverError` and keeps its `data`.
445449
- -32000 and -32001 are local transport conditions in this SDK. From the wire they decode as
446450
`serverError`, because servers use those codes for their own errors.
447451
- Unknown codes decode as `serverError` and keep `data`.

‎docs/client.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ The result's `action` is `.accept`, `.decline` or `.cancel`. Only a form `.accep
439439

440440
### URL elicitation required
441441

442-
A server can refuse a request until the user completes URL elicitations. It answers with `urlElicitationRequired` (-32042), whose `data.elicitations` lists `URLElicitationInfo` values (`elicitationId`, `url`, `message`). The SDK neither opens the URLs nor retries.
442+
On 2025-11-25 connections, a server can refuse a request until the user completes URL elicitations. It answers with `urlElicitationRequired` (-32042), whose `data.elicitations` lists `URLElicitationInfo` values (`elicitationId`, `url`, `message`). If the received data contains malformed elicitations or other fields, it decodes as `serverError` so the data remains available. The SDK neither opens the URLs nor retries.
443443

444444
```swift
445445
var pending: [URLElicitationInfo] = []
@@ -992,8 +992,8 @@ func describe(_ error: Error) -> String {
992992
| `headerMismatch` | -32020 | `Mcp-*` headers do not match the body. See [Header parameters](#header-parameters). |
993993
| `missingRequiredClientCapabilities` | -32021 | The request needs capabilities the client did not declare (`data.requiredCapabilities`). |
994994
| `unsupportedProtocolVersion(supported:requested:)` | -32022 | The server does not serve the requested version (`data.supported`). |
995-
| `urlElicitationRequired(message:elicitations:)` | -32042 | Complete the listed URL elicitations, then retry. |
996-
| `serverError(code:message:data:)` | other | Any other code, including -32000 and -32001 received from a server. |
995+
| `urlElicitationRequired(message:elicitations:)` | -32042 | Complete the listed URL elicitations, then retry (2025-11-25 only). |
996+
| `serverError(code:message:data:)` | any | Unknown codes, -32000 and -32001 received from a server, or a known code whose data cannot fit its typed case. |
997997
| `connectionClosed`, `transportError` | -32000, -32001 | Local transport failures; never decoded from the wire. |
998998

999999
See [troubleshooting.md](troubleshooting.md) for causes and fixes.

‎docs/migration.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ each change that breaks source code.
1919
|---|---|---|
2020
| `MCPError` | New cases; `serverError` has a third associated value | Update exhaustive `switch` statements and `serverError` patterns |
2121
| `MCPError` decoding | -32000 and -32001 decode as `serverError`; -32602 with `data.uri` as `resourceNotFound`; without `data.detail`, the standard cases drop their own message text | Match the new cases |
22+
| -32042 error decoding | If the data cannot be represented entirely by `urlElicitationRequired`, decodes as `serverError` and keeps `data` | Handle `serverError(code:message:data:)` for malformed or extended URL elicitation errors |
2223
| `HTTPResponse` | `.data` and `.error` have new associated values | Update patterns |
2324
| `Client.Capabilities.experimental` | `[String: String]?` became `[String: Value]?` | Pass `Value`s |
2425
| `OAuthAuthorizationError` | A struct with a `code`, not an enum; eight new codes | Read details from properties instead of binding associated values |
@@ -59,7 +60,7 @@ each change that breaks source code.
5960

6061
| Case | Code | `data` |
6162
|---|---|---|
62-
| `serverError(code:message:data:)` | any other code | as sent |
63+
| `serverError(code:message:data:)` | any code | as sent |
6364
| `resourceNotFound(uri:message:)` | -32602 | `{"uri": ...}` |
6465
| `headerMismatch(_:)` | -32020 | `{"detail": ...}` |
6566
| `missingRequiredClientCapabilities(_:message:)` | -32021 | `{"requiredCapabilities": ...}` |

‎docs/protocol.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,8 +1098,8 @@ Every JSON-RPC error the SDK sends or receives is an `MCPError`. `code` is the J
10981098
| `headerMismatch(_:)` | -32020 | `{"detail"}` | `Mcp-Method`, `Mcp-Name`, `Mcp-Param-*` or `MCP-Protocol-Version` missing or different from the body. |
10991099
| `missingRequiredClientCapabilities(_:message:)` | -32021 | `{"requiredCapabilities"}` | An input-required result needs a client capability the request did not declare; a tool that requires tasks, a task method or a listen stream naming tasks from a client without the tasks extension. |
11001100
| `unsupportedProtocolVersion(supported:requested:)` | -32022 | `{"supported", "requested"}` | Version not served; stateless request to the stateful transport. |
1101-
| `urlElicitationRequired(message:elicitations:)` | -32042 | `{"elicitations"}` | The user must complete URL elicitations first. |
1102-
| `serverError(code:message:data:)` | any other | as sent | Implementation-defined codes; -32000 and -32001 from a peer. |
1101+
| `urlElicitationRequired(message:elicitations:)` | -32042 | `{"elicitations"}` | The user must complete URL elicitations first (2025-11-25 only). |
1102+
| `serverError(code:message:data:)` | any code | as sent | Implementation-defined codes, -32000 and -32001 from a peer, or a known code whose data cannot fit its typed case. |
11031103
| `connectionClosed` | -32000 | none | Local only: the transport closed. |
11041104
| `transportError(_:)` | -32001 | `{"error"}` | Local only: an I/O error. |
11051105

‎docs/rough_edges.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ will change in a later major version.
4545
the wire, -32000 and -32001 are `serverError(code:message:data:)`.
4646

4747
- `serverError(code:message:data:)` is the case for every code without its
48-
own case, including errors from clients. Its `localizedDescription` starts
49-
with `Server error:`.
48+
own case, including errors from clients, and for known codes whose data
49+
cannot fit their typed case. Its `localizedDescription` starts with `Server error:`.
5050

5151
- `resourceNotFound` and `invalidParams` share -32602. Decoding picks
5252
`resourceNotFound` when `data` has a `uri` and no `detail`.

‎docs/src/client.src.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ The result's `action` is `.accept`, `.decline` or `.cancel`. Only a form `.accep
238238

239239
### URL elicitation required
240240

241-
A server can refuse a request until the user completes URL elicitations. It answers with `urlElicitationRequired` (-32042), whose `data.elicitations` lists `URLElicitationInfo` values (`elicitationId`, `url`, `message`). The SDK neither opens the URLs nor retries.
241+
On 2025-11-25 connections, a server can refuse a request until the user completes URL elicitations. It answers with `urlElicitationRequired` (-32042), whose `data.elicitations` lists `URLElicitationInfo` values (`elicitationId`, `url`, `message`). If the received data contains malformed elicitations or other fields, it decodes as `serverError` so the data remains available. The SDK neither opens the URLs nor retries.
242242

243243
%include Examples/Snippets/Client/Features.swift url-elicitation-required
244244

@@ -521,8 +521,8 @@ Requests throw `MCPError` for protocol errors, `CancellationError` for cancelled
521521
| `headerMismatch` | -32020 | `Mcp-*` headers do not match the body. See [Header parameters](#header-parameters). |
522522
| `missingRequiredClientCapabilities` | -32021 | The request needs capabilities the client did not declare (`data.requiredCapabilities`). |
523523
| `unsupportedProtocolVersion(supported:requested:)` | -32022 | The server does not serve the requested version (`data.supported`). |
524-
| `urlElicitationRequired(message:elicitations:)` | -32042 | Complete the listed URL elicitations, then retry. |
525-
| `serverError(code:message:data:)` | other | Any other code, including -32000 and -32001 received from a server. |
524+
| `urlElicitationRequired(message:elicitations:)` | -32042 | Complete the listed URL elicitations, then retry (2025-11-25 only). |
525+
| `serverError(code:message:data:)` | any | Unknown codes, -32000 and -32001 received from a server, or a known code whose data cannot fit its typed case. |
526526
| `connectionClosed`, `transportError` | -32000, -32001 | Local transport failures; never decoded from the wire. |
527527

528528
See [troubleshooting.md](troubleshooting.md) for causes and fixes.

‎docs/src/migration.src.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ each change that breaks source code.
1717
|---|---|---|
1818
| `MCPError` | New cases; `serverError` has a third associated value | Update exhaustive `switch` statements and `serverError` patterns |
1919
| `MCPError` decoding | -32000 and -32001 decode as `serverError`; -32602 with `data.uri` as `resourceNotFound`; without `data.detail`, the standard cases drop their own message text | Match the new cases |
20+
| -32042 error decoding | If the data cannot be represented entirely by `urlElicitationRequired`, decodes as `serverError` and keeps `data` | Handle `serverError(code:message:data:)` for malformed or extended URL elicitation errors |
2021
| `HTTPResponse` | `.data` and `.error` have new associated values | Update patterns |
2122
| `Client.Capabilities.experimental` | `[String: String]?` became `[String: Value]?` | Pass `Value`s |
2223
| `OAuthAuthorizationError` | A struct with a `code`, not an enum; eight new codes | Read details from properties instead of binding associated values |
@@ -57,7 +58,7 @@ each change that breaks source code.
5758

5859
| Case | Code | `data` |
5960
|---|---|---|
60-
| `serverError(code:message:data:)` | any other code | as sent |
61+
| `serverError(code:message:data:)` | any code | as sent |
6162
| `resourceNotFound(uri:message:)` | -32602 | `{"uri": ...}` |
6263
| `headerMismatch(_:)` | -32020 | `{"detail": ...}` |
6364
| `missingRequiredClientCapabilities(_:message:)` | -32021 | `{"requiredCapabilities": ...}` |

0 commit comments

Comments
 (0)