Skip to content

Commit c996aaa

Browse files
adamwulfmattt
andauthored
Add unit test to check that AnyRequest handles missing parameters (modelcontextprotocol#24)
* Add unit test to check that AnyRequest handles missing parameters * Conform Value to NotRequired * Add test for decoding AnyRequest with empty parameters --------- Co-authored-by: Mattt Zmuda <mattt@loopwork.com>
1 parent 05e7314 commit c996aaa

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Sources/MCP/Base/Messages.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ public struct Empty: NotRequired, Hashable, Codable, Sendable {
1111
public init() {}
1212
}
1313

14+
extension Value: NotRequired {
15+
public init() {
16+
self = .null
17+
}
18+
}
19+
1420
// MARK: -
1521

1622
/// A method that can be used to send requests and receive responses.

Tests/MCPTests/RequestTests.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,4 +260,49 @@ struct RequestTests {
260260
from: withCursor.data(using: .utf8)!)
261261
#expect(decodedWithCursor.params.cursor == "next-page")
262262
}
263+
264+
@Test("AnyRequest parameters request decoding - without params")
265+
func testAnyRequestParametersRequestDecodingWithoutParams() throws {
266+
// Test decoding when params field is missing
267+
let jsonString = """
268+
{"jsonrpc":"2.0","id":1,"method":"ping"}
269+
"""
270+
let data = jsonString.data(using: .utf8)!
271+
272+
let decoder = JSONDecoder()
273+
let decoded = try decoder.decode(AnyRequest.self, from: data)
274+
275+
#expect(decoded.id == 1)
276+
#expect(decoded.method == Ping.name)
277+
}
278+
279+
@Test("AnyRequest parameters request decoding - with null params")
280+
func testAnyRequestParametersRequestDecodingWithNullParams() throws {
281+
// Test decoding when params field is null
282+
let jsonString = """
283+
{"jsonrpc":"2.0","id":1,"method":"ping","params":null}
284+
"""
285+
let data = jsonString.data(using: .utf8)!
286+
287+
let decoder = JSONDecoder()
288+
let decoded = try decoder.decode(Request<Ping>.self, from: data)
289+
290+
#expect(decoded.id == 1)
291+
#expect(decoded.method == Ping.name)
292+
}
293+
294+
@Test("AnyRequest parameters request decoding - with empty params")
295+
func testAnyRequestParametersRequestDecodingWithEmptyParams() throws {
296+
// Test decoding when params field is null
297+
let jsonString = """
298+
{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}
299+
"""
300+
let data = jsonString.data(using: .utf8)!
301+
302+
let decoder = JSONDecoder()
303+
let decoded = try decoder.decode(Request<Ping>.self, from: data)
304+
305+
#expect(decoded.id == 1)
306+
#expect(decoded.method == Ping.name)
307+
}
263308
}

0 commit comments

Comments
 (0)