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,44 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpSyncServer;
import io.modelcontextprotocol.server.transport.HttpServletStreamableServerTransportProvider;
import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.ee11.servlet.ServletHolder;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
/** Streamable HTTP: the SDK gives you a servlet, you give it a container. */
public final class HttpMain {
private HttpMain() {}
/** Handle to a running server so tests can stop it. */
public record Running(Server jetty, McpSyncServer mcp, int port) implements AutoCloseable {
@Override public void close() throws Exception {
mcp.closeGracefully();
jetty.stop();
}
}
/** Pass 0 for a free port. */
public static Running start(int port) throws Exception {
var transport = HttpServletStreamableServerTransportProvider.builder()
.jsonMapper(McpJsonDefaults.getMapper())
.mcpEndpoint("/mcp")
.build();
McpSyncServer mcp = PlainMcpServer.configure(McpServer.sync(transport)).build();
Server jetty = new Server();
ServerConnector connector = new ServerConnector(jetty);
connector.setHost("127.0.0.1"); // loopback only: see the security accordion in the post
connector.setPort(port);
jetty.addConnector(connector);
ServletContextHandler context = new ServletContextHandler("/");
context.addServlet(new ServletHolder(transport), "/mcp");
jetty.setHandler(context);
jetty.start();
return new Running(jetty, mcp, connector.getLocalPort());
}
}
@@ -0,0 +1,36 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpSyncServer;
import io.modelcontextprotocol.server.transport.StdioServerTransportProvider;
import java.util.concurrent.CountDownLatch;
/** java -jar mcp-sdk-plain.jar stdio | http [port] */
public final class Main {
public static void main(String[] args) throws Exception {
String mode = args.length > 0 ? args[0] : "stdio";
switch (mode) {
case "stdio" -> runStdio();
case "http" -> {
int port = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
HttpMain.start(port);
System.err.println("Streamable HTTP MCP server on http://127.0.0.1:" + port + "/mcp");
new CountDownLatch(1).await();
}
default -> {
System.err.println("usage: stdio | http [port]");
System.exit(2);
}
}
}
private static void runStdio() {
var transport = new StdioServerTransportProvider(McpJsonDefaults.getMapper());
McpSyncServer server = PlainMcpServer.configure(McpServer.sync(transport)).build();
// stdout belongs to the protocol. Anything human-readable goes to stderr.
System.err.println("notes-server ready on stdio");
// No join() here: the transport's own threads keep the JVM alive, and it exits when stdin reaches EOF.
}
}
@@ -0,0 +1,51 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.server.McpServerFeatures.SyncResourceSpecification;
import io.modelcontextprotocol.server.McpServerFeatures.SyncResourceTemplateSpecification;
import io.modelcontextprotocol.spec.McpSchema.ReadResourceResult;
import io.modelcontextprotocol.spec.McpSchema.Resource;
import io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
import java.util.List;
import java.util.Map;
/** Resources are read-only data the client can list and fetch. A template describes a family of URIs. */
final class NoteResources {
private NoteResources() {}
static final Map<String, String> NOTES = Map.of(
"todo", "1. Write the post\n2. Run the server\n3. Publish",
"ideas", "A tool that summarises a git log");
/** A fixed URI: shows up in resources/list. */
static SyncResourceSpecification readme() {
Resource resource = Resource.builder()
.uri("notes://readme")
.name("readme")
.description("What this server is")
.mimeType("text/markdown")
.build();
return new SyncResourceSpecification(resource, (exchange, request) ->
new ReadResourceResult(List.of(new TextResourceContents(
request.uri(), "text/markdown", "# Notes server\nBuilt with the plain MCP Java SDK."))));
}
/** A URI template: shows up in resources/templates/list, not in resources/list. */
static SyncResourceTemplateSpecification note() {
ResourceTemplate template = ResourceTemplate.builder()
.uriTemplate("notes://{name}")
.name("note")
.description("A note by name")
.mimeType("text/plain")
.build();
return new SyncResourceTemplateSpecification(template, (exchange, request) -> {
String name = request.uri().substring("notes://".length());
String body = NOTES.get(name);
if (body == null) {
throw new IllegalArgumentException("No note called " + name);
}
return new ReadResourceResult(List.of(new TextResourceContents(request.uri(), "text/plain", body)));
});
}
}
@@ -0,0 +1,81 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import java.util.Arrays;
import java.util.List;
/** The tools. Each one is a Tool (name + JSON Schema) plus a handler that returns a CallToolResult. */
final class NoteTools {
private NoteTools() {}
static List<SyncToolSpecification> all() {
return List.of(wordStats(), divide(), explode());
}
/** Happy path: validated input in, text out. */
static SyncToolSpecification wordStats() {
Tool tool = Tool.builder()
.name("word_stats")
.description("Count words and characters in a piece of text and report the longest word.")
.inputSchema(McpJsonDefaults.getMapper(), """
{
"type": "object",
"properties": { "text": { "type": "string", "description": "The text to analyse" } },
"required": ["text"]
}""")
.build();
return SyncToolSpecification.builder()
.tool(tool)
.callHandler((exchange, request) -> {
String text = (String) request.arguments().get("text");
String[] words = text.isBlank() ? new String[0] : text.trim().split("\\s+");
String longest = Arrays.stream(words).max(java.util.Comparator.comparingInt(String::length)).orElse("");
return CallToolResult.builder()
.addTextContent("words=" + words.length + " chars=" + text.length() + " longest=" + longest)
.build();
})
.build();
}
/** A domain failure the model should see and recover from: returned as isError=true, not thrown. */
static SyncToolSpecification divide() {
Tool tool = Tool.builder()
.name("divide")
.description("Divide a by b.")
.inputSchema(McpJsonDefaults.getMapper(), """
{
"type": "object",
"properties": { "a": { "type": "number" }, "b": { "type": "number" } },
"required": ["a", "b"]
}""")
.build();
return SyncToolSpecification.builder()
.tool(tool)
.callHandler((exchange, request) -> {
double a = ((Number) request.arguments().get("a")).doubleValue();
double b = ((Number) request.arguments().get("b")).doubleValue();
if (b == 0) {
return CallToolResult.builder().addTextContent("Cannot divide " + a + " by zero.").isError(true).build();
}
return CallToolResult.builder().addTextContent(String.valueOf(a / b)).build();
})
.build();
}
/** A handler that throws, to see what the SDK does with an uncaught exception. */
static SyncToolSpecification explode() {
Tool tool = Tool.builder()
.name("explode")
.description("Always throws. Exists to show what an uncaught exception looks like to the client.")
.inputSchema(McpJsonDefaults.getMapper(), "{\"type\":\"object\",\"properties\":{}}")
.build();
return SyncToolSpecification.builder()
.tool(tool)
.callHandler((exchange, request) -> { throw new IllegalStateException("boom from the handler"); })
.build();
}
}
@@ -0,0 +1,20 @@
package com.ankurm.mcpplain;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema.ServerCapabilities;
/** The one place that decides what the server offers. Both transports call it. */
final class PlainMcpServer {
private PlainMcpServer() {}
/** Applies name, capabilities, tools and resources to either kind of builder (stdio or Streamable HTTP). */
static <S extends McpServer.SyncSpecification<S>> S configure(S spec) {
spec.serverInfo("notes-server", "1.0.0")
.instructions("Tools: word_stats, divide, explode. Resources: notes://readme and notes://{name}.")
.capabilities(ServerCapabilities.builder().tools(true).resources(false, true).build())
.tools(NoteTools.all())
.resources(NoteResources.readme())
.resourceTemplates(NoteResources.note());
return spec;
}
}
@@ -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);
}
}