Add mcp-sdk-plain module: MCP server on the plain Java SDK 2.1.0 over stdio and Streamable HTTP, fat jar, wire transcripts and a Spring AI client

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5oh78z7gcH6QkxafF
This commit is contained in:
Claude
2026-11-08 18:28:07 +00:00
parent 7c20ea1370
commit 58eaf4c2e1
29 changed files with 864 additions and 0 deletions
@@ -0,0 +1,71 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema.*;
import java.util.Map;
/** The same client-side tour against either transport, written into a Transcript. */
final class Exercise {
private Exercise() {}
static String text(CallToolResult r) {
return ((TextContent) r.content().get(0)).text();
}
static void tour(McpSyncClient client, Transcript t) {
InitializeResult init = client.initialize();
t.line("server: " + init.serverInfo().name() + " " + init.serverInfo().version());
t.line("protocol: " + init.protocolVersion());
t.line("capabilities: tools=" + (init.capabilities().tools() != null)
+ " resources=" + (init.capabilities().resources() != null)
+ " prompts=" + (init.capabilities().prompts() != null));
t.line("instructions: " + init.instructions());
t.line("-- tools/list");
for (Tool tool : client.listTools().tools()) {
t.line(tool.name() + " required=" + tool.inputSchema().get("required"));
}
t.line("-- tools/call word_stats");
CallToolResult ok = client.callTool(new CallToolRequest("word_stats", Map.of("text", "the quick brown fox")));
t.line("isError=" + ok.isError() + " text=" + text(ok));
t.line("-- tools/call divide 1/0");
CallToolResult div = client.callTool(new CallToolRequest("divide", Map.of("a", 1, "b", 0)));
t.line("isError=" + div.isError() + " text=" + text(div));
t.line("-- tools/call word_stats with a missing argument");
try {
CallToolResult bad = client.callTool(new CallToolRequest("word_stats", Map.of()));
t.line("isError=" + bad.isError() + " text=" + text(bad));
} catch (RuntimeException e) {
t.line("threw " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
t.line("-- tools/call explode");
try {
CallToolResult boom = client.callTool(new CallToolRequest("explode", Map.of()));
t.line("isError=" + boom.isError() + " text=" + text(boom));
} catch (RuntimeException e) {
t.line("threw " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
t.line("-- resources/list");
for (Resource r : client.listResources().resources()) t.line(r.uri() + " " + r.mimeType());
t.line("-- resources/templates/list");
for (ResourceTemplate r : client.listResourceTemplates().resourceTemplates()) t.line(r.uriTemplate());
t.line("-- resources/read notes://readme");
t.line(((TextResourceContents) client.readResource(new ReadResourceRequest("notes://readme")).contents().get(0)).text());
t.line("-- resources/read notes://todo");
t.line(((TextResourceContents) client.readResource(new ReadResourceRequest("notes://todo")).contents().get(0)).text());
t.line("-- resources/read notes://missing");
try {
client.readResource(new ReadResourceRequest("notes://missing"));
t.line("no error");
} catch (RuntimeException e) {
t.line("threw " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
@@ -0,0 +1,100 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.json.McpJsonDefaults;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;
/** Streamable HTTP, once through the SDK client and once as raw HTTP so the wire is visible. */
class HttpTest {
@Test
void sdkClientTour() throws Exception {
var t = new Transcript("02-http-tour.txt");
try (HttpMain.Running s = HttpMain.start(0)) {
var transport = HttpClientStreamableHttpTransport.builder("http://127.0.0.1:" + s.port())
.endpoint("/mcp").jsonMapper(McpJsonDefaults.getMapper()).build();
try (McpSyncClient client = McpClient.sync(transport).requestTimeout(Duration.ofSeconds(20)).build()) {
Exercise.tour(client, t);
}
}
t.write();
}
/** Prints only the JSON-RPC error and whether the body also carries a Java stack trace. */
private static void error(Transcript t, HttpResponse<String> r, String sid) {
String b = r.body();
var m = java.util.regex.Pattern.compile("\\{\"jsonRpcError\":(\\{[^}]*\\})").matcher(b);
String err = m.find() ? m.group(1) : b;
if (sid != null) err = err.replace(sid, "<session-id>");
t.line("jsonRpcError: " + err);
t.line("body also contains a Java stackTrace: " + b.contains("\"stackTrace\""));
}
private static HttpResponse<String> send(HttpClient http, HttpRequest.Builder b) throws Exception {
return http.send(b.build(), HttpResponse.BodyHandlers.ofString());
}
@Test
void rawWire() throws Exception {
var t = new Transcript("03-http-wire.txt");
try (HttpMain.Running s = HttpMain.start(0)) {
String url = "http://127.0.0.1:" + s.port() + "/mcp";
HttpClient http = HttpClient.newHttpClient();
String init = """
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"raw","version":"0"}}}""";
t.line("-- POST initialize, Accept: application/json, text/event-stream");
HttpResponse<String> r1 = send(http, HttpRequest.newBuilder(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString(init)));
t.line("status " + r1.statusCode());
t.line("content-type " + r1.headers().firstValue("content-type").orElse("-"));
String sid = r1.headers().firstValue("mcp-session-id").orElse(null);
t.line("mcp-session-id present: " + (sid != null));
t.line("body: " + r1.body().replaceAll("\\s+$", ""));
assertEquals(200, r1.statusCode());
assertNotNull(sid);
t.line("-- POST tools/list without the Mcp-Session-Id header");
HttpResponse<String> r2 = send(http, HttpRequest.newBuilder(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}")));
t.line("status " + r2.statusCode());
error(t, r2, sid);
t.line("-- POST initialize with Accept: application/json only");
HttpResponse<String> r3 = send(http, HttpRequest.newBuilder(URI.create(url))
.header("Content-Type", "application/json").header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(init)));
t.line("status " + r3.statusCode());
error(t, r3, sid);
t.line("-- DELETE with the session id ends the session");
HttpResponse<String> r4 = send(http, HttpRequest.newBuilder(URI.create(url))
.header("Mcp-Session-Id", sid).DELETE());
t.line("status " + r4.statusCode());
t.line("-- POST tools/list on the ended session");
HttpResponse<String> r5 = send(http, HttpRequest.newBuilder(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("Mcp-Session-Id", sid)
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}")));
t.line("status " + r5.statusCode());
error(t, r5, sid);
}
t.write();
}
}
@@ -0,0 +1,14 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.transport.StdioServerTransportProvider;
/** The classic mistake: one System.out.println before the server starts. */
public final class NoisyMain {
public static void main(String[] args) throws Exception {
System.out.println("Starting notes server...");
var transport = new StdioServerTransportProvider(McpJsonDefaults.getMapper());
PlainMcpServer.configure(McpServer.sync(transport)).build();
}
}
@@ -0,0 +1,28 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.client.McpSyncClient;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class NoisyStdoutTest {
@Test
void oneStrayPrintlnBreaksTheHandshake() throws Exception {
var t = new Transcript("04-stdout-pollution.txt");
boolean failed = false;
try (McpSyncClient client = StdioTest.clientFor("com.ankurm.mcpplain.NoisyMain")) {
var init = client.initialize();
t.line("initialize succeeded: " + init.serverInfo().name());
t.line("tools: " + client.listTools().tools().size());
} catch (RuntimeException e) {
failed = true;
t.line("client failed: " + e.getClass().getSimpleName() + ": " + e.getMessage());
for (Throwable c = e.getCause(); c != null; c = c.getCause()) {
t.line(" caused by " + c.getClass().getSimpleName() + ": " + c.getMessage());
}
}
t.write();
assertTrue(failed, "a stray println on stdout used to break the handshake; if this now passes, the SDK changed");
}
}
@@ -0,0 +1,36 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import io.modelcontextprotocol.json.McpJsonDefaults;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;
/** Starts the server as a real child JVM, exactly the way Claude Desktop does, and talks to it over its stdin and stdout. */
class StdioTest {
static McpSyncClient clientFor(String mainClass, String... args) {
String javaBin = Path.of(System.getProperty("java.home"), "bin", "java").toString();
// args(...) REPLACES the list on every call, so build the whole list once.
var all = new java.util.ArrayList<String>(java.util.List.of("-cp", System.getProperty("java.class.path"), mainClass));
all.addAll(java.util.List.of(args));
var params = ServerParameters.builder(javaBin).args(all).build();
return McpClient.sync(new StdioClientTransport(params, McpJsonDefaults.getMapper()))
.requestTimeout(Duration.ofSeconds(20)).build();
}
@Test
void stdioTour() throws Exception {
var t = new Transcript("01-stdio-tour.txt");
try (McpSyncClient client = clientFor("com.ankurm.mcpplain.Main", "stdio")) {
Exercise.tour(client, t);
}
t.write();
}
}
@@ -0,0 +1,23 @@
package com.ankurm.mcpplain;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Collects lines and writes them to output/NN-name.txt, so the test IS the transcript. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file) { this.file = file; }
void line(String s) { lines.add(s); }
void write() throws IOException {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(file), lines);
}
}