Add code-search-mcp module: JavaParser index, swappable embedder and three MCP tools on the 2026-07-28 stateless spec (MCP Java SDK 2.2.0)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6BHcz4muRH44T3br3
This commit is contained in:
Ankur
2026-11-25 13:29:50 +05:30
co-authored by Claude Sonnet 5.5
parent 26e0a3875a
commit e116c4d5a4
45 changed files with 2002 additions and 0 deletions
@@ -0,0 +1,99 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* The OpenAI-compatible embedder against a stub /v1/embeddings server. This checks the request shape, batching,
* ordering and the dimension guard. It says nothing about how good any real model's vectors are.
*/
class EmbedderSwapTest {
static final JsonMapper JSON = JsonMapper.builder().build();
/** Replies with a 4-number vector per input, deliberately out of order, so the "index" field matters. */
private static HttpServer stub(List<String> seenBodies, int dims) throws IOException {
HttpServer s = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
s.createContext("/v1/embeddings", ex -> {
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
seenBodies.add(ex.getRequestHeaders().getFirst("Authorization") + " | " + body);
JsonNode in = JSON.readTree(body).get("input");
List<String> items = new ArrayList<>();
for (int i = in.size() - 1; i >= 0; i--) { // reversed on purpose
StringBuilder v = new StringBuilder();
for (int d = 0; d < dims; d++) {
v.append(d == 0 ? "" : ",").append(d == i % dims ? "3.0" : "0.0");
}
items.add("{\"index\":" + i + ",\"embedding\":[" + v + "]}");
}
byte[] out = ("{\"data\":[" + String.join(",", items) + "]}").getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, out.length);
ex.getResponseBody().write(out);
ex.close();
});
s.start();
return s;
}
@Test
void requestShapeBatchingAndOrder() throws Exception {
List<String> seen = new ArrayList<>();
HttpServer s = stub(seen, 4);
try {
String base = "http://127.0.0.1:" + s.getAddress().getPort() + "/v1";
var embedder = new OpenAiCompatibleEmbedder(base, "nomic-embed-text", "secret-key", 4);
List<String> texts = new ArrayList<>();
for (int i = 0; i < 70; i++) {
texts.add("text " + i);
}
List<float[]> vectors = embedder.embedAll(texts);
Transcript t = new Transcript("09-embedder-swap.txt", "OpenAiCompatibleEmbedder against a stub /v1/embeddings server");
t.line("requests sent for 70 texts: " + seen.size());
t.line("first request: " + seen.get(0).substring(0, 78) + "...");
t.line("vectors returned: " + vectors.size() + ", each normalised to length 1: "
+ (Math.abs(norm(vectors.get(0)) - 1.0) < 1e-6));
t.line("text 5 got the vector the stub built for index 5: " + (vectors.get(5)[1] == 1.0f));
t.write();
assertThat(seen).hasSize(2); // 64 + 6
assertThat(seen.get(0)).startsWith("Bearer secret-key | {\"model\":\"nomic-embed-text\",\"input\":[\"text 0\"");
assertThat(vectors).hasSize(70);
assertThat(vectors.get(5)[1]).isEqualTo(1.0f); // index honoured despite reversed reply
} finally {
s.stop(0);
}
}
@Test
void aWrongDimensionIsRefusedInsteadOfCorruptingTheIndex() throws Exception {
HttpServer s = stub(new ArrayList<>(), 4);
try {
var embedder = new OpenAiCompatibleEmbedder("http://127.0.0.1:" + s.getAddress().getPort() + "/v1", "m", "", 768);
assertThatThrownBy(() -> embedder.embed("x")).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("expected 768 dimensions but the model returned 4");
} finally {
s.stop(0);
}
}
private static double norm(float[] v) {
double s = 0;
for (float x : v) s += x * x;
return Math.sqrt(s);
}
}
@@ -0,0 +1,24 @@
package com.ankurm.codesearch;
import java.nio.file.Path;
/** One shared, parsed copy of the sample monorepo: parsing and resolving is the slow part, so do it once. */
final class Fixtures {
static final Path MONOREPO = Path.of("sample-monorepo");
private static CodeIndexer code;
private Fixtures() {}
static synchronized CodeIndexer code() throws Exception {
if (code == null) {
code = new CodeIndexer(MONOREPO).index();
}
return code;
}
static VectorIndex hashingIndex() throws Exception {
return new VectorIndex(new HashingEmbedder(512), code().codeUnits());
}
}
@@ -0,0 +1,54 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.TreeMap;
import org.junit.jupiter.api.Test;
/** What JavaParser makes of the sample monorepo: one unit per type and per method or constructor. */
class IndexTest {
@Test
void everyTypeAndMethodBecomesAUnit() throws Exception {
CodeIndexer code = Fixtures.code();
Transcript t = new Transcript("01-index.txt", "Indexing sample-monorepo with JavaParser");
t.line("files parsed: " + code.compilationUnits().size());
t.line("parse problems: " + code.parseProblems().size());
long types = code.codeUnits().stream().filter(u -> u.kind() == CodeUnit.Kind.TYPE).count();
long methods = code.codeUnits().stream().filter(u -> u.kind() == CodeUnit.Kind.METHOD).count();
t.line("types: " + types);
t.line("methods+constructors:" + methods);
t.section("every unit: kind, short name, file:line");
for (CodeUnit u : code.codeUnits()) {
t.line(String.format("%-6s %-34s %s", u.kind(), u.shortName(), u.location()));
}
t.write();
assertThat(code.compilationUnits()).hasSize(10);
assertThat(code.parseProblems()).isEmpty();
assertThat(types).isEqualTo(10);
assertThat(methods).isEqualTo(20);
}
@Test
void javadocAndSignatureAreKept() throws Exception {
CodeUnit refund = Fixtures.code().codeUnits().stream()
.filter(u -> u.shortName().equals("PaymentService#refund")).findFirst().orElseThrow();
assertThat(refund.javadoc()).isEqualTo("Returns money to the customer's card after a cancelled order.");
assertThat(refund.signature()).isEqualTo("public String refund(String customerId, BigDecimal amount)");
assertThat(refund.file()).isEqualTo("payments/src/main/java/shop/payments/PaymentService.java");
assertThat(refund.line()).isEqualTo(23);
}
@Test
void sameMethodNameLivesInTwoClasses() throws Exception {
Map<String, Integer> byName = new TreeMap<>();
Fixtures.code().codeUnits().stream().filter(u -> u.kind() == CodeUnit.Kind.METHOD)
.forEach(u -> byName.merge(u.qualifiedName().substring(u.qualifiedName().indexOf('#') + 1), 1,
Integer::sum));
assertThat(byName.get("save")).isEqualTo(2);
}
}
@@ -0,0 +1,96 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** The server as a plain HTTP endpoint: what a request carries, how it fails, and that two copies are interchangeable. */
class McpWireTest {
static CodeSearchServer.Running a;
static CodeSearchServer.Running b;
@BeforeAll
static void start() throws Exception {
a = CodeSearchServer.serve(Fixtures.code(), Fixtures.hashingIndex(), 0);
b = CodeSearchServer.serve(Fixtures.code(), Fixtures.hashingIndex(), 0);
}
@AfterAll
static void stop() throws Exception {
a.close();
b.close();
}
@Test
void oneRequestIsEnoughAndAnyInstanceCanAnswerIt() throws Exception {
Transcript t = new Transcript("05-wire.txt", "code-search-mcp over HTTP, 2026-07-28: no handshake, no session");
String listBody = Wire.list(1);
Wire.Reply list = Wire.post(a.url(), Wire.headers("tools/list", null), listBody);
t.section("1. tools/list: the names and input schemas the model will see");
t.line("< " + list.status());
for (var tool : list.json().path("result").path("tools")) {
t.line(" " + tool.path("name").asString() + " readOnlyHint="
+ tool.path("annotations").path("readOnlyHint").asBoolean());
t.line(" " + tool.path("description").asString());
}
assertThat(list.status()).isEqualTo(200);
assertThat(list.json().path("result").path("tools")).hasSize(3);
// Two different server processes, no shared state, one request each.
String args = "{\"query\":\"charge the customer's card\",\"k\":2}";
Wire.Reply onA = Wire.post(a.url(), Wire.headers("tools/call", "search_code"), Wire.call(2, "search_code", args));
Wire.Reply onB = Wire.post(b.url(), Wire.headers("tools/call", "search_code"), Wire.call(3, "search_code", args));
Wire.show(t, "2. tools/call search_code sent to instance A", Wire.headers("tools/call", "search_code"),
Wire.call(2, "search_code", args), onA);
t.section("3. the same call sent to instance B, a separate server that never saw request 2");
t.line("< " + onB.status());
String textA = onA.json().path("result").path("content").path(0).path("text").asString();
String textB = onB.json().path("result").path("content").path(0).path("text").asString();
t.line(" same answer text as instance A: " + textA.equals(textB));
t.write();
assertThat(onA.status()).isEqualTo(200);
assertThat(textA).startsWith("1. ").contains("PaymentService#charge");
assertThat(textB).isEqualTo(textA);
assertThat(onA.json().path("result").path("isError").asBoolean()).isFalse();
}
@Test
void aMissingHeaderIsRejectedBeforeAnyToolRuns() throws Exception {
Transcript t = new Transcript("06-wire-errors.txt", "How a malformed request fails");
String args = "{\"query\":\"refund\"}";
String body = Wire.call(7, "search_code", args);
Map<String, String> noMethod = Wire.headers("tools/call", "search_code");
noMethod.remove("Mcp-Method");
Wire.Reply r1 = Wire.post(a.url(), noMethod, body);
Wire.show(t, "1. Mcp-Method header missing", noMethod, body, r1);
Map<String, String> wrongName = Wire.headers("tools/call", "find_usages");
Wire.Reply r2 = Wire.post(a.url(), wrongName, body);
Wire.show(t, "2. Mcp-Name header says find_usages but the body calls search_code", wrongName, body, r2);
Map<String, String> oldVersion = Wire.headers("tools/call", "search_code");
oldVersion.put("MCP-Protocol-Version", "2025-11-25");
Wire.Reply r3 = Wire.post(a.url(), oldVersion, body);
Wire.show(t, "3. a client still speaking 2025-11-25", oldVersion, body, r3);
// The client capabilities are part of every request now, because there is no handshake to carry them.
String noCaps = body.replace(",\"io.modelcontextprotocol/clientCapabilities\":{}", "");
Wire.Reply r4 = Wire.post(a.url(), Wire.headers("tools/call", "search_code"), noCaps);
Wire.show(t, "4. _meta without clientCapabilities", Wire.headers("tools/call", "search_code"), noCaps, r4);
t.write();
assertThat(r4.status()).isEqualTo(400);
assertThat(r4.json().path("error").path("code").asInt()).isEqualTo(-32602);
assertThat(r1.status()).isEqualTo(400);
assertThat(r2.status()).isEqualTo(400);
assertThat(r3.status()).isGreaterThanOrEqualTo(400);
}
}
@@ -0,0 +1,70 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.Map;
import io.modelcontextprotocol.modern.McpSchema.CallToolResult;
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;
/** The real SDK client against the real server: the three tools as an agent would call them, and their failures. */
class SdkClientTest {
private static String text(CallToolResult r) {
return ((TextContent) r.content().get(0)).text();
}
@Test
void anAgentSearchesThenReadsCallersThenSource() throws Exception {
try (var server = CodeSearchServer.serve(Fixtures.code(), Fixtures.hashingIndex(), 0)) {
McpSyncClient client = McpClient.sync(HttpClientMcpTransport.builder(URI.create(server.url())).build())
.clientInfo(Implementation.builder("sdk-client-test", "1").build()).build();
Transcript t = new Transcript("07-sdk-client.txt",
"An agent's session through the 2.2.0 SDK client: search, then callers, then source");
CallToolResult found = client.tool("search_code").arguments(Map.of("query", "return money to the customer", "k", 2)).call();
t.section("search_code {query: return money to the customer, k: 2}").line(text(found));
assertThat(text(found)).startsWith("1. ").contains("PaymentService#refund");
CallToolResult callers = client.tool("find_usages").arguments(Map.of("symbol", "PaymentService#refund")).call();
t.section("find_usages {symbol: PaymentService#refund}").line(text(callers));
assertThat(text(callers)).startsWith("1 usage(s) of PaymentService#refund (resolved)")
.contains("OrderService#cancelOrder").contains("[unresolved: matched by name]");
CallToolResult source = client.tool("get_source").arguments(Map.of("name", "OrderService#cancelOrder")).call();
t.section("get_source {name: OrderService#cancelOrder}").line(text(source));
assertThat(text(source)).contains("payments.refund(order.customerId(), order.total());");
t.write();
}
}
@Test
void failuresComeBackAsToolResultsTheModelCanReadAndRecoverFrom() throws Exception {
try (var server = CodeSearchServer.serve(Fixtures.code(), Fixtures.hashingIndex(), 0)) {
McpSyncClient client = McpClient.sync(HttpClientMcpTransport.builder(URI.create(server.url())).build()).build();
Transcript t = new Transcript("08-tool-errors.txt", "Tool failures are results with isError=true, not protocol errors");
CallToolResult missing = client.tool("get_source").arguments(Map.of("name", "PaymentService#chargeback")).call();
t.section("get_source with a name that does not exist").line("isError=" + Boolean.TRUE.equals(missing.isError())).line(text(missing));
CallToolResult blank = client.tool("search_code").arguments(Map.of("query", " ")).call();
t.section("search_code with a blank query").line("isError=" + blank.isError()).line(text(blank));
CallToolResult noHits = client.tool("search_code").arguments(Map.of("query", "chargeback")).call();
t.section("search_code that matches nothing (not an error: an empty answer with advice)")
.line("isError=" + Boolean.TRUE.equals(noHits.isError())).line(text(noHits));
t.write();
assertThat(missing.isError()).isTrue();
assertThat(text(missing)).contains("Use search_code to find the exact name");
assertThat(blank.isError()).isTrue();
assertThat(noHits.isError()).isNotEqualTo(true);
}
}
}
@@ -0,0 +1,60 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
/** Ranking behaviour of the hashing embedder: what it finds, and the honest limit of a word-overlap embedder. */
class SearchTest {
private static String top(VectorIndex index, String query) {
return index.search(query, 1).get(0).unit().shortName();
}
@Test
void findsMethodsByWhatTheyDo() throws Exception {
VectorIndex index = Fixtures.hashingIndex();
Transcript t = new Transcript("02-search.txt", "search_code ranking with the " + index.embedder().name()
+ " embedder (top 3 per query)");
List<String> queries = List.of(
"charge the customer's card",
"take units off the shelf for an order",
"email the customer that the order was cancelled",
"find an order by its id",
"return money to the customer");
for (String q : queries) {
t.section("query: " + q);
for (VectorIndex.Hit h : index.search(q, 3)) {
t.line(String.format("%.3f %-34s %s", h.score(), h.unit().shortName(), h.unit().location()));
}
}
assertThat(top(index, "charge the customer's card")).isEqualTo("PaymentService#charge");
assertThat(top(index, "take units off the shelf for an order")).isEqualTo("InventoryService#reserve");
assertThat(top(index, "email the customer that the order was cancelled"))
.isEqualTo("EmailNotifier#sendCancellation");
assertThat(top(index, "find an order by its id")).isEqualTo("OrderRepository#findById");
assertThat(top(index, "return money to the customer")).isEqualTo("PaymentService#refund");
// The same query typed in the vocabulary the code does NOT use. No shared words, no score.
t.section("the limit: a query that shares no words with the code");
String paraphrase = "chargeback";
List<VectorIndex.Hit> none = index.search(paraphrase, 3);
t.line("query: " + paraphrase + " -> " + none.size() + " result(s)");
t.write();
assertThat(none).isEmpty();
}
@Test
void identicalTextEmbedsToIdenticalVectors() {
HashingEmbedder e = new HashingEmbedder(512);
assertThat(e.embed("placeOrder reserve stock")).isEqualTo(e.embed("placeOrder reserve stock"));
}
@Test
void camelCaseIsSplitIntoWords() {
assertThat(HashingEmbedder.words("placeOrderHTTPClient")).containsExactly("place", "order", "http", "client");
}
}
@@ -0,0 +1,41 @@
package com.ankurm.codesearch;
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 {@code output/NN-name.txt}, so the test that asserts a fact is the test that records it. */
final class Transcript {
private final List<String> lines = new ArrayList<>();
private final String file;
Transcript(String file, String title) {
this.file = file;
lines.add("# " + title);
}
Transcript line(String s) {
lines.add(s);
return this;
}
Transcript blank() {
lines.add("");
return this;
}
Transcript section(String s) {
lines.add("");
lines.add("## " + s);
return this;
}
void write() throws IOException {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(file), lines);
}
}
@@ -0,0 +1,82 @@
package com.ankurm.codesearch;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/** find_usages: the name-only answer over-reports, the symbol-solved answer does not, and gaps are counted. */
class UsageTest {
private static void print(Transcript t, UsageFinder.Result r) {
for (UsageFinder.Usage u : r.usages()) {
t.line(String.format(" %s:%d in %s%s", u.file(), u.line(), u.inMethod(),
u.exact() ? "" : " [not confirmed by the solver]"));
t.line(" " + u.code());
}
if (r.unresolved() > 0) {
t.line(" not confirmed by the solver: " + r.unresolved());
}
}
@Test
void nameMatchingConfusesTwoSaveMethods() throws Exception {
UsageFinder finder = new UsageFinder(Fixtures.code());
Transcript t = new Transcript("03-usages.txt", "find_usages for OrderRepository#save: name match vs resolved");
UsageFinder.Result byName = finder.find("OrderRepository#save", false);
t.section("name match only (resolve=false): " + byName.usages().size() + " usages");
print(t, byName);
UsageFinder.Result resolved = finder.find("OrderRepository#save", true);
t.section("resolved (resolve=true): " + resolved.usages().size() + " usage");
print(t, resolved);
UsageFinder.Result other = finder.find("InventoryRepository#save", true);
t.section("the other save, InventoryRepository#save, resolved: " + other.usages().size() + " usages");
print(t, other);
UsageFinder.Result iface = finder.find("CardGateway#authorize", true);
t.section("a call through an interface, CardGateway#authorize, resolved: " + iface.usages().size() + " usage");
print(t, iface);
t.write();
assertThat(byName.usages()).hasSize(3);
assertThat(resolved.usages()).hasSize(1);
assertThat(resolved.usages().get(0).inMethod()).isEqualTo("OrderService#placeOrder");
assertThat(resolved.usages().get(0).exact()).isTrue();
assertThat(other.usages()).hasSize(2);
assertThat(other.usages()).extracting(UsageFinder.Usage::inMethod)
.containsExactly("InventoryService#reserve", "InventoryService#release");
assertThat(iface.usages()).hasSize(1);
}
@Test
void aTypeIsUsedWhereverItsNameAppears() throws Exception {
UsageFinder finder = new UsageFinder(Fixtures.code());
UsageFinder.Result r = finder.find("PaymentService", true);
Transcript t = new Transcript("04-usages-type-and-gaps.txt", "find_usages for a type, and for a library that is not in the monorepo");
t.section("PaymentService (resolved): " + r.usages().size() + " usages");
print(t, r);
UsageFinder.Result gap = finder.find("AuditClient#record", true);
t.section("AuditClient#record (resolved): the class lives in a library outside the monorepo");
print(t, gap);
// The second gap is not about missing libraries at all: calls whose ARGUMENTS use a record accessor.
UsageFinder.Result refund = finder.find("PaymentService#refund", true);
t.section("PaymentService#refund (resolved): the call passes order.customerId(), an implicit record accessor");
print(t, refund);
t.write();
// The import line is not a usage: it is a Name node, not a type. Field and constructor parameter are.
assertThat(r.usages()).hasSize(2);
assertThat(gap.usages()).hasSize(1);
assertThat(gap.usages().get(0).exact()).isFalse();
assertThat(gap.unresolved()).isEqualTo(1);
// Found, but only because unresolved candidates are kept: the solver cannot bind a call whose argument
// is an implicit record accessor (JavaParser 3.28.2), so the caller is reported as a name-only match.
assertThat(refund.usages()).hasSize(1);
assertThat(refund.usages().get(0).inMethod()).isEqualTo("OrderService#cancelOrder");
assertThat(refund.usages().get(0).exact()).isFalse();
}
}
@@ -0,0 +1,75 @@
package com.ankurm.codesearch;
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 the MCP endpoint, so a transcript shows exactly what is on the wire. */
final class Wire {
static final String VERSION = "2026-07-28";
static final JsonMapper JSON = JsonMapper.builder().build();
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
private Wire() {}
record Reply(int status, String body) {
JsonNode json() {
return JSON.readTree(body);
}
}
/** Every request names its own protocol version and client: that is the whole "stateless" idea. */
static String call(int id, String tool, String argumentsJson) {
return "{\"jsonrpc\":\"2.0\",\"id\":" + id + ",\"method\":\"tools/call\",\"params\":{\"name\":\"" + tool
+ "\",\"arguments\":" + argumentsJson + ",\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\""
+ VERSION + "\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"wire-test\",\"version\":\"1\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}";
}
static String list(int id) {
return "{\"jsonrpc\":\"2.0\",\"id\":" + id + ",\"method\":\"tools/list\",\"params\":{\"_meta\":"
+ "{\"io.modelcontextprotocol/protocolVersion\":\"" + VERSION
+ "\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"wire-test\",\"version\":\"1\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}";
}
static Map<String, String> headers(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", VERSION);
h.put("Mcp-Method", method);
if (name != null) {
h.put("Mcp-Name", name);
}
return h;
}
static Reply post(String url, Map<String, String> headers, String body) throws Exception {
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());
return new Reply(r.statusCode(), r.body());
}
/** One compact exchange for a transcript. Ports in the URL are not printed, so reruns diff cleanly. */
static void show(Transcript t, String label, Map<String, String> headers, String body, Reply reply) {
t.section(label);
t.line("> POST /mcp");
for (String h : new String[] {"MCP-Protocol-Version", "Mcp-Method", "Mcp-Name"}) {
if (headers.containsKey(h)) {
t.line("> " + h + ": " + headers.get(h));
}
}
t.line("> " + body);
t.line("< " + reply.status());
t.line("< " + reply.body());
}
}