Add code-search-mcp module: JavaParser index, swappable embedder and three MCP tools on the 2026-07-28 stateless spec (MCP Java SDK 2.2.0)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6BHcz4muRH44T3br3
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
26e0a3875a
commit
e116c4d5a4
@@ -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<CompilationUnit> units = new ArrayList<>();
|
||||
private final List<CodeUnit> codeUnits = new ArrayList<>();
|
||||
private final List<String> 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<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;
|
||||
}
|
||||
|
||||
private List<Path> findSourceRoots() throws IOException {
|
||||
try (Stream<Path> 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<CompilationUnit> compilationUnits() { return List.copyOf(units); }
|
||||
public List<CodeUnit> codeUnits() { return List.copyOf(codeUnits); }
|
||||
public List<String> parseProblems() { return List.copyOf(parseProblems); }
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, McpSyncTool> 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<VectorIndex.Hit> 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<CodeUnit> 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<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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<float[]> embedAll(List<String> texts) {
|
||||
return texts.stream().map(this::embed).toList();
|
||||
}
|
||||
|
||||
/** A short name for logs and transcripts. */
|
||||
String name();
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>This is the "hashing trick". It matches <em>words</em>, not <em>meaning</em>: "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<String> 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<String> 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<String> words(String text) {
|
||||
String spaced = text
|
||||
.replaceAll("([a-z0-9])([A-Z])", "$1 $2")
|
||||
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2");
|
||||
List<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ankurm.codesearch;
|
||||
|
||||
/**
|
||||
* {@code java -jar code-search-mcp.jar <monorepo-root> [port]}. Indexes every {@code src/main/java} folder under
|
||||
* the root and serves MCP 2026-07-28 at {@code http://127.0.0.1:<port>/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 <monorepo-root> [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();
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<float[]> embedAll(List<String> texts) {
|
||||
List<float[]> 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<float[]> request(List<String> batch) {
|
||||
try {
|
||||
// LinkedHashMap, not Map.of: Map.of iterates in a per-JVM random order, which makes request bytes unstable.
|
||||
Map<String, Object> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>Two modes, because the cheap one is wrong in a useful way:
|
||||
* <ul>
|
||||
* <li><b>name</b> 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.</li>
|
||||
* <li><b>resolved</b> asks JavaParser's symbol solver which declaration each call really binds to. A call the
|
||||
* solver rules out is dropped. A call it <em>cannot</em> 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.</li>
|
||||
* </ul>
|
||||
*/
|
||||
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<Usage> usages, int unresolved) {}
|
||||
|
||||
private final List<CompilationUnit> 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<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]);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<CodeUnit> units;
|
||||
private final List<float[]> vectors;
|
||||
|
||||
public VectorIndex(Embedder embedder, List<CodeUnit> 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<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()));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user