connect MCP language queries to project LSP

This commit is contained in:
2026-09-29 09:21:59 +01:00
parent feb57c5298
commit c1834bad1f
24 changed files with 757 additions and 21 deletions
@@ -0,0 +1,245 @@
package p.studio.app.lsp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.lsp4j.*;
import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.launch.LSPLauncher;
import org.eclipse.lsp4j.services.*;
import p.studio.api.automation.*;
import p.studio.api.project.ProjectCatalog;
import p.studio.core.language.LanguageQueryPort;
import p.studio.lsp.api.LspServerLifecycle;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/** A real client of the already-running project LSP. Each query owns and closes its connection. */
public final class AutomationLspQueries implements LanguageQueryPort {
private final LspServerLifecycle lifecycle;
private final ProjectCatalog projects;
private final ProjectKnowledge knowledge;
private final ObjectMapper mapper;
private final com.google.gson.Gson gson = new MessageJsonHandler(Map.of()).getGson();
private final Map<TaskIdentity, Map<String, CallHierarchyItem>> items = new ConcurrentHashMap<>();
private static final Set<String> OPERATIONS = Set.of("diagnostics", "completion", "hover", "signatureHelp", "definition",
"references", "documentSymbols", "workspaceSymbols", "prepareRename", "rename", "codeActions", "formatting",
"documentLinks", "foldingRanges", "selectionRanges", "prepareCallHierarchy", "incomingCalls", "outgoingCalls", "semanticTokens");
private static final Set<String> EDITS = Set.of("completion", "prepareRename", "rename", "codeActions", "formatting");
public AutomationLspQueries(LspServerLifecycle lifecycle, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) {
this.lifecycle = lifecycle; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper;
}
@Override public void endTask(TaskIdentity task) { items.remove(task); }
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> parameters) throws Exception {
if (!OPERATIONS.contains(operation)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "Unsupported language operation: " + operation);
var context = knowledge.context(task.projectRoot());
var primary = context.languages().stream().filter(ProjectKnowledge.Language::primary).findFirst().orElseThrow();
if (primary.capabilities().stream().anyMatch(cap -> cap.name().equals("lsp") && cap.support() != ProjectKnowledge.Support.SUPPORTED))
throw failure(AutomationFailure.Code.UNSUPPORTED_LANGUAGE, "Project language has no available LSP");
var project = projects.openProject(context.projectRoot());
var binding = LspLifecycleAdapter.context(project);
var endpoint = lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Project LSP is not running; reopen the project if its language changed"));
var params = mapper.valueToTree(parameters);
CallHierarchyItem item = null;
String uri = null;
if (operation.equals("incomingCalls") || operation.equals("outgoingCalls")) {
item = items.getOrDefault(task, Map.of()).get(params.path("itemId").asText());
if (item == null) throw new IllegalArgumentException("Unknown task-local hierarchy itemId");
uri = item.getUri();
} else if (!operation.equals("workspaceSymbols")) {
uri = params.path("uri").asText(null);
if (uri == null) throw new IllegalArgumentException("uri is required");
}
Path document = uri == null ? null : sourcePath(context, uri);
if (document != null && EDITS.contains(operation)) requireEditable(context, document.toUri().toString());
String source = null;
if (document != null) {
try (var input = Files.newInputStream(document)) {
var bytes = input.readNBytes(4 * 1024 * 1024 + 1);
if (bytes.length > 4 * 1024 * 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Source document exceeds 4 MiB");
source = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
}
uri = document.toUri().toString();
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
var workers = Executors.newCachedThreadPool(r -> { var thread = new Thread(r, "studio-automation-lsp"); thread.setDaemon(true); return thread; });
try (var socket = new Socket()) {
if (!InetAddress.getByName(endpoint.host()).isLoopbackAddress()) throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Project LSP endpoint is not local");
socket.connect(new InetSocketAddress(endpoint.host(), endpoint.port()), 2000);
var diagnostics = new CompletableFuture<List<Diagnostic>>();
String expectedUri = uri;
LanguageClient client = new LanguageClient() {
public void telemetryEvent(Object event) {}
public void publishDiagnostics(PublishDiagnosticsParams event) { if (Objects.equals(event.getUri(), expectedUri)) diagnostics.complete(List.copyOf(event.getDiagnostics())); }
public void showMessage(MessageParams message) {}
public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams request) { return CompletableFuture.completedFuture(null); }
public void logMessage(MessageParams message) {}
@Override public CompletableFuture<ApplyWorkspaceEditResponse> applyEdit(ApplyWorkspaceEditParams edit) {
return CompletableFuture.completedFuture(new ApplyWorkspaceEditResponse(false));
}
};
var launcher = LSPLauncher.createClientLauncher(client, socket.getInputStream(), socket.getOutputStream(), workers, consumer -> consumer);
var listening = launcher.startListening();
try {
var server = launcher.getRemoteProxy();
var initialize = new InitializeParams();
initialize.setRootUri(binding.projectRoot().toUri().toString());
initialize.setCapabilities(new ClientCapabilities());
var capabilities = await(server.initialize(initialize), deadline).getCapabilities();
server.initialized(new InitializedParams());
requireCapability(operation, capabilities);
List<Diagnostic> currentDiagnostics = List.of();
if (document != null) {
// Fresh client overlay contains exactly the saved UTF-8 file. Wait for analysis before querying.
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), 1, source)));
currentDiagnostics = await(diagnostics, deadline);
}
var text = server.getTextDocumentService();
var id = uri == null ? null : new TextDocumentIdentifier(uri);
Object result = switch (operation) {
case "diagnostics" -> currentDiagnostics;
case "hover" -> await(text.hover(new HoverParams(id, position(params.path("position"), source))), deadline);
case "completion" -> await(text.completion(new CompletionParams(id, position(params.path("position"), source))), deadline);
case "signatureHelp" -> await(text.signatureHelp(new SignatureHelpParams(id, position(params.path("position"), source))), deadline);
case "definition" -> await(text.definition(new DefinitionParams(id, position(params.path("position"), source))), deadline);
case "references" -> await(text.references(new ReferenceParams(id, position(params.path("position"), source), new ReferenceContext(params.path("includeDeclaration").asBoolean(false)))), deadline);
case "documentSymbols" -> await(text.documentSymbol(new DocumentSymbolParams(id)), deadline);
case "workspaceSymbols" -> await(server.getWorkspaceService().symbol(new WorkspaceSymbolParams(params.path("query").asText(""))), deadline);
case "prepareRename" -> await(text.prepareRename(new PrepareRenameParams(id, position(params.path("position"), source))), deadline);
case "rename" -> {
String name = params.path("newName").asText("");
if (name.isBlank()) throw new IllegalArgumentException("newName is required");
yield await(text.rename(new RenameParams(id, position(params.path("position"), source), name)), deadline);
}
case "formatting" -> await(text.formatting(new DocumentFormattingParams(id, new FormattingOptions(4, true))), deadline);
case "codeActions" -> await(text.codeAction(new CodeActionParams(id,
range(params.path("range"), source),
new CodeActionContext(currentDiagnostics))), deadline);
case "documentLinks" -> await(text.documentLink(new DocumentLinkParams(id)), deadline);
case "foldingRanges" -> await(text.foldingRange(new FoldingRangeRequestParams(id)), deadline);
case "selectionRanges" -> {
if (!params.path("positions").isArray() || params.path("positions").isEmpty()) throw new IllegalArgumentException("positions are required");
var positions = new ArrayList<Position>();
for (var p : params.path("positions")) positions.add(position(p, source));
yield await(text.selectionRange(new SelectionRangeParams(id, positions)), deadline);
}
case "prepareCallHierarchy" -> await(text.prepareCallHierarchy(new CallHierarchyPrepareParams(id, position(params.path("position"), source))), deadline);
case "incomingCalls" -> await(text.callHierarchyIncomingCalls(new CallHierarchyIncomingCallsParams(item)), deadline);
case "outgoingCalls" -> await(text.callHierarchyOutgoingCalls(new CallHierarchyOutgoingCallsParams(item)), deadline);
case "semanticTokens" -> await(text.semanticTokensFull(new SemanticTokensParams(id)), deadline);
default -> throw new IllegalArgumentException("Unsupported operation");
};
var wire = mapper.readTree(gson.toJson(result));
validateEdits(context, wire);
var limitations = new ArrayList<String>();
if (operation.equals("codeActions") && wire.isArray()) {
for (var action : wire) if (action.has("command")) {
((com.fasterxml.jackson.databind.node.ObjectNode) action).remove("command");
limitations.add("Executable LSP commands are not exposed; only edit proposals are returned");
}
}
if (operation.equals("prepareCallHierarchy") || operation.equals("incomingCalls") || operation.equals("outgoingCalls")) addItemIds(task, wire);
var output = new LinkedHashMap<String, Object>();
output.put("operation", operation); output.put("result", mapper.convertValue(wire, Object.class));
output.put("limitations", limitations);
return Collections.unmodifiableMap(output);
} finally { listening.cancel(true); }
} finally { workers.shutdownNow(); }
}
private void addItemIds(TaskIdentity task, com.fasterxml.jackson.databind.JsonNode node) {
if (node.isObject() && node.has("uri") && node.has("selectionRange") && node.has("name") && node.has("kind")) {
var stored = items.computeIfAbsent(task, ignored -> new ConcurrentHashMap<>());
if (stored.size() >= 1024) throw failure(AutomationFailure.Code.LIMIT_EXCEEDED, "Too many hierarchy items for this task");
String key = UUID.randomUUID().toString();
stored.put(key, gson.fromJson(node.toString(), CallHierarchyItem.class));
((com.fasterxml.jackson.databind.node.ObjectNode) node).put("itemId", key);
} else if (node.isContainerNode()) node.forEach(child -> addItemIds(task, child));
}
private static void requireCapability(String operation, ServerCapabilities caps) {
Object capability = switch (operation) {
case "diagnostics" -> caps.getTextDocumentSync();
case "hover" -> caps.getHoverProvider(); case "completion" -> caps.getCompletionProvider();
case "signatureHelp" -> caps.getSignatureHelpProvider(); case "definition" -> caps.getDefinitionProvider();
case "references" -> caps.getReferencesProvider(); case "documentSymbols" -> caps.getDocumentSymbolProvider();
case "workspaceSymbols" -> caps.getWorkspaceSymbolProvider(); case "rename", "prepareRename" -> caps.getRenameProvider();
case "codeActions" -> caps.getCodeActionProvider(); case "formatting" -> caps.getDocumentFormattingProvider();
case "documentLinks" -> caps.getDocumentLinkProvider(); case "foldingRanges" -> caps.getFoldingRangeProvider();
case "selectionRanges" -> caps.getSelectionRangeProvider(); case "prepareCallHierarchy", "incomingCalls", "outgoingCalls" -> caps.getCallHierarchyProvider();
case "semanticTokens" -> caps.getSemanticTokensProvider(); default -> null;
};
if (capability instanceof Either<?, ?> either) capability = either.isLeft() ? either.getLeft() : either.getRight();
if (operation.equals("prepareRename") && (!(capability instanceof RenameOptions options) || !Boolean.TRUE.equals(options.getPrepareProvider())))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise prepareRename");
if (capability == null || Boolean.FALSE.equals(capability)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP does not advertise " + operation);
}
private static Position position(com.fasterxml.jackson.databind.JsonNode node, String text) {
if (!node.path("line").isIntegralNumber() || !node.path("character").isIntegralNumber()
|| !node.path("line").canConvertToInt() || !node.path("character").canConvertToInt()) throw new IllegalArgumentException("UTF-16 position is required");
int line = node.path("line").intValue(), character = node.path("character").intValue();
String[] lines = text.split("\\r\\n|\\n|\\r", -1);
if (line < 0 || line >= lines.length || character < 0 || character > lines[line].length()
|| character > 0 && character < lines[line].length() && Character.isHighSurrogate(lines[line].charAt(character - 1)) && Character.isLowSurrogate(lines[line].charAt(character)))
throw new IllegalArgumentException("Position is outside the saved document or splits a UTF-16 pair");
return new Position(line, character);
}
private static Range range(com.fasterxml.jackson.databind.JsonNode node, String text) {
var start = position(node.path("start"), text); var end = position(node.path("end"), text);
if (start.getLine() > end.getLine() || start.getLine() == end.getLine() && start.getCharacter() > end.getCharacter())
throw new IllegalArgumentException("Range end precedes its start");
return new Range(start, end);
}
private static Path sourcePath(ProjectKnowledge.Context context, String uri) throws Exception {
final Path path;
try { path = Path.of(URI.create(uri)).toRealPath(); }
catch (RuntimeException | java.io.IOException invalid) { throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Source URI is not an accessible local project/dependency file"); }
boolean scope = path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith)
|| context.libraries().stream().flatMap(lib -> lib.roots().stream()).anyMatch(path::startsWith);
boolean source = context.languages().stream().flatMap(lang -> lang.extensions().stream()).anyMatch(extension -> path.getFileName().toString().endsWith("." + extension));
if (!scope || !source || !Files.isRegularFile(path)) throw failure(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "URI is outside the known source scope");
return path;
}
private static void requireEditable(ProjectKnowledge.Context context, String uri) throws Exception {
Path path = sourcePath(context, uri);
if (!path.startsWith(context.projectRoot()) || context.readOnlyRoots().stream().anyMatch(path::startsWith))
throw failure(AutomationFailure.Code.READ_ONLY_SCOPE, "LSP edit proposal targets a read-only SDK/dependency");
}
private static void validateEdits(ProjectKnowledge.Context context, com.fasterxml.jackson.databind.JsonNode node) throws Exception {
if (node.isObject()) {
if (node.has("changes")) {
var fields = node.path("changes").fieldNames();
while (fields.hasNext()) requireEditable(context, fields.next());
}
if (node.has("textDocument") && node.has("edits")) requireEditable(context, node.path("textDocument").path("uri").asText());
if (node.has("kind") && Set.of("create", "rename", "delete").contains(node.path("kind").asText()))
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "LSP file operations are not exposed");
}
if (node.isContainerNode()) for (var child : node) validateEdits(context, child);
}
private static <T> T await(CompletableFuture<T> future, long deadline) throws Exception {
try { return future.get(Math.max(1, deadline - System.nanoTime()), TimeUnit.NANOSECONDS); }
catch (ExecutionException failure) {
if (failure.getCause() instanceof org.eclipse.lsp4j.jsonrpc.ResponseErrorException response) {
int code = response.getResponseError().getCode();
if (code == -32602) throw new IllegalArgumentException("LSP rejected query parameters");
if (code == -32601 || code == -32600)
throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, response.getResponseError().getMessage());
}
throw failure;
}
catch (Exception failure) { future.cancel(true); throw failure; }
}
private static AutomationException failure(AutomationFailure.Code code, String message) { return new AutomationException(code, message); }
}