connect MCP language queries to project LSP
This commit is contained in:
@@ -30,9 +30,10 @@ class StudioApplicationConfigurationTest {
|
||||
assertFalse(executor.isShutdown());
|
||||
assertTrue(mcp.isRunning());
|
||||
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
|
||||
org.junit.jupiter.api.Assertions.assertEquals(2, tools.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals(3, tools.size());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
|
||||
org.junit.jupiter.api.Assertions.assertEquals("studio_language_query", tools.get(2).path("name").asText());
|
||||
}
|
||||
assertTrue(executor.isShutdown());
|
||||
assertFalse(mcp.isRunning());
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
package p.studio.app.lsp;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.session.ProjectSession;
|
||||
import p.studio.app.compiler.CompilerProjectKnowledge;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.language.TaskLanguageQueries;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.session.DefaultProjectSessionFactory;
|
||||
import p.studio.lsp.services.LspServerLifecycleImpl;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AutomationLspQueriesTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ExecutorService workers = Executors.newCachedThreadPool();
|
||||
final LspServerLifecycleImpl lifecycle = new LspServerLifecycleImpl();
|
||||
ProjectSession session;
|
||||
TaskLanguageQueries queries;
|
||||
final ProjectAccessRegistry access = new ProjectAccessRegistry();
|
||||
Path root, source;
|
||||
String task;
|
||||
static final String CODE = "fn helper() -> int { return 1; }\nfn main() -> int { return helper(); }\n";
|
||||
|
||||
@BeforeEach void open() throws Exception {
|
||||
root = Files.createDirectory(temporary.resolve("app")).toRealPath();
|
||||
source = Files.createDirectories(root.resolve("src")).resolve("main.pbs");
|
||||
manifest(root, "app", List.of());
|
||||
Files.writeString(source, CODE);
|
||||
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn helper() -> int;\npub fn main() -> int;\n");
|
||||
var setup = new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog = new ProjectCatalogService(temporary, mapper, setup);
|
||||
session = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup,
|
||||
new LspLifecycleAdapter(lifecycle), access, new ExecutorOperationExecutor(workers)).open(catalog.openProject(root));
|
||||
var knowledge = new CompilerProjectKnowledge(access, catalog, mapper);
|
||||
queries = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle, catalog, knowledge, mapper));
|
||||
}
|
||||
@AfterEach void close() { if (session != null) session.close(); workers.shutdownNow(); }
|
||||
void acquire() {
|
||||
assertTrue(session.automation().grant(false).toCompletableFuture().join().success());
|
||||
task = session.automation().acquire().task().value();
|
||||
}
|
||||
JsonNode query(String operation, Map<String, Object> parameters) {
|
||||
return mapper.valueToTree(queries.query(root, task, operation, parameters));
|
||||
}
|
||||
Map<String, Object> at(int line, int character) {
|
||||
return Map.of("uri", source.toUri().toString(), "position", Map.of("line", line, "character", character));
|
||||
}
|
||||
@Test void diagnosticsAndNavigationSeeSavedChangesOverTheActualServer() throws Exception {
|
||||
acquire();
|
||||
assertTrue(query("diagnostics", at(0, 0)).path("result").isArray());
|
||||
var definition = query("definition", at(1, 26)).path("result");
|
||||
assertFalse(definition.isEmpty(), definition.toString());
|
||||
assertEquals(source.toUri().toString(), definition.get(0).path("uri").asText());
|
||||
Files.writeString(source, "fn main( {");
|
||||
assertFalse(query("diagnostics", at(0, 0)).path("result").isEmpty());
|
||||
Files.writeString(source, CODE.replace("helper", "renamed"));
|
||||
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn renamed() -> int;\npub fn main() -> int;\n");
|
||||
var symbols = query("documentSymbols", at(0, 0)).path("result");
|
||||
assertTrue(symbols.toString().contains("renamed"), symbols.toString());
|
||||
assertFalse(symbols.toString().contains("helper"), symbols.toString());
|
||||
}
|
||||
@Test void proposalsDoNotWriteFilesAndQueriesCoverAdvertisedOperations() throws Exception {
|
||||
acquire();
|
||||
for (String operation : List.of("hover", "completion", "signatureHelp", "references", "prepareRename", "semanticTokens"))
|
||||
assertEquals(operation, query(operation, at(1, 26)).path("operation").asText());
|
||||
for (String operation : List.of("documentLinks", "foldingRanges", "formatting"))
|
||||
assertEquals(operation, query(operation, at(0, 0)).path("operation").asText());
|
||||
assertEquals("workspaceSymbols", query("workspaceSymbols", Map.of("query", "helper")).path("operation").asText());
|
||||
var rename = new HashMap<>(at(1, 26)); rename.put("newName", "renamed");
|
||||
assertTrue(query("rename", rename).path("result").has("changes"));
|
||||
assertEquals(CODE, Files.readString(source));
|
||||
var selections = Map.<String, Object>of("uri", source.toUri().toString(), "positions", List.of(Map.of("line", 0, "character", 4)));
|
||||
assertEquals("selectionRanges", query("selectionRanges", selections).path("operation").asText());
|
||||
var actions = Map.<String, Object>of("uri", source.toUri().toString(), "range", Map.of("start", Map.of("line", 0, "character", 0), "end", Map.of("line", 0, "character", 10)));
|
||||
assertEquals("codeActions", query("codeActions", actions).path("operation").asText());
|
||||
}
|
||||
@Test void hierarchyIdsBelongToTheTaskAndDisappearOnReturn() {
|
||||
acquire();
|
||||
var prepared = query("prepareCallHierarchy", at(0, 4)).path("result");
|
||||
assertFalse(prepared.isEmpty(), prepared.toString());
|
||||
String id = prepared.get(0).path("itemId").asText();
|
||||
assertFalse(id.isBlank());
|
||||
assertFalse(query("incomingCalls", Map.of("itemId", id)).path("result").isEmpty());
|
||||
assertEquals("outgoingCalls", query("outgoingCalls", Map.of("itemId", id)).path("operation").asText());
|
||||
session.automation().reclaim().toCompletableFuture().join();
|
||||
acquire();
|
||||
assertThrows(IllegalArgumentException.class, () -> query("incomingCalls", Map.of("itemId", id)));
|
||||
}
|
||||
@Test void admissionUnsupportedOperationsAndSourceScopeAreExplicit() throws Exception {
|
||||
assertThrows(ControlDeniedException.class, () -> queries.query(root, "ungranted", "diagnostics", at(0, 0)));
|
||||
acquire();
|
||||
assertThrows(ControlDeniedException.class, () -> queries.query(root, "wrong-task", "diagnostics", at(0, 0)));
|
||||
assertEquals(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, assertThrows(AutomationException.class,
|
||||
() -> query("typeHierarchy", at(0, 0))).failure().code());
|
||||
Path outside = temporary.resolve("outside.pbs"); Files.writeString(outside, CODE);
|
||||
assertEquals(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, assertThrows(AutomationException.class,
|
||||
() -> query("diagnostics", Map.of("uri", outside.toUri().toString()))).failure().code());
|
||||
assertThrows(IllegalArgumentException.class, () -> query("definition", at(999, 0)));
|
||||
var context = LspLifecycleAdapter.context(session.projectReference());
|
||||
var endpoint = lifecycle.endpoint(context).orElseThrow();
|
||||
session.close(); session = null;
|
||||
assertTrue(lifecycle.endpoint(context).isEmpty());
|
||||
assertThrows(java.io.IOException.class, () -> new java.net.Socket(endpoint.host(), endpoint.port()));
|
||||
assertEquals(AutomationFailure.Code.PROJECT_NOT_OPEN, assertThrows(AutomationException.class,
|
||||
() -> query("diagnostics", at(0, 0))).failure().code());
|
||||
}
|
||||
|
||||
@Test void mcpDispatchPreservesTaskFailuresAndReturnsNeutralLspResults() {
|
||||
var tools = new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper), mapper,
|
||||
p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper));
|
||||
var arguments = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "missing").put("operation", "diagnostics");
|
||||
arguments.putObject("parameters").put("uri", source.toUri().toString());
|
||||
var denied = tools.call("studio_language_query", arguments).wire();
|
||||
assertEquals("INVALID_TASK", denied.path("structuredContent").path("error").path("code").asText());
|
||||
acquire(); arguments.put("taskId", task);
|
||||
var success = tools.call("studio_language_query", arguments).wire();
|
||||
assertFalse(success.path("isError").asBoolean(), success.toString());
|
||||
assertTrue(success.path("structuredContent").path("value").path("result").isArray());
|
||||
session.automation().reclaim().toCompletableFuture().join();
|
||||
assertEquals("INVALID_TASK", tools.call("studio_language_query", arguments).wire().path("structuredContent").path("error").path("code").asText());
|
||||
}
|
||||
|
||||
@Test void authenticatedHttpToolUsesTheRealLspButDoesNotGrantTaskAuthority() throws Exception {
|
||||
var tools = new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper), mapper,
|
||||
p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper));
|
||||
try (var server = new p.studio.app.mcp.LocalMcpServer(mapper, tools);
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
|
||||
var setup = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
setup.putObject("capabilities"); setup.putObject("clientInfo").put("name", "language-test").put("version", "1");
|
||||
String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized"));
|
||||
var request = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call");
|
||||
var args = request.putObject("params").put("name", "studio_language_query").putObject("arguments")
|
||||
.put("projectRoot", root.toString()).put("taskId", "ungranted").put("operation", "documentSymbols");
|
||||
args.putObject("parameters").put("uri", source.toUri().toString());
|
||||
var denied = mapper.readTree(post(client, server, connection, request).body()).path("result");
|
||||
assertEquals("INVALID_TASK", denied.path("structuredContent").path("error").path("code").asText());
|
||||
acquire(); args.put("taskId", task);
|
||||
var result = mapper.readTree(post(client, server, connection, request).body()).path("result");
|
||||
assertFalse(result.path("isError").asBoolean(), result.toString());
|
||||
assertTrue(result.path("structuredContent").path("value").path("result").toString().contains("helper"));
|
||||
}
|
||||
}
|
||||
|
||||
private java.net.http.HttpResponse<String> post(java.net.http.HttpClient client, p.studio.app.mcp.LocalMcpServer server,
|
||||
String connection, JsonNode body) throws Exception {
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(15))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
@Test void reclaimCancelsTheQueryAndEndsTaskResourcesAfterTheWorkerStops() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var stopped = new CountDownLatch(1);
|
||||
var cleaned = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var slow = new TaskLanguageQueries(access, new p.studio.core.language.LanguageQueryPort() {
|
||||
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> params) throws Exception {
|
||||
entered.countDown();
|
||||
try { new CountDownLatch(1).await(); return Map.of(); }
|
||||
finally { stopped.countDown(); }
|
||||
}
|
||||
@Override public void endTask(TaskIdentity task) { assertEquals(0, stopped.getCount()); cleaned.set(true); }
|
||||
});
|
||||
acquire();
|
||||
var pending = workers.submit(() -> slow.query(root, task, "diagnostics", at(0, 0)));
|
||||
assertTrue(entered.await(2, TimeUnit.SECONDS));
|
||||
assertEquals(ControlResult.Status.BUSY, assertThrows(ControlDeniedException.class,
|
||||
() -> queries.query(root, task, "diagnostics", at(0, 0))).status());
|
||||
assertTrue(session.automation().reclaim().toCompletableFuture().get(2, TimeUnit.SECONDS).success());
|
||||
assertThrows(ExecutionException.class, () -> pending.get(2, TimeUnit.SECONDS));
|
||||
assertTrue(cleaned.get());
|
||||
assertEquals(ControlState.MANUAL, session.automation().snapshot().state());
|
||||
}
|
||||
@Test void externalDependencyNavigationIsReadableButRefactoringIsReadOnly() throws Exception {
|
||||
Path lib = Files.createDirectories(temporary.resolve("lib")).toRealPath();
|
||||
manifest(lib, "lib", List.of());
|
||||
Path module = Files.createDirectories(lib.resolve("src/shared"));
|
||||
Path declaration = module.resolve("main.pbs");
|
||||
Files.writeString(declaration, "fn answer() -> int { return 42; }\n");
|
||||
Files.writeString(module.resolve("mod.barrel"), "pub fn answer() -> int;\n");
|
||||
manifest(root, "app", List.of(Map.of("path", "../lib")));
|
||||
Files.createDirectories(root.resolve(".workspace/repos")); Files.writeString(root.resolve(".workspace/repos/registry.json"), "{}");
|
||||
Files.writeString(source, "import { answer } from @lib:shared;\nfn main() -> int { return answer(); }\n");
|
||||
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn main() -> int;\n");
|
||||
acquire();
|
||||
var locations = query("definition", at(1, 26)).path("result");
|
||||
assertFalse(locations.isEmpty(), locations.toString());
|
||||
assertEquals(declaration.toUri().toString(), locations.get(0).path("uri").asText());
|
||||
assertEquals("documentSymbols", query("documentSymbols", Map.of("uri", declaration.toUri().toString())).path("operation").asText());
|
||||
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class,
|
||||
() -> query("formatting", Map.of("uri", declaration.toUri().toString()))).failure().code());
|
||||
var rename = new HashMap<>(at(1, 26)); rename.put("newName", "renamed");
|
||||
assertEquals(AutomationFailure.Code.READ_ONLY_SCOPE, assertThrows(AutomationException.class, () -> query("rename", rename)).failure().code());
|
||||
}
|
||||
private void manifest(Path path, String name, List<?> dependencies) throws Exception {
|
||||
mapper.writeValue(path.resolve("prometeu.json").toFile(), Map.of("name", name, "version", "1.0.0", "language", "pbs", "stdlib", "1", "target", "Game", "dependencies", dependencies));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user