Skip to content

Use monotonic integer IDs for ID.random by default - #259

Closed
JamieScanlon wants to merge 1 commit into
modelcontextprotocol:rel/1.0.0from
JamieScanlon:integer-request-ids
Closed

JamieScanlon wants to merge 1 commit into
modelcontextprotocol:rel/1.0.0from
JamieScanlon:integer-request-ids

Conversation

@JamieScanlon

Copy link
Copy Markdown

Summary

  • Change ID.random to allocate monotonic JSON integer ids (.number) instead of UUID strings.
  • Keep the previous UUID behavior available as ID.randomUUID.
  • Integer ids remain JSON-RPC 2.0 valid and work with servers that only accept numeric id values.

Motivation

Apple's xcrun mcpbridge (Xcode) never responds to JSON-RPC requests whose id is a string, null, or float — it only answers integer ids. With the current UUID-string default, clients built on this SDK hang forever on initialize when talking to mcpbridge, while ad-hoc clients that use integer ids work.

String/UUID ids are legal per JSON-RPC 2.0; mcpbridge is non-compliant. Defaulting to integers preserves legality and maximizes real-world server compatibility.

Test plan

  • Unit: ID.random yields unique .number values; encoding produces a bare JSON number
  • Unit: ID.randomUUID still yields UUID strings
  • Unit: string/number Codable round-trips unchanged
  • Manual (macOS + Xcode): connect client to xcrun mcpbridge; initialize completes; tools/list returns tools

Made with Cursor

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]>
ianegordon added a commit to ianegordon/swift-sdk that referenced this pull request Sep 12, 2026
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
jeanmatthieu changed the base branch from main to rel/1.0.0 November 26, 2026 15:40
@jeanmatthieu
jeanmatthieu requested a review from a team as a code owner November 26, 2026 15:40

@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 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 with Could 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.

Comment thread Sources/MCP/Base/ID.swift
@@ -1,4 +1,5 @@
import struct Foundation.UUID
import struct os.OSAllocatedUnfairLock

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.

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
        }
    }
}

Comment thread Sources/MCP/Base/ID.swift
///
/// 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)

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.

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?

Comment thread Sources/MCP/Base/ID.swift
private static let counter = OSAllocatedUnfairLock(initialState: 0)

/// Generates a monotonic numeric ID suitable for outbound client requests.
public static var random: ID {

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.

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.

Comment thread Sources/MCP/Base/ID.swift
}

/// Generates a random UUID string ID (previous `random` behavior).
public static var randomUUID: ID {

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 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 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 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:1229 and :1257 (:1179 and :1207 on main): json["id"] as! String traps when the ID is a number.
  • Tests/MCPTests/ClientConnectionFailureTests.swift:349, :437, :692 (rel/1.0.0): message["id"] as? String fails to match. UnansweredDiscoverProtocol then returns 202 with an empty body and ChallengedDiscoverProtocol replies with "id": "". closesTimedOutDiscover, signInOutlastsDiscoveryTimeout and timeoutAfterSignIn would 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.random is public and documented as "Generates a random string ID". Returning 1, 2, 3, ... contradicts the name and changes documented behaviour, which VERSIONING.md treats as breaking.
  • ID is ExpressibleByIntegerLiteral, so a caller can send Ping.request(id: 1) before the counter reaches 1. pendingRequests[request.id] (Client.swift:1269, Server.swift:1788) then overwrites the in-flight entry. In Server that leaks the CheckedContinuation. In Client the earlier ResponseSlot hangs.

Suggested fix, either:

  • keep .random random, 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 per Client / Server, and leave .random alone.

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.

@jeanmatthieu

Copy link
Copy Markdown
Contributor

I'd rather random kept its UUID approach and we work with Xcode to fix the mcpbridge hang.
@modelcontextprotocol/swift-sdk what do you think ?

@jonathanpenn

Copy link
Copy Markdown

Hmm, this was an issue with mcpbridge before, but it was fixed a while back before the full Xcode 27.0 was released. I just ran this small snippet and it can use UUIDs just fine.

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?

@jeanmatthieu

Copy link
Copy Markdown
Contributor

Thanks @jonathanpenn. @JamieScanlon if all is good on your end, please feel free to close the PR.

@JamieScanlon

Copy link
Copy Markdown
Author

verified that Xcode 27 fixes this issue. closing

JamieScanlon added a commit to JamieScanlon/SwiftAgentKit that referenced this pull request Dec 2, 2026
* 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]>
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.

4 participants