Repository navigation
Use monotonic integer IDs for ID.random by default - #259
JamieScanlon wants to merge 1 commit into
Conversation
UUID string request IDs are JSON-RPC valid but cause Apple mcpbridge to hang silently. Default to monotonic .number IDs for broader server compatibility; keep UUID generation via ID.randomUUID. Co-authored-by: Cursor <[email protected]>
Issue titles are now bare 'Upstream PR#<n>'; the merge/investigate/decline label carries the decision, so the title does not duplicate it. Two places named the old convention and are updated. The investigate count was also stale: it said twelve, which was true at triage on 2026-09-10. Four were declined since (modelcontextprotocol#280, modelcontextprotocol#226, modelcontextprotocol#118, modelcontextprotocol#204) and two were promoted and merged (modelcontextprotocol#266 as entries 9/9a, modelcontextprotocol#275 as 10/10a/10b), leaving six — modelcontextprotocol#178, modelcontextprotocol#213, modelcontextprotocol#216, modelcontextprotocol#257, modelcontextprotocol#258, modelcontextprotocol#259 — now listed by number rather than by count, so the sentence cannot drift again. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Eb9yGSXH1TVkg5Afsu9phk
jeanmatthieu
left a comment
There was a problem hiding this comment.
Thanks for tracking down the mcpbridge hang. Defaulting to integer IDs seems reasonable, since they're valid JSON-RPC 2.0. A few things to resolve before merge.
The branch needs a rebase on rel/1.0.0. It's about 200 commits behind and no CI ran on it. I applied the commit to the current base and ran swift test on macOS, and the existing suite breaks. The test mocks assume request IDs are strings:
HTTPClientTransportTests.swift, "Client with HTTP Transport complete flow":json["id"] as! String(around lines 1229 and 1257) crashes the test process withCould not cast value of type '__NSCFNumber' to 'NSString'. Every test after it is skipped.ClientConnectionFailureTests.swift, the "Discovery timeout over HTTP" tests:message["id"] as? String ?? ""(around lines 349, 437 and 692) replies with"id":"". That never matches the client's numeric ID, so three tests time out after 60 seconds.
The SDK itself handles numeric IDs correctly. The mocks need to send back the id they received, whatever its type. With the old ID.swift these tests pass.
Linux build. See the inline comment on the os import. CI builds on Linux and the static musl SDK, so this has to be portable.
API and semver. ID.random is public, and this changes its result from a UUID string to a counter that restarts at 1 on every launch. Any caller that relies on it being unique across processes or launches, or on it being a string, will break silently, and the name random no longer fits. This also adds public API (randomUUID) without a CHANGELOG.md entry or a migration-guide note.
A smaller change may get the same result: keep random as it is, add a sequential generator, and make that the default id: where requests are built (Messages.swift, the three id: ID = .random defaults). Requests the SDK builds itself would then send integer IDs, and ID.random keeps its documented behavior. Maintainers, which approach do you prefer?
Test plan. The manual mcpbridge check is still unticked. Can you confirm initialize and tools/list succeed against xcrun mcpbridge with this change?
This review was conducted with the assistance of Claude.
| @@ -1,4 +1,5 @@ | |||
| import struct Foundation.UUID | |||
| import struct os.OSAllocatedUnfairLock | |||
There was a problem hiding this comment.
The os module is Apple-only, so this won't compile on Linux or the static musl SDK, both of which CI builds. It also needs macOS 13 / iOS 16, which happens to match the package minimums today but ties ID to them.
Elsewhere the library uses an NSLock-guarded class for this (for example DeprecationNotices.swift, PendingRequest.swift):
private final class IDCounter: @unchecked Sendable {
// Serialized by `lock`.
private let lock = NSLock()
private var value = 0
func next() -> Int {
lock.withLock {
value += 1
return value
}
}
}| /// | ||
| /// Integer IDs are JSON-RPC 2.0–valid and avoid silent hangs against servers | ||
| /// that only accept numeric `id` values (e.g. Apple's `mcpbridge`). | ||
| private static let counter = OSAllocatedUnfairLock(initialState: 0) |
There was a problem hiding this comment.
Callers can still create integer IDs by hand (for example Ping.request(id: 1)). Before, generated IDs were UUID strings and could never clash with those. Now a generated .number(1) can match a hand-set one on the same Client, and both requests would share a key in pendingRequests. This is probably rare, but can the doc comment say that generated IDs are small positive integers, so callers who set their own IDs know to avoid that range?
| private static let counter = OSAllocatedUnfairLock(initialState: 0) | ||
|
|
||
| /// Generates a monotonic numeric ID suitable for outbound client requests. | ||
| public static var random: ID { |
There was a problem hiding this comment.
The name says random but the value is now sequential and predictable, and the doc comment change reverses a documented contract on a public API in the 1.0 line. If we keep this approach, it needs a changelog entry. Alternatively, see the review body for leaving random as it was and changing only the default request ID.
| } | ||
|
|
||
| /// Generates a random UUID string ID (previous `random` behavior). | ||
| public static var randomUUID: ID { |
There was a problem hiding this comment.
This is new public API. If random keeps its UUID behavior (the alternative in the review body), this property isn't needed. If it stays, please add a CHANGELOG.md entry.
varun06
left a comment
There was a problem hiding this comment.
Thanks for this. Making request IDs numeric for servers that ignore string IDs (e.g. xcrun mcpbridge) is a reasonable goal, but as written the PR doesn't build on Linux, breaks existing tests, and changes the contract of ID.random. I read the diff and the surrounding code but haven't run the build, so the failures below come from code reading, not CI (there are no CI runs on this branch).
Blocking
1. Sources/MCP/Base/ID.swift:2,16: does not compile on Linux
import struct os.OSAllocatedUnfairLock is Darwin-only, so the ubuntu-24.04, swift:6.1-noble, swift:6.1-rhel-ubi9, fuzz and Linux Static SDK jobs will fail with no such module 'os'. Synchronization.Mutex isn't an option either, because Package.swift targets .macOS("13.0") / .iOS("16.0") and Mutex needs macOS 15 / iOS 18. The other locks in Sources/MCP (PendingRequest.swift, DeprecationNotices.swift, OAuthAuthorizer.swift) use NSLock.
Suggested fix:
import class Foundation.NSLock
import struct Foundation.UUID
private static let counterLock = NSLock()
nonisolated(unsafe) private static var counterValue = 0
private static func nextNumber() -> Int {
counterLock.withLock {
counterValue &+= 1
return counterValue
}
}2. ID.swift:19-26: breaks existing tests, and the branch is stale
The branch is based on a0ae212e, 217 commits behind rel/1.0.0 and 27 behind main. Tests that inspect raw outbound JSON assume string IDs:
Tests/MCPTests/HTTPClientTransportTests.swift:1229and:1257(:1179and:1207onmain):json["id"] as! Stringtraps when the ID is a number.Tests/MCPTests/ClientConnectionFailureTests.swift:349,:437,:692(rel/1.0.0):message["id"] as? Stringfails to match.UnansweredDiscoverProtocolthen returns 202 with an empty body andChallengedDiscoverProtocolreplies with"id": "".closesTimedOutDiscover,signInOutlastsDiscoveryTimeoutandtimeoutAfterSignInwould hang until the 1-minute suite time limit.
Suggested fix: rebase onto rel/1.0.0, then update those mock handlers to decode ID or echo the raw message["id"].
3. ID.swift:19-26: ID.random is no longer random, and sequential IDs can collide
ID.randomis public and documented as "Generates a random string ID". Returning1, 2, 3, ...contradicts the name and changes documented behaviour, whichVERSIONING.mdtreats as breaking.IDisExpressibleByIntegerLiteral, so a caller can sendPing.request(id: 1)before the counter reaches 1.pendingRequests[request.id](Client.swift:1269,Server.swift:1788) then overwrites the in-flight entry. InServerthat leaks theCheckedContinuation. InClientthe earlierResponseSlothangs.
Suggested fix, either:
- keep
.randomrandom, e.g.Int.random(in: 1...9_007_199_254_740_991)(inside the IEEE-754 safe-integer range), or - add a separate
ID.sequential/nextNumber(), or allocate IDs perClient/Server, and leave.randomalone.
Should-fix
4. Tests/MCPTests/IDTests.swift:38-53: no concurrency test
testRandomID calls ID.random twice on one task. The lock exists for concurrent access, so add a withTaskGroup test that spawns N tasks and asserts the resulting Set<ID> has N elements.
Nit
5. IDTests.swift:61-66: testRandomUUIDID only validates id1
id2 is only compared against id1, never pattern-matched or parsed. Loop over both:
for id in [id1, id2] {
guard case .string(let str) = id else {
Issue.record("randomUUID ID should be string type")
return
}
#expect(UUID(uuidString: str) != nil)
}I'd request changes until the Linux build, the stale base and the .random contract are sorted out.
|
I'd rather |
|
Hmm, this was an issue with import json, subprocess, threading, uuid
def try_id(request_id):
bridge = subprocess.Popen(["xcrun", "mcpbridge"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
request = {"jsonrpc": "2.0", "id": request_id, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "probe", "version": "1"}}}
bridge.stdin.write(json.dumps(request) + "\n")
bridge.stdin.flush()
watchdog = threading.Timer(15, bridge.kill)
watchdog.start()
reply = bridge.stdout.readline().strip()
watchdog.cancel()
bridge.kill()
print(f"sent id {json.dumps(request_id)} -> " + (f"got {reply[:120]}" if reply else "no reply after 15s"))
try_id(str(uuid.uuid4()))
try_id(1)Do you have an example you can share that still doesn't work? |
|
Thanks @jonathanpenn. @JamieScanlon if all is good on your end, please feel free to close the PR. |
|
verified that Xcode 27 fixes this issue. closing |
* Drop swift-sdk fork; use upstream MCP Swift SDK 0.12.1 Xcode 27's `xcrun mcpbridge` now answers JSON-RPC requests with string ids, so the fork that made ID.random emit integers (PR modelcontextprotocol/swift-sdk#259) is no longer needed. Verified on Xcode 27.1 (mcpbridge xcode-tools 25320): stock SDK 0.12.1 completes initialize and tools/list with UUID-string ids. - Depend on modelcontextprotocol/swift-sdk from 0.12.1 - Remove the test asserting integer request ids - README: document the mcpbridge hang on Xcode versions before 27 Co-Authored-By: Claude Opus 5.5 <[email protected]> * version Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
ID.randomto allocate monotonic JSON integer ids (.number) instead of UUID strings.ID.randomUUID.idvalues.Motivation
Apple's
xcrun mcpbridge(Xcode) never responds to JSON-RPC requests whoseidis a string, null, or float — it only answers integer ids. With the current UUID-string default, clients built on this SDK hang forever oninitializewhen talking tomcpbridge, while ad-hoc clients that use integer ids work.String/UUID ids are legal per JSON-RPC 2.0;
mcpbridgeis non-compliant. Defaulting to integers preserves legality and maximizes real-world server compatibility.Test plan
ID.randomyields unique.numbervalues; encoding produces a bare JSON numberID.randomUUIDstill yields UUID stringsxcrun mcpbridge;initializecompletes;tools/listreturns toolsMade with Cursor