Skip to main content

Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings)

A small MCP server that lets a coding agent search a Java monorepo by behaviour, find real callers with JavaParser’s symbol solver, and read one method at a time, on the stateless 2026-07-28 MCP spec. Every transcript comes from a tested companion module.

Picture a coding agent that you have pointed at a large monorepo and asked where refunds are handled. It runs grep -r refund, gets hundreds of lines back, and has to read files it did not need to find the one method that matters. That is the problem this post addresses, with a small server the agent can ask instead of grepping. The server does three jobs. It parses every Java file with JavaParser so it knows what a class and a method are, not just which lines of text exist. It embeds each method so the agent can ask “return money to the customer” and be pointed at PaymentService#refund. And it finds usages so the agent can then ask who calls that method. All three are exposed as tools over the Model Context Protocol, on the new stateless 2026-07-28 revision, so any MCP client can use them. Every transcript below is copied from a file in the companion repository, and the tests that write those files assert the same facts.
Versions tested. MCP Java SDK 2.2.0 (mcp aggregator over mcp-core; the 2026-07-28 “modern” server API is in io.modelcontextprotocol.modern), JavaParser 3.28.2 (javaparser-symbol-solver-core), Jetty 12.1.14 (jetty-ee11-servlet), JUnit 6.1.3, JDK 25 (Temurin 25.0.5.1). All versions read from Maven Central metadata on 2026-11-25. The MCP specification revision 2026-07-28 was released on July 28, 2026. Code: the code-search-mcp module of the java-ai-agents repository.

An agent does not need your files, it needs answers to three questions

When an agent works in a large repository it keeps asking the same three things: where is the code that does X, who uses this method, and show me that method. A text search answers the first badly, because it matches the words you typed and the code may use different ones. It answers the second badly too, because a method called save exists in every repository class you own. The design below gives each question its own tool, and keeps the answers short, because a language model pays for every line it reads.
Monorepo.java filesJavaParserone unit pertype / methodEmbeddertext → vectorVector indexcosine, brute forceMCP toolssearch_codefind_usages, get_sourceAgentasks in plain wordsParsed trees + symbol solverkept in memory for find_usagesTwo readers of the same parse: the vector index answers “what does this”, the trees answer “who calls this”.
The diagram shows the one idea the rest of the post depends on: the monorepo is parsed once, and two different structures are built from that single parse. The vector index (amber and green boxes) answers “what does this code do”. The parsed trees (blue box underneath) answer “who calls this”. Searching by meaning and searching by structure are different problems, and mixing them in one tool is how code-search tools end up doing both badly. The sample monorepo the tests index is four small modules (orders, payments, inventory, notifications) under sample-monorepo/ in the module. I wrote it, including the Javadoc, so keep in mind that results on it are friendlier than results on a repository nobody wrote for a demo. I come back to that in the embeddings section.
Why not just give the agent grep, an IDE index or an LSP? For many repositories you should. grep is exact, free and already in the agent’s toolbox. A language server (Eclipse JDT LS, for example) already knows how to find references and is typically more complete than the JavaParser code here. What this server adds is the search by behaviour tool, plus a single, small, read-only interface that works from any MCP client and returns compact text. If your agent’s only pain is “find all callers”, reach for a language server first. The “should you build this” callout at the end says more.

Going deeper

  • The three tools and exactly what each one returns: see the tool section below and CodeSearchTools.java.
  • Why the server is read-only and loopback-only: the security accordion near the end.

JavaParser turns files into units an agent can name

A source file is text. A unit, in this server, is the smallest thing a developer would point at: a type (class, interface, record or enum) or one method or constructor. JavaParser reads a file and gives back a tree of exactly those things, with their names, signatures, Javadoc and line numbers attached. That tree is what lets the server say PaymentService#refund at PaymentService.java:23 instead of “somewhere around line 40”. The indexer finds every src/main/java folder under the root you give it, parses each file once, and keeps the parsed trees. The part to notice is the type solver: one CombinedTypeSolver that knows the JDK and every module’s source folder, so a call in the orders module can be followed into the payments module later. This is code from CodeIndexer.java:
public CodeIndexer index() throws IOException {
    List<Path> 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<Path> 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;
}
Each parsed type is then flattened into units, one for the type and one per method or constructor. This is CodeIndexer.java:
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()));
        }
    }
}
Running the indexer over the sample monorepo gives 10 files, 0 parse problems, 10 types and 20 methods and constructors. Here is the start of the captured transcript, 01-index.txt, showing that the same method name appears in two classes, which matters in two sections from now:
# 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
Constructors count as methods here. OrderService#OrderService appears in the index. That is deliberate (an agent may ask who builds a PaymentService), but it means a count of “methods” includes constructors. The 20 in the transcript is methods plus constructors.
Why one unit per method, and not fixed-size chunks of text? The common way to feed code to an embedding model is to cut files into chunks of a few hundred tokens. The cut falls wherever the token count runs out, so a method can be split in half, and a chunk can hold the tail of one method and the head of the next. A unit boundary that follows the language means a search result is always a whole thing with a name, a signature and a line number. The cost is that a very long method becomes one very long unit; this server keeps only the signature and Javadoc in the embedded text (next section), so length does not hurt ranking, and get_source returns the body only on request.
How the type solver is wired, and what it costs JavaParser can parse a file without knowing anything about the rest of the code. Parsing is cheap. Resolving (“this call, which method is it?”) needs a type solver that can look up other classes. ReflectionTypeSolver covers the JDK; one JavaParserTypeSolver per source root covers your own modules. A solver rooted at the wrong folder resolves nothing, which is why the indexer finds source roots by the src/main/java convention. The solver only sees what you register: a call into a library that is not on that list stays unresolved, and the usages section shows what the server does about that. Resolution runs lazily, only when find_usages asks. Language level is set to JAVA_25, which is accepted by 3.28.2; I did not try to parse any Java 25 syntax beyond records, so treat newer language features as untested.

Going deeper

An embedding is just a list of numbers that lets you measure “similar”

An embedder turns a piece of text into a fixed-length list of numbers, a vector. The useful property is that text about the same thing ends up as vectors pointing the same way, so the angle between two vectors (the cosine similarity) is a score for how alike the texts are. To search, embed the query, compare it with the vector of every unit, and return the closest few. The server hides the embedder behind a one-method interface, because this is the part you will want to change. Embedder.java:
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<float[]> embedAll(List<String> texts) {
    return texts.stream().map(this::embed).toList();
}

/** A short name for logs and transcripts. */
String name();
What gets embedded for a unit is its name (twice, because the name is the densest summary a developer wrote), its signature, and its Javadoc. The search is a plain loop: dot product against every vector, keep the positive scores, sort. From VectorIndex.java:
static String embeddingText(CodeUnit u) {
    String name = u.shortName().replace('#', ' ');
    return name + " " + name + " " + u.signature() + " " + u.javadoc();
}
public List<Hit> search(String query, int k) {
    float[] q = embedder.embed(query);
    List<Hit> 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()));
}
There is no vector database here, on purpose. A brute-force loop over a few hundred thousand vectors is a matter of milliseconds, and I would not add an approximate-nearest-neighbour index until I had measured that the loop was too slow. The default embedder, HashingEmbedder.java, uses no model and no network. It splits identifiers into words (placeOrder becomes place and order), hashes each word into one of 512 buckets, and normalises. Because it only matches words, it cannot know that “chargeback” and “refund” are related. Here is what it does on a query I wrote after the code, from 02-search.txt (the file has five queries; all five put the method I had in mind first), and then on a query that shares no words with any unit:
# 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: 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)
These results flatter the embedder, and you should discount them. I wrote the sample code and its Javadoc, then wrote the queries, so the words overlap by construction. “return money to the customer” finds PaymentService#refund only because its Javadoc says “Returns money to the customer’s card”. On a real repository with thin Javadoc the hashing embedder behaves like a slightly smarter grep. It exists so the whole server runs and tests offline and so the seam is real; use a model when meaning matters.
The hashing trick in a few lines Hashing every word to a bucket number means no vocabulary has to be stored, and two different words occasionally land in the same bucket. To keep such collisions from always adding up, the top bit of the hash picks a plus or minus sign, so unrelated collisions tend to cancel. A pair of neighbouring words is also hashed, at half weight, so word order counts a little. This is the part of HashingEmbedder.java:
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;
}
Swapping in a real embedding model (OpenAI-compatible endpoint) OpenAiCompatibleEmbedder calls any server that speaks POST /v1/embeddings in the OpenAI request shape. That is the shape OpenAI uses, and several local model servers offer an endpoint of the same shape; I have not run it against any real server, and I have not checked each one’s compatibility, so confirm that your server exposes that endpoint. Construction takes the base URL, the model name, an API key and the vector length:
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;
}
Two details come from thinking about how this fails. The response lists vectors with an index, and the code places each by that index rather than trusting the order. And if the model returns a different length than you declared, it refuses instead of silently building an index of mismatched vectors:
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;
The test runs it against a small stub server that deliberately replies in reverse order. This proves request shape, batching (70 texts go out as 64 + 6), ordering and the dimension guard. It says nothing about how good any real model’s vectors are. From 09-embedder-swap.txt:
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
Switching models means re-embedding everything, because vectors from different models are not comparable. The index is built at startup from the embedder you pass in, so a model change is a restart, not a migration. Measuring whether the real model beats the hashing one on your repository is the step this post does not do; a golden set of questions with recall@k is the usual approach.

Going deeper

“Who calls this?” has a trap: two classes can both have a save

Finding usages sounds like a search for a name. It is not, and the sample monorepo is built to show why. There are two save methods, OrderRepository#save and InventoryRepository#save, and three call sites named save.
orders.save(order)OrderService#placeOrderstock.save(item)InventoryService#reservestock.save(item)InventoryService#releaseName matchfind_usages OrderRepository#savereturns 3 usagesResolvedsame questionreturns 1 usageA name is not an identity: two classes can both have a save.The solver follows each receiver to the class it was declared as.Green: the call that really targets OrderRepository.save.Amber calls are InventoryRepository.save. Name matching cannot tell the two apart.
The picture is the whole argument. Asked for callers of OrderRepository#save, a name match returns all three (the red box). The symbol solver follows each call’s receiver to the class it was declared as, and returns only the one that really targets OrderRepository (green). An agent that trusts the red answer will go and read two inventory methods for no reason. The finder walks the parsed trees and runs both modes. This is UsageFinder.java:
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<Usage> 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]);
}
The captured result, from 03-usages.txt:
# 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
      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));
  orders/src/main/java/shop/orders/OrderService.java:31  in OrderService#placeOrder
      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));
Real finding: the solver cannot resolve a call whose argument is an implicit record accessor. OrderService#cancelOrder calls payments.refund(order.customerId(), order.total()), and Order is a record, so customerId() is an accessor the compiler generates. With JavaParser 3.28.2 the solver throws on that call, and the failure spreads to any call that takes it as an argument. I first wrote the finder so that an unresolved call was left out, and the tool reported no callers of PaymentService#refund. I confirmed the cause in an uncommitted scratch copy of the sample, where I replaced the record with a plain class with explicit accessors, and then everything resolved. The fix in the finder is below: keep unresolved candidates and mark them, instead of dropping them.
An agent can use a flagged result: it is a probable caller that the solver could not confirm. A silently missing caller is worse than a flagged guess. The same path handles a call into a library that is not in the monorepo (an AuditClient here). From 04-usages-type-and-gaps.txt:
## 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
How the finder decides between match, no match and unknown The solver can say three things about a call: it binds to the class you asked about (yes), it binds to a different class (no, drop it), or it throws (unknown, keep it and flag it). Collapsing “no” and “unknown” into one is the bug described above. This is UsageFinder.java:
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;
    }
}
Two smaller points. Searching by a type name (PaymentService with no #) finds fields and parameters (the sample finds a field and a constructor parameter), and does not count the import line, because an import is a name, not a type node; the test asserts 2 usages for PaymentService, a field and a constructor parameter.
What this finder does not do It does not follow calls made through reflection, method references or frameworks that wire beans by name; it does not see code outside the indexed src/main/java folders (tests, generated sources); and it reports the call site, not the chain of callers above it, so asking “what is the blast radius of changing this” takes repeated calls. A language server does all of that better. This is the part of the server I would replace first if it grew.

Going deeper

Serving it as an MCP server: one request is enough

An MCP server is a program that tells an AI client which tools it offers and runs them on request. Before the 2026-07-28 revision, a client first had to run an initialize handshake and then send a session id with every call, which meant a second server copy behind a load balancer would reject calls that landed on it. The new revision removes both: every request carries its own protocol version, client info and capabilities. My earlier post on migrating an MCP server to the stateless spec covers that change in depth; here it is just what lets this server be simple.
Clientno handshakeno session idInstance Arequest 2: 200 OKnever saw request 3Instance Brequest 3: 200 OKnever saw request 2Each request names its ownprotocol version, client andcapabilities in _meta.So any instance can answerany request, behind a plainround-robin balancer.
The diagram shows what the test in the next transcript proves: two separate server instances, a client that sent one request to each, and both answered. No instance needed to have seen the other’s request. Wiring is short. The tools go into a ToolsFeature, the feature into an McpServer, and the server into a servlet that Jetty hosts at /mcp. Source: CodeSearchServer.java:
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());
}
Two lines carry reasoning. The connector binds to 127.0.0.1 because this server hands out source code and has no authentication. And setAsyncSupported(true) is there because the SDK documentation asks for async support on the servlet; I also ran the wire test with that line removed and it still passed, so I do not know what, if anything, breaks without it. Here is the raw HTTP, from 05-wire.txt. The first call lists the tools; the second is a tools/call to instance A; the third sends the same call to instance B and compares the answers:
## 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
What the model sees: the tool definitions A tool definition is a name, a description and a JSON schema for its arguments, and that text is all the model has to decide when to call it. Spend your effort here. The descriptions say what the tool is for and when to use the other one (“Use find_usages for callers”), and the schema explains the argument format with an example. All three tools are marked readOnlyHint so a client can allow them without asking. This is CodeSearchTools.java:
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();
}
How the server rejects a malformed request The 2026-07-28 transport requires Mcp-Method and (for calls) Mcp-Name headers that must match the body, and each request must carry clientCapabilities in _meta. I found the last one the hard way: my first tools/list returned HTTP 400 with -32602 because I had left it out, and I added a case to the test so the message is on record. All four failures, from 06-wire-errors.txt:
What the request didHTTPJSON-RPC error
Mcp-Method header missing400-32020 Missing required header: Mcp-Method
Mcp-Name says find_usages, body calls search_code400-32020 Mcp-Name header does not match request name/uri
client still sends MCP-Protocol-Version: 2025-11-25400-32020 MCP-Protocol-Version header does not match _meta protocol version
_meta without clientCapabilities400-32602 _meta[‘io.modelcontextprotocol/clientCapabilities’] is required
The last transcript block, quoted verbatim:
## 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"}}
One thing the SDK warns about: a per-process key When the server starts, the SDK logs that no key is configured for its request-state codec, so it generated a random per-process key, and that state sealed by one instance cannot be opened by another. This server never uses request state (that is for multi-round-trip calls such as asking the user a question mid-call), so the warning does not affect it. If you add such a feature and run more than one instance, configure a shared key or the instances will reject each other’s state. The warning is in the committed transcript of the packaged jar, 10-fat-jar-curl.txt, line 2:
# 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:<port>/mcp

Going deeper

What an agent’s session looks like, and how the tools fail

The point of the three tools is that they chain: search by behaviour, read the callers of what you found, then read the one body you need. Here is that session, driven by the real 2.2.0 SDK client (not hand-written HTTP) in 07-sdk-client.txt. Note the middle step: the caller of refund comes back flagged, for the record-accessor reason from the usages section:
## 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
A tool that fails should fail in a way the model can read and act on. A bad argument comes back as a normal tool result with isError set, and a message that says what to do next, not as a protocol error. A search that finds nothing is not an error; it is an empty answer with advice. From 08-tool-errors.txt:
# 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)
The handler that does this is small. All three tools go through it, so a thrown IllegalArgumentException becomes a readable error result; from CodeSearchTools.java:
/** A failure the model can read and act on is a tool result with isError, not a protocol error. */
private static McpSyncResponse<CallToolOutcome> run(java.util.function.Supplier<String> 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);
}
Run the packaged jar and call it with curl The module builds a fat jar with the Maven shade plugin (the services transformer matters: without it the SDK cannot find its JSON mapper). scripts/curl-demo.sh starts the jar on a port, waits for it, and calls search_code with plain curl. The output, from 10-fat-jar-curl.txt:
indexed 30 units from sample-monorepo with the hashing-512 embedder
serving MCP 2026-07-28 at http://127.0.0.1:<port>/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.
To use it from a real client, point the client at http://127.0.0.1:8765/mcp after java -jar target/code-search-mcp.jar <monorepo-root>. I tested only the Java SDK client and curl. I did not connect Claude Code, Claude Desktop or any other client, and clients that still speak only the 2025 protocol are refused (the third wire case above).

Going deeper

Should you build this, and what to lock down first

Be honest about whether you need it. If your agent can already run grep and your repository is small or well named, a search-by-meaning tool will add little, and the hashing embedder here will not beat grep on vocabulary it has never seen. A language server finds references more completely than this finder. Build this when the vocabulary mismatch is real (people ask in business terms, the code uses technical ones), when you want one small read-only interface for many clients, or as a base to swap a real embedding model into. I measured none of that on a real monorepo: everything above is on a four-module sample I wrote.
Security: this server hands out your source code The server has no authentication, and it returns source. It binds to loopback for that reason. Before you expose it to a network, put authentication in front of it (OAuth2 with a scope per tool is the pattern in Securing an MCP Server with Spring Security 7), keep the tools read-only, and think about what is in the repository: a monorepo often contains configuration with secrets, and a search tool will happily return them. Tool descriptions and tool results are also text an attacker may influence if your repository accepts outside contributions, which makes a code-search tool an injection path into the agent; the post on prompt injection defence covers that. Per the SDK’s documentation, the server rejects requests that carry an Origin header by default, which blocks browser pages from calling a local server; I did not test that, but it is a default worth leaving on.
What I would change before using it on a real repository Persist the index instead of rebuilding it at startup, and re-index only changed files. Index test sources separately. Cap the size of a get_source result. Add a list_modules tool so an agent can orient itself. Replace the usage finder with a language-server call if you already run one. And measure retrieval quality with a golden set of questions before trusting any embedder, including the one you swap in.

Run it yourself

You need JDK 25 and Maven. From a clone of the repository:
export JAVA_HOME=/path/to/jdk-25
mvn test -pl code-search-mcp                 # tests write output/01 to 09
bash code-search-mcp/scripts/run-all.sh      # also builds the jar and writes output/10
java -jar code-search-mcp/target/code-search-mcp.jar <monorepo-root> [port]
Those commands are in README.md and scripts/run-all.sh. Every file in output/ is regenerated by them, and the tests that write each file also assert the facts quoted above, so the build fails if a number in this post stops being true.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.