Add mcp-stateless module: migrate an MCP server from the 2025 stateful protocol to 2026-07-28 on Spring AI 2.1.0
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4tJPXfq5UyiLSFr49
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
3aa20a1dce
commit
26e0a3875a
@@ -17,6 +17,7 @@ facts, so the build fails when a claim stops being true.
|
|||||||
| `mcp-sdk-plain` | Write an MCP Server with the Plain MCP Java SDK (No Spring): stdio and Streamable HTTP | tools, a resource and a resource template on the framework-free SDK, a fat jar over stdio and Streamable HTTP, wire-level transcripts, and a Spring AI client connecting to it |
|
| `mcp-sdk-plain` | Write an MCP Server with the Plain MCP Java SDK (No Spring): stdio and Streamable HTTP | tools, a resource and a resource template on the framework-free SDK, a fat jar over stdio and Streamable HTTP, wire-level transcripts, and a Spring AI client connecting to it |
|
||||||
| `koog` | Koog: JetBrains' Kotlin AI Agent Framework on the JVM, Your First Agent with Tools in Java | a tool-calling agent, a strategy graph with a plain-Java node before the model, and the Spring Boot starter, tested against a scripted OpenAI-compatible endpoint, with tool-error, bad-argument, iteration-cap and Kotlin-BOM failure modes |
|
| `koog` | Koog: JetBrains' Kotlin AI Agent Framework on the JVM, Your First Agent with Tools in Java | a tool-calling agent, a strategy graph with a plain-Java node before the model, and the Spring Boot starter, tested against a scripted OpenAI-compatible endpoint, with tool-error, bad-argument, iteration-cap and Kotlin-BOM failure modes |
|
||||||
| `claude-code-spring` | Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ | a Spring Boot 4.2 orders service with a complete committed Claude Code setup: `CLAUDE.md`, a path-scoped rule, two skills, four hooks (command guard, protected files, tests after edit, a Stop gate) run against real hook JSON, project-scoped `.mcp.json` generated by the real `claude mcp` CLI, and tests that lint the setup |
|
| `claude-code-spring` | Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ | a Spring Boot 4.2 orders service with a complete committed Claude Code setup: `CLAUDE.md`, a path-scoped rule, two skills, four hooks (command guard, protected files, tests after edit, a Stop gate) run against real hook JSON, project-scoped `.mcp.json` generated by the real `claude mcp` CLI, and tests that lint the setup |
|
||||||
|
| `mcp-stateless` | MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec | one order server as a 2025-era stateful and a 2026-07-28 stateless Spring AI server, behind a round-robin balancer, with multi-round-trip requests, a version router and real SDK clients |
|
||||||
|
|
||||||
## Versions (verified on Maven Central, 2026-10-11)
|
## Versions (verified on Maven Central, 2026-10-11)
|
||||||
|
|
||||||
@@ -40,6 +41,7 @@ facts, so the build fails when a claim stops being true.
|
|||||||
| Kotlin `kotlin-stdlib` | 2.3.10 | the Spring Boot 3.5.16 BOM pins 1.9.25 and would win; the `koog` pom imports the Kotlin BOMs first |
|
| Kotlin `kotlin-stdlib` | 2.3.10 | the Spring Boot 3.5.16 BOM pins 1.9.25 and would win; the `koog` pom imports the Kotlin BOMs first |
|
||||||
| Spring Boot (`claude-code-spring`) | 4.2.0 | GA 2026-11-19, verified on Maven Central 2026-11-21; `claude-code-spring` only |
|
| Spring Boot (`claude-code-spring`) | 4.2.0 | GA 2026-11-19, verified on Maven Central 2026-11-21; `claude-code-spring` only |
|
||||||
| Claude Code CLI | 2.1.330 | `claude mcp` run for `claude-code-spring/output/08`; the model-side behaviour is documented, not executed |
|
| Claude Code CLI | 2.1.330 | `claude mcp` run for `claude-code-spring/output/08`; the model-side behaviour is documented, not executed |
|
||||||
|
| Spring Boot / Spring AI / MCP Java SDK (`mcp-stateless`) | 4.2.0 / 2.1.0 / 2.2.0 | verified on Maven Central 2026-11-22; this module overrides the Spring versions above |
|
||||||
| JDK | 25 LTS | |
|
| JDK | 25 LTS | |
|
||||||
| JUnit | 6.1.3 | |
|
| JUnit | 6.1.3 | |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# mcp-stateless
|
||||||
|
|
||||||
|
Companion module for the ankurm.com post **MCP 2026-07-28 for Java Developers: Migrating an MCP Server to the Stateless Spec**.
|
||||||
|
|
||||||
|
One order-lookup MCP server that runs as a 2025-era stateful server (`legacy` profile) or as a 2026-07-28 stateless server
|
||||||
|
(`modern` profile). The tools are the same `@McpTool` beans in both. The tests start real instances, put a plain
|
||||||
|
round-robin proxy in front of them and write what happened to `output/`.
|
||||||
|
|
||||||
|
## Versions (verified on Maven Central, 2026-11-22)
|
||||||
|
|
||||||
|
| Component | Version | Note |
|
||||||
|
|---|---|---|
|
||||||
|
| Spring Boot | 4.2.0 | GA 2026-11-19 |
|
||||||
|
| Spring AI `spring-ai-starter-mcp-server-webmvc` | 2.1.0 | GA 2026-11-19. `protocol: MODERN` first exists in 2.1.0-RC2; it is absent from 2.0.x and 2.1.0-RC1 |
|
||||||
|
| MCP Java SDK `io.modelcontextprotocol.sdk:mcp` | 2.2.0 | brought in by Spring AI. The `io.modelcontextprotocol.modern` package first appears in 2.2.0-M1; 2.1.0 has none |
|
||||||
|
| JDK | 25 LTS | Temurin 25.0.5 |
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scripts/run-all.sh # all tests, regenerates output/
|
||||||
|
scripts/run.sh modern 8082 M1 # one 2026-07-28 server
|
||||||
|
scripts/run.sh legacy 8081 L1 # one 2025-era server
|
||||||
|
scripts/curl-modern.sh 8082 A-101 # a single stateless request
|
||||||
|
```
|
||||||
|
|
||||||
|
## Profiles
|
||||||
|
|
||||||
|
| Profile | Property | Wire behaviour |
|
||||||
|
|---|---|---|
|
||||||
|
| `legacy` | `spring.ai.mcp.server.protocol=STREAMABLE` | `initialize`, `Mcp-Session-Id`, session held in server memory |
|
||||||
|
| `modern` | `spring.ai.mcp.server.protocol=MODERN` | `server/discover`, `_meta` on every request, `Mcp-Method` / `Mcp-Name` headers, no session |
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
| Tool | Profiles | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `order_status` | both | read-only lookup; reports which instance answered |
|
||||||
|
| `cancel_order` | `modern` | asks for confirmation by returning `input_required` (multi-round-trip request) |
|
||||||
|
|
||||||
|
## Captured output (`output/`)
|
||||||
|
|
||||||
|
| File | Shows |
|
||||||
|
|---|---|
|
||||||
|
| `01-legacy-handshake.txt` | initialize, session id, a call without a session, an unknown session |
|
||||||
|
| `02-legacy-behind-lb.txt` | two 2025 instances behind round-robin: 3 of 6 calls fail; affinity; instance stopped |
|
||||||
|
| `03-modern-wire.txt` | `server/discover`, `tools/list`, `tools/call` with no session |
|
||||||
|
| `04-modern-errors.txt` | header and body mismatches, wrong version, a 2025 `initialize`, a stray session header |
|
||||||
|
| `05-modern-behind-lb.txt` | two 2026-07-28 instances behind round-robin, one stopped mid-run |
|
||||||
|
| `06-modern-mrtr.txt` | `input_required`, `requestState`, a retry on another instance with and without a shared secret |
|
||||||
|
| `07-both-versions.txt` | one URL, two generations, routed on `MCP-Protocol-Version` |
|
||||||
|
| `08-sdk-modern-client.txt` | the 2.2.0 modern SDK client through round-robin |
|
||||||
|
| `09-sdk-version-mismatch.txt` | what each SDK client says against the other generation's server |
|
||||||
|
| `10-sdk-clients-through-router.txt` | both SDK clients through the version router |
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/java/com/ankurm/mcpstateless/ StatelessApp, OrderTools, CancelOrderTool
|
||||||
|
src/main/resources/ application.yml, application-legacy.yml, application-modern.yml
|
||||||
|
src/test/java/com/ankurm/mcpstateless/ one test class per transcript group
|
||||||
|
src/test/java/.../support/ Wire (raw HTTP), Transcript, Instance, Proxy (the stand-in balancer)
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# 2025-era server (protocol STREAMABLE): the session lives in the server's memory
|
||||||
|
# Error bodies are shown without the Java stack trace the SDK serialises into them.
|
||||||
|
|
||||||
|
## 1. tools/call with no session yet
|
||||||
|
> POST /mcp
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonRpcError":{"code":-32601,"message":"Session ID missing"}}
|
||||||
|
|
||||||
|
## 2. initialize
|
||||||
|
> POST /mcp
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"wire-test","version":"1"}}}
|
||||||
|
< 200
|
||||||
|
< Mcp-Session-Id: <session-id>
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}},"serverInfo":{"name":"orders","version":"1.0.0"},"instructions":"Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations."}}
|
||||||
|
|
||||||
|
## 3. notifications/initialized
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","method":"notifications/initialized"}
|
||||||
|
< 202
|
||||||
|
|
||||||
|
## 4. tools/call with the session
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: text/event-stream
|
||||||
|
< id:<session-id>
|
||||||
|
< event:message
|
||||||
|
< data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"order A-101 is SHIPPED (answered by instance L1)"}],"isError":false}}
|
||||||
|
|
||||||
|
## 5. tools/call with a session id this server never issued
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"}}}
|
||||||
|
< 404
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonRpcError":{"code":-32603,"message":"Session not found: <session-id>"}}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Two 2025-era instances behind a balancer: round-robin, then session affinity, then an instance dies
|
||||||
|
# PART A: plain round-robin. Request n goes to L1 when n is even and to L2 when n is odd.
|
||||||
|
|
||||||
|
## A1. initialize
|
||||||
|
> POST balancer/mcp
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"wire-test","version":"1"}}}
|
||||||
|
< 200
|
||||||
|
< Mcp-Session-Id: <session-id>
|
||||||
|
< Content-Type: application/json
|
||||||
|
< X-Served-By: L1
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}},"serverInfo":{"name":"orders","version":"1.0.0"},"instructions":"Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations."}}
|
||||||
|
|
||||||
|
## A2. notifications/initialized
|
||||||
|
> POST balancer/mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","method":"notifications/initialized"}
|
||||||
|
< 404
|
||||||
|
< Content-Type: application/json
|
||||||
|
< X-Served-By: L2
|
||||||
|
< {"jsonRpcError":{"code":-32603,"message":"Session not found: <session-id>"}}
|
||||||
|
|
||||||
|
# Six tools/call with the same session id, through the same balancer:
|
||||||
|
call 1 -> L1: 200 OK
|
||||||
|
call 2 -> L2: 404 Session not found: <session-id>
|
||||||
|
call 3 -> L1: 200 OK
|
||||||
|
call 4 -> L2: 404 Session not found: <session-id>
|
||||||
|
call 5 -> L1: 200 OK
|
||||||
|
call 6 -> L2: 404 Session not found: <session-id>
|
||||||
|
succeeded: 3 of 6
|
||||||
|
|
||||||
|
# PART B: the balancer learns Mcp-Session-Id from the initialize response and pins the session.
|
||||||
|
initialize served by L1, then 6 calls pinned to the same instance
|
||||||
|
succeeded: 6 of 6
|
||||||
|
|
||||||
|
# PART C: the pinned instance L1 is stopped, as in a rolling deploy.
|
||||||
|
|
||||||
|
## C1. the same session after L1 is gone
|
||||||
|
> POST balancer/mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","id":30,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"}}}
|
||||||
|
< 404
|
||||||
|
< Content-Type: application/json
|
||||||
|
< X-Served-By: L2
|
||||||
|
< {"jsonRpcError":{"code":-32603,"message":"Session not found: <session-id>"}}
|
||||||
|
|
||||||
|
## C2. the client has to start over with initialize
|
||||||
|
> POST balancer/mcp
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"wire-test","version":"1"}}}
|
||||||
|
< 200
|
||||||
|
< Mcp-Session-Id: <session-id>
|
||||||
|
< Content-Type: application/json
|
||||||
|
< X-Served-By: L2
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}},"serverInfo":{"name":"orders","version":"1.0.0"},"instructions":"Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations."}}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# 2026-07-28 server (protocol MODERN): no handshake, no session, three self-contained POSTs
|
||||||
|
|
||||||
|
## 1. server/discover replaces initialize
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: server/discover
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28"],"capabilities":{"completions":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}},"instructions":"Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations.","ttlMs":300000,"cacheScope":"public","resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## 2. tools/list
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/list
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"cancel_order","title":"cancel_order","description":"Cancels an order after the user confirms","inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"orderId":{"type":"string","description":"Order id such as A-101"}},"required":["orderId"]},"annotations":{"title":"","readOnlyHint":false,"destructiveHint":true,"idempotentHint":true,"openWorldHint":false}},{"name":"order_status","title":"order_status","description":"Looks up the status of an order by its id","inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"orderId":{"type":"string","description":"Order id such as A-101"}},"required":["orderId"]},"annotations":{"title":"","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}],"ttlMs":300000,"cacheScope":"public","resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## 3. tools/call carries the tool name in a header as well as in the body
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: order_status
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"order A-101 is SHIPPED (answered by instance M1)"}],"isError":false,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# 2026-07-28 server: how a malformed request fails
|
||||||
|
|
||||||
|
## 1. tools/call without Mcp-Name
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"error":{"code":-32020,"message":"Missing required header: Mcp-Name"}}
|
||||||
|
|
||||||
|
## 2. Mcp-Method says tools/list, the body says tools/call
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/list
|
||||||
|
> Mcp-Name: order_status
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"error":{"code":-32020,"message":"Mcp-Method header does not match request method"}}
|
||||||
|
|
||||||
|
## 3. the version header is present but params._meta is missing
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/list
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"params._meta is required"}}
|
||||||
|
|
||||||
|
## 4. a protocol version the server does not support
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2027-01-01
|
||||||
|
> Mcp-Method: tools/list
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2027-01-01"}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"error":{"code":-32022,"message":"Unsupported protocol version","data":{"supported":["2026-07-28"],"requested":"2027-01-01"}}}
|
||||||
|
|
||||||
|
## 5. a 2025-era client's first request, initialize
|
||||||
|
> POST /mcp
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"wire-test","version":"1"}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"Missing required header: Mcp-Method"}}
|
||||||
|
|
||||||
|
## 6. a stray Mcp-Session-Id on a modern request
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: order_status
|
||||||
|
> Mcp-Session-Id: left-over-from-a-2025-client
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"order A-101 is SHIPPED (answered by instance M1)"}],"isError":false,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## 7. GET /mcp
|
||||||
|
< 405
|
||||||
|
< Allow: POST
|
||||||
|
|
||||||
|
## 8. unknown tool
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: nope
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"nope","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"Unknown tool: nope"}}
|
||||||
|
|
||||||
|
## 9. a missing argument
|
||||||
|
> POST /mcp
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: order_status
|
||||||
|
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"order_status","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Invalid arguments: Validation failed: JSON schema validation errors: [: required property 'orderId' not found]"}],"isError":true,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Two 2026-07-28 instances behind plain round-robin: no affinity, no handshake, no state to lose
|
||||||
|
# PART A: six tools/call, no initialize, no session id, one URL.
|
||||||
|
call 1 -> M1: 200 order A-102 is DELIVERED (answered by instance M1)
|
||||||
|
call 2 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
call 3 -> M1: 200 order A-102 is DELIVERED (answered by instance M1)
|
||||||
|
call 4 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
call 5 -> M1: 200 order A-102 is DELIVERED (answered by instance M1)
|
||||||
|
call 6 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
succeeded: 6 of 6
|
||||||
|
|
||||||
|
# PART B: M1 is stopped, as in a rolling deploy. The client changes nothing.
|
||||||
|
call 1 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
call 2 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
call 3 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
call 4 -> M2: 200 order A-102 is DELIVERED (answered by instance M2)
|
||||||
|
succeeded: 4 of 4
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Multi-round-trip request: cancel_order asks for confirmation by returning input_required
|
||||||
|
# PART A: no spring.ai.mcp.server.modern.request-state-secret, so each instance seals with its own random key.
|
||||||
|
|
||||||
|
## A1. first call, no answer yet
|
||||||
|
> POST /mcp (M1)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"inputRequests":{"confirm":{"params":{"mode":"form","message":"Cancel order A-101?","requestedSchema":{"type":"object","properties":{"ok":{"type":"boolean"}}}},"method":"elicitation/create"}},"requestState":"<requestState>","resultType":"input_required","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
# The part of requestState before the dot is base64url JSON, readable by anyone who holds it:
|
||||||
|
{"v":1,"s":"orderId=A-101","exp":<epoch-millis>,"m":"tools/call","n":"cancel_order"}
|
||||||
|
|
||||||
|
## A2. retry, answer yes, back on the SAME instance
|
||||||
|
> POST /mcp (M1)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"inputResponses":{"confirm":{"action":"accept","content":{"ok":true}}},"requestState":"<requestState>","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"order A-101 cancelled (answered by instance M1)"}],"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## A3. the same retry, but the balancer sends it to the OTHER instance
|
||||||
|
> POST /mcp (M2)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"inputResponses":{"confirm":{"action":"accept","content":{"ok":true}}},"requestState":"<requestState>","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid or expired requestState"}}
|
||||||
|
|
||||||
|
## A4. the right instance, but the state was altered in transit
|
||||||
|
> POST /mcp (M1)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"inputResponses":{"confirm":{"action":"accept","content":{"ok":true}}},"requestState":"<requestState>","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 400
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid or expired requestState"}}
|
||||||
|
|
||||||
|
# PART B: the same secret on every instance (32 bytes or more).
|
||||||
|
|
||||||
|
## B1. first call on M1
|
||||||
|
> POST /mcp (M1)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"inputRequests":{"confirm":{"params":{"mode":"form","message":"Cancel order A-101?","requestedSchema":{"type":"object","properties":{"ok":{"type":"boolean"}}}},"method":"elicitation/create"}},"requestState":"<requestState>","resultType":"input_required","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## B2. retry, answer yes, on M2
|
||||||
|
> POST /mcp (M2)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"inputResponses":{"confirm":{"action":"accept","content":{"ok":true}}},"requestState":"<requestState>","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"order A-101 cancelled (answered by instance M2)"}],"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
|
|
||||||
|
## B3. the user declines, retry on M1
|
||||||
|
> POST /mcp (M1)
|
||||||
|
> MCP-Protocol-Version: 2026-07-28
|
||||||
|
> Mcp-Method: tools/call
|
||||||
|
> Mcp-Name: cancel_order
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"cancel_order","arguments":{"orderId":"A-101"},"inputResponses":{"confirm":{"action":"decline"}},"requestState":"<requestState>","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: application/json
|
||||||
|
< {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"order A-101 kept (answered by instance M1)"}],"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"orders","version":"1.0.0"}}}}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# One URL, two server generations, split on the MCP-Protocol-Version header
|
||||||
|
# Rule: MCP-Protocol-Version >= 2026-07-28 goes to the modern pool (M1, M2). Everything else goes to the legacy pool (L1).
|
||||||
|
|
||||||
|
# A 2025-era client: initialize, initialized, tools/call.
|
||||||
|
|
||||||
|
## 1. initialize carries no MCP-Protocol-Version header
|
||||||
|
> POST router/mcp
|
||||||
|
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"wire-test","version":"1"}}}
|
||||||
|
< 200
|
||||||
|
< Mcp-Session-Id: <session-id>
|
||||||
|
< Content-Type: application/json
|
||||||
|
< X-Served-By: L1
|
||||||
|
< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}},"serverInfo":{"name":"orders","version":"1.0.0"},"instructions":"Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations."}}
|
||||||
|
|
||||||
|
## 2. tools/call with the session and MCP-Protocol-Version: 2025-11-25
|
||||||
|
> POST router/mcp
|
||||||
|
> MCP-Protocol-Version: 2025-11-25
|
||||||
|
> Mcp-Session-Id: <session-id>
|
||||||
|
> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"A-101"}}}
|
||||||
|
< 200
|
||||||
|
< Content-Type: text/event-stream
|
||||||
|
< X-Served-By: L1
|
||||||
|
< id:<session-id>
|
||||||
|
< event:message
|
||||||
|
< data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"order A-101 is SHIPPED (answered by instance L1)"}],"isError":false}}
|
||||||
|
|
||||||
|
# A 2026-07-28 client through the same URL: four tools/call, nothing else.
|
||||||
|
modern call 1 -> M1: 200 order A-101 is SHIPPED (answered by instance M1)
|
||||||
|
modern call 2 -> M2: 200 order A-101 is SHIPPED (answered by instance M2)
|
||||||
|
modern call 3 -> M1: 200 order A-101 is SHIPPED (answered by instance M1)
|
||||||
|
modern call 4 -> M2: 200 order A-101 is SHIPPED (answered by instance M2)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# The 2.2.0 modern SDK client against two 2026-07-28 instances behind round-robin
|
||||||
|
discover: supportedVersions=[2026-07-28] ttlMs=300000 cacheScope=PUBLIC
|
||||||
|
tools: [cancel_order, order_status]
|
||||||
|
order_status #1: order A-100 is PACKED (answered by instance M1)
|
||||||
|
order_status #2: order A-100 is PACKED (answered by instance M2)
|
||||||
|
order_status #3: order A-100 is PACKED (answered by instance M1)
|
||||||
|
order_status #4: order A-100 is PACKED (answered by instance M2)
|
||||||
|
cancel_order (the client answered the confirmation itself): order A-102 cancelled (answered by instance M2)
|
||||||
|
|
||||||
|
What the balancer saw, in order:
|
||||||
|
POST server/discover
|
||||||
|
POST tools/list
|
||||||
|
POST tools/call
|
||||||
|
POST tools/call
|
||||||
|
POST tools/call
|
||||||
|
POST tools/call
|
||||||
|
POST tools/call
|
||||||
|
POST tools/call
|
||||||
|
total requests: 8
|
||||||
|
|
||||||
|
# Same client and balancer, but the instances have no shared request-state-secret:
|
||||||
|
cancel_order: io.modelcontextprotocol.modern.McpException
|
||||||
|
Invalid or expired requestState
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# What each SDK client says when it meets a server of the other generation
|
||||||
|
2025-era client -> modern server: java.lang.RuntimeException
|
||||||
|
RuntimeException: Client failed to initialize by explicit API call
|
||||||
|
McpTransportException: Bad Request. Status code:400, response body: {"jsonrpc":"2.0","id":"<id>","error":{"code":-32020,"message":"Missing required header: Mcp-Method"}}
|
||||||
|
modern client -> 2025-era server: io.modelcontextprotocol.modern.client.transport.McpHttpStatusException
|
||||||
|
HTTP 400 from http://localhost:<port>/mcp: {"jsonRpcError":{"code":-32601,"message":"Session ID missing"}... (stack trace omitted)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# A 2025-era SDK client and a 2026-07-28 SDK client, one router URL, split on MCP-Protocol-Version
|
||||||
|
2025-era client: order A-101 is SHIPPED (answered by instance L1)
|
||||||
|
2026-07-28 client: order A-101 is SHIPPED (answered by instance M2)
|
||||||
|
|
||||||
|
What the router saw (HTTP method and Mcp-Method header; '-' means the header is absent):
|
||||||
|
1 x DELETE -
|
||||||
|
1 x GET -
|
||||||
|
3 x POST -
|
||||||
|
1 x POST tools/call
|
||||||
|
1 x POST tools/list
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.ankurm.agents</groupId>
|
||||||
|
<artifactId>java-ai-agents</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>mcp-stateless</artifactId>
|
||||||
|
<name>MCP 2026-07-28: migrating a Java MCP server to the stateless spec</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- Verified on Maven Central 2026-11-22. These override the parent's older values for this module only. -->
|
||||||
|
<spring-boot.version>4.2.0</spring-boot.version>
|
||||||
|
<spring-ai.version>2.1.0</spring-ai.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.ai</groupId>
|
||||||
|
<artifactId>spring-ai-bom</artifactId>
|
||||||
|
<version>${spring-ai.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.ai</groupId>
|
||||||
|
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>mcp-stateless</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals><goal>repackage</goal></goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# One self-contained 2026-07-28 request, no handshake. Usage: scripts/curl-modern.sh [port] [order-id]
|
||||||
|
port="${1:-8082}"; order="${2:-A-101}"
|
||||||
|
curl -si -X POST "localhost:${port}/mcp" \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
|
||||||
|
-H 'MCP-Protocol-Version: 2026-07-28' -H 'Mcp-Method: tools/call' -H 'Mcp-Name: order_status' \
|
||||||
|
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"order_status","arguments":{"orderId":"'"${order}"'"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}}'
|
||||||
|
echo
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file in output/. The tests write the transcripts and assert the same facts,
|
||||||
|
# so a failing build means a number in the post stopped being true.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mvn -B -q test
|
||||||
|
ls -1 output
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Starts one instance by hand so you can poke it with curl.
|
||||||
|
# scripts/run.sh modern 8082 M1 (2026-07-28 server)
|
||||||
|
# scripts/run.sh legacy 8081 L1 (2025-era server)
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
profile="${1:?profile: legacy or modern}"; port="${2:-8080}"; name="${3:-solo}"
|
||||||
|
[ -f target/mcp-stateless.jar ] || mvn -B -q -DskipTests package
|
||||||
|
exec java -jar target/mcp-stateless.jar --spring.profiles.active="$profile" --server.port="$port" --instance.name="$name"
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.CallToolResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.ElicitFormRequest;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.ElicitResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.InputRequiredResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.TextContent;
|
||||||
|
|
||||||
|
import org.springframework.ai.mcp.annotation.McpTool;
|
||||||
|
import org.springframework.ai.mcp.annotation.McpToolParam;
|
||||||
|
import org.springframework.ai.mcp.annotation.context.McpModernRequestContext;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 2026-07-28 replacement for "ask the user in the middle of a tool call". The tool does not call
|
||||||
|
* back into the client. It returns {@code InputRequiredResult}, the client answers, and the client
|
||||||
|
* retries the SAME call with the answer attached. Nothing is parked on the server between the two
|
||||||
|
* requests, which is why any instance can take the retry.
|
||||||
|
*
|
||||||
|
* <p>Modern profile only: a legacy server has no way to express this tool.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("modern")
|
||||||
|
public class CancelOrderTool {
|
||||||
|
|
||||||
|
private final String instance;
|
||||||
|
|
||||||
|
public CancelOrderTool(@Value("${instance.name:solo}") String instance) {
|
||||||
|
this.instance = instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A LinkedHashMap, not Map.of: Map.of iterates in a different order in every JVM, which makes the wire output unstable. */
|
||||||
|
private static Map<String, Object> schema() {
|
||||||
|
Map<String, Object> ok = new LinkedHashMap<>();
|
||||||
|
ok.put("type", "boolean");
|
||||||
|
Map<String, Object> properties = new LinkedHashMap<>();
|
||||||
|
properties.put("ok", ok);
|
||||||
|
Map<String, Object> schema = new LinkedHashMap<>();
|
||||||
|
schema.put("type", "object");
|
||||||
|
schema.put("properties", properties);
|
||||||
|
return schema;
|
||||||
|
}
|
||||||
|
|
||||||
|
@McpTool(name = "cancel_order", description = "Cancels an order after the user confirms",
|
||||||
|
annotations = @McpTool.McpAnnotations(readOnlyHint = false, destructiveHint = true,
|
||||||
|
idempotentHint = true, openWorldHint = false))
|
||||||
|
public CallToolOutcome cancelOrder(McpModernRequestContext ctx,
|
||||||
|
@McpToolParam(description = "Order id such as A-101") String orderId) {
|
||||||
|
|
||||||
|
ElicitResult confirmation = ctx.inputResponse("confirm", ElicitResult.class);
|
||||||
|
if (confirmation == null) {
|
||||||
|
// First request: no answer yet. Ask, and seal the order id into requestState.
|
||||||
|
return InputRequiredResult.builder()
|
||||||
|
.elicit("confirm", ElicitFormRequest.builder("Cancel order " + orderId + "?", schema()).build())
|
||||||
|
.requestState("orderId=" + orderId)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
boolean confirmed = confirmation.action() == ElicitResult.Action.ACCEPT
|
||||||
|
&& Boolean.TRUE.equals(confirmation.content().get("ok"));
|
||||||
|
String text = confirmed
|
||||||
|
? "order " + orderId + " cancelled (answered by instance " + instance + ")"
|
||||||
|
: "order " + orderId + " kept (answered by instance " + instance + ")";
|
||||||
|
return CallToolResult.builder().addContent(TextContent.builder(text).build()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.ai.mcp.annotation.McpTool;
|
||||||
|
import org.springframework.ai.mcp.annotation.McpToolParam;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The same {@code @McpTool} bean serves both protocol generations. The tool reports which
|
||||||
|
* instance answered, so a load-balancer test can see the requests spreading out.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class OrderTools {
|
||||||
|
|
||||||
|
private static final Map<String, String> ORDERS = Map.of(
|
||||||
|
"A-100", "PACKED",
|
||||||
|
"A-101", "SHIPPED",
|
||||||
|
"A-102", "DELIVERED");
|
||||||
|
|
||||||
|
private final String instance;
|
||||||
|
|
||||||
|
public OrderTools(@Value("${instance.name:solo}") String instance) {
|
||||||
|
this.instance = instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
@McpTool(name = "order_status", description = "Looks up the status of an order by its id",
|
||||||
|
annotations = @McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false,
|
||||||
|
idempotentHint = true, openWorldHint = false))
|
||||||
|
public String orderStatus(@McpToolParam(description = "Order id such as A-101") String orderId) {
|
||||||
|
String status = ORDERS.getOrDefault(orderId, "UNKNOWN");
|
||||||
|
return "order " + orderId + " is " + status + " (answered by instance " + instance + ")";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One order-lookup MCP server that can run as a 2025-era stateful server ({@code legacy} profile)
|
||||||
|
* or as a 2026-07-28 stateless server ({@code modern} profile). The tools are identical in both.
|
||||||
|
*/
|
||||||
|
@SpringBootApplication
|
||||||
|
public class StatelessApp {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(StatelessApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# The 2025-era server: initialize handshake, Mcp-Session-Id, one session per client held in server memory.
|
||||||
|
spring:
|
||||||
|
ai:
|
||||||
|
mcp:
|
||||||
|
server:
|
||||||
|
protocol: STREAMABLE
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# The 2026-07-28 server: no handshake, no session, every POST stands alone.
|
||||||
|
spring:
|
||||||
|
ai:
|
||||||
|
mcp:
|
||||||
|
server:
|
||||||
|
protocol: MODERN
|
||||||
|
modern:
|
||||||
|
# Tell clients how long they may cache server/discover and the *list results. Safe here because
|
||||||
|
# nothing in them depends on who is asking. Anything per-caller must stay PRIVATE.
|
||||||
|
discover-ttl: 5m
|
||||||
|
discover-cache-scope: PUBLIC
|
||||||
|
list-ttl: 5m
|
||||||
|
list-cache-scope: PUBLIC
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
spring:
|
||||||
|
main:
|
||||||
|
banner-mode: off
|
||||||
|
jmx:
|
||||||
|
enabled: false
|
||||||
|
ai:
|
||||||
|
mcp:
|
||||||
|
server:
|
||||||
|
name: orders
|
||||||
|
version: 1.0.0
|
||||||
|
instructions: Order lookup server used to compare the 2025 and 2026-07-28 MCP protocol generations.
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
root: warn
|
||||||
|
com.ankurm: info
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Proxy;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spring AI picks ONE protocol per application ({@code spring.ai.mcp.server.protocol}), so serving both
|
||||||
|
* generations during a migration means two deployments behind one URL, split on the version header.
|
||||||
|
*/
|
||||||
|
class BothVersionsTest {
|
||||||
|
|
||||||
|
static Instance legacy;
|
||||||
|
static Instance modern1;
|
||||||
|
static Instance modern2;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void start() {
|
||||||
|
legacy = Instance.start("legacy", "L1");
|
||||||
|
modern1 = Instance.start("modern", "M1");
|
||||||
|
modern2 = Instance.start("modern", "M2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void stop() {
|
||||||
|
legacy.close();
|
||||||
|
modern1.close();
|
||||||
|
modern2.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The routing rule: a request that names 2026-07-28 or later in MCP-Protocol-Version goes to the modern pool. */
|
||||||
|
static boolean isModern(Map<String, String> headers) {
|
||||||
|
String v = headers.get("mcp-protocol-version");
|
||||||
|
return v != null && v.compareTo(Wire.MODERN_VERSION) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oneUrlTwoGenerations() {
|
||||||
|
Transcript t = new Transcript("07-both-versions.txt",
|
||||||
|
"One URL, two server generations, split on the MCP-Protocol-Version header");
|
||||||
|
Proxy.Pool legacyPool = new Proxy.Pool(List.of(legacy), true);
|
||||||
|
Proxy.Pool modernPool = new Proxy.Pool(List.of(modern1, modern2));
|
||||||
|
try (Proxy router = new Proxy(h -> isModern(h) ? modernPool : legacyPool)) {
|
||||||
|
String url = router.url();
|
||||||
|
t.note("Rule: MCP-Protocol-Version >= 2026-07-28 goes to the modern pool (M1, M2). Everything else goes to the legacy pool (L1).");
|
||||||
|
|
||||||
|
t.blank().note("A 2025-era client: initialize, initialized, tools/call.");
|
||||||
|
Reply init = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
t.exchange("1. initialize carries no MCP-Protocol-Version header", "router/mcp", Wire.legacyHeaders(null),
|
||||||
|
Wire.INITIALIZE, init);
|
||||||
|
assertThat(init.status()).isEqualTo(200);
|
||||||
|
assertThat(init.header("X-Served-By")).isEqualTo("L1");
|
||||||
|
Map<String, String> h = Wire.legacyHeaders(init.header("Mcp-Session-Id"));
|
||||||
|
assertThat(Wire.post(url, h, Wire.INITIALIZED).status()).isEqualTo(202);
|
||||||
|
Reply old = Wire.post(url, h, Wire.legacyCall(2, "A-101"));
|
||||||
|
t.exchange("2. tools/call with the session and MCP-Protocol-Version: 2025-11-25", "router/mcp", h,
|
||||||
|
Wire.legacyCall(2, "A-101"), old);
|
||||||
|
assertThat(old.header("X-Served-By")).isEqualTo("L1");
|
||||||
|
assertThat(old.text()).isEqualTo("order A-101 is SHIPPED (answered by instance L1)");
|
||||||
|
|
||||||
|
t.blank().note("A 2026-07-28 client through the same URL: four tools/call, nothing else.");
|
||||||
|
String args = "{\"orderId\":\"A-101\"}";
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
Reply r = Wire.post(url, Wire.modernHeaders("tools/call", "order_status"),
|
||||||
|
Wire.modernCall(60 + i, "order_status", args));
|
||||||
|
t.line("modern call " + (i + 1) + " -> " + r.header("X-Served-By") + ": " + r.status() + " " + r.text());
|
||||||
|
assertThat(r.status()).isEqualTo(200);
|
||||||
|
assertThat(r.header("X-Served-By")).isEqualTo(i % 2 == 0 ? "M1" : "M2");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Proxy;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** The same 2025-era server twice, behind a balancer that does not know what an MCP session is. */
|
||||||
|
class LegacyBehindLoadBalancerTest {
|
||||||
|
|
||||||
|
static Instance l1;
|
||||||
|
static Instance l2;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void start() {
|
||||||
|
l1 = Instance.start("legacy", "L1");
|
||||||
|
l2 = Instance.start("legacy", "L2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void stop() {
|
||||||
|
l1.close();
|
||||||
|
l2.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundRobinBreaksTheSessionAndAffinityMendsItUntilAnInstanceDies() {
|
||||||
|
Transcript t = new Transcript("02-legacy-behind-lb.txt",
|
||||||
|
"Two 2025-era instances behind a balancer: round-robin, then session affinity, then an instance dies");
|
||||||
|
|
||||||
|
// ---- round-robin: the session exists on one instance only ------------------------------------------
|
||||||
|
t.note("PART A: plain round-robin. Request n goes to L1 when n is even and to L2 when n is odd.");
|
||||||
|
Proxy.Pool roundRobin = new Proxy.Pool(List.of(l1, l2));
|
||||||
|
try (Proxy lb = new Proxy(h -> roundRobin)) {
|
||||||
|
String url = lb.url();
|
||||||
|
Reply init = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
String session = init.header("Mcp-Session-Id");
|
||||||
|
t.exchange("A1. initialize", "balancer/mcp", Wire.legacyHeaders(null), Wire.INITIALIZE, init);
|
||||||
|
assertThat(init.header("X-Served-By")).isEqualTo("L1");
|
||||||
|
|
||||||
|
Map<String, String> h = Wire.legacyHeaders(session);
|
||||||
|
Reply initialized = Wire.post(url, h, Wire.INITIALIZED);
|
||||||
|
t.exchange("A2. notifications/initialized", "balancer/mcp", h, Wire.INITIALIZED, initialized);
|
||||||
|
assertThat(initialized.header("X-Served-By")).isEqualTo("L2");
|
||||||
|
assertThat(initialized.status()).isEqualTo(404);
|
||||||
|
|
||||||
|
t.blank().note("Six tools/call with the same session id, through the same balancer:");
|
||||||
|
List<String> outcomes = new ArrayList<>();
|
||||||
|
int ok = 0;
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
Reply r = Wire.post(url, h, Wire.legacyCall(10 + i, "A-101"));
|
||||||
|
String detail = r.status() == 200 ? "200 OK" : r.status() + " "
|
||||||
|
+ r.json().path("jsonRpcError").path("message").asString().replaceAll("[0-9a-f-]{36}", "<session-id>");
|
||||||
|
outcomes.add("call " + (i + 1) + " -> " + r.header("X-Served-By") + ": " + detail);
|
||||||
|
if (r.status() == 200) {
|
||||||
|
ok++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outcomes.forEach(t::line);
|
||||||
|
t.line("succeeded: " + ok + " of 6");
|
||||||
|
assertThat(ok).isEqualTo(3);
|
||||||
|
assertThat(outcomes).filteredOn(s -> s.contains("404 Session not found")).hasSize(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- affinity: the workaround the 2025 protocol forces ---------------------------------------------
|
||||||
|
t.blank().note("PART B: the balancer learns Mcp-Session-Id from the initialize response and pins the session.");
|
||||||
|
// One Pool for the whole proxy, because the pool is where the learned session-to-instance table lives.
|
||||||
|
Proxy.Pool pinned = new Proxy.Pool(List.of(l1, l2), true);
|
||||||
|
try (Proxy lb = new Proxy(h -> pinned)) {
|
||||||
|
String url = lb.url();
|
||||||
|
Reply init = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
String session = init.header("Mcp-Session-Id");
|
||||||
|
Map<String, String> h = Wire.legacyHeaders(session);
|
||||||
|
Reply initialized = Wire.post(url, h, Wire.INITIALIZED);
|
||||||
|
assertThat(initialized.status()).isEqualTo(202);
|
||||||
|
int ok = 0;
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
Reply r = Wire.post(url, h, Wire.legacyCall(20 + i, "A-101"));
|
||||||
|
if (r.status() == 200 && "L1".equals(r.header("X-Served-By"))) {
|
||||||
|
ok++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.line("initialize served by " + init.header("X-Served-By") + ", then 6 calls pinned to the same instance");
|
||||||
|
t.line("succeeded: " + ok + " of 6");
|
||||||
|
assertThat(ok).isEqualTo(6);
|
||||||
|
|
||||||
|
// ---- the pinned instance goes away (deploy, crash, autoscaler) ------------------------------
|
||||||
|
t.blank().note("PART C: the pinned instance L1 is stopped, as in a rolling deploy.");
|
||||||
|
l1.close();
|
||||||
|
Reply after = Wire.post(url, h, Wire.legacyCall(30, "A-101"));
|
||||||
|
t.exchange("C1. the same session after L1 is gone", "balancer/mcp", h, Wire.legacyCall(30, "A-101"), after);
|
||||||
|
assertThat(after.header("X-Served-By")).isEqualTo("L2");
|
||||||
|
assertThat(after.status()).isEqualTo(404);
|
||||||
|
|
||||||
|
Reply again = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
t.exchange("C2. the client has to start over with initialize", "balancer/mcp", Wire.legacyHeaders(null),
|
||||||
|
Wire.INITIALIZE, again);
|
||||||
|
assertThat(again.status()).isEqualTo(200);
|
||||||
|
assertThat(again.header("X-Served-By")).isEqualTo("L2");
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** What the 2025-era protocol needs before the first useful call, and what the server remembers afterwards. */
|
||||||
|
class LegacyHandshakeTest {
|
||||||
|
|
||||||
|
static Instance server;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void start() {
|
||||||
|
server = Instance.start("legacy", "L1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void stop() {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void handshakeThenCallNeedsAServerSideSession() {
|
||||||
|
Transcript t = new Transcript("01-legacy-handshake.txt",
|
||||||
|
"2025-era server (protocol STREAMABLE): the session lives in the server's memory");
|
||||||
|
String url = server.url();
|
||||||
|
t.note("Error bodies are shown without the Java stack trace the SDK serialises into them.");
|
||||||
|
|
||||||
|
// 1. A call before any handshake is refused.
|
||||||
|
Reply early = Wire.post(url, Wire.legacyHeaders(null), Wire.legacyCall(2, "A-101"));
|
||||||
|
t.exchange("1. tools/call with no session yet", "/mcp", Wire.legacyHeaders(null), Wire.legacyCall(2, "A-101"), early);
|
||||||
|
assertThat(early.status()).isEqualTo(400);
|
||||||
|
assertThat(early.json().path("jsonRpcError").path("message").asString()).isEqualTo("Session ID missing");
|
||||||
|
|
||||||
|
// 2. initialize creates the session and returns its id in a header.
|
||||||
|
Reply init = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
t.exchange("2. initialize", "/mcp", Wire.legacyHeaders(null), Wire.INITIALIZE, init);
|
||||||
|
String session = init.header("Mcp-Session-Id");
|
||||||
|
assertThat(init.status()).isEqualTo(200);
|
||||||
|
assertThat(session).isNotBlank();
|
||||||
|
assertThat(init.json().path("result").path("protocolVersion").asString()).isEqualTo(Wire.LEGACY_VERSION);
|
||||||
|
|
||||||
|
// 3. The client confirms the handshake.
|
||||||
|
Map<String, String> withSession = Wire.legacyHeaders(session);
|
||||||
|
Reply initialized = Wire.post(url, withSession, Wire.INITIALIZED);
|
||||||
|
t.exchange("3. notifications/initialized", "/mcp", withSession, Wire.INITIALIZED, initialized);
|
||||||
|
assertThat(initialized.status()).isEqualTo(202);
|
||||||
|
|
||||||
|
// 4. Now the call works, and only because the session id names state held by THIS instance.
|
||||||
|
Reply call = Wire.post(url, withSession, Wire.legacyCall(2, "A-101"));
|
||||||
|
t.exchange("4. tools/call with the session", "/mcp", withSession, Wire.legacyCall(2, "A-101"), call);
|
||||||
|
assertThat(call.status()).isEqualTo(200);
|
||||||
|
assertThat(call.text()).isEqualTo("order A-101 is SHIPPED (answered by instance L1)");
|
||||||
|
|
||||||
|
// 5. A session id this instance has never seen is a 404, not a recoverable condition.
|
||||||
|
Map<String, String> stranger = Wire.legacyHeaders("00000000-0000-0000-0000-000000000000");
|
||||||
|
Reply unknown = Wire.post(url, stranger, Wire.legacyCall(2, "A-101"));
|
||||||
|
t.exchange("5. tools/call with a session id this server never issued", "/mcp", stranger,
|
||||||
|
Wire.legacyCall(2, "A-101"), unknown);
|
||||||
|
assertThat(unknown.status()).isEqualTo(404);
|
||||||
|
assertThat(unknown.json().path("jsonRpcError").path("message").asString()).startsWith("Session not found");
|
||||||
|
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Proxy;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** The 2026-07-28 server twice behind the same naive round-robin balancer that broke the 2025 one. */
|
||||||
|
class ModernBehindLoadBalancerTest {
|
||||||
|
|
||||||
|
static Instance m1;
|
||||||
|
static Instance m2;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void start() {
|
||||||
|
m1 = Instance.start("modern", "M1");
|
||||||
|
m2 = Instance.start("modern", "M2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void stop() {
|
||||||
|
m1.close();
|
||||||
|
m2.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anyInstanceCanTakeAnyRequestAndAnInstanceCanDisappear() {
|
||||||
|
Transcript t = new Transcript("05-modern-behind-lb.txt",
|
||||||
|
"Two 2026-07-28 instances behind plain round-robin: no affinity, no handshake, no state to lose");
|
||||||
|
Proxy.Pool pool = new Proxy.Pool(List.of(m1, m2));
|
||||||
|
try (Proxy lb = new Proxy(h -> pool)) {
|
||||||
|
String url = lb.url();
|
||||||
|
String args = "{\"orderId\":\"A-102\"}";
|
||||||
|
|
||||||
|
t.note("PART A: six tools/call, no initialize, no session id, one URL.");
|
||||||
|
List<String> served = new ArrayList<>();
|
||||||
|
int ok = 0;
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
Reply r = Wire.post(url, Wire.modernHeaders("tools/call", "order_status"),
|
||||||
|
Wire.modernCall(40 + i, "order_status", args));
|
||||||
|
served.add(r.header("X-Served-By"));
|
||||||
|
if (r.status() == 200 && r.text().endsWith("(answered by instance " + r.header("X-Served-By") + ")")) {
|
||||||
|
ok++;
|
||||||
|
}
|
||||||
|
t.line("call " + (i + 1) + " -> " + r.header("X-Served-By") + ": " + r.status() + " " + r.text());
|
||||||
|
}
|
||||||
|
t.line("succeeded: " + ok + " of 6");
|
||||||
|
assertThat(ok).isEqualTo(6);
|
||||||
|
assertThat(served).containsExactly("M1", "M2", "M1", "M2", "M1", "M2");
|
||||||
|
|
||||||
|
t.blank().note("PART B: M1 is stopped, as in a rolling deploy. The client changes nothing.");
|
||||||
|
m1.close();
|
||||||
|
int ok2 = 0;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
Reply r = Wire.post(url, Wire.modernHeaders("tools/call", "order_status"),
|
||||||
|
Wire.modernCall(50 + i, "order_status", args));
|
||||||
|
if (r.status() == 200 && "M2".equals(r.header("X-Served-By"))) {
|
||||||
|
ok2++;
|
||||||
|
}
|
||||||
|
t.line("call " + (i + 1) + " -> " + r.header("X-Served-By") + ": " + r.status() + " " + r.text());
|
||||||
|
}
|
||||||
|
t.line("succeeded: " + ok2 + " of 4");
|
||||||
|
assertThat(ok2).isEqualTo(4);
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** The 2026-07-28 wire contract as one real server enforces it: what a request must carry, and how it fails. */
|
||||||
|
class ModernWireTest {
|
||||||
|
|
||||||
|
static Instance server;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void start() {
|
||||||
|
server = Instance.start("modern", "M1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void stop() {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void everyRequestStandsAlone() {
|
||||||
|
Transcript t = new Transcript("03-modern-wire.txt",
|
||||||
|
"2026-07-28 server (protocol MODERN): no handshake, no session, three self-contained POSTs");
|
||||||
|
String url = server.url();
|
||||||
|
|
||||||
|
Map<String, String> discoverHeaders = Wire.modernHeaders("server/discover", null);
|
||||||
|
Reply discover = Wire.post(url, discoverHeaders, Wire.modernDiscover());
|
||||||
|
t.exchange("1. server/discover replaces initialize", "/mcp", discoverHeaders, Wire.modernDiscover(), discover);
|
||||||
|
assertThat(discover.status()).isEqualTo(200);
|
||||||
|
assertThat(discover.header("Mcp-Session-Id")).isNull();
|
||||||
|
assertThat(discover.json().path("result").path("supportedVersions").get(0).asString()).isEqualTo(Wire.MODERN_VERSION);
|
||||||
|
assertThat(discover.json().path("result").path("ttlMs").asLong()).isEqualTo(300_000L);
|
||||||
|
assertThat(discover.json().path("result").path("cacheScope").asString()).isEqualTo("public");
|
||||||
|
|
||||||
|
Map<String, String> listHeaders = Wire.modernHeaders("tools/list", null);
|
||||||
|
Reply list = Wire.post(url, listHeaders, Wire.modernList());
|
||||||
|
t.exchange("2. tools/list", "/mcp", listHeaders, Wire.modernList(), list);
|
||||||
|
assertThat(list.status()).isEqualTo(200);
|
||||||
|
assertThat(list.json().path("result").path("tools")).hasSize(2);
|
||||||
|
for (var tool : list.json().path("result").path("tools")) {
|
||||||
|
if (tool.path("name").asString().equals("order_status")) {
|
||||||
|
assertThat(tool.path("annotations").path("readOnlyHint").asBoolean()).isTrue();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
assertThat(tool.path("annotations").path("destructiveHint").asBoolean()).isTrue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String args = "{\"orderId\":\"A-101\"}";
|
||||||
|
Map<String, String> callHeaders = Wire.modernHeaders("tools/call", "order_status");
|
||||||
|
Reply call = Wire.post(url, callHeaders, Wire.modernCall(3, "order_status", args));
|
||||||
|
t.exchange("3. tools/call carries the tool name in a header as well as in the body", "/mcp", callHeaders,
|
||||||
|
Wire.modernCall(3, "order_status", args), call);
|
||||||
|
assertThat(call.status()).isEqualTo(200);
|
||||||
|
assertThat(call.header("Mcp-Session-Id")).isNull();
|
||||||
|
assertThat(call.text()).isEqualTo("order A-101 is SHIPPED (answered by instance M1)");
|
||||||
|
assertThat(call.json().path("result").path("resultType").asString()).isEqualTo("complete");
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void theServerChecksTheHeadersAgainstTheBody() {
|
||||||
|
Transcript t = new Transcript("04-modern-errors.txt", "2026-07-28 server: how a malformed request fails");
|
||||||
|
String url = server.url();
|
||||||
|
String args = "{\"orderId\":\"A-101\"}";
|
||||||
|
String call = Wire.modernCall(3, "order_status", args);
|
||||||
|
|
||||||
|
// Mcp-Name is required for tools/call
|
||||||
|
Map<String, String> noName = Wire.modernHeaders("tools/call", null);
|
||||||
|
Reply r1 = Wire.post(url, noName, call);
|
||||||
|
t.exchange("1. tools/call without Mcp-Name", "/mcp", noName, call, r1);
|
||||||
|
assertThat(r1.status()).isEqualTo(400);
|
||||||
|
assertThat(r1.json().path("error").path("code").asInt()).isEqualTo(-32020);
|
||||||
|
|
||||||
|
// Mcp-Method must agree with the body
|
||||||
|
Map<String, String> wrongMethod = Wire.modernHeaders("tools/list", "order_status");
|
||||||
|
Reply r2 = Wire.post(url, wrongMethod, call);
|
||||||
|
t.exchange("2. Mcp-Method says tools/list, the body says tools/call", "/mcp", wrongMethod, call, r2);
|
||||||
|
assertThat(r2.status()).isEqualTo(400);
|
||||||
|
assertThat(r2.json().path("error").path("code").asInt()).isEqualTo(-32020);
|
||||||
|
|
||||||
|
// The body must carry _meta, the header alone is not enough
|
||||||
|
String noMeta = "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}";
|
||||||
|
Map<String, String> listHeaders = Wire.modernHeaders("tools/list", null);
|
||||||
|
Reply r3 = Wire.post(url, listHeaders, noMeta);
|
||||||
|
t.exchange("3. the version header is present but params._meta is missing", "/mcp", listHeaders, noMeta, r3);
|
||||||
|
assertThat(r3.status()).isEqualTo(400);
|
||||||
|
assertThat(r3.json().path("error").path("message").asString()).isEqualTo("params._meta is required");
|
||||||
|
|
||||||
|
// A version the server does not speak
|
||||||
|
Map<String, String> future = Wire.modernHeaders("tools/list", null);
|
||||||
|
future.put("MCP-Protocol-Version", "2027-01-01");
|
||||||
|
String futureBody = "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":"
|
||||||
|
+ "{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2027-01-01\"}}}";
|
||||||
|
Reply r4 = Wire.post(url, future, futureBody);
|
||||||
|
t.exchange("4. a protocol version the server does not support", "/mcp", future, futureBody, r4);
|
||||||
|
assertThat(r4.status()).isEqualTo(400);
|
||||||
|
assertThat(r4.json().path("error").path("code").asInt()).isEqualTo(-32022);
|
||||||
|
assertThat(r4.json().path("error").path("data").path("supported").get(0).asString()).isEqualTo(Wire.MODERN_VERSION);
|
||||||
|
|
||||||
|
// What a 2025 client sends first
|
||||||
|
Reply r5 = Wire.post(url, Wire.legacyHeaders(null), Wire.INITIALIZE);
|
||||||
|
t.exchange("5. a 2025-era client's first request, initialize", "/mcp", Wire.legacyHeaders(null), Wire.INITIALIZE, r5);
|
||||||
|
assertThat(r5.status()).isEqualTo(400);
|
||||||
|
assertThat(r5.json().path("error").path("code").asInt()).isEqualTo(-32020);
|
||||||
|
|
||||||
|
// A session id is simply not part of this protocol; this server does not reject it either
|
||||||
|
Map<String, String> stray = new LinkedHashMap<>(Wire.modernHeaders("tools/call", "order_status"));
|
||||||
|
stray.put("Mcp-Session-Id", "left-over-from-a-2025-client");
|
||||||
|
Reply r6 = Wire.post(url, stray, call);
|
||||||
|
t.exchange("6. a stray Mcp-Session-Id on a modern request", "/mcp", stray, call, r6);
|
||||||
|
assertThat(r6.status()).isEqualTo(200);
|
||||||
|
|
||||||
|
// POST only
|
||||||
|
Reply r7 = Wire.get(url);
|
||||||
|
t.blank().line("## 7. GET /mcp").line("< " + r7.status()).line("< Allow: " + r7.header("Allow"));
|
||||||
|
assertThat(r7.status()).isEqualTo(405);
|
||||||
|
|
||||||
|
// Unknown tool and invalid arguments
|
||||||
|
Map<String, String> nope = Wire.modernHeaders("tools/call", "nope");
|
||||||
|
Reply r8 = Wire.post(url, nope, Wire.modernCall(3, "nope", "{}"));
|
||||||
|
t.exchange("8. unknown tool", "/mcp", nope, Wire.modernCall(3, "nope", "{}"), r8);
|
||||||
|
assertThat(r8.json().path("error").path("code").asInt()).isEqualTo(-32602);
|
||||||
|
|
||||||
|
Map<String, String> noArg = Wire.modernHeaders("tools/call", "order_status");
|
||||||
|
Reply r9 = Wire.post(url, noArg, Wire.modernCall(3, "order_status", "{}"));
|
||||||
|
t.exchange("9. a missing argument", "/mcp", noArg, Wire.modernCall(3, "order_status", "{}"), r9);
|
||||||
|
assertThat(r9.status()).isEqualTo(200);
|
||||||
|
assertThat(r9.json().path("result").path("isError").asBoolean()).isTrue();
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire.Reply;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The replacement for asking the user in the middle of a call: return input_required, let the client retry.
|
||||||
|
* The retry may land on a different instance, and that is where the sealed requestState needs a shared secret.
|
||||||
|
*/
|
||||||
|
class MultiRoundTripTest {
|
||||||
|
|
||||||
|
static final String ARGS = "{\"orderId\":\"A-101\"}";
|
||||||
|
static final String YES = "{\"action\":\"accept\",\"content\":{\"ok\":true}}";
|
||||||
|
static final String NO = "{\"action\":\"decline\"}";
|
||||||
|
|
||||||
|
private static Reply firstRound(Instance on, Transcript t, String label) {
|
||||||
|
Map<String, String> h = Wire.modernHeaders("tools/call", "cancel_order");
|
||||||
|
String body = Wire.modernCall(1, "cancel_order", ARGS);
|
||||||
|
Reply r = Wire.post(on.url(), h, body);
|
||||||
|
t.exchange(label, "/mcp (" + on.name() + ")", h, body, r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Reply retry(Instance on, Transcript t, String label, String state, String answer) {
|
||||||
|
Map<String, String> h = Wire.modernHeaders("tools/call", "cancel_order");
|
||||||
|
String body = Wire.modernRetry(2, "cancel_order", ARGS, answer, state);
|
||||||
|
Reply r = Wire.post(on.url(), h, body);
|
||||||
|
t.exchange(label, "/mcp (" + on.name() + ")", h, body.replace(state, "<requestState>"), r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void withoutASharedSecretTheRetryMustReturnToTheSameInstance() {
|
||||||
|
Transcript t = new Transcript("06-modern-mrtr.txt",
|
||||||
|
"Multi-round-trip request: cancel_order asks for confirmation by returning input_required");
|
||||||
|
try (Instance m1 = Instance.start("modern", "M1"); Instance m2 = Instance.start("modern", "M2")) {
|
||||||
|
t.note("PART A: no spring.ai.mcp.server.modern.request-state-secret, so each instance seals with its own random key.");
|
||||||
|
Reply first = firstRound(m1, t, "A1. first call, no answer yet");
|
||||||
|
assertThat(first.status()).isEqualTo(200);
|
||||||
|
assertThat(first.json().path("result").path("resultType").asString()).isEqualTo("input_required");
|
||||||
|
assertThat(first.json().path("result").path("inputRequests").path("confirm").path("method").asString())
|
||||||
|
.isEqualTo("elicitation/create");
|
||||||
|
String state = first.json().path("result").path("requestState").asString();
|
||||||
|
|
||||||
|
// What "sealed" means: signed, not encrypted
|
||||||
|
String payload = new String(Base64.getUrlDecoder().decode(state.split("\\.")[0]), StandardCharsets.UTF_8);
|
||||||
|
t.blank().note("The part of requestState before the dot is base64url JSON, readable by anyone who holds it:");
|
||||||
|
t.line(" " + payload.replaceAll("\"exp\":[0-9]+", "\"exp\":<epoch-millis>"));
|
||||||
|
assertThat(payload).contains("\"s\":\"orderId=A-101\"").contains("\"m\":\"tools/call\"")
|
||||||
|
.contains("\"n\":\"cancel_order\"");
|
||||||
|
|
||||||
|
Reply sameInstance = retry(m1, t, "A2. retry, answer yes, back on the SAME instance", state, YES);
|
||||||
|
assertThat(sameInstance.text()).isEqualTo("order A-101 cancelled (answered by instance M1)");
|
||||||
|
|
||||||
|
Reply otherInstance = retry(m2, t, "A3. the same retry, but the balancer sends it to the OTHER instance", state, YES);
|
||||||
|
assertThat(otherInstance.status()).isEqualTo(400);
|
||||||
|
assertThat(otherInstance.json().path("error").path("code").asInt()).isEqualTo(-32602);
|
||||||
|
assertThat(otherInstance.json().path("error").path("message").asString())
|
||||||
|
.isEqualTo("Invalid or expired requestState");
|
||||||
|
|
||||||
|
String tampered = state.substring(0, state.length() - 3) + (state.endsWith("AAA") ? "BBB" : "AAA");
|
||||||
|
Reply forged = retry(m1, t, "A4. the right instance, but the state was altered in transit", tampered, YES);
|
||||||
|
assertThat(forged.status()).isEqualTo(400);
|
||||||
|
assertThat(forged.json().path("error").path("message").asString()).isEqualTo("Invalid or expired requestState");
|
||||||
|
}
|
||||||
|
|
||||||
|
t.blank().note("PART B: the same secret on every instance (32 bytes or more).");
|
||||||
|
Map<String, Object> secret = Map.of("spring.ai.mcp.server.modern.request-state-secret",
|
||||||
|
"0123456789abcdef0123456789abcdef-demo-only-secret");
|
||||||
|
try (Instance m1 = Instance.start("modern", "M1", secret); Instance m2 = Instance.start("modern", "M2", secret)) {
|
||||||
|
Reply first = firstRound(m1, t, "B1. first call on M1");
|
||||||
|
String state = first.json().path("result").path("requestState").asString();
|
||||||
|
Reply other = retry(m2, t, "B2. retry, answer yes, on M2", state, YES);
|
||||||
|
assertThat(other.status()).isEqualTo(200);
|
||||||
|
assertThat(other.text()).isEqualTo("order A-101 cancelled (answered by instance M2)");
|
||||||
|
|
||||||
|
Reply declined = retry(m1, t, "B3. the user declines, retry on M1", state, NO);
|
||||||
|
assertThat(declined.text()).isEqualTo("order A-101 kept (answered by instance M1)");
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package com.ankurm.mcpstateless;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.support.Instance;
|
||||||
|
import com.ankurm.mcpstateless.support.Proxy;
|
||||||
|
import com.ankurm.mcpstateless.support.Transcript;
|
||||||
|
import com.ankurm.mcpstateless.support.Wire;
|
||||||
|
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.CallToolResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.DiscoverResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.ElicitResult;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.Implementation;
|
||||||
|
import io.modelcontextprotocol.modern.McpSchema.TextContent;
|
||||||
|
import io.modelcontextprotocol.modern.client.McpClient;
|
||||||
|
import io.modelcontextprotocol.modern.client.McpSyncClient;
|
||||||
|
import io.modelcontextprotocol.modern.client.transport.HttpClientMcpTransport;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Real SDK clients, not hand-written HTTP: the 2.2.0 modern client and the 2025-era client against both server generations. */
|
||||||
|
class SdkClientsTest {
|
||||||
|
|
||||||
|
static final Map<String, Object> SECRET = Map.of("spring.ai.mcp.server.modern.request-state-secret",
|
||||||
|
"0123456789abcdef0123456789abcdef-demo-only-secret");
|
||||||
|
|
||||||
|
static McpSyncClient modernClient(String url) {
|
||||||
|
URI uri = URI.create(url);
|
||||||
|
return McpClient.sync(HttpClientMcpTransport.builder(uri).build())
|
||||||
|
.clientInfo(Implementation.builder("sdk-modern-client", "1").build())
|
||||||
|
.formElicitation(req -> ElicitResult.builder(ElicitResult.Action.ACCEPT).content(Map.of("ok", true)).build())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First line only, ports masked and the serialised Java stack trace cut off, so reruns diff cleanly. */
|
||||||
|
static String shorten(String message) {
|
||||||
|
String m = message.lines().findFirst().orElse("").replaceAll("localhost:[0-9]+", "localhost:<port>")
|
||||||
|
.replaceAll("\"id\":\"[0-9a-f]{8}-[0-9]+\"", "\"id\":\"<id>\"");
|
||||||
|
int cut = m.indexOf(",\"cause\"");
|
||||||
|
return cut > 0 ? m.substring(0, cut) + "... (stack trace omitted)" : m;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String text(CallToolResult r) {
|
||||||
|
return ((TextContent) r.content().get(0)).text();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modernClientThroughARoundRobinBalancer() {
|
||||||
|
Transcript t = new Transcript("08-sdk-modern-client.txt",
|
||||||
|
"The 2.2.0 modern SDK client against two 2026-07-28 instances behind round-robin");
|
||||||
|
try (Instance m1 = Instance.start("modern", "M1", SECRET); Instance m2 = Instance.start("modern", "M2", SECRET)) {
|
||||||
|
Proxy.Pool pool = new Proxy.Pool(List.of(m1, m2));
|
||||||
|
try (Proxy lb = new Proxy(h -> pool)) {
|
||||||
|
McpSyncClient client = modernClient(lb.url());
|
||||||
|
DiscoverResult discover = client.discover();
|
||||||
|
t.line("discover: supportedVersions=" + discover.supportedVersions() + " ttlMs=" + discover.ttlMs()
|
||||||
|
+ " cacheScope=" + discover.cacheScope());
|
||||||
|
t.line("tools: " + client.listTools().list().tools().stream().map(x -> x.name()).sorted().toList());
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
CallToolResult r = client.tool("order_status").arguments(Map.of("orderId", "A-100")).call();
|
||||||
|
t.line("order_status #" + (i + 1) + ": " + text(r));
|
||||||
|
}
|
||||||
|
CallToolResult cancel = client.tool("cancel_order").arguments(Map.of("orderId", "A-102")).call();
|
||||||
|
t.line("cancel_order (the client answered the confirmation itself): " + text(cancel));
|
||||||
|
t.blank().line("What the balancer saw, in order:");
|
||||||
|
lb.seen().forEach(s -> t.line(" " + s));
|
||||||
|
t.line("total requests: " + lb.seen().size());
|
||||||
|
|
||||||
|
assertThat(discover.supportedVersions()).containsExactly(Wire.MODERN_VERSION);
|
||||||
|
assertThat(discover.ttlMs()).isEqualTo(300_000L);
|
||||||
|
assertThat(text(cancel)).isEqualTo("order A-102 cancelled (answered by instance M2)");
|
||||||
|
assertThat(lb.seen()).hasSize(8).noneMatch(x -> x.contains("initialize"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.blank().note("Same client and balancer, but the instances have no shared request-state-secret:");
|
||||||
|
try (Instance m1 = Instance.start("modern", "M1"); Instance m2 = Instance.start("modern", "M2")) {
|
||||||
|
Proxy.Pool pool = new Proxy.Pool(List.of(m1, m2));
|
||||||
|
try (Proxy lb = new Proxy(h -> pool)) {
|
||||||
|
McpSyncClient client = modernClient(lb.url());
|
||||||
|
Throwable failure = org.assertj.core.api.Assertions.catchThrowable(
|
||||||
|
() -> client.tool("cancel_order").arguments(Map.of("orderId", "A-102")).call());
|
||||||
|
t.line("cancel_order: " + failure.getClass().getName());
|
||||||
|
t.line(" " + shorten(String.valueOf(failure.getMessage())));
|
||||||
|
assertThat(failure).isNotNull();
|
||||||
|
assertThat(String.valueOf(failure.getMessage())).contains("Invalid or expired requestState");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oldAndNewClientsAgainstTheWrongServer() {
|
||||||
|
Transcript t = new Transcript("09-sdk-version-mismatch.txt",
|
||||||
|
"What each SDK client says when it meets a server of the other generation");
|
||||||
|
try (Instance legacy = Instance.start("legacy", "L1"); Instance modern = Instance.start("modern", "M1")) {
|
||||||
|
|
||||||
|
// 2025-era client -> modern server
|
||||||
|
String base = "http://localhost:" + modern.port();
|
||||||
|
var oldClient = io.modelcontextprotocol.client.McpClient
|
||||||
|
.sync(io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport.builder(base)
|
||||||
|
.endpoint("/mcp").build())
|
||||||
|
.build();
|
||||||
|
Throwable a = org.assertj.core.api.Assertions.catchThrowable(oldClient::initialize);
|
||||||
|
t.line("2025-era client -> modern server: " + a.getClass().getName());
|
||||||
|
for (Throwable c = a; c != null; c = c.getCause()) {
|
||||||
|
t.line(" " + c.getClass().getSimpleName() + ": " + shorten(String.valueOf(c.getMessage())));
|
||||||
|
}
|
||||||
|
assertThat(a).isNotNull();
|
||||||
|
|
||||||
|
// modern client -> 2025-era server
|
||||||
|
McpSyncClient newClient = modernClient(legacy.url());
|
||||||
|
Throwable b = org.assertj.core.api.Assertions.catchThrowable(newClient::discover);
|
||||||
|
t.line("modern client -> 2025-era server: " + b.getClass().getName());
|
||||||
|
t.line(" " + shorten(String.valueOf(b.getMessage())));
|
||||||
|
assertThat(b).isNotNull();
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bothSdkClientsThroughOneUrl() {
|
||||||
|
Transcript t = new Transcript("10-sdk-clients-through-router.txt",
|
||||||
|
"A 2025-era SDK client and a 2026-07-28 SDK client, one router URL, split on MCP-Protocol-Version");
|
||||||
|
try (Instance legacy = Instance.start("legacy", "L1");
|
||||||
|
Instance m1 = Instance.start("modern", "M1", SECRET);
|
||||||
|
Instance m2 = Instance.start("modern", "M2", SECRET)) {
|
||||||
|
Proxy.Pool legacyPool = new Proxy.Pool(List.of(legacy), true);
|
||||||
|
Proxy.Pool modernPool = new Proxy.Pool(List.of(m1, m2));
|
||||||
|
try (Proxy router = new Proxy(h -> BothVersionsTest.isModern(h) ? modernPool : legacyPool)) {
|
||||||
|
String base = router.url().replace("/mcp", "");
|
||||||
|
|
||||||
|
var oldClient = io.modelcontextprotocol.client.McpClient
|
||||||
|
.sync(io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport.builder(base)
|
||||||
|
.endpoint("/mcp").build())
|
||||||
|
.build();
|
||||||
|
oldClient.initialize();
|
||||||
|
var oldResult = oldClient.callTool(new io.modelcontextprotocol.spec.McpSchema.CallToolRequest(
|
||||||
|
"order_status", Map.of("orderId", "A-101")));
|
||||||
|
String oldText = ((io.modelcontextprotocol.spec.McpSchema.TextContent) oldResult.content().get(0)).text();
|
||||||
|
t.line("2025-era client: " + oldText);
|
||||||
|
oldClient.closeGracefully();
|
||||||
|
|
||||||
|
McpSyncClient newClient = modernClient(router.url());
|
||||||
|
String newText = text(newClient.tool("order_status").arguments(Map.of("orderId", "A-101")).call());
|
||||||
|
t.line("2026-07-28 client: " + newText);
|
||||||
|
|
||||||
|
// The 2025 client's GET (its optional server-to-client stream) races with its other calls, so count, don't order.
|
||||||
|
t.blank().line("What the router saw (HTTP method and Mcp-Method header; '-' means the header is absent):");
|
||||||
|
java.util.Map<String, Long> counts = router.seen().stream()
|
||||||
|
.collect(java.util.stream.Collectors.groupingBy(x -> x, java.util.TreeMap::new,
|
||||||
|
java.util.stream.Collectors.counting()));
|
||||||
|
counts.forEach((k, v) -> t.line(" " + v + " x " + k));
|
||||||
|
assertThat(oldText).isEqualTo("order A-101 is SHIPPED (answered by instance L1)");
|
||||||
|
assertThat(newText).startsWith("order A-101 is SHIPPED (answered by instance M");
|
||||||
|
assertThat(counts).containsEntry("POST -", 3L).containsEntry("GET -", 1L).containsEntry("DELETE -", 1L)
|
||||||
|
.containsEntry("POST tools/list", 1L).containsEntry("POST tools/call", 1L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.ankurm.mcpstateless.support;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.ankurm.mcpstateless.StatelessApp;
|
||||||
|
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
|
||||||
|
/** One real server process-in-a-JVM: a full Spring Boot application on its own random port. */
|
||||||
|
public final class Instance implements AutoCloseable {
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
private final ConfigurableApplicationContext context;
|
||||||
|
private final int port;
|
||||||
|
|
||||||
|
private Instance(String name, ConfigurableApplicationContext context) {
|
||||||
|
this.name = name;
|
||||||
|
this.context = context;
|
||||||
|
this.port = Integer.parseInt(context.getEnvironment().getProperty("local.server.port"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param profile {@code legacy} or {@code modern}; @param extra extra properties, e.g. the request-state secret */
|
||||||
|
public static Instance start(String profile, String name, Map<String, Object> extra) {
|
||||||
|
Map<String, Object> props = new LinkedHashMap<>();
|
||||||
|
props.put("server.port", 0);
|
||||||
|
props.put("instance.name", name);
|
||||||
|
props.put("spring.main.web-application-type", "servlet");
|
||||||
|
props.putAll(extra);
|
||||||
|
return new Instance(name, new SpringApplicationBuilder(StatelessApp.class)
|
||||||
|
.profiles(profile)
|
||||||
|
.properties(props)
|
||||||
|
.run("--logging.level.root=error"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Instance start(String profile, String name) {
|
||||||
|
return start(profile, name, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String name() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int port() {
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String url() {
|
||||||
|
return "http://localhost:" + port + "/mcp";
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean running() {
|
||||||
|
return context.isActive();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
context.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package com.ankurm.mcpstateless.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deliberately plain HTTP reverse proxy, standing in for a cloud load balancer. A {@link Pool} hands out
|
||||||
|
* its backends round-robin. A request whose backend refuses the connection is retried on the next one,
|
||||||
|
* as any real balancer does with a failed health check. It never looks at MCP, except that a pool can
|
||||||
|
* be told to learn session affinity from the {@code Mcp-Session-Id} response header.
|
||||||
|
*/
|
||||||
|
public final class Proxy implements AutoCloseable {
|
||||||
|
|
||||||
|
/** A set of interchangeable servers. */
|
||||||
|
public static final class Pool {
|
||||||
|
|
||||||
|
private final List<Instance> backends;
|
||||||
|
private final boolean sticky;
|
||||||
|
private final AtomicInteger next = new AtomicInteger();
|
||||||
|
private final Map<String, Instance> bySession = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public Pool(List<Instance> backends, boolean sticky) {
|
||||||
|
this.backends = backends;
|
||||||
|
this.sticky = sticky;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pool(List<Instance> backends) {
|
||||||
|
this(backends, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Instance> candidates(String sessionId) {
|
||||||
|
if (sticky && sessionId != null && bySession.containsKey(sessionId) && bySession.get(sessionId).running()) {
|
||||||
|
return List.of(bySession.get(sessionId));
|
||||||
|
}
|
||||||
|
int start = Math.floorMod(next.getAndIncrement(), backends.size());
|
||||||
|
return java.util.stream.IntStream.range(0, backends.size())
|
||||||
|
.mapToObj(i -> backends.get((start + i) % backends.size())).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
void learn(String sessionId, Instance served) {
|
||||||
|
if (sticky && sessionId != null) {
|
||||||
|
bySession.put(sessionId, served);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Set<String> SKIP_REQUEST = Set.of("host", "content-length", "connection", "expect", "upgrade");
|
||||||
|
private static final Set<String> SKIP_RESPONSE = Set.of("transfer-encoding", "content-length", "connection");
|
||||||
|
|
||||||
|
private final java.util.List<String> seen = new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||||
|
private final HttpServer server;
|
||||||
|
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
|
||||||
|
private final Function<Map<String, String>, Pool> route;
|
||||||
|
|
||||||
|
/** @param route picks the pool from the request headers (lower-cased names) */
|
||||||
|
public Proxy(Function<Map<String, String>, Pool> route) {
|
||||||
|
this.route = route;
|
||||||
|
try {
|
||||||
|
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
server.createContext("/", exchange -> {
|
||||||
|
try {
|
||||||
|
byte[] body = exchange.getRequestBody().readAllBytes();
|
||||||
|
Map<String, String> headers = new ConcurrentHashMap<>();
|
||||||
|
exchange.getRequestHeaders().forEach((k, v) -> headers.put(k.toLowerCase(Locale.ROOT), v.get(0)));
|
||||||
|
seen.add(exchange.getRequestMethod() + " " + headers.getOrDefault("mcp-method", "-"));
|
||||||
|
if (exchange.getRequestMethod().equals("GET")) {
|
||||||
|
// The optional server-initiated SSE stream of the 2025 transport. A real balancer would have to hold
|
||||||
|
// that connection open and pinned to one instance. This one answers 405, which the 2025 clients accept.
|
||||||
|
exchange.getResponseHeaders().add("Allow", "POST");
|
||||||
|
exchange.sendResponseHeaders(405, -1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Pool pool = route.apply(headers);
|
||||||
|
String session = headers.get("mcp-session-id");
|
||||||
|
HttpResponse<byte[]> response = null;
|
||||||
|
Instance served = null;
|
||||||
|
for (Instance candidate : pool.candidates(session)) {
|
||||||
|
if (!candidate.running()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
HttpRequest.Builder b = HttpRequest.newBuilder(
|
||||||
|
URI.create("http://localhost:" + candidate.port() + exchange.getRequestURI()))
|
||||||
|
.method(exchange.getRequestMethod(), HttpRequest.BodyPublishers.ofByteArray(body));
|
||||||
|
exchange.getRequestHeaders().forEach((k, v) -> {
|
||||||
|
if (!SKIP_REQUEST.contains(k.toLowerCase(Locale.ROOT))) {
|
||||||
|
b.header(k, v.get(0));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
response = client.send(b.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||||
|
served = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (IOException refused) {
|
||||||
|
// connection refused: try the next backend
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (response == null) {
|
||||||
|
exchange.sendResponseHeaders(502, -1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
response.headers().map().forEach((k, v) -> {
|
||||||
|
if (!SKIP_RESPONSE.contains(k.toLowerCase(Locale.ROOT))) {
|
||||||
|
exchange.getResponseHeaders().add(k, v.get(0));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
exchange.getResponseHeaders().add("X-Served-By", served.name());
|
||||||
|
final Instance finalServed = served;
|
||||||
|
response.headers().firstValue("Mcp-Session-Id").ifPresent(id -> pool.learn(id, finalServed));
|
||||||
|
byte[] out = response.body();
|
||||||
|
exchange.sendResponseHeaders(response.statusCode(), out.length == 0 ? -1 : out.length);
|
||||||
|
if (out.length > 0) {
|
||||||
|
exchange.getResponseBody().write(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
exchange.sendResponseHeaders(500, -1);
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
exchange.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every request the proxy has received, as {@code HTTP-METHOD mcp-method-header}. */
|
||||||
|
public java.util.List<String> seen() {
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String url() {
|
||||||
|
return "http://localhost:" + server.getAddress().getPort() + "/mcp";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package com.ankurm.mcpstateless.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import tools.jackson.databind.JsonNode;
|
||||||
|
import tools.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes {@code output/NN-name.txt}. The test that fills a transcript also asserts the same facts, so a
|
||||||
|
* number quoted in the post is a number the build checks. Random values are replaced so reruns diff cleanly.
|
||||||
|
*/
|
||||||
|
public final class Transcript {
|
||||||
|
|
||||||
|
private static final List<String> SHOWN = List.of("mcp-session-id", "content-type", "allow", "x-served-by");
|
||||||
|
private static final List<String> REQUEST_HEADERS = List.of("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name",
|
||||||
|
"Mcp-Session-Id");
|
||||||
|
|
||||||
|
private final StringBuilder out = new StringBuilder();
|
||||||
|
private final String file;
|
||||||
|
|
||||||
|
public Transcript(String file, String title) {
|
||||||
|
this.file = file;
|
||||||
|
out.append("# ").append(title).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
public Transcript note(String text) {
|
||||||
|
out.append("# ").append(text).append('\n');
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Transcript blank() {
|
||||||
|
out.append('\n');
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Transcript line(String text) {
|
||||||
|
out.append(text).append('\n');
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One request/response pair. {@code via} says where the request was sent. */
|
||||||
|
public Transcript exchange(String label, String via, Map<String, String> requestHeaders, String requestBody,
|
||||||
|
Wire.Reply reply) {
|
||||||
|
out.append('\n').append("## ").append(label).append('\n');
|
||||||
|
out.append("> POST ").append(via).append('\n');
|
||||||
|
for (String name : REQUEST_HEADERS) {
|
||||||
|
requestHeaders.forEach((k, v) -> {
|
||||||
|
if (k.equalsIgnoreCase(name)) {
|
||||||
|
out.append("> ").append(k).append(": ").append(clean(v)).append('\n');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.append("> ").append(clean(compact(requestBody))).append('\n');
|
||||||
|
out.append("< ").append(reply.status()).append('\n');
|
||||||
|
for (String name : SHOWN) {
|
||||||
|
String v = reply.header(name);
|
||||||
|
if (v != null) {
|
||||||
|
out.append("< ").append(canonical(name)).append(": ").append(clean(v)).append('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String body = reply.body();
|
||||||
|
if (!body.isBlank()) {
|
||||||
|
for (String l : body.strip().split("\n")) {
|
||||||
|
if (!l.isBlank()) {
|
||||||
|
out.append("< ").append(clean(compact(l))).append('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String canonical(String lower) {
|
||||||
|
return switch (lower) {
|
||||||
|
case "mcp-session-id" -> "Mcp-Session-Id";
|
||||||
|
case "content-type" -> "Content-Type";
|
||||||
|
case "x-served-by" -> "X-Served-By";
|
||||||
|
default -> "Allow";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-serialises JSON on one line and drops the Java stack trace the 2.x SDK serialises into 2025-era error bodies. */
|
||||||
|
private static String compact(String s) {
|
||||||
|
String t = s.strip();
|
||||||
|
String prefix = "";
|
||||||
|
if (t.startsWith("data:")) {
|
||||||
|
prefix = "data: ";
|
||||||
|
t = t.substring(5).strip();
|
||||||
|
}
|
||||||
|
if (!t.startsWith("{")) {
|
||||||
|
return s.strip();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonNode n = Wire.JSON.readTree(t);
|
||||||
|
if (n instanceof ObjectNode o && o.has("stackTrace")) {
|
||||||
|
o.remove(List.of("stackTrace", "suppressed", "localizedMessage", "cause", "message"));
|
||||||
|
}
|
||||||
|
return prefix + Wire.JSON.writeValueAsString(n);
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
return s.strip();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s) {
|
||||||
|
s = s.replaceAll("\"requestState\":\"[^\"]+\"", "\"requestState\":\"<requestState>\"");
|
||||||
|
return s.replaceAll("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "<session-id>");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void write() {
|
||||||
|
try {
|
||||||
|
Path dir = Path.of(System.getProperty("user.dir"), "output");
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
Files.writeString(dir.resolve(file), out.toString(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String text() {
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package com.ankurm.mcpstateless.support;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import tools.jackson.databind.JsonNode;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Raw HTTP to an MCP endpoint, so the tests see exactly what is on the wire and nothing is hidden by a client library. */
|
||||||
|
public final class Wire {
|
||||||
|
|
||||||
|
public static final String LEGACY_VERSION = "2025-11-25";
|
||||||
|
public static final String MODERN_VERSION = "2026-07-28";
|
||||||
|
public static final JsonMapper JSON = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||||
|
|
||||||
|
private Wire() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Reply(int status, Map<String, String> headers, String body) {
|
||||||
|
|
||||||
|
public String header(String name) {
|
||||||
|
return headers.get(name.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The JSON-RPC message: the body itself, or the {@code data:} line of an SSE frame. */
|
||||||
|
public JsonNode json() {
|
||||||
|
String text = body;
|
||||||
|
for (String line : body.split("\n")) {
|
||||||
|
if (line.startsWith("data:")) {
|
||||||
|
text = line.substring(5).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return JSON.readTree(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String text() {
|
||||||
|
return json().path("result").path("content").path(0).path("text").asString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Reply post(String url, Map<String, String> headers, String body) {
|
||||||
|
try {
|
||||||
|
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url))
|
||||||
|
.timeout(Duration.ofSeconds(10))
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||||
|
headers.forEach(b::header);
|
||||||
|
HttpResponse<String> r = HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString());
|
||||||
|
Map<String, String> h = new LinkedHashMap<>();
|
||||||
|
r.headers().map().forEach((k, v) -> h.put(k.toLowerCase(), String.join(", ", v)));
|
||||||
|
return new Reply(r.statusCode(), h, r.body());
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
throw new IllegalStateException("POST " + url + " failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Reply get(String url) {
|
||||||
|
try {
|
||||||
|
HttpResponse<String> r = HTTP.send(HttpRequest.newBuilder(URI.create(url)).GET().build(),
|
||||||
|
HttpResponse.BodyHandlers.ofString());
|
||||||
|
Map<String, String> h = new LinkedHashMap<>();
|
||||||
|
r.headers().map().forEach((k, v) -> h.put(k.toLowerCase(), String.join(", ", v)));
|
||||||
|
return new Reply(r.statusCode(), h, r.body());
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
throw new IllegalStateException("GET " + url + " failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 2025-era requests -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static Map<String, String> legacyHeaders(String sessionId) {
|
||||||
|
Map<String, String> h = new LinkedHashMap<>();
|
||||||
|
h.put("Content-Type", "application/json");
|
||||||
|
h.put("Accept", "application/json, text/event-stream");
|
||||||
|
if (sessionId != null) {
|
||||||
|
h.put("Mcp-Session-Id", sessionId);
|
||||||
|
h.put("MCP-Protocol-Version", LEGACY_VERSION);
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final String INITIALIZE = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":"
|
||||||
|
+ "{\"protocolVersion\":\"" + LEGACY_VERSION + "\",\"capabilities\":{},"
|
||||||
|
+ "\"clientInfo\":{\"name\":\"wire-test\",\"version\":\"1\"}}}";
|
||||||
|
|
||||||
|
public static final String INITIALIZED = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}";
|
||||||
|
|
||||||
|
public static String legacyCall(int id, String orderId) {
|
||||||
|
return "{\"jsonrpc\":\"2.0\",\"id\":" + id + ",\"method\":\"tools/call\",\"params\":"
|
||||||
|
+ "{\"name\":\"order_status\",\"arguments\":{\"orderId\":\"" + orderId + "\"}}}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 2026-07-28 requests -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static final String META = "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"" + MODERN_VERSION + "\","
|
||||||
|
+ "\"io.modelcontextprotocol/clientInfo\":{\"name\":\"wire-test\",\"version\":\"1\"},"
|
||||||
|
+ "\"io.modelcontextprotocol/clientCapabilities\":{\"elicitation\":{\"form\":{}}}}";
|
||||||
|
|
||||||
|
/** Headers for a modern request. {@code name} is the tool/prompt/resource name, or null for methods without one. */
|
||||||
|
public static Map<String, String> modernHeaders(String method, String name) {
|
||||||
|
Map<String, String> h = new LinkedHashMap<>();
|
||||||
|
h.put("Content-Type", "application/json");
|
||||||
|
h.put("Accept", "application/json, text/event-stream");
|
||||||
|
h.put("MCP-Protocol-Version", MODERN_VERSION);
|
||||||
|
h.put("Mcp-Method", method);
|
||||||
|
if (name != null) {
|
||||||
|
h.put("Mcp-Name", name);
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String modernDiscover() {
|
||||||
|
return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{" + META + "}}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String modernList() {
|
||||||
|
return "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" + META + "}}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String modernCall(int id, String tool, String arguments) {
|
||||||
|
return "{\"jsonrpc\":\"2.0\",\"id\":" + id + ",\"method\":\"tools/call\",\"params\":{\"name\":\"" + tool
|
||||||
|
+ "\",\"arguments\":" + arguments + "," + META + "}}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The retry of an input-required call: the same call plus the client's answer and the server's sealed state. */
|
||||||
|
public static String modernRetry(int id, String tool, String arguments, String answerJson, String requestState) {
|
||||||
|
return "{\"jsonrpc\":\"2.0\",\"id\":" + id + ",\"method\":\"tools/call\",\"params\":{\"name\":\"" + tool
|
||||||
|
+ "\",\"arguments\":" + arguments + ",\"inputResponses\":{\"confirm\":" + answerJson
|
||||||
|
+ "},\"requestState\":\"" + requestState + "\"," + META + "}}";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user