Skip to content

[P11] fix: request lifecycle, server replies, OAuth hardening - #360

Merged
jeanmatthieu merged 6 commits into
rel/1.0.0from
conformance/p11-fixes
Nov 25, 2026
Merged

jeanmatthieu merged 6 commits into
rel/1.0.0from
conformance/p11-fixes

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P11 of P0–P35, merged into rel/1.0.0 in order (previous: P9 (#361) · next: P12 (#359))
Branch conformance/p11-fixes
Base conformance/p9-flip (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits f00b681 fix: request lifecycle, server replies, OAuth hardening
3175667 fix: review fixes
6cb3f9f client: fail pending requests when the transport stream ends
b615f35 oauth: close gaps in the private address check
e579d9c fix: second-pass review fixes
d9624f8 fix: third-pass review fixes
Size 53 files, +3499 / -451

Summary

Fixes ten of the 13 bugs found while writing the documentation in P10 (#362), plus one of the API warts listed in docs/rough_edges.md. The client registers a request before send(_:) returns and runs its handlers outside the receive loop, withBatch goes through the same path as send, the server stops answering notifications and unreadable messages with random ids, sessionless servers handle initialize correctly, the replay store is bounded, and the OAuth client uses swift-crypto, treats a plain client ID as pre-registered and checks redirects and the registration endpoint. Bugs 5 and 7 and the .stateless(v) retry were fixed in P3 (#368) and P4 (#367), bug 13 in P0 (#371); the migration and server guides describe 5 and 7 here. A review fix bounds server-to-client requests (4 at once, 64 waiting), delivers responses without waiting for unrelated notification handlers, makes the replay store per stream with a byte cap, parses IP literals with inet_pton, and applies the redirect checks on Linux. Docs, design notes and the migration guide describe the new behavior.

Motivation

The issues found while writing the documentation in P10 (#362), by number:

  1. Client cancellation race: dispatch registered and sent from an unstructured Task, so a cancelRequest right after send found nothing and the cancel could overtake the request.
  2. Client handlers ran inside the receive loop: a handler that awaited a request on the same client deadlocked, a slow one stalled the connection.
  3. withBatch bypassed dispatch: no 2026-07-28 _meta, no MRTR loop, no header parameters, and the same registration race.
  4. A strict server threw on a notification before initialize, and the receive loop answered it with an error response with a random id.
  5. A server configured with protocolVersions: Version.stateless still answered initialize. Fixed in P3 ([P3] server: serve 2026-07-28 stateless requests #368).
  6. One Server behind StatelessHTTPServerTransport accepted only one initialize.
  7. StatelessHTTPServerTransport did not cancel the handler of a pending JSON reply when the client disconnected. Fixed in P3 ([P3] server: serve 2026-07-28 stateless requests #368); the test is in this PR.
  8. StatefulHTTPServerTransport's replay event store was unbounded per session.
  9. The private_key_jwt helper used CryptoKit only and threw on Linux. (PKCE had the same problem; P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363) fixes it.)
  10. .none(clientID:) with a non-URL client ID still triggered DCR when a registration endpoint existed.
  11. The SSRF private-IP check was not applied to the registration endpoint, redirects were not validated, and isPrivateIPHost blocked host names starting with fc, fd or fe8-feb.
  12. Tool.encode wrote "description": null.
  13. scripts/run-conformance.sh wrote the fixture output and the harness log to the same server.log. Fixed in P0 ([P0] conformance: pin harness 0.2.0-alpha.11 and run per-revision legs #371).

Warts: decoding -32603 dropped the peer's message (fixed here); .stateless(v) retried with another version despite its doc (fixed in P4 (#367)).

Changes

Client (Sources/MCP/Client/Client.swift, Sources/MCP/Base/PendingRequest.swift)

  • Bug 1: new internal ResponseSlot<T>, a lock-protected one-shot result that can be resolved before anyone waits. register(_:) encodes the request, stores its slot in pendingRequests and its id in unsentRequests, synchronously; dispatch(_:) then hands it to transmit(_:on:) in a task. transmit sends only if the id is still in unsentRequests. cancelRequest(_:reason:) resolves the slot with CancellationError and, for an unsent request, returns without sending notifications/cancelled. addPendingRequest is removed.
  • Bug 2: connect starts an ordered inbound queue (AsyncStream<Inbound>) consumed by one task. Notifications (except notifications/cancelled and notifications/subscriptions/acknowledged, which only update client state and stay in the loop) and responses go through the queue, so a response is delivered after the notifications that arrived before it. Requests sent while a notification handler runs (task-local isHandlingNotification) are recorded in immediateResponses; their responses skip the queue. Server-to-client requests run in their own tasks (incomingRequests); notifications/cancelled from the server cancels the task and suppresses the response. disconnect() cancels these tasks without awaiting them. The review fix narrows the queue to notifications (see Review fixes).
  • Bug 3: Batch.addRequest(_:) calls registerBatchRequest(_:), which uses register and the MRTR wrapper withRoundTrips(_:first:). sendBatch(_:on:) sends one JSON array at 2025-11-25 and each request alone on stateless connections (per-request headers). When the withBatch body throws, abandonBatch(_:with:) fails the requests it added. A send failure fails the batch's requests.
  • ProtocolMode.stateless and discoverOrInitialize(_:fallback:) document that a pinned version never retries or falls back; retried starts at !fallback. No behavior change: P4 ([P4] client: connect with server/discover at 2026-07-28 #367) already stopped the retry.

Server (Sources/MCP/Server/Server.swift, Sources/MCP/Server/Tools.swift, Sources/MCP/Base/Error.swift)

  • Bug 4: a strict, non-sessionless server logs and ignores notifications before initialize. A request before initialize gets -32600 "Server is not initialized"; before, checkInitialized() threw out of handleRequest and no response was sent. Processing errors without a request id are not answered, except parse errors, which are answered with "id": null (sendUnattributedError). An empty batch gets "id": null instead of a random id.
  • Bug 6: isSessionless is connection is StatelessHTTPServerTransport. There, every initialize is answered, setInitialState is not called, strict mode does not apply, and the HandlerContext of a handshake request takes its protocol version from the MCP-Protocol-Version header and has no client capabilities or info.
  • Bug 12: Tool encodes description with encodeIfPresent.
  • Wart: MCPError decoding of -32603 keeps the peer's message (internalError(message)), except the bare "Internal error", which stays internalError(nil).

HTTP server transports (Sources/MCP/Base/Transports/HTTPServer/)

  • Bug 8: StatefulHTTPServerTransport.init gains eventStoreCapacity: Int = 1000 (values below 1 become 1). The oldest events are dropped first; a client that resumes after a dropped event gets HTTP 400. The review fix makes the store per stream and adds a byte cap.

OAuth (Sources/MCP/Base/Authorization/)

  • Bug 9: OAuthConfiguration.swift imports Crypto; its #if canImport(CryptoKit) branches are gone (PKCE.swift already uses Crypto since P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363)). PrivateKeyJWTAssertionError.cryptographyUnavailable remains but is documented as never thrown, as pkceS256Unavailable is since P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363).
  • Bug 10: OAuthClientRegistrar.register returns nil (no DCR) for a non-empty client ID that is not a URL. An expired registered secret now resets to .none(clientID: ""), so the client registers again instead of being treated as pre-registered.
  • Bug 11:
    • the registration endpoint host is checked with isPrivateIPHost (privateIPAddressBlocked);
    • new internal OAuthRedirectGuard and URLSession.oauthData(for:redirects:validator:): discovery requests (OAuthDiscoveryClient) follow a redirect only to an https URL, or to a loopback http URL from an http request, whose host is not a private IP literal; token and registration requests follow no redirect;
    • OAuthURLValidator.isPrivateIPHost(_:) returns false for host names, strips brackets and IPv6 zone ids, checks IPv4-mapped IPv6 (::ffff:a.b.c.d) and adds 0.0.0.0/8.

Package and fixtures

  • Package.swift: MCPTests depends on Crypto (the OAuth tests no longer guard on CryptoKit).
  • conformance/everything-client/main.swift: the client-credentials and authorization-code cases pass context["client_id"] ?? "" instead of a "test-client" default, which would now count as pre-registered.

Docs

  • CLAUDE.md: the client request lifecycle (registration before send returns, the inbound queue, server-to-client request tasks).
  • docs/src/migration.src.md: summary rows for client handlers, .stateless(version) and .none(clientID:); -32603 decoding; server, client, HTTP transport and OAuth behavior changes, including the -32022 refusal of a stateless-only server and the cancelled JSON reply (implemented in P3 ([P3] server: serve 2026-07-28 stateless requests #368)).
  • docs/src/server.src.md: strict mode ignores early notifications and does not apply behind StatelessHTTPServerTransport; -32022 for initialize without a handshake revision; a nil tool description is omitted.
  • docs/src/rough_edges.src.md: the -32603 item is removed; the one-initialize item becomes the sessionless handshake limitation.
  • docs/src/protocol_versions.src.md: a pinned client never connects at another version.
  • docs/src/troubleshooting.src.md: "Server is already initialized" applies to a connection or session.
  • Examples/Snippets/Client/Notifications.swift: notification handlers call the client directly, without a Task wrapper.
  • design/design.md, design/auth.md, DEPENDENCY_POLICY.md and the other guides follow.

Review fixes

Client (f00b681, Sources/MCP/Client/Client.swift, Sources/MCP/Base/Utilities/RequestContext.swift)

  • Server-to-client requests: each got a task, without limit, so a server could start any number of sampling or elicitation handlers. Now at most Configuration.maxConcurrentServerRequests (new, default 4) run at once; up to 64 more wait in arrival order (incomingRequestBacklog); further ones get -32603 "Too many requests from the server". A request whose id is already running or waiting gets -32600; a finished handler no longer frees the slot of a later request that reuses its id (per-run token). At 2026-07-28 such requests get -32601. notifications/cancelled drops a waiting request.
  • Ordering: every response waited behind all queued notifications, so a slow notification handler delayed unrelated results, and a handler that awaited a request started elsewhere deadlocked. Now only notifications go through the inbound queue, and only those with a registered handler. A response is delivered at once, except that a request carrying a progress token, sent while progress handlers are registered, gets its response after the progress notifications for that token already queued (progressTokens, queuedProgress, parkedResponses). Requests sent from a notification handler never wait. Log notifications are no longer ordered with results.
  • Built-in notifications: connect registered onNotification handlers for notifications/cancelled and the listen acknowledgement, so user handlers for those methods ran in the receive loop. The client now handles them itself in the loop (handleBuiltIn), and user handlers for them run on the inbound queue like any other.
  • Cancellation: cancelling the task that awaited RequestContext.value, or a convenience method such as callTool, left the request running. It now resolves the request with CancellationError and sends notifications/cancelled through cancelRequest; the MRTR loop forwards the cancellation to the round in flight.

Server (Sources/MCP/Server/Server.swift)

  • A strict server dropped notifications/cancelled from a 2026-07-28 client, which never sends initialize, so its requests could not be cancelled. notifications/cancelled now always passes, and other notifications pass once the connection has served a stateless request (servedStatelessRequest).
  • Behind StatelessHTTPServerTransport, handshake requests carry no client capabilities, and the capability check of server-to-client requests failed with -32601 "Client capabilities not initialized". The request now goes to the client, which answers.

StatefulHTTPServerTransport

  • The replay store was one list capped by event count for all streams of a session: a busy stream evicted the events of a quiet one, which then could not resume; priming events took slots; messages had no size limit; a Last-Event-ID whose own event was evicted failed even when nothing after it was lost. Now priming events get an ID but are not stored; new eventStoreByteCapacity: Int = 16 << 20 caps the stored bytes; the newest event is always kept. A resumption parses <stream>_<counter> from the ID and gets 400 only when the stream is unknown or one of its events after the ID was dropped (evictedThrough). Eviction advances a head index and compacts in batches.

OAuth (Sources/MCP/Base/Authorization/)

  • OAuthURLValidator.isPrivateIPHost: literals were parsed by hand, so other spellings of private addresses passed (::ffff:a00:1, 64:ff9b::a00:1, ::10.0.0.1, 167772161, 10.1, 0x0a.0.0.1, 012.0.0.1), and several reserved ranges were missing. Hosts are now parsed with inet_pton; IPv4 addresses embedded as IPv4-mapped, IPv4-compatible (::/96) or NAT64 (64:ff9b::/96) are classified as IPv4; a dotted quad in non-canonical form and a numeric host that inet_aton accepts are blocked. Added ranges: 192.0.0.0/24, 198.18.0.0/15, 224.0.0.0/4, 240.0.0.0/4, ::, fec0::/10, ff00::/8. Host names and loopback addresses are still allowed.
  • URLSession.oauthData(for:redirects:validator:) ignored the redirect policy under swift-corelibs-foundation, which has no per-task delegates. On Linux it now runs the request in a session with the caller's configuration and OAuthRedirectGuard as its delegate, invalidated after the request.

Docs

  • CLAUDE.md, design/design.md (dispatch table, response ordering, built-in notifications), docs/src/client.src.md (ordering, request limits, cancellation through RequestContext.value), docs/src/migration.src.md (summary row, limits, eventStoreByteCapacity), docs/src/protocol.src.md (replay store, private address ranges, Linux redirects).

Diagram

Client inbound routing after this PR:

flowchart TD
    L["receive loop"] --> K{"message"}
    K -->|"response, or each response of a batch"| R{"progress of its request still queued?"}
    R -->|no| NOW["deliver at once"]
    R -->|yes| PARK["deliver after that progress is handled"]
    K -->|"notification"| N{"cancelled or subscriptions/acknowledged?"}
    N -->|yes| IN["client handles it in the loop"]
    N --> H{"handler registered?"}
    H -->|yes| Q["inbound queue: one handler at a time, in arrival order"]
    K -->|"server-to-client request"| T{"slot free?"}
    T -->|yes| TASK["own task, cancelled by notifications/cancelled"]
    T -->|"no, fewer than 64 waiting"| WAIT["wait for a slot"]
    T -->|"no, backlog full"| REF["-32603"]
Loading

API changes

Added

Symbol Notes
Client.Configuration.maxConcurrentServerRequests default 4; new defaulted parameter of Client.Configuration.init(strict:protocolMode:logLevel:discoveryTimeout:multiRoundTrip:maxConcurrentServerRequests:); decoded with a default when absent

Changed

Symbol Change
StatefulHTTPServerTransport.init(sessionIDGenerator:validationPipeline:retryInterval:eventStoreCapacity:eventStoreByteCapacity:logger:) new eventStoreCapacity: Int = 1000 and eventStoreByteCapacity: Int = 16 << 20; source compatible
OAuthConfiguration.TokenEndpointAuthentication.none(clientID:) a non-empty, non-URL client ID is pre-registered (no DCR); breaking (behavior)
OAuthURLValidator.isPrivateIPHost(_:) false for host names; parses literals with inet_pton, classifies embedded IPv4, blocks non-canonical numeric hosts and more reserved ranges
RequestContext.value cancelling the awaiting task cancels the request
MCPError decoding of -32603 keeps the peer's message
OAuthConfiguration.makePrivateKeyJWTAssertion(...) signature unchanged; no longer throws cryptographyUnavailable

Removed

None.

Behavior changes

Client

  • cancelRequest(_:reason:) right after send(_:) always ends the request. A request cancelled before it was handed to the transport is not sent, and no notifications/cancelled is sent for it. Cancelling the task that awaits RequestContext.value has the same effect.
  • Notification handlers run outside the receive loop, one at a time, in order, and may await requests on the same client. Responses do not wait for them, except for the queued progress notifications of the same request.
  • Server-to-client requests (2025-11-25) run concurrently, each in its own task, at most 4 at once by default; up to 64 more wait, further ones get -32603, and a duplicate id gets -32600. At 2026-07-28 they get -32601.
  • withBatch(body:) requests carry the 2026-07-28 envelope and header parameters and run the MRTR loop; on stateless connections they are sent as separate requests. A throwing body fails the requests it added.

Server

  • Strict servers ignore early notifications, except notifications/cancelled, and accept every notification once the connection has served a stateless request. Messages that cannot be parsed, and empty batches, are answered with "id": null. A strict request before initialize gets -32600.
  • One Server behind StatelessHTTPServerTransport answers every initialize, keeps no client state for handshake clients, and sends their server-to-client requests without a capability check.
  • StatefulHTTPServerTransport keeps at most 1000 replay events and 16 MiB per session by default, always the newest event; priming events are not stored; a quiet stream stays resumable while other streams fill the store.
  • Tool with a nil description omits the key.

OAuth

  • private_key_jwt works on Linux (PKCE does since P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363)).
  • .none(clientID: "my-app") no longer triggers dynamic registration; pass "" to register.
  • Registration endpoints on private IP literals are rejected; discovery redirects are validated and token and registration requests do not follow redirects, on Apple platforms and on Linux.
  • Host names beginning with fc, fd or fe8-feb are no longer rejected as private. Every spelling of a private or reserved IP literal is rejected, including numeric forms such as 167772161 and 0x0a.0.0.1.

Conformance

No baseline changes:

Leg Before (P9) After (P11)
2025-11-25 0 / 0 0 / 0
2026-07-28 0 / 0 0 / 0
default 25 / 11 25 / 11

Tier score 100% for client and server at 2025-11-25 and 2026-07-28. One 2025-11-25 server run crashed inside the harness (Node UnhandledPromiseRejection in server-sse-multiple-streams); 6 reruns and 5 solo runs passed.

Tests

  • New Tests/MCPTests/RequestLifecycleTests.swift:
    • "Request lifecycle": cancel right after send never overtakes the request; a notification handler and a server-to-client request handler can each wait for a request on the same client; a notification handler can await a request started elsewhere; a server-cancelled request stops the client handler without an answer; progress notifications of a request are handled before its response is delivered; handlers registered for notifications/cancelled run outside the receive loop; cancelling the task that awaits a request cancels the request.
    • "Server-to-client request limits": at most the configured number of handlers run at once and the rest wait; a request whose id is already running is refused.
    • "Batches": stateless batches carry _meta and run the round-trip loop; a 2025-11-25 batch is one array; a throwing body fails its requests.
    • "Server replies": strict server ignores an early notification; a strict server takes notifications/cancelled from a 2026-07-28 client; unreadable message and empty batch get a null id; every initialize is answered behind the stateless HTTP transport.
  • HTTPServerTransportTests: the replay store keeps the newest events only, and a resumption from the dropped event itself still works; suite "Stateful replay store": a quiet stream can be resumed after other streams filled the store, the byte capacity holds and the newest event is kept, a malformed or unknown Last-Event-ID gets 400; a client that goes away before a JSON reply cancels the request (P3 ([P3] server: serve 2026-07-28 stateless requests #368) behavior).
  • OAuthURLValidatorTests: host names that start like IPv6 prefixes are not blocked; bracketed, zoned and IPv4-mapped literals; every spelling of a private address is blocked (parameterized: mapped, NAT64, IPv4-compatible, decimal, short, hex and octal forms, multicast, reserved); public and loopback addresses in any spelling are not blocked; discovery redirects must stay https and public; token and registration requests follow no redirect.
  • OAuthClientRegistrarTests: a pre-registered plain client ID is not registered again.
  • ToolTests: a tool without a description encodes no description key.
  • OAuthAuthorizationTests: the #if canImport(CryptoKit) guards are removed, so the private_key_jwt tests run on every platform. OAuthTestScenarios that expect DCR pass .none(clientID: "").
  • GuidesSnippetTests: -32603 keeps its message; a second initialize behind the stateless transport succeeds. The pinned-mode and stateless-only tests are in P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362).
  • swift test: 815 swift-testing tests plus the XCTest suites, all passed.

Review notes

  • Ordering: notification handlers still run one at a time, so a slow one delays later notifications, not responses. Only progress is ordered with its request's result; log notifications are not. A request sent from a notification handler gets its result before its own progress is handled.
  • Server-to-client request handlers now run concurrently, up to maxConcurrentServerRequests; handlers that relied on serial execution need their own synchronization or a limit of 1.
  • isSessionless is a type check on StatelessHTTPServerTransport; other transports keep session semantics.
  • OAuthRedirectGuard uses per-task URLSession delegates on Apple platforms. On Linux each OAuth request runs in its own session built from the caller's configuration, so the caller session's own delegate does not see it.
  • The .none(clientID:) change affects callers that passed a placeholder ID and relied on DCR to replace it. The migration guide lists it.
  • pkceS256Unavailable and cryptographyUnavailable are kept for source compatibility although they are never thrown.
  • isPrivateIPHost blocks every non-canonical numeric host, public or not (012.0.0.1 is blocked although inet_pton reads it as 12.0.0.1), because resolvers read such hosts differently.
  • Warts left in docs/rough_edges.md: tuple convenience results, no built-in logging/setLevel and resources/subscribe handlers, Server.Info fields, OAuth errors as internalError, start overwriting earlier built-in handlers, -32600 for bad request-state keys.

Verification

swift build
swift test
swift test --filter RequestLifecycleTests
swift test --filter SnippetTests
swift scripts/weave.swift --check
swift package generate-documentation --target MCP --warnings-as-errors
BIN=$(swift build --show-bin-path)
"$BIN/HelloClient" "$BIN/HelloServer"
export npm_config_registry=https://registry.npmjs.org
scripts/run-conformance.sh --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2026-07-28 --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2026-07-28 --bin-path "$BIN"

State: the branch builds and passes swift test (815 swift-testing tests plus the XCTest suites, all passed); swift scripts/weave.swift --check passes; DocC builds with --warnings-as-errors; the three conformance legs pass at their baselines, and the tier score is 100% at both revisions.


AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.

Fixes ten of the 13 bugs found while writing the documentation, plus one
of the API warts listed in `docs/rough_edges.md`. The client registers a
request before `send(_:)` returns and runs its handlers outside the
receive loop, `withBatch` goes through the same path as `send`, the
server stops answering notifications and unreadable messages with random
ids, sessionless servers handle `initialize` correctly, the replay store
is bounded, and the OAuth client treats a plain client ID as
pre-registered and checks redirects and the registration endpoint. The
other three were fixed earlier; the migration and server guides now
describe them. It also bounds server-to-client requests (4 at once, 64
waiting), delivers responses without waiting for unrelated notification
handlers, makes the replay store per stream with a byte cap, parses IP
literals with `inet_pton`, and applies the redirect checks on Linux.
Docs, design notes and the migration guide describe the new behavior.
- Let the input-request bridge send elicitation, sampling and roots
  requests behind StatelessHTTPServerTransport: a sessionless handshake
  request carries no capabilities, so the client answers instead of the
  server refusing with -32021 up front.
- Gate sessionless handshake requests: behind
  StatelessHTTPServerTransport no session ties a request to the
  initialize that passed the initialize hook, so the stateless request
  hook runs before every request other than initialize, and with only
  an initialize hook such requests are refused with -32600.
- Send list-changed and resource-updated notifications from a handshake
  handler behind StatelessHTTPServerTransport on that request's stream;
  2026-07-28 handlers still deliver them only through listen streams.
- Never send notifications/cancelled for initialize: cancelling connect
  forgets the request locally, as the 2025-11-25 cancellation rules
  require.
- Keep a cancelled server-to-client handler counted against
  maxConcurrentServerRequests until it returns, and answer a server
  ping at once with an empty result outside that limit instead of
  queueing it (it was answered with -32601).
- Decode -32603 without data.detail like the other standard codes, so
  "Internal error: x" becomes internalError("x") instead of repeating
  the prefix.
- Document that a notification handler must not await a request with a
  progress token sent outside a notification handler, and the hook,
  slot and ping behavior, in the guides.
- Stop the message loop when the transport finishes its receive stream,
  normally or with an error. It called receive() again and spun on the
  already finished stream (stdio server exit), so pending requests and
  connect() waited forever. The client now runs the same teardown as
  disconnect() (listen stream and its retry, subscribe waiters, round
  trips, server-to-client handlers, inbound queue, unsent requests),
  disconnects the transport and fails every pending request with
  connectionClosed, or with the stream's error (wrapped in
  transportError unless it is an MCPError).
- Rethrow that error from server/discover in .automatic instead of
  falling back to initialize on a closed connection, so connect() fails
  with it whether the server exits before answering initialize or
  server/discover.
- Track a connection generation: an old message loop never tears down a
  newer connection, a batch built for a closed or replaced connection
  throws connectionClosed and is not sent, and the listen backoff does
  not reopen a stream once its connection closed.
- connect(transport:) on a connected client releases the previous
  connection first, failing its requests with "Client disconnected";
  the handler that reconnects is not cancelled, and server-to-client
  requests are answered on the transport they came from.
- Document on Transport that finishing the receive stream means the
  connection is closed, and that disconnect() should finish it.

Port of #67.
- isPrivateIPHost blocks IPv4-translated (::ffff:0:0:0/96) and 6to4
  (2002::/16) addresses that embed a private IPv4 address, and the
  local-use NAT64 prefix 64:ff9b:1::/48.
- A host that contains ':' but is not an IPv6 address (fc00::1::2), an
  embedded IPv4 address that is not a canonical dotted quad
  ([::ffff:012.0.0.1], which inet_pton reads as 12.0.0.1), and brackets
  around anything but an IPv6 address or unbalanced brackets
  ([127.0.0.1], [::1) are blocked instead of passing as host names.
- A numeric host with a trailing root label (10.0.0.1.) is read as the
  address resolvers see, so it is blocked like other non-canonical
  spellings.
- OAuthLoopbackHost.isLoopback also accepts [::1]: URLComponents.host
  keeps the brackets of an IPv6 literal, so http://[::1] was refused as
  a loopback endpoint, redirect URI and redirect target, while URL.host
  callers pass ::1.
- Tests cover each range edge and neighbour, hosts taken from URLs the
  way the OAuth flow takes them, and loopback with brackets.

Port of #68.
- A reconnect keeps the slots of cancelled server-to-client handlers that
  are still running until they return, so maxConcurrentServerRequests
  also holds across connect(transport:), as the client guide says.
  detachConnection used to clear that accounting.
- Discovery redirects reach a loopback host (localhost, a name under
  .localhost per RFC 6761 section 6.3, 127.0.0.0/8, ::1, also embedded
  in IPv6) only from a loopback host, and each hop is checked against the
  previous one (response.url) instead of the first URL of the chain.
  Before, a public metadata URL could redirect to https://127.0.0.1 and
  an intermediate https hop could lead to a loopback http URL.
- RequestContext.value says that the request is shared: cancelling one
  awaiting task cancels it for every task that awaits it. A test pins
  that a second waiter fails too.
- The client guide says that queued notifications have no size limit, so
  a handler that does not return keeps later notifications in memory.
- Behind StatelessHTTPServerTransport, notify(_:to:) from a handler of a
  handshake request sends the notification on that request's stream only
  when recipients accepts the request's context. One server serves every
  client there, so a filter on the caller (for example its principal in
  httpContext) used to apply to listen streams but not to the caller's
  own stream. The protocol guide says so.
- Cancelling a round of a multi round-trip exchange with cancelRequest
  sends one notifications/cancelled. Stopping the exchange cancels the
  round's task, whose cancellation handler cancelled the request again
  after cancelRequest had already removed it, and sent a second
  notification. A cancelled task now cancels its request only while it
  is still pending (2025-11-25 cancellation: notifications reference
  requests believed to be in progress).
- A connect(transport:) whose server/discover fails because another
  connect replaced its connection throws "Client disconnected" instead of
  falling back to initialize on the new connection, which sent a second
  initialize there and downgraded it to 2025-11-25. Discovery also stops
  before retrying or adopting a result for a replaced connection.
- The reconnect-from-a-handler test uses roots/list: a ping runs outside
  the handler slots, so it did not exercise the spared handler.
canarik
canarik previously approved these changes Nov 25, 2026

@canarik canarik left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @jeanmatthieu

Base automatically changed from conformance/p9-flip to rel/1.0.0 November 25, 2026 12:39
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:39

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit d28b8b3 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p11-fixes branch November 25, 2026 12:40
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.

2 participants