diff --git a/README.md b/README.md index beda750..e53956c 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ facts, so the build fails when a claim stops being true. | `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 | | `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 | +| `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client | ## Versions (verified on Maven Central, 2026-10-11) @@ -42,6 +43,7 @@ facts, so the build fails when a claim stops being true. | 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 | | 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 | +| MCP Java SDK / JavaParser (`code-search-mcp`) | 2.2.0 / 3.28.2 | verified on Maven Central 2026-11-25; `code-search-mcp` only. The 2026-07-28 "modern" server API (`io.modelcontextprotocol.modern`) is in `mcp-core` 2.2.0; JavaParser 3.28.2 cannot resolve calls to implicit record accessors | | JDK | 25 LTS | | | JUnit | 6.1.3 | | diff --git a/code-search-mcp/README.md b/code-search-mcp/README.md new file mode 100644 index 0000000..93f529d --- /dev/null +++ b/code-search-mcp/README.md @@ -0,0 +1,23 @@ +# code-search-mcp + +A code-search MCP server for a Java monorepo, on the stateless MCP 2026-07-28 spec. JavaParser turns every +`src/main/java` folder under a root into one unit per type and method; an `Embedder` turns each unit into a vector; +three read-only tools (`search_code`, `find_usages`, `get_source`) are served over Streamable HTTP at `/mcp`. + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn test -pl code-search-mcp # tests write output/01..09 +bash code-search-mcp/scripts/run-all.sh # also packages the jar and writes output/10 with curl +java -jar code-search-mcp/target/code-search-mcp.jar [port] +``` + +| Class | Role | +|---|---| +| `CodeIndexer` | JavaParser + one `CombinedTypeSolver` over every module's source folder | +| `Embedder`, `HashingEmbedder`, `OpenAiCompatibleEmbedder` | the seam: offline word-overlap vectors, or any `/v1/embeddings` endpoint | +| `VectorIndex` | brute-force cosine search | +| `UsageFinder` | name match vs symbol-solved usages, unresolved candidates kept and flagged | +| `CodeSearchTools`, `CodeSearchServer`, `Main` | the three MCP tools, Jetty wiring, the entry point | + +`sample-monorepo/` is the four-module shop the tests index. It is deliberately not part of the build. +`output/` holds the transcripts the tests and `scripts/curl-demo.sh` write; the post quotes them verbatim. diff --git a/code-search-mcp/output/01-index.txt b/code-search-mcp/output/01-index.txt new file mode 100644 index 0000000..faf15e5 --- /dev/null +++ b/code-search-mcp/output/01-index.txt @@ -0,0 +1,37 @@ +# Indexing sample-monorepo with JavaParser +files parsed: 10 +parse problems: 0 +types: 10 +methods+constructors:20 + +## every unit: kind, short name, file:line +TYPE InventoryRepository inventory/src/main/java/shop/inventory/InventoryRepository.java:7 +METHOD InventoryRepository#save inventory/src/main/java/shop/inventory/InventoryRepository.java:12 +METHOD InventoryRepository#get inventory/src/main/java/shop/inventory/InventoryRepository.java:18 +TYPE InventoryService inventory/src/main/java/shop/inventory/InventoryService.java:4 +METHOD InventoryService#InventoryService inventory/src/main/java/shop/inventory/InventoryService.java:8 +METHOD InventoryService#reserve inventory/src/main/java/shop/inventory/InventoryService.java:13 +METHOD InventoryService#release inventory/src/main/java/shop/inventory/InventoryService.java:22 +TYPE StockItem inventory/src/main/java/shop/inventory/StockItem.java:4 +TYPE AuditTrail notifications/src/main/java/shop/notifications/AuditTrail.java:6 +METHOD AuditTrail#AuditTrail notifications/src/main/java/shop/notifications/AuditTrail.java:10 +METHOD AuditTrail#recordEmail notifications/src/main/java/shop/notifications/AuditTrail.java:15 +TYPE EmailNotifier notifications/src/main/java/shop/notifications/EmailNotifier.java:4 +METHOD EmailNotifier#sendConfirmation notifications/src/main/java/shop/notifications/EmailNotifier.java:7 +METHOD EmailNotifier#sendCancellation notifications/src/main/java/shop/notifications/EmailNotifier.java:12 +METHOD EmailNotifier#send notifications/src/main/java/shop/notifications/EmailNotifier.java:16 +TYPE Order orders/src/main/java/shop/orders/Order.java:7 +TYPE OrderRepository orders/src/main/java/shop/orders/OrderRepository.java:8 +METHOD OrderRepository#save orders/src/main/java/shop/orders/OrderRepository.java:13 +METHOD OrderRepository#findById orders/src/main/java/shop/orders/OrderRepository.java:19 +TYPE OrderService orders/src/main/java/shop/orders/OrderService.java:11 +METHOD OrderService#OrderService orders/src/main/java/shop/orders/OrderService.java:18 +METHOD OrderService#placeOrder orders/src/main/java/shop/orders/OrderService.java:27 +METHOD OrderService#cancelOrder orders/src/main/java/shop/orders/OrderService.java:38 +TYPE CardGateway payments/src/main/java/shop/payments/CardGateway.java:6 +METHOD CardGateway#authorize payments/src/main/java/shop/payments/CardGateway.java:9 +METHOD CardGateway#reverse payments/src/main/java/shop/payments/CardGateway.java:12 +TYPE PaymentService payments/src/main/java/shop/payments/PaymentService.java:6 +METHOD PaymentService#PaymentService payments/src/main/java/shop/payments/PaymentService.java:10 +METHOD PaymentService#charge payments/src/main/java/shop/payments/PaymentService.java:15 +METHOD PaymentService#refund payments/src/main/java/shop/payments/PaymentService.java:23 diff --git a/code-search-mcp/output/02-search.txt b/code-search-mcp/output/02-search.txt new file mode 100644 index 0000000..3f7913d --- /dev/null +++ b/code-search-mcp/output/02-search.txt @@ -0,0 +1,29 @@ +# search_code ranking with the hashing-512 embedder (top 3 per query) + +## query: charge the customer's card +0.607 PaymentService#charge payments/src/main/java/shop/payments/PaymentService.java:15 +0.532 PaymentService payments/src/main/java/shop/payments/PaymentService.java:6 +0.427 PaymentService#refund payments/src/main/java/shop/payments/PaymentService.java:23 + +## query: take units off the shelf for an order +0.456 InventoryService#reserve inventory/src/main/java/shop/inventory/InventoryService.java:13 +0.345 OrderService#cancelOrder orders/src/main/java/shop/orders/OrderService.java:38 +0.330 OrderRepository#save orders/src/main/java/shop/orders/OrderRepository.java:13 + +## query: email the customer that the order was cancelled +0.489 EmailNotifier#sendCancellation notifications/src/main/java/shop/notifications/EmailNotifier.java:12 +0.466 Order orders/src/main/java/shop/orders/Order.java:7 +0.466 EmailNotifier#sendConfirmation notifications/src/main/java/shop/notifications/EmailNotifier.java:7 + +## query: find an order by its id +0.741 OrderRepository#findById orders/src/main/java/shop/orders/OrderRepository.java:19 +0.424 OrderRepository#save orders/src/main/java/shop/orders/OrderRepository.java:13 +0.387 OrderService#cancelOrder orders/src/main/java/shop/orders/OrderService.java:38 + +## query: return money to the customer +0.406 PaymentService#refund payments/src/main/java/shop/payments/PaymentService.java:23 +0.227 CardGateway#authorize payments/src/main/java/shop/payments/CardGateway.java:9 +0.224 PaymentService#charge payments/src/main/java/shop/payments/PaymentService.java:15 + +## the limit: a query that shares no words with the code +query: chargeback -> 0 result(s) diff --git a/code-search-mcp/output/03-usages.txt b/code-search-mcp/output/03-usages.txt new file mode 100644 index 0000000..c78c804 --- /dev/null +++ b/code-search-mcp/output/03-usages.txt @@ -0,0 +1,23 @@ +# find_usages for OrderRepository#save: name match vs resolved + +## name match only (resolve=false): 3 usages + inventory/src/main/java/shop/inventory/InventoryService.java:18 in InventoryService#reserve [not confirmed by the solver] + stock.save(new StockItem(sku, item.onHand() - units)); + inventory/src/main/java/shop/inventory/InventoryService.java:24 in InventoryService#release [not confirmed by the solver] + stock.save(new StockItem(sku, item.onHand() + units)); + orders/src/main/java/shop/orders/OrderService.java:31 in OrderService#placeOrder [not confirmed by the solver] + Order order = orders.save(new Order("ord-" + skus.hashCode(), customerId, skus, total)); + +## resolved (resolve=true): 1 usage + orders/src/main/java/shop/orders/OrderService.java:31 in OrderService#placeOrder + Order order = orders.save(new Order("ord-" + skus.hashCode(), customerId, skus, total)); + +## the other save, InventoryRepository#save, resolved: 2 usages + inventory/src/main/java/shop/inventory/InventoryService.java:18 in InventoryService#reserve + stock.save(new StockItem(sku, item.onHand() - units)); + inventory/src/main/java/shop/inventory/InventoryService.java:24 in InventoryService#release + stock.save(new StockItem(sku, item.onHand() + units)); + +## a call through an interface, CardGateway#authorize, resolved: 1 usage + payments/src/main/java/shop/payments/PaymentService.java:19 in PaymentService#charge + return gateway.authorize(customerId, amount); diff --git a/code-search-mcp/output/04-usages-type-and-gaps.txt b/code-search-mcp/output/04-usages-type-and-gaps.txt new file mode 100644 index 0000000..ed99757 --- /dev/null +++ b/code-search-mcp/output/04-usages-type-and-gaps.txt @@ -0,0 +1,17 @@ +# find_usages for a type, and for a library that is not in the monorepo + +## PaymentService (resolved): 2 usages + orders/src/main/java/shop/orders/OrderService.java:15 in OrderService#(type level) + private final PaymentService payments; + orders/src/main/java/shop/orders/OrderService.java:18 in OrderService#OrderService + public OrderService(OrderRepository orders, InventoryService inventory, PaymentService payments, EmailNotifier notifier) + +## AuditClient#record (resolved): the class lives in a library outside the monorepo + notifications/src/main/java/shop/notifications/AuditTrail.java:16 in AuditTrail#recordEmail [not confirmed by the solver] + client.record("email", customerId, subject); + not confirmed by the solver: 1 + +## PaymentService#refund (resolved): the call passes order.customerId(), an implicit record accessor + orders/src/main/java/shop/orders/OrderService.java:43 in OrderService#cancelOrder [not confirmed by the solver] + payments.refund(order.customerId(), order.total()); + not confirmed by the solver: 1 diff --git a/code-search-mcp/output/05-wire.txt b/code-search-mcp/output/05-wire.txt new file mode 100644 index 0000000..b54690c --- /dev/null +++ b/code-search-mcp/output/05-wire.txt @@ -0,0 +1,23 @@ +# code-search-mcp over HTTP, 2026-07-28: no handshake, no session + +## 1. tools/list: the names and input schemas the model will see +< 200 + search_code readOnlyHint=true + Find classes and methods by what they do. Ranks by similarity to the query, so describe behaviour rather than guessing an exact name. Use find_usages for callers. + find_usages readOnlyHint=true + List every place a class or method is used, with file, line and the calling method. + get_source readOnlyHint=true + Return the source of one method, so the model reads the body only when it needs it. + +## 2. tools/call search_code sent to instance A +> POST /mcp +> MCP-Protocol-Version: 2026-07-28 +> Mcp-Method: tools/call +> Mcp-Name: search_code +> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search_code","arguments":{"query":"charge the customer's card","k":2},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}} +< 200 +< {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"1. 0.607 PaymentService#charge payments/src/main/java/shop/payments/PaymentService.java:15\n public String charge(String customerId, BigDecimal amount)\n // Charges the customer's card for the given amount and returns the receipt id.\n2. 0.532 PaymentService payments/src/main/java/shop/payments/PaymentService.java:6\n class PaymentService\n // Takes payments from customers and refunds them, through a card gateway."}],"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"code-search-mcp","version":"1.0.0"}}}} + +## 3. the same call sent to instance B, a separate server that never saw request 2 +< 200 + same answer text as instance A: true diff --git a/code-search-mcp/output/06-wire-errors.txt b/code-search-mcp/output/06-wire-errors.txt new file mode 100644 index 0000000..43bafbd --- /dev/null +++ b/code-search-mcp/output/06-wire-errors.txt @@ -0,0 +1,36 @@ +# How a malformed request fails + +## 1. Mcp-Method header missing +> POST /mcp +> MCP-Protocol-Version: 2026-07-28 +> Mcp-Name: search_code +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"search_code","arguments":{"query":"refund"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}} +< 400 +< {"jsonrpc":"2.0","id":7,"error":{"code":-32020,"message":"Missing required header: Mcp-Method"}} + +## 2. Mcp-Name header says find_usages but the body calls search_code +> POST /mcp +> MCP-Protocol-Version: 2026-07-28 +> Mcp-Method: tools/call +> Mcp-Name: find_usages +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"search_code","arguments":{"query":"refund"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}} +< 400 +< {"jsonrpc":"2.0","id":7,"error":{"code":-32020,"message":"Mcp-Name header does not match request name/uri"}} + +## 3. a client still speaking 2025-11-25 +> POST /mcp +> MCP-Protocol-Version: 2025-11-25 +> Mcp-Method: tools/call +> Mcp-Name: search_code +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"search_code","arguments":{"query":"refund"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}} +< 400 +< {"jsonrpc":"2.0","id":7,"error":{"code":-32020,"message":"MCP-Protocol-Version header does not match _meta protocol version"}} + +## 4. _meta without clientCapabilities +> POST /mcp +> MCP-Protocol-Version: 2026-07-28 +> Mcp-Method: tools/call +> Mcp-Name: search_code +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"search_code","arguments":{"query":"refund"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"wire-test","version":"1"}}}} +< 400 +< {"jsonrpc":"2.0","id":7,"error":{"code":-32602,"message":"_meta['io.modelcontextprotocol/clientCapabilities'] is required"}} diff --git a/code-search-mcp/output/07-sdk-client.txt b/code-search-mcp/output/07-sdk-client.txt new file mode 100644 index 0000000..377cff6 --- /dev/null +++ b/code-search-mcp/output/07-sdk-client.txt @@ -0,0 +1,29 @@ +# An agent's session through the 2.2.0 SDK client: search, then callers, then source + +## search_code {query: return money to the customer, k: 2} +1. 0.406 PaymentService#refund payments/src/main/java/shop/payments/PaymentService.java:23 + public String refund(String customerId, BigDecimal amount) + // Returns money to the customer's card after a cancelled order. +2. 0.227 CardGateway#authorize payments/src/main/java/shop/payments/CardGateway.java:9 + abstract String authorize(String customerId, BigDecimal amount) + // Asks the processor to take the amount from the customer's card. Returns a receipt id. + +## find_usages {symbol: PaymentService#refund} +1 usage(s) of PaymentService#refund (resolved) + orders/src/main/java/shop/orders/OrderService.java:43 in OrderService#cancelOrder [unresolved: matched by name] + payments.refund(order.customerId(), order.total()); +1 of these could not be resolved by the symbol solver; check them by hand + +## get_source {name: OrderService#cancelOrder} +// orders/src/main/java/shop/orders/OrderService.java:38 +/** + * Cancels an order, puts the stock back on the shelf and returns the money to the customer. + */ +public void cancelOrder(String orderId) { + Order order = orders.findById(orderId).orElseThrow(); + for (String sku : order.skus()) { + inventory.release(sku, 1); + } + payments.refund(order.customerId(), order.total()); + notifier.sendCancellation(order.customerId(), orderId); +} diff --git a/code-search-mcp/output/08-tool-errors.txt b/code-search-mcp/output/08-tool-errors.txt new file mode 100644 index 0000000..34e6137 --- /dev/null +++ b/code-search-mcp/output/08-tool-errors.txt @@ -0,0 +1,13 @@ +# Tool failures are results with isError=true, not protocol errors + +## get_source with a name that does not exist +isError=true +no class or method called 'PaymentService#chargeback'. Use search_code to find the exact name. + +## search_code with a blank query +isError=true +'query' is required and must be a non-empty string + +## search_code that matches nothing (not an error: an empty answer with advice) +isError=false +no matches for 'chargeback' (the hashing-512 embedder matches words, so try other words from the code's vocabulary) diff --git a/code-search-mcp/output/09-embedder-swap.txt b/code-search-mcp/output/09-embedder-swap.txt new file mode 100644 index 0000000..fa573c6 --- /dev/null +++ b/code-search-mcp/output/09-embedder-swap.txt @@ -0,0 +1,5 @@ +# OpenAiCompatibleEmbedder against a stub /v1/embeddings server +requests sent for 70 texts: 2 +first request: Bearer secret-key | {"model":"nomic-embed-text","input":["text 0","text 1","te... +vectors returned: 70, each normalised to length 1: true +text 5 got the vector the stub built for index 5: true diff --git a/code-search-mcp/output/10-fat-jar-curl.txt b/code-search-mcp/output/10-fat-jar-curl.txt new file mode 100644 index 0000000..5e5f864 --- /dev/null +++ b/code-search-mcp/output/10-fat-jar-curl.txt @@ -0,0 +1,12 @@ +# java -jar target/code-search-mcp.jar sample-monorepo 8791, then curl +[main] WARN io.modelcontextprotocol.modern.server.HmacRequestStateCodec - HmacRequestStateCodec: no key configured, generated a random per-process key. State sealed by this instance cannot be opened by another instance; configure a shared key for multi-instance deployments. +indexed 30 units from sample-monorepo with the hashing-512 embedder +serving MCP 2026-07-28 at http://127.0.0.1:/mcp + +$ curl ... -H "Mcp-Method: tools/call" -H "Mcp-Name: search_code" -d {"query":"cancel an order","k":2} +1. 0.844 OrderService#cancelOrder orders/src/main/java/shop/orders/OrderService.java:38 + public void cancelOrder(String orderId) + // Cancels an order, puts the stock back on the shelf and returns the money to the customer. +2. 0.541 OrderService orders/src/main/java/shop/orders/OrderService.java:11 + class OrderService + // Places and cancels customer orders by coordinating stock, payment and email. diff --git a/code-search-mcp/pom.xml b/code-search-mcp/pom.xml new file mode 100644 index 0000000..0d9b620 --- /dev/null +++ b/code-search-mcp/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + + com.ankurm.agents + java-ai-agents + 1.0.0 + + + code-search-mcp + Code-search MCP server for a Java monorepo: JavaParser + embeddings on the stateless MCP spec + + + + 2.2.0 + 3.28.2 + + + + + + io.modelcontextprotocol.sdk + mcp + ${mcp.sdk.version} + + + + org.eclipse.jetty.ee11 + jetty-ee11-servlet + ${jetty.version} + + + com.github.javaparser + javaparser-symbol-solver-core + ${javaparser.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + code-search-mcp + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.1 + + + package + shade + + false + + + + com.ankurm.codesearch.Main + true + + + + + *:* + + META-INF/*.SFMETA-INF/*.DSAMETA-INF/*.RSA + module-info.classMETA-INF/versions/*/module-info.class + + + + + + + + + + diff --git a/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryRepository.java b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryRepository.java new file mode 100644 index 0000000..3ed5690 --- /dev/null +++ b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryRepository.java @@ -0,0 +1,21 @@ +package shop.inventory; + +import java.util.HashMap; +import java.util.Map; + +/** Keeps stock levels in memory. */ +public class InventoryRepository { + + private final Map bySku = new HashMap<>(); + + /** Stores the stock level for a product, replacing the earlier value. */ + public StockItem save(StockItem item) { + bySku.put(item.sku(), item); + return item; + } + + /** Returns the stock level for a product, or zero units when the product is unknown. */ + public StockItem get(String sku) { + return bySku.getOrDefault(sku, new StockItem(sku, 0)); + } +} diff --git a/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryService.java b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryService.java new file mode 100644 index 0000000..81ed4b3 --- /dev/null +++ b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/InventoryService.java @@ -0,0 +1,26 @@ +package shop.inventory; + +/** Reserves and releases units of stock so the shop never sells what it does not have. */ +public class InventoryService { + + private final InventoryRepository stock; + + public InventoryService(InventoryRepository stock) { + this.stock = stock; + } + + /** Takes units off the shelf for an order. Fails when there is not enough stock. */ + public void reserve(String sku, int units) { + StockItem item = stock.get(sku); + if (item.onHand() < units) { + throw new IllegalStateException("out of stock: " + sku); + } + stock.save(new StockItem(sku, item.onHand() - units)); + } + + /** Puts units back on the shelf, for example after a cancelled order. */ + public void release(String sku, int units) { + StockItem item = stock.get(sku); + stock.save(new StockItem(sku, item.onHand() + units)); + } +} diff --git a/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/StockItem.java b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/StockItem.java new file mode 100644 index 0000000..4dc1671 --- /dev/null +++ b/code-search-mcp/sample-monorepo/inventory/src/main/java/shop/inventory/StockItem.java @@ -0,0 +1,5 @@ +package shop.inventory; + +/** How many units of one product are on the shelf. */ +public record StockItem(String sku, int onHand) { +} diff --git a/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/AuditTrail.java b/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/AuditTrail.java new file mode 100644 index 0000000..74bbe7d --- /dev/null +++ b/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/AuditTrail.java @@ -0,0 +1,18 @@ +package shop.notifications; + +import com.acme.audit.AuditClient; + +/** Records who was emailed what. The audit client is a company library that is not part of this monorepo. */ +public class AuditTrail { + + private final AuditClient client; + + public AuditTrail(AuditClient client) { + this.client = client; + } + + /** Writes one audit record for an email that was sent. */ + public void recordEmail(String customerId, String subject) { + client.record("email", customerId, subject); + } +} diff --git a/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/EmailNotifier.java b/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/EmailNotifier.java new file mode 100644 index 0000000..219b244 --- /dev/null +++ b/code-search-mcp/sample-monorepo/notifications/src/main/java/shop/notifications/EmailNotifier.java @@ -0,0 +1,19 @@ +package shop.notifications; + +/** Sends transactional emails to customers. */ +public class EmailNotifier { + + /** Emails the customer that their order was placed. */ + public void sendConfirmation(String customerId, String orderId) { + send(customerId, "Order " + orderId + " confirmed"); + } + + /** Emails the customer that their order was cancelled and the money is on its way back. */ + public void sendCancellation(String customerId, String orderId) { + send(customerId, "Order " + orderId + " cancelled"); + } + + private void send(String customerId, String subject) { + System.out.println("mail to " + customerId + ": " + subject); + } +} diff --git a/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/Order.java b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/Order.java new file mode 100644 index 0000000..891f289 --- /dev/null +++ b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/Order.java @@ -0,0 +1,8 @@ +package shop.orders; + +import java.math.BigDecimal; +import java.util.List; + +/** A customer order: the lines being bought and the total the customer will be charged. */ +public record Order(String id, String customerId, List skus, BigDecimal total) { +} diff --git a/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderRepository.java b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderRepository.java new file mode 100644 index 0000000..0f608f5 --- /dev/null +++ b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderRepository.java @@ -0,0 +1,22 @@ +package shop.orders; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** Keeps orders in memory. A real service would sit on a database. */ +public class OrderRepository { + + private final Map byId = new HashMap<>(); + + /** Stores the order, replacing any earlier version with the same id. */ + public Order save(Order order) { + byId.put(order.id(), order); + return order; + } + + /** Looks an order up by its id. */ + public Optional findById(String id) { + return Optional.ofNullable(byId.get(id)); + } +} diff --git a/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderService.java b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderService.java new file mode 100644 index 0000000..09f636b --- /dev/null +++ b/code-search-mcp/sample-monorepo/orders/src/main/java/shop/orders/OrderService.java @@ -0,0 +1,46 @@ +package shop.orders; + +import java.math.BigDecimal; +import java.util.List; + +import shop.inventory.InventoryService; +import shop.notifications.EmailNotifier; +import shop.payments.PaymentService; + +/** Places and cancels customer orders by coordinating stock, payment and email. */ +public class OrderService { + + private final OrderRepository orders; + private final InventoryService inventory; + private final PaymentService payments; + private final EmailNotifier notifier; + + public OrderService(OrderRepository orders, InventoryService inventory, PaymentService payments, + EmailNotifier notifier) { + this.orders = orders; + this.inventory = inventory; + this.payments = payments; + this.notifier = notifier; + } + + /** Reserves stock, charges the customer's card and emails a confirmation. */ + public Order placeOrder(String customerId, List skus, BigDecimal total) { + for (String sku : skus) { + inventory.reserve(sku, 1); + } + Order order = orders.save(new Order("ord-" + skus.hashCode(), customerId, skus, total)); + payments.charge(customerId, total); + notifier.sendConfirmation(customerId, order.id()); + return order; + } + + /** Cancels an order, puts the stock back on the shelf and returns the money to the customer. */ + public void cancelOrder(String orderId) { + Order order = orders.findById(orderId).orElseThrow(); + for (String sku : order.skus()) { + inventory.release(sku, 1); + } + payments.refund(order.customerId(), order.total()); + notifier.sendCancellation(order.customerId(), orderId); + } +} diff --git a/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/CardGateway.java b/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/CardGateway.java new file mode 100644 index 0000000..dd46382 --- /dev/null +++ b/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/CardGateway.java @@ -0,0 +1,13 @@ +package shop.payments; + +import java.math.BigDecimal; + +/** The boundary to the external card processor. */ +public interface CardGateway { + + /** Asks the processor to take the amount from the customer's card. Returns a receipt id. */ + String authorize(String customerId, BigDecimal amount); + + /** Asks the processor to give the amount back to the customer's card. Returns a receipt id. */ + String reverse(String customerId, BigDecimal amount); +} diff --git a/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/PaymentService.java b/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/PaymentService.java new file mode 100644 index 0000000..311c4de --- /dev/null +++ b/code-search-mcp/sample-monorepo/payments/src/main/java/shop/payments/PaymentService.java @@ -0,0 +1,26 @@ +package shop.payments; + +import java.math.BigDecimal; + +/** Takes payments from customers and refunds them, through a card gateway. */ +public class PaymentService { + + private final CardGateway gateway; + + public PaymentService(CardGateway gateway) { + this.gateway = gateway; + } + + /** Charges the customer's card for the given amount and returns the receipt id. */ + public String charge(String customerId, BigDecimal amount) { + if (amount.signum() <= 0) { + throw new IllegalArgumentException("amount must be positive"); + } + return gateway.authorize(customerId, amount); + } + + /** Returns money to the customer's card after a cancelled order. */ + public String refund(String customerId, BigDecimal amount) { + return gateway.reverse(customerId, amount); + } +} diff --git a/code-search-mcp/scripts/curl-demo.sh b/code-search-mcp/scripts/curl-demo.sh new file mode 100755 index 0000000..d4d470b --- /dev/null +++ b/code-search-mcp/scripts/curl-demo.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Runs the packaged fat jar and talks to it with curl: the same three tools, no SDK, no test harness. +# Writes output/10-fat-jar-curl.txt. +set -eu +cd "$(dirname "$0")/.." +PORT=8791 +OUT=output/10-fat-jar-curl.txt +META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}' + +java -jar target/code-search-mcp.jar sample-monorepo "$PORT" > /tmp/code-search-mcp.log 2>&1 & +PID=$! +trap 'kill $PID 2>/dev/null || true' EXIT +for _ in $(seq 1 60); do grep -q 'serving MCP' /tmp/code-search-mcp.log && break; sleep 0.5; done + +call() { # $1 tool, $2 arguments json + curl -s -X POST "http://127.0.0.1:$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: $1" \ + -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2,$META}}" +} + +{ + echo '# java -jar target/code-search-mcp.jar sample-monorepo 8791, then curl' + grep -E 'indexed|serving|HmacRequestStateCodec' /tmp/code-search-mcp.log | sed -E 's#/[^ ]*/sample-monorepo#sample-monorepo#; s#:[0-9]{4,5}/mcp#:/mcp#' + echo + echo '$ curl ... -H "Mcp-Method: tools/call" -H "Mcp-Name: search_code" -d {"query":"cancel an order","k":2}' + call search_code '{"query":"cancel an order","k":2}' | python3 -c 'import sys,json; print(json.load(sys.stdin)["result"]["content"][0]["text"])' +} > "$OUT" +cat "$OUT" diff --git a/code-search-mcp/scripts/run-all.sh b/code-search-mcp/scripts/run-all.sh new file mode 100755 index 0000000..299f041 --- /dev/null +++ b/code-search-mcp/scripts/run-all.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Regenerates every file in output/: the tests write 01-09, the jar plus curl writes 10. +set -eu +cd "$(dirname "$0")/.." +mvn -B -q -f ../pom.xml -pl code-search-mcp package +bash scripts/curl-demo.sh diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeIndexer.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeIndexer.java new file mode 100644 index 0000000..bb2187a --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeIndexer.java @@ -0,0 +1,124 @@ +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; +import java.util.stream.Stream; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.CallableDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc; +import com.github.javaparser.symbolsolver.JavaSymbolSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; + +/** + * Turns a monorepo into {@link CodeUnit}s with JavaParser. It finds every {@code src/main/java} folder under the + * root, parses each {@code .java} file once, and keeps the parsed trees so the usage finder can walk them later. + */ +public final class CodeIndexer { + + private final Path root; + private final List units = new ArrayList<>(); + private final List codeUnits = new ArrayList<>(); + private final List parseProblems = new ArrayList<>(); + + public CodeIndexer(Path root) { + this.root = root.toAbsolutePath().normalize(); + } + + /** Parses everything. Call once; the result is read through the accessors. */ + public CodeIndexer index() throws IOException { + List sourceRoots = findSourceRoots(); + + // One type solver for the whole monorepo: every module's source folder plus the JDK. + CombinedTypeSolver solver = new CombinedTypeSolver(new ReflectionTypeSolver()); + for (Path sourceRoot : sourceRoots) { + solver.add(new JavaParserTypeSolver(sourceRoot)); + } + ParserConfiguration config = new ParserConfiguration() + .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_25) + .setSymbolResolver(new JavaSymbolSolver(solver)); + JavaParser parser = new JavaParser(config); + + for (Path sourceRoot : sourceRoots) { + try (Stream files = Files.walk(sourceRoot)) { + for (Path file : files.filter(f -> f.toString().endsWith(".java")).sorted().toList()) { + var result = parser.parse(file); + if (result.getResult().isEmpty() || !result.isSuccessful()) { + parseProblems.add(relative(file) + ": " + result.getProblems().size() + " problem(s)"); + } + result.getResult().ifPresent(cu -> { + cu.setStorage(file); + units.add(cu); + cu.findAll(TypeDeclaration.class).forEach(t -> addType(cu, t)); + }); + } + } + } + return this; + } + + private List findSourceRoots() throws IOException { + try (Stream walk = Files.walk(root)) { + return walk.filter(Files::isDirectory) + .filter(p -> p.endsWith(Path.of("src", "main", "java"))) + .sorted().toList(); + } + } + + private void addType(CompilationUnit cu, TypeDeclaration type) { + String qualified = type.getFullyQualifiedName().orElse(type.getNameAsString()); + codeUnits.add(new CodeUnit(CodeUnit.Kind.TYPE, qualified, header(type), relative(cu), line(type), + javadoc(type), type.getNameAsString() + " (" + type.getMembers().size() + " members)")); + for (var member : type.getMembers()) { + if (member instanceof CallableDeclaration callable) { + codeUnits.add(new CodeUnit(CodeUnit.Kind.METHOD, qualified + "#" + callable.getNameAsString(), + callable.getDeclarationAsString(true, false, true), relative(cu), line(callable), + javadoc(callable), callable.toString())); + } + } + } + + private static String header(TypeDeclaration type) { + String kind = switch (type) { + case com.github.javaparser.ast.body.ClassOrInterfaceDeclaration c -> c.isInterface() ? "interface" : "class"; + case com.github.javaparser.ast.body.RecordDeclaration r -> "record"; + case com.github.javaparser.ast.body.EnumDeclaration e -> "enum"; + default -> "type"; + }; + return kind + " " + type.getNameAsString(); + } + + private static int line(Node node) { + return node.getRange().map(r -> r.begin.line).orElse(0); + } + + private static String javadoc(Node node) { + if (node instanceof NodeWithJavadoc documented) { + return documented.getJavadoc().map(j -> j.getDescription().toText().replaceAll("\\s+", " ").trim()) + .orElse(""); + } + return ""; + } + + private String relative(CompilationUnit cu) { + return relative(cu.getStorage().orElseThrow().getPath()); + } + + private String relative(Path file) { + return root.relativize(file.toAbsolutePath().normalize()).toString().replace('\\', '/'); + } + + public Path root() { return root; } + public List compilationUnits() { return List.copyOf(units); } + public List codeUnits() { return List.copyOf(codeUnits); } + public List parseProblems() { return List.copyOf(parseProblems); } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchServer.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchServer.java new file mode 100644 index 0000000..e532ca3 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchServer.java @@ -0,0 +1,69 @@ +package com.ankurm.codesearch; + +import java.io.IOException; +import java.nio.file.Path; + +import io.modelcontextprotocol.modern.McpSchema.Implementation; +import io.modelcontextprotocol.modern.server.McpServer; +import io.modelcontextprotocol.modern.server.feature.ToolsFeature; +import io.modelcontextprotocol.modern.server.transport.HttpServletMcpTransport; +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; + +/** + * Wires the index to the 2026-07-28 "modern" MCP server and serves it from Jetty at {@code /mcp}. The server + * holds no per-client state: any request can go to any copy of this process. + */ +public final class CodeSearchServer { + + private CodeSearchServer() {} + + /** A running server. Closing stops Jetty and the MCP server. */ + public record Running(Server jetty, McpServer mcp, CodeIndexer code, VectorIndex index, int port) + implements AutoCloseable { + + public String url() { return "http://127.0.0.1:" + port + "/mcp"; } + + @Override public void close() throws Exception { + mcp.closeGracefully(); + jetty.stop(); + } + } + + /** Index {@code monorepo}, then serve it. Pass port 0 for a free port. */ + public static Running start(Path monorepo, Embedder embedder, int port) throws Exception { + CodeIndexer code = new CodeIndexer(monorepo).index(); + VectorIndex index = new VectorIndex(embedder, code.codeUnits()); + return serve(code, index, port); + } + + static Running serve(CodeIndexer code, VectorIndex index, int port) throws Exception { + McpServer mcp = McpServer.builder() + .serverInfo(Implementation.builder("code-search-mcp", "1.0.0").build()) + .instructions("Search a Java monorepo by behaviour (search_code), then read callers " + + "(find_usages) and bodies (get_source).") + .feature(ToolsFeature.ofSync(new CodeSearchTools(code, index))) + .build(); + HttpServletMcpTransport transport = HttpServletMcpTransport.builder(mcp).endpoint("/mcp").build(); + + Server jetty = new Server(); + ServerConnector connector = new ServerConnector(jetty); + connector.setHost("127.0.0.1"); // source code is sensitive: loopback only until you add auth + connector.setPort(port); + jetty.addConnector(connector); + ServletContextHandler context = new ServletContextHandler("/"); + ServletHolder holder = new ServletHolder(transport); + holder.setAsyncSupported(true); // the SDK docs ask for async support on this servlet + context.addServlet(holder, "/mcp"); + jetty.setHandler(context); + jetty.start(); + return new Running(jetty, mcp, code, index, connector.getLocalPort()); + } + + /** Convenience for {@link Main}. */ + static Running start(String root, int port) throws IOException, Exception { + return start(Path.of(root), new HashingEmbedder(512), port); + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchTools.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchTools.java new file mode 100644 index 0000000..5bc88e0 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeSearchTools.java @@ -0,0 +1,173 @@ +package com.ankurm.codesearch; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome; +import io.modelcontextprotocol.modern.McpSchema.CallToolRequest; +import io.modelcontextprotocol.modern.McpSchema.CallToolResult; +import io.modelcontextprotocol.modern.McpSchema.TextContent; +import io.modelcontextprotocol.modern.McpSchema.Tool; +import io.modelcontextprotocol.modern.McpSchema.ToolAnnotations; +import io.modelcontextprotocol.modern.server.McpRequestContext; +import io.modelcontextprotocol.modern.server.McpSyncResponse; +import io.modelcontextprotocol.modern.server.feature.McpSyncTool; +import io.modelcontextprotocol.modern.server.feature.McpSyncToolRepository; +import io.modelcontextprotocol.modern.server.feature.ToolsPage; + +/** + * The three tools an agent gets: {@code search_code}, {@code find_usages} and {@code get_source}. Each one is + * read-only and returns plain text, because the reader is a language model and a compact listing costs fewer + * tokens than the same facts as JSON. + */ +public final class CodeSearchTools implements McpSyncToolRepository { + + private final VectorIndex index; + private final CodeIndexer code; + private final UsageFinder usages; + private final Map tools; + + public CodeSearchTools(CodeIndexer code, VectorIndex index) { + this.code = code; + this.index = index; + this.usages = new UsageFinder(code); + McpSyncTool search = McpSyncTool.of(searchDefinition(), (ctx, req) -> run(() -> search(req))); + McpSyncTool find = McpSyncTool.of(usagesDefinition(), (ctx, req) -> run(() -> findUsages(req))); + McpSyncTool source = McpSyncTool.of(sourceDefinition(), (ctx, req) -> run(() -> getSource(req))); + this.tools = new java.util.LinkedHashMap<>(); + for (McpSyncTool t : List.of(search, find, source)) { + tools.put(t.definition().name(), t); + } + } + + @Override + public ToolsPage list(McpRequestContext ctx, String cursor) { + return ToolsPage.of(tools.values().stream().map(McpSyncTool::definition).toList()); + } + + @Override + public McpSyncTool find(McpRequestContext ctx, String name) { + return tools.get(name); + } + + // ---- definitions: what the model reads when it decides which tool to call ------------------------------- + + private static Tool searchDefinition() { + return Tool.builder("search_code", Map.of( + "type", "object", + "properties", Map.of( + "query", Map.of("type", "string", + "description", "What the code does, in plain words, e.g. 'refund a customer'"), + "k", Map.of("type", "integer", "minimum", 1, "maximum", 20, + "description", "How many results to return. Default 5.")), + "required", List.of("query"))) + .description("Find classes and methods by what they do. Ranks by similarity to the query, so " + + "describe behaviour rather than guessing an exact name. Use find_usages for callers.") + .annotations(ToolAnnotations.builder().readOnlyHint(true).build()) + .build(); + } + + private static Tool usagesDefinition() { + return Tool.builder("find_usages", Map.of( + "type", "object", + "properties", Map.of( + "symbol", Map.of("type", "string", + "description", "'Type#method' for a method or 'Type' for a class, as " + + "returned by search_code, e.g. 'PaymentService#refund'"), + "resolve", Map.of("type", "boolean", + "description", "true (default) binds each call to its real declaration " + + "with a symbol solver; false matches on the method name only " + + "and over-reports.")), + "required", List.of("symbol"))) + .description("List every place a class or method is used, with file, line and the calling method.") + .annotations(ToolAnnotations.builder().readOnlyHint(true).build()) + .build(); + } + + private static Tool sourceDefinition() { + return Tool.builder("get_source", Map.of( + "type", "object", + "properties", Map.of("name", Map.of("type", "string", + "description", "'Type#method' or a fully qualified name from search_code")), + "required", List.of("name"))) + .description("Return the source of one method, so the model reads the body only when it needs it.") + .annotations(ToolAnnotations.builder().readOnlyHint(true).build()) + .build(); + } + + // ---- handlers ---------------------------------------------------------------------------------------------- + + private String search(CallToolRequest req) { + String query = string(req, "query"); + int k = req.arguments().get("k") instanceof Number n ? n.intValue() : 5; + List hits = index.search(query, k); + if (hits.isEmpty()) { + return "no matches for '" + query + "' (the " + index.embedder().name() + " embedder matches words, " + + "so try other words from the code's vocabulary)"; + } + StringBuilder sb = new StringBuilder(); + int rank = 1; + for (VectorIndex.Hit h : hits) { + CodeUnit u = h.unit(); + sb.append(String.format("%d. %.3f %s %s%n", rank++, h.score(), u.shortName(), u.location())); + sb.append(" ").append(u.signature()).append('\n'); + if (!u.javadoc().isBlank()) { + sb.append(" // ").append(u.javadoc()).append('\n'); + } + } + return sb.toString().stripTrailing(); + } + + private String findUsages(CallToolRequest req) { + String symbol = string(req, "symbol"); + boolean resolve = !(req.arguments().get("resolve") instanceof Boolean b) || b; + UsageFinder.Result r = usages.find(symbol, resolve); + StringBuilder sb = new StringBuilder(); + sb.append(r.usages().size()).append(" usage(s) of ").append(symbol) + .append(resolve ? " (resolved)" : " (name match only)").append('\n'); + for (UsageFinder.Usage u : r.usages()) { + sb.append(" ").append(u.file()).append(':').append(u.line()).append(" in ").append(u.inMethod()) + .append(resolve && !u.exact() ? " [unresolved: matched by name]" : "") + .append("\n ").append(u.code()).append('\n'); + } + if (resolve && r.unresolved() > 0) { + sb.append(r.unresolved()).append(" of these could not be resolved by the symbol solver; check them by hand\n"); + } + return sb.toString().stripTrailing(); + } + + private String getSource(CallToolRequest req) { + String name = string(req, "name"); + List matches = code.codeUnits().stream() + .filter(u -> u.qualifiedName().equals(name) || u.shortName().equals(name)).toList(); + if (matches.isEmpty()) { + throw new IllegalArgumentException("no class or method called '" + name + + "'. Use search_code to find the exact name."); + } + return matches.stream().map(u -> "// " + u.location() + "\n" + u.source()) + .collect(Collectors.joining("\n\n")); + } + + // ---- plumbing ------------------------------------------------------------------------------------------------ + + private static String string(CallToolRequest req, String key) { + Object v = req.arguments() == null ? null : req.arguments().get(key); + if (!(v instanceof String s) || s.isBlank()) { + throw new IllegalArgumentException("'" + key + "' is required and must be a non-empty string"); + } + return s; + } + + /** A failure the model can read and act on is a tool result with isError, not a protocol error. */ + private static McpSyncResponse run(java.util.function.Supplier body) { + CallToolResult result; + try { + result = CallToolResult.builder().addContent(TextContent.builder(body.get()).build()).build(); + } catch (IllegalArgumentException e) { + result = CallToolResult.builder().addContent(TextContent.builder(e.getMessage()).build()) + .isError(true).build(); + } + return McpSyncResponse.result(result); + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeUnit.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeUnit.java new file mode 100644 index 0000000..4eeb122 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeUnit.java @@ -0,0 +1,25 @@ +package com.ankurm.codesearch; + +/** + * One searchable piece of the monorepo: a type or a method. {@code qualifiedName} is {@code pkg.Type} for a + * type and {@code pkg.Type#method} for a method, which is also what {@code get_source} takes. + */ +public record CodeUnit(Kind kind, String qualifiedName, String signature, String file, int line, String javadoc, + String source) { + + public enum Kind { TYPE, METHOD } + + /** The short {@code Type#method} (or {@code Type}) form people type into a prompt. */ + public String shortName() { + String q = qualifiedName; + int hash = q.indexOf('#'); + String type = hash < 0 ? q : q.substring(0, hash); + String simple = type.substring(type.lastIndexOf('.') + 1); + return hash < 0 ? simple : simple + q.substring(hash); + } + + /** {@code path:line}, the form an editor can jump to. */ + public String location() { + return file + ":" + line; + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/Embedder.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/Embedder.java new file mode 100644 index 0000000..10caef1 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/Embedder.java @@ -0,0 +1,24 @@ +package com.ankurm.codesearch; + +import java.util.List; + +/** + * Turns text into a fixed-length vector. The index only needs two promises: the same text always gives the same + * vector, and similar text gives vectors that point the same way, so cosine similarity can rank them. + */ +public interface Embedder { + + /** Vector length. Every vector this embedder returns has exactly this many entries. */ + int dimensions(); + + /** Embeds one text. The result is L2-normalised, so a dot product is the cosine similarity. */ + float[] embed(String text); + + /** Embeds many texts. Remote embedders override this to send one request. */ + default List embedAll(List texts) { + return texts.stream().map(this::embed).toList(); + } + + /** A short name for logs and transcripts. */ + String name(); +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/HashingEmbedder.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/HashingEmbedder.java new file mode 100644 index 0000000..2a63c66 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/HashingEmbedder.java @@ -0,0 +1,92 @@ +package com.ankurm.codesearch; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** + * A bag-of-words embedder with no model and no network: split identifiers into words, hash each word (and each + * pair of neighbouring words) into one of {@code dimensions} buckets with a random-looking sign, then normalise. + * + *

This is the "hashing trick". It matches words, not meaning: "refund" finds "refund" but + * not "give money back". It exists so the whole server runs and tests offline, and so the {@link Embedder} + * seam is real. Swap in {@link OpenAiCompatibleEmbedder} when you need meaning. + */ +public final class HashingEmbedder implements Embedder { + + private static final Set STOP = Set.of("a", "an", "the", "of", "to", "and", "or", "for", "in", "on", "is", + "it", "this", "that", "with", "by", "be", "as", "at", "from", "when", "are", "not", "so", "does"); + + private final int dimensions; + + public HashingEmbedder(int dimensions) { + this.dimensions = dimensions; + } + + @Override public int dimensions() { return dimensions; } + + @Override public String name() { return "hashing-" + dimensions; } + + @Override + public float[] embed(String text) { + List words = words(text); + float[] v = new float[dimensions]; + for (int i = 0; i < words.size(); i++) { + add(v, words.get(i), 1f); + if (i + 1 < words.size()) { + add(v, words.get(i) + " " + words.get(i + 1), 0.5f); + } + } + double norm = 0; + for (float x : v) { + norm += x * x; + } + norm = Math.sqrt(norm); + if (norm > 0) { + for (int i = 0; i < v.length; i++) { + v[i] /= (float) norm; + } + } + return v; + } + + private void add(float[] v, String feature, float weight) { + int h = fnv1a(feature); + int bucket = Math.floorMod(h, dimensions); + float sign = ((h >>> 31) == 0) ? 1f : -1f; // the top bit picks the sign, so collisions tend to cancel + v[bucket] += sign * weight; + } + + /** {@code placeOrder} becomes {@code place order}; {@code HTTP_Client} becomes {@code http client}. */ + static List words(String text) { + String spaced = text + .replaceAll("([a-z0-9])([A-Z])", "$1 $2") + .replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2"); + List out = new ArrayList<>(); + for (String raw : spaced.toLowerCase(Locale.ROOT).split("[^a-z0-9]+")) { + if (raw.length() < 2 || STOP.contains(raw)) { + continue; + } + out.add(stem(raw)); + } + return out; + } + + /** Deliberately tiny: strip a plural or an "ed"/"ing" so "refunds" and "refunded" meet "refund". */ + private static String stem(String w) { + if (w.length() > 5 && w.endsWith("ing")) return w.substring(0, w.length() - 3); + if (w.length() > 4 && w.endsWith("ed")) return w.substring(0, w.length() - 2); + if (w.length() > 3 && w.endsWith("s") && !w.endsWith("ss")) return w.substring(0, w.length() - 1); + return w; + } + + private static int fnv1a(String s) { + int h = 0x811c9dc5; + for (int i = 0; i < s.length(); i++) { + h ^= s.charAt(i); + h *= 16777619; + } + return h; + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/Main.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/Main.java new file mode 100644 index 0000000..4d25945 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/Main.java @@ -0,0 +1,26 @@ +package com.ankurm.codesearch; + +/** + * {@code java -jar code-search-mcp.jar [port]}. Indexes every {@code src/main/java} folder under + * the root and serves MCP 2026-07-28 at {@code http://127.0.0.1:/mcp}. + */ +public final class Main { + + private Main() {} + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.err.println("usage: java -jar code-search-mcp.jar [port]"); + System.exit(2); + } + int port = args.length > 1 ? Integer.parseInt(args[1]) : 8765; + CodeSearchServer.Running running = CodeSearchServer.start(args[0], port); + System.err.println("indexed " + running.index().size() + " units from " + running.code().root() + + " with the " + running.index().embedder().name() + " embedder"); + System.err.println("serving MCP 2026-07-28 at " + running.url()); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { running.close(); } catch (Exception ignored) { } + })); + Thread.currentThread().join(); + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/OpenAiCompatibleEmbedder.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/OpenAiCompatibleEmbedder.java new file mode 100644 index 0000000..529b17d --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/OpenAiCompatibleEmbedder.java @@ -0,0 +1,108 @@ +package com.ankurm.codesearch; + +import java.io.IOException; +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.ArrayList; +import java.util.List; +import java.util.Map; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Calls any {@code POST /v1/embeddings} endpoint that speaks the OpenAI request shape: OpenAI itself, Ollama + * ({@code http://localhost:11434/v1}), vLLM, LM Studio, llama.cpp's server. This is the swap-in for + * {@link HashingEmbedder} when you want meaning instead of word overlap. + * + *

The tests run it against a stub server, which proves the request and response handling and nothing about + * the quality of any real model's vectors. + */ +public final class OpenAiCompatibleEmbedder implements Embedder { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final URI endpoint; + private final String model; + private final String apiKey; + private final int dimensions; + private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + + /** @param baseUrl for example {@code http://localhost:11434/v1}; {@code /embeddings} is appended. */ + public OpenAiCompatibleEmbedder(String baseUrl, String model, String apiKey, int dimensions) { + this.endpoint = URI.create(baseUrl.replaceAll("/+$", "") + "/embeddings"); + this.model = model; + this.apiKey = apiKey; + this.dimensions = dimensions; + } + + @Override public int dimensions() { return dimensions; } + + @Override public String name() { return "openai-compatible:" + model; } + + @Override + public float[] embed(String text) { + return embedAll(List.of(text)).get(0); + } + + @Override + public List embedAll(List texts) { + List out = new ArrayList<>(); + // 64 texts per request keeps every request body small and every server's batch limit happy. + for (int from = 0; from < texts.size(); from += 64) { + out.addAll(request(texts.subList(from, Math.min(from + 64, texts.size())))); + } + return out; + } + + private List request(List batch) { + try { + // LinkedHashMap, not Map.of: Map.of iterates in a per-JVM random order, which makes request bytes unstable. + Map payload = new java.util.LinkedHashMap<>(); + payload.put("model", model); + payload.put("input", batch); + String body = JSON.writeValueAsString(payload); + HttpRequest.Builder req = HttpRequest.newBuilder(endpoint).timeout(Duration.ofSeconds(60)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)); + if (apiKey != null && !apiKey.isBlank()) { + req.header("Authorization", "Bearer " + apiKey); + } + HttpResponse res = http.send(req.build(), HttpResponse.BodyHandlers.ofString()); + if (res.statusCode() != 200) { + throw new IllegalStateException("embedding endpoint returned HTTP " + res.statusCode() + ": " + + res.body()); + } + // The spec returns "data" with an "index" per item; sort by it rather than trusting the order. + JsonNode data = JSON.readTree(res.body()).get("data"); + float[][] vectors = new float[batch.size()][]; + for (JsonNode item : data) { + JsonNode e = item.get("embedding"); + float[] v = new float[e.size()]; + double norm = 0; + for (int i = 0; i < v.length; i++) { + v[i] = (float) e.get(i).asDouble(); + norm += v[i] * v[i]; + } + norm = Math.sqrt(norm); + for (int i = 0; i < v.length && norm > 0; i++) { + v[i] /= (float) norm; + } + if (v.length != dimensions) { + throw new IllegalStateException("expected " + dimensions + " dimensions but the model returned " + + v.length + "; change the dimensions you passed in, or re-index"); + } + vectors[item.get("index").asInt()] = v; + } + return List.of(vectors); + } catch (IOException e) { + throw new IllegalStateException("could not call " + endpoint, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while calling " + endpoint, e); + } + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/UsageFinder.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/UsageFinder.java new file mode 100644 index 0000000..1cf3eee --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/UsageFinder.java @@ -0,0 +1,117 @@ +package com.ankurm.codesearch; + +import java.util.ArrayList; +import java.util.List; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.body.CallableDeclaration; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.type.ClassOrInterfaceType; + +/** + * Answers "where is this used?" by walking the parsed trees. + * + *

Two modes, because the cheap one is wrong in a useful way: + *

    + *
  • name matches on the method name alone. Instant, never throws, and reports every {@code save(...)} + * in the monorepo as a usage of every {@code save} method.
  • + *
  • resolved asks JavaParser's symbol solver which declaration each call really binds to. A call the + * solver rules out is dropped. A call it cannot resolve (a library outside the monorepo, or a + * construct the solver does not support) is kept and marked {@code exact=false}, because dropping it would + * hide a real caller.
  • + *
+ */ +public final class UsageFinder { + + /** One place a symbol is used. */ + public record Usage(String file, int line, String inMethod, String code, boolean exact) {} + + /** The usages, plus how many of them are name-only guesses the solver could not confirm or rule out. */ + public record Result(List usages, int unresolved) {} + + private final List units; + private final String root; + + public UsageFinder(CodeIndexer index) { + this.units = index.compilationUnits(); + this.root = index.root().toString(); + } + + /** @param symbol {@code Type#method} or {@code Type}, simple or fully qualified */ + public Result find(String symbol, boolean resolve) { + int hash = symbol.indexOf('#'); + String type = hash < 0 ? symbol : symbol.substring(0, hash); + String method = hash < 0 ? null : symbol.substring(hash + 1); + List found = new ArrayList<>(); + int[] unresolved = {0}; + + for (CompilationUnit cu : units) { + if (method != null) { + for (MethodCallExpr call : cu.findAll(MethodCallExpr.class)) { + if (!call.getNameAsString().equals(method)) continue; + Binding b = resolve ? bindsTo(call, type) : Binding.UNKNOWN; + if (b == Binding.NO) continue; + if (resolve && b == Binding.UNKNOWN) unresolved[0]++; + found.add(usage(cu, call, b == Binding.YES)); + } + } else { + for (ClassOrInterfaceType t : cu.findAll(ClassOrInterfaceType.class)) { + if (!t.getNameAsString().equals(simple(type))) continue; + Binding b = resolve ? typeBindsTo(t, type) : Binding.UNKNOWN; + if (b == Binding.NO) continue; + if (resolve && b == Binding.UNKNOWN) unresolved[0]++; + found.add(usage(cu, t, b == Binding.YES)); + } + } + } + return new Result(List.copyOf(found), unresolved[0]); + } + + private enum Binding { YES, NO, UNKNOWN } + + private static Binding bindsTo(MethodCallExpr call, String type) { + try { + return matches(call.resolve().declaringType().getQualifiedName(), type) ? Binding.YES : Binding.NO; + } catch (RuntimeException e) { // UnsolvedSymbolException, IllegalStateException, ... + return Binding.UNKNOWN; + } + } + + private static Binding typeBindsTo(ClassOrInterfaceType t, String type) { + try { + return matches(t.resolve().describe(), type) ? Binding.YES : Binding.NO; + } catch (RuntimeException e) { + return Binding.UNKNOWN; + } + } + + private static boolean matches(String qualified, String wanted) { + return qualified.equals(wanted) || qualified.endsWith("." + wanted); + } + + private static String simple(String type) { + return type.substring(type.lastIndexOf('.') + 1); + } + + private Usage usage(CompilationUnit cu, Node node, boolean exact) { + String file = cu.getStorage().orElseThrow().getPath().toString(); + String rel = file.startsWith(root) ? file.substring(root.length() + 1) : file; + String in = node.findAncestor(CallableDeclaration.class).map(CallableDeclaration::getNameAsString) + .orElse("(type level)"); + String owner = cu.getPrimaryTypeName().orElse("?"); + return new Usage(rel, node.getRange().map(r -> r.begin.line).orElse(0), owner + "#" + in, snippet(node), exact); + } + + /** The statement around a call; for a type named in a signature or a field, that signature or field. */ + private static String snippet(Node node) { + String text = node.findAncestor(Statement.class).map(Object::toString) + .or(() -> node.findAncestor(CallableDeclaration.class) + .map(c -> c.getDeclarationAsString(true, false, true))) + .or(() -> node.findAncestor(FieldDeclaration.class).map(Object::toString)) + .orElse(node.toString()); + return text.replaceAll("\\s+", " ").trim(); + } +} diff --git a/code-search-mcp/src/main/java/com/ankurm/codesearch/VectorIndex.java b/code-search-mcp/src/main/java/com/ankurm/codesearch/VectorIndex.java new file mode 100644 index 0000000..0155f09 --- /dev/null +++ b/code-search-mcp/src/main/java/com/ankurm/codesearch/VectorIndex.java @@ -0,0 +1,61 @@ +package com.ankurm.codesearch; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * The whole "vector database": an array of vectors and a loop. For a monorepo of a few hundred thousand methods a + * brute-force dot product per query is still milliseconds; reach for an ANN index only when you can measure that + * it is too slow. + */ +public final class VectorIndex { + + /** A unit and how close it is to the query, 1.0 meaning "same direction". */ + public record Hit(CodeUnit unit, double score) {} + + private final Embedder embedder; + private final List units; + private final List vectors; + + public VectorIndex(Embedder embedder, List units) { + this.embedder = embedder; + this.units = List.copyOf(units); + this.vectors = embedder.embedAll(units.stream().map(VectorIndex::embeddingText).toList()); + } + + /** + * What gets embedded for a unit. The name is repeated because a method name is the densest summary a + * developer wrote; the Javadoc adds the vocabulary the name leaves out; the signature adds the types. + */ + static String embeddingText(CodeUnit u) { + String name = u.shortName().replace('#', ' '); + return name + " " + name + " " + u.signature() + " " + u.javadoc(); + } + + /** Top {@code k} units by cosine similarity. Units with a non-positive score are not returned. */ + public List search(String query, int k) { + float[] q = embedder.embed(query); + List hits = new ArrayList<>(); + for (int i = 0; i < units.size(); i++) { + double score = dot(q, vectors.get(i)); + if (score > 0) { + hits.add(new Hit(units.get(i), score)); + } + } + hits.sort(Comparator.comparingDouble(Hit::score).reversed()); + return hits.subList(0, Math.min(k, hits.size())); + } + + public int size() { return units.size(); } + + public Embedder embedder() { return embedder; } + + private static double dot(float[] a, float[] b) { + double s = 0; + for (int i = 0; i < a.length; i++) { + s += a[i] * b[i]; + } + return s; + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/EmbedderSwapTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/EmbedderSwapTest.java new file mode 100644 index 0000000..96fef1a --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/EmbedderSwapTest.java @@ -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 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 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 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 texts = new ArrayList<>(); + for (int i = 0; i < 70; i++) { + texts.add("text " + i); + } + List 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); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/Fixtures.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/Fixtures.java new file mode 100644 index 0000000..a2f6293 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/Fixtures.java @@ -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()); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/IndexTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/IndexTest.java new file mode 100644 index 0000000..db48409 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/IndexTest.java @@ -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 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); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/McpWireTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/McpWireTest.java new file mode 100644 index 0000000..d2cef15 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/McpWireTest.java @@ -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 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 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 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); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/SdkClientTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/SdkClientTest.java new file mode 100644 index 0000000..dac0f21 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/SdkClientTest.java @@ -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); + } + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/SearchTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/SearchTest.java new file mode 100644 index 0000000..20b9195 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/SearchTest.java @@ -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 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 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"); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/Transcript.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/Transcript.java new file mode 100644 index 0000000..eef0354 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/Transcript.java @@ -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 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); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/UsageTest.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/UsageTest.java new file mode 100644 index 0000000..aa23baf --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/UsageTest.java @@ -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(); + } +} diff --git a/code-search-mcp/src/test/java/com/ankurm/codesearch/Wire.java b/code-search-mcp/src/test/java/com/ankurm/codesearch/Wire.java new file mode 100644 index 0000000..f814e44 --- /dev/null +++ b/code-search-mcp/src/test/java/com/ankurm/codesearch/Wire.java @@ -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 headers(String method, String name) { + Map 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 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 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 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()); + } +} diff --git a/pom.xml b/pom.xml index 9561dc3..c80f60a 100644 --- a/pom.xml +++ b/pom.xml @@ -22,6 +22,7 @@ koog claude-code-spring mcp-stateless + code-search-mcp