feat(mcp): expose language operation discovery contract
This commit is contained in:
@@ -26,6 +26,7 @@ class AutomationLspQueriesTest {
|
||||
final LspServerLifecycleImpl lifecycle = new LspServerLifecycleImpl();
|
||||
ProjectSession session;
|
||||
TaskLanguageQueries queries;
|
||||
ProjectKnowledge knowledge;
|
||||
final ProjectAccessRegistry access = new ProjectAccessRegistry();
|
||||
Path root, source;
|
||||
String task;
|
||||
@@ -41,7 +42,7 @@ class AutomationLspQueriesTest {
|
||||
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);
|
||||
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(); }
|
||||
@@ -183,12 +184,71 @@ class AutomationLspQueriesTest {
|
||||
acquire();
|
||||
assertThrows(IllegalArgumentException.class, () -> query("incomingCalls", Map.of("itemId", id)));
|
||||
}
|
||||
@Test void discoveredOperationsReachTheRealServerThroughMcpValidation() throws Exception {
|
||||
var catalog = new p.studio.app.mcp.McpToolCatalog(mapper);
|
||||
var handlers = new HashMap<>(p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper));
|
||||
handlers.putAll(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper));
|
||||
var tools = new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers);
|
||||
var context = tools.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()))
|
||||
.wire().path("structuredContent").path("value");
|
||||
assertEquals(catalog.languageQueryDescription(), context.path("languageQuery"));
|
||||
assertEquals(20, context.path("languageQuery").path("operations").size());
|
||||
assertEquals(ControlState.MANUAL, session.automation().snapshot().state());
|
||||
acquire();
|
||||
// Obtain an actual task-owned URI using the same MCP entry point.
|
||||
var sdkSource = source.resolveSibling("sdk.pbs");
|
||||
var sdkFunction = "fn sdk() -> void { Gfx.clear(0); }";
|
||||
Files.writeString(sdkSource, "import { Gfx } from @sdk:gfx;\n" + sdkFunction + "\n");
|
||||
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn helper() -> int;\npub fn main() -> int;\npub fn sdk() -> void;\n");
|
||||
String externalUri = mcpQuery(tools, "definition", Map.of("uri", sdkSource.toUri().toString(),
|
||||
"position", Map.of("line", 1, "character", sdkFunction.indexOf("clear") + 1)))
|
||||
.path("result").get(0).path("uri").asText();
|
||||
assertTrue(externalUri.startsWith("prometeu-source:"));
|
||||
String itemId = mcpQuery(tools, "prepareCallHierarchy", at(0, 4)).path("result").get(0).path("itemId").asText();
|
||||
var values = new HashMap<>(at(1, 26));
|
||||
values.put("newName", "renamed"); values.put("itemId", itemId);
|
||||
values.put("positions", List.of(Map.of("line", 0, "character", 4)));
|
||||
values.put("range", Map.of("start", Map.of("line", 0, "character", 0), "end", Map.of("line", 0, "character", 10)));
|
||||
var invoked = new HashSet<String>();
|
||||
for (var operation : context.path("languageQuery").path("operations")) {
|
||||
String name = operation.path("operation").asText();
|
||||
assertTrue(invoked.add(name), name);
|
||||
var parameters = new HashMap<String, Object>();
|
||||
operation.path("requiredParameters").forEach(key -> parameters.put(key.asText(), values.get(key.asText())));
|
||||
if (name.equals("readExternalSource")) parameters.put("uri", externalUri);
|
||||
assertEquals(name, mcpQuery(tools, name, parameters).path("operation").asText());
|
||||
}
|
||||
assertEquals(20, invoked.size());
|
||||
assertEquals(CODE, Files.readString(source), "Query proposals must never write files");
|
||||
session.automation().reclaim().toCompletableFuture().join(); acquire();
|
||||
assertThrows(IllegalArgumentException.class, () -> mcpQuery(tools, "incomingCalls", Map.of("itemId", itemId)));
|
||||
}
|
||||
|
||||
private JsonNode mcpQuery(p.studio.app.mcp.McpToolRegistry tools, String operation, Map<String, Object> parameters) {
|
||||
var arguments = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", task).put("operation", operation);
|
||||
arguments.set("parameters", mapper.valueToTree(parameters));
|
||||
var reply = tools.call("studio_language_query", arguments).wire();
|
||||
assertFalse(reply.path("isError").asBoolean(), operation + ": " + reply);
|
||||
return reply.path("structuredContent").path("value");
|
||||
}
|
||||
|
||||
@Test void savedUtf16PositionsAndOrderedRangesAreValidatedByTheRealAdapter() throws Exception {
|
||||
Files.writeString(source, "// 😀\r\n" + CODE); acquire();
|
||||
// The emoji occupies UTF-16 offsets 3 and 4; offset 4 splits its pair.
|
||||
assertEquals("hover", query("hover", at(0, 5)).path("operation").asText());
|
||||
assertThrows(IllegalArgumentException.class, () -> query("hover", at(0, 4)));
|
||||
assertThrows(IllegalArgumentException.class, () -> query("hover", at(0, 6)));
|
||||
var parameters = Map.<String, Object>of("uri", source.toUri().toString(),
|
||||
"range", Map.of("start", Map.of("line", 1, "character", 10), "end", Map.of("line", 1, "character", 0)));
|
||||
assertThrows(IllegalArgumentException.class, () -> query("codeActions", parameters));
|
||||
}
|
||||
@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());
|
||||
for (String operation : List.of("callHierarchy", "typeHierarchy"))
|
||||
assertEquals(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, assertThrows(AutomationException.class,
|
||||
() -> query(operation, 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());
|
||||
@@ -218,8 +278,9 @@ class AutomationLspQueriesTest {
|
||||
}
|
||||
|
||||
@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));
|
||||
var handlers = new HashMap<>(p.studio.app.mcp.McpLanguageTools.handlers(queries, mapper));
|
||||
handlers.putAll(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper));
|
||||
var tools = new p.studio.app.mcp.McpToolRegistry(new p.studio.app.mcp.McpToolCatalog(mapper), mapper, handlers);
|
||||
try (var server = new p.studio.app.mcp.LocalMcpServer(mapper, tools);
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
@@ -228,8 +289,27 @@ class AutomationLspQueriesTest {
|
||||
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();
|
||||
var initialized = post(client, server, null, initialize);
|
||||
assertTrue(mapper.readTree(initialized.body()).path("result").path("instructions").asText().contains("languageQuery"));
|
||||
String connection = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized"));
|
||||
var list = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 10).put("method", "tools/list");
|
||||
JsonNode languageDescriptor = null;
|
||||
for (var descriptor : mapper.readTree(post(client, server, connection, list).body()).path("result").path("tools"))
|
||||
if (descriptor.path("name").asText().equals("studio_language_query")) languageDescriptor = descriptor;
|
||||
assertNotNull(languageDescriptor);
|
||||
assertEquals(20, languageDescriptor.path("inputSchema").path("properties").path("operation").path("enum").size());
|
||||
var contextRequest = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 11).put("method", "tools/call");
|
||||
contextRequest.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString());
|
||||
var context = mapper.readTree(post(client, server, connection, contextRequest).body()).path("result").path("structuredContent").path("value");
|
||||
assertEquals(languageDescriptor.path("inputSchema").path("properties").path("parameters"), context.path("languageQuery").path("parametersSchema"));
|
||||
JsonNode symbols = null;
|
||||
for (var operation : context.path("languageQuery").path("operations"))
|
||||
if (operation.path("operation").asText().equals("documentSymbols")) symbols = operation;
|
||||
assertNotNull(symbols);
|
||||
assertEquals(mapper.valueToTree(List.of("uri")), symbols.path("requiredParameters"));
|
||||
assertEquals("documentSymbols", symbols.path("capability").asText());
|
||||
assertEquals(ControlState.MANUAL, session.automation().snapshot().state());
|
||||
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");
|
||||
@@ -240,6 +320,9 @@ class AutomationLspQueriesTest {
|
||||
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"));
|
||||
args.put("operation", "callHierarchy");
|
||||
var rejected = mapper.readTree(post(client, server, connection, request).body());
|
||||
assertEquals(-32602, rejected.path("error").path("code").asInt(), rejected.toString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,113 @@ class McpContractTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final McpToolCatalog catalog = new McpToolCatalog(mapper);
|
||||
|
||||
@Test void languageOperationsExposeAndEnforceTheirRequiredParameters() {
|
||||
var required = Map.ofEntries(
|
||||
Map.entry("readExternalSource", List.of("uri")),
|
||||
Map.entry("diagnostics", List.of("uri")),
|
||||
Map.entry("completion", List.of("uri", "position")),
|
||||
Map.entry("hover", List.of("uri", "position")),
|
||||
Map.entry("signatureHelp", List.of("uri", "position")),
|
||||
Map.entry("definition", List.of("uri", "position")),
|
||||
Map.entry("references", List.of("uri", "position")),
|
||||
Map.entry("documentSymbols", List.of("uri")),
|
||||
Map.entry("workspaceSymbols", List.<String>of()),
|
||||
Map.entry("prepareRename", List.of("uri", "position")),
|
||||
Map.entry("rename", List.of("uri", "position", "newName")),
|
||||
Map.entry("codeActions", List.of("uri", "range")),
|
||||
Map.entry("formatting", List.of("uri")),
|
||||
Map.entry("documentLinks", List.of("uri")),
|
||||
Map.entry("foldingRanges", List.of("uri")),
|
||||
Map.entry("selectionRanges", List.of("uri", "positions")),
|
||||
Map.entry("prepareCallHierarchy", List.of("uri", "position")),
|
||||
Map.entry("incomingCalls", List.of("itemId")),
|
||||
Map.entry("outgoingCalls", List.of("itemId")),
|
||||
Map.entry("semanticTokens", List.of("uri")));
|
||||
var advertised = new HashSet<String>();
|
||||
var descriptor = catalog.descriptor("studio_language_query");
|
||||
descriptor.path("inputSchema").path("properties").path("operation").path("enum")
|
||||
.forEach(value -> assertTrue(advertised.add(value.asText())));
|
||||
assertEquals(required.keySet(), advertised);
|
||||
var discovery = catalog.languageQueryDescription();
|
||||
assertEquals(required.size(), discovery.path("operations").size());
|
||||
var described = new HashSet<String>();
|
||||
for (var operation : discovery.path("operations")) {
|
||||
String name = operation.path("operation").asText();
|
||||
assertTrue(described.add(name), name);
|
||||
assertEquals(mapper.valueToTree(required.get(name)), operation.path("requiredParameters"), name);
|
||||
assertFalse(operation.path("description").asText().isBlank(), name);
|
||||
var args = languageArguments(name);
|
||||
var parameters = args.putObject("parameters");
|
||||
var values = languageParameters();
|
||||
required.get(name).forEach(key -> parameters.set(key, values.get(key)));
|
||||
catalog.validateArguments("studio_language_query", args);
|
||||
ContractSchema.validate(discovery.path("parametersSchema"), parameters);
|
||||
ContractSchema.validate(operation.path("parametersSchema"), parameters);
|
||||
for (String key : required.get(name)) {
|
||||
var missing = args.deepCopy();
|
||||
((ObjectNode) missing.get("parameters")).remove(key);
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", missing), name + ": " + key);
|
||||
}
|
||||
// Existing clients may include known parameters unused by this operation.
|
||||
args.set("parameters", values);
|
||||
catalog.validateArguments("studio_language_query", args);
|
||||
}
|
||||
assertEquals(advertised, described);
|
||||
assertEquals("callHierarchy", capability(discovery, "prepareCallHierarchy"));
|
||||
assertEquals("callHierarchy", capability(discovery, "incomingCalls"));
|
||||
assertEquals("callHierarchy", capability(discovery, "outgoingCalls"));
|
||||
assertEquals("rename", capability(discovery, "prepareRename"));
|
||||
assertEquals("rename", capability(discovery, "rename"));
|
||||
// Returned metadata must not expose mutable canonical catalog nodes.
|
||||
((ObjectNode) discovery.path("parametersSchema")).removeAll();
|
||||
assertTrue(catalog.languageQueryDescription().path("parametersSchema").has("properties"));
|
||||
}
|
||||
|
||||
private String capability(com.fasterxml.jackson.databind.JsonNode discovery, String operation) {
|
||||
for (var entry : discovery.path("operations"))
|
||||
if (entry.path("operation").asText().equals(operation)) return entry.path("capability").asText();
|
||||
throw new AssertionError(operation);
|
||||
}
|
||||
|
||||
private ObjectNode languageArguments(String operation) {
|
||||
return mapper.createObjectNode().put("projectRoot", "/project").put("taskId", "task").put("operation", operation);
|
||||
}
|
||||
|
||||
private ObjectNode languageParameters() {
|
||||
return mapper.valueToTree(Map.of("uri", "file:///project/src/main.pbs", "position", Map.of("line", 0, "character", 4),
|
||||
"range", Map.of("start", Map.of("line", 0, "character", 0), "end", Map.of("line", 0, "character", 4)),
|
||||
"positions", List.of(Map.of("line", 0, "character", 4)), "newName", "renamed", "itemId", "opaque-id",
|
||||
"query", "helper", "includeDeclaration", false));
|
||||
}
|
||||
|
||||
@Test void languageSchemaRejectsUnsupportedOperationsAndInvalidStructures() {
|
||||
var args = languageArguments("selectionRanges");
|
||||
args.set("parameters", languageParameters());
|
||||
var parameters = (ObjectNode) args.get("parameters");
|
||||
parameters.putArray("positions");
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args));
|
||||
// Empty positions unrelated to workspaceSymbols were previously tolerated.
|
||||
args.put("operation", "workspaceSymbols");
|
||||
catalog.validateArguments("studio_language_query", args);
|
||||
for (String operation : List.of("callHierarchy", "typeHierarchy", "prepareTypeHierarchy", "unknown")) {
|
||||
args.put("operation", operation);
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args), operation);
|
||||
}
|
||||
args.put("operation", "hover"); args.set("parameters", languageParameters());
|
||||
var position = (ObjectNode) args.path("parameters").path("position");
|
||||
for (String coordinate : List.of("line", "character")) {
|
||||
position.put(coordinate, -1);
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args));
|
||||
position.put(coordinate, 0.5);
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args));
|
||||
position.put(coordinate, "0");
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args));
|
||||
position.put(coordinate, 0);
|
||||
}
|
||||
((ObjectNode) args.get("parameters")).put("unexpected", true);
|
||||
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_language_query", args));
|
||||
}
|
||||
|
||||
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
|
||||
assertEquals(48, catalog.names().size());
|
||||
for (var name : catalog.names()) {
|
||||
|
||||
Reference in New Issue
Block a user