Skip to content

mcpcompat/client: add real-client integration tests for protocol-status handling (stacklok/toolhive#7034) - #522

Merged
rdimitrov merged 4 commits into
stacklok:mainfrom
mangopep:test/mcpcompat-protocol-status-integration
Nov 20, 2026
Merged

rdimitrov merged 4 commits into
stacklok:mainfrom
mangopep:test/mcpcompat-protocol-status-integration

Conversation

@mangopep

@mangopep mangopep commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

What this does

Adds integration tests that drive the real mcpcompat client over real HTTP against a real go-sdk MCP server. They prove the protocol-status handling works end to end: JSON-RPC errors, method-not-found versus session termination, auth challenges, and recovery on the same client.

Tests only. No production code, dependency, or API changes.

Refs stacklok/toolhive#7034

Why it was needed

The error handling in errorbody.go, errors.go and rfc9728.go was only covered by unit tests. Those feed a pre-seeded context straight into the error mappers. The only end-to-end test used a healthy server. Nothing checked the whole chain when a real server answers with a failing HTTP status:

go-sdk decodes (or doesn't decode) the response, then the shim captures the status and WWW-Authenticate, then the mapper classifies the error.

How the tests work

Each test starts a real go-sdk Streamable HTTP server behind a thin handler. That handler only injects a fault (a status code, a JSON-RPC error body, an auth challenge) for chosen requests. Everything else, including the initialize handshake, is served by the real SDK. Nothing is mocked on the client/server path, and no network or API key is needed.

sequenceDiagram
    participant T as Test
    participant C as mcpcompat client
    participant R as headerRoundTripper<br/>(captureErrorBody)
    participant F as Fault-injecting handler
    participant S as go-sdk StreamableHTTPHandler + Server
    T->>C: Initialize / CallTool / ListResources
    C->>R: HTTP request via go-sdk transport
    R->>F: forward request
    alt no fault armed
        F->>S: pass through
        S-->>F: real MCP response
    else fault armed for this request
        F-->>R: injected status / headers / body
    end
    F-->>R: response
    R-->>R: record status, WWW-Authenticate, body (max 8 KiB)
    R-->>C: response (body restored)
    C-->>C: mapCallError / mapConnectError
    C-->>T: classified error (or result)
    T->>C: next request on the same client
Loading

What is covered (maps to the issue's four checkboxes)

Issue item Tests
JSON-RPC errors preserved Code, message and data survive HTTP 400/403/422 and are not reclassified as auth or session errors. A 503 body is re-attached by the shim, since go-sdk does not decode 429/5xx bodies.
Method-not-found vs session termination A server lacking an optional method returns method-not-found and the session keeps working. A 404 carrying a -32601 body is still method-not-found. A real out-of-band DELETE of the session gives ErrSessionTerminated, as do the JSON-RPC-shaped "session not found" 404s of ToolHive's proxy, the TypeScript SDK and the Python SDK.
Auth challenges retained 401 status, WWW-Authenticate and the RFC 9728 resource_metadata URL are kept, including empty-body, missing, malformed and multiple-header cases. A cleanup DELETE answered with a different non-2xx does not overwrite the original 401.
Same client works after an error One client takes five different errors in a row, with successful calls in between. Each error is checked for its own classification, and the session ID never changes.

Also covered:

  • The 8 KiB error-body cap (read from the real constant via export_test.go).
  • 24 concurrent calls (mixed 401 / 400 / success) on one client, which is where per-call error capture could leak through the shared RoundTripper.
  • 8 concurrent independent clients.
  • Deadlines and cancellation, with no hang and the client usable afterwards.
  • Server disconnect.

Tests are split by topic: protocol_status_ (shared harness), protocol_errors_, protocol_auth_ and protocol_session_integration_test.go.

404 classification (deliberately unchanged)

The shim reports ErrSessionTerminated for every HTTP 404 except one carrying JSON-RPC method-not-found (-32601). That rule is broad on purpose, and TestProtocolStatus_Bare404WithJSONRPCBody now pins it:

404 response Result
ToolHive proxy: -32001 "Session not found" with the request's id echoed (pkg/transport/session.WriteNotFound) ErrSessionTerminated
TypeScript SDK: "id": null ErrSessionTerminated
Python SDK: "id": "server-error" ErrSessionTerminated
Application error with the request's id echoed ErrSessionTerminated (go-sdk keeps the connection, so the session still works)

A narrower rule was tried during review (keep the session when the JSON-RPC error echoes the request id) and reverted. ToolHive's proxy echoes the id in its session-not-found 404, and vMCP relies on 404 → ErrSessionTerminated → re-initialize. With the narrower rule, clients behind ToolHive's proxy would retry a dead session forever. The cost of the broad rule is an occasional unnecessary re-initialize when a server reports an application error with a 404.

Things worth knowing

  • go-sdk reserved JSON-RPC codes: go-sdk uses -32001, -32003, -32004 and -32005 internally. A server error with -32003 ("client is closing") is reported as "connection closed" and the *jsonrpc.Error is dropped. The tests avoid these codes where they assert on the decoded error. This is go-sdk behavior and may be worth raising upstream.
  • go-sdk behavior I did not assert around: it closes the connection on a 4xx without a JSON-RPC body (for example a bodiless 401 or a plain-text 403). So recovery is only asserted where the SDK keeps the session open.
  • There is no goroutine-leak detector, to avoid a new dependency.

Reliability

  • Every client gets its own HTTP transport. Without this, httptest.Server.Close() closes the shared http.DefaultTransport's idle connections and breaks other parallel tests. This showed up as a rare flake and is fixed.
  • A fault fires exactly once: onMethod disarms with CompareAndSwap, so concurrent matching requests cannot both be faulted.
  • Cancellation is triggered by a server-side signal, not a sleep. The deadline case disarms the fault before the recovery call, so a deadline that expires before the request reaches the server cannot stall it.
  • Every blocking call has a 10 s bound, and clients and servers are cleaned up with t.Cleanup.
  • A mutation check confirmed the cleanup-DELETE test fails if the "first non-2xx response wins" guard is removed.

Verification (local)

  • task (golangci-lint: 0 issues, go vet, go test -race ./...): pass
  • task license-check: pass
  • mcpcompat/client coverage: 72.1%
  • New tests under -race: -count=30 -cpu 1,2,4, plus -count=50 -shuffle=on: all pass
  • Original submission also ran the 4 nested Redis modules and govulncheck; no dependencies changed since.

…us handling

The error-mapping logic (errorbody.go, errors.go, rfc9728.go) was only
covered by unit tests that feed seeded contexts into the mappers, plus a
happy-path end-to-end test. Nothing drove the real client against a real
go-sdk server that answers with a failing HTTP status.

Add tests that run the mcpcompat client over real HTTP against a go-sdk
Streamable HTTP server. A thin front handler only injects faults for
selected requests; initialize and all other calls are served by the SDK.

Covered:
- JSON-RPC errors on non-2xx responses keep code, message and data, and
  are not reclassified as auth or session errors
- method-not-found is distinguishable from a genuinely terminated session,
  and the session stays usable after method-not-found
- 401 status, WWW-Authenticate and the RFC 9728 resource_metadata URL are
  retained, including missing, malformed and multiple challenge headers
  and empty-body responses
- a cleanup DELETE answered with a different non-2xx does not overwrite
  the original 401
- error-body capture respects the 8 KiB limit
- the same client recovers after recoverable errors
- concurrent clients, deadlines, cancellation and server disconnect

Each test client uses its own HTTP transport so parallel tests do not
close each other's pooled connections.

Tests only; no production code changes.

Refs stacklok/toolhive#7034
@mangopep mangopep changed the title mcpcompat/client: add real-client integration tests for protocol-status handling stacklok/toolhive#7034 mcpcompat/client: add real-client integration tests for protocol-status handling stacklok/toolhive #7034 Nov 15, 2026
rdimitrov and others added 2 commits November 20, 2026 12:03
Review follow-ups on the new protocol-status integration tests:

- onMethod disarms with CompareAndSwap, so exactly one request is faulted
  even with concurrent calls; drop the per-handler arm.Store(false).
- Deadline subtest disarms the fault before the recovery call, so a
  deadline that expires before the request reaches the server can no
  longer stall the recovery call (latent flake).
- Add TestProtocolStatus_ConcurrentCallsOnOneClient: parallel 401/400/ok
  calls on one client, which is where per-call error capture could leak
  through the shared RoundTripper.
- RecoveryAfterRecoverableErrors now checks each failure's
  classification, not only "not terminated". Step 8 uses -32010 because
  go-sdk reserves -32003 (client closing) and reports a server error
  with that code as "connection closed", dropping the JSON-RPC error.
- Share the echo server (newEchoSDKServer) with newTestServer, share an
  isolatedHTTPClient helper with deleteSession, and parse the echo
  argument once in the harness (rpcCall.echoMessage).
- Expose maxCapturedErrBody through export_test.go instead of copying 8 KiB.
- Flag the 404 + JSON-RPC body classification as a known gap in
  Bare404WithJSONRPCBody rather than as intended behavior.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mapStatusError reported ErrSessionTerminated for every HTTP 404 except
JSON-RPC method-not-found. go-sdk servers on newer protocol versions
also return 404 with a JSON-RPC error for application errors on a live
session, and go-sdk keeps the connection open for those, so ToolHive
would tear down and re-initialize a healthy session.

captureErrorBody now records, for a 404 only, whether the body is a
JSON-RPC error whose non-null ID equals the request's ID (re-read via
req.GetBody). mapStatusError surfaces that case unchanged. Every other
404 still maps to ErrSessionTerminated, including the JSON-RPC-shaped
session-not-found responses of the TypeScript SDK (null ID) and the
Python SDK ("server-error" ID), plain-text bodies, notifications and
bodies truncated at the capture limit.

Tests: table-driven TestCaptureErrorBody_404AnswersRequest, and the
integration test (renamed TestProtocolStatus_404WithJSONRPCBody) now
asserts the live-session case plus the TypeScript and Python variants.
A mutation check confirms both fail without the new branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov rdimitrov changed the title mcpcompat/client: add real-client integration tests for protocol-status handling stacklok/toolhive #7034 mcpcompat/client: add protocol-status integration tests and keep the session on a 404 that answers the request (stacklok/toolhive#7034) Nov 20, 2026
…request"

This reverts commit b7530e6.

A JSON-RPC error carrying the request's own ID does not prove the
session is alive. ToolHive's proxy (pkg/transport/session.WriteNotFound)
answers an expired session with HTTP 404 and a -32001 "Session not
found" error that echoes the request ID, and vMCP relies on that 404
mapping to ErrSessionTerminated so the client re-initializes. With the
reverted change, clients behind ToolHive's proxy would retry a dead
session forever.

The broad rule (every 404 except JSON-RPC method-not-found is a
terminated session) is restored and now pinned by
TestProtocolStatus_Bare404WithJSONRPCBody, which covers ToolHive's
echoed-ID format, the TypeScript (null ID) and Python (placeholder ID)
SDK formats, and an application error with an echoed ID.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov rdimitrov changed the title mcpcompat/client: add protocol-status integration tests and keep the session on a 404 that answers the request (stacklok/toolhive#7034) mcpcompat/client: add real-client integration tests for protocol-status handling (stacklok/toolhive#7034) Nov 20, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Thanks for the thorough harness. I pushed review follow-ups (one-shot CAS fault arming, a deadline-case flake fix, same-client concurrency coverage, per-step classification checks in the recovery test, shared helpers). I also pinned the broad 404 -> ErrSessionTerminated rule against ToolHive's proxy format (echoed id), the TypeScript SDK (null id) and the Python SDK (placeholder id), since vMCP's session recovery depends on it.

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