feat(mcp): expose language operation discovery contract
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

This commit is contained in:
2026-11-27 01:19:37 +00:00
parent 219969b9e6
commit 82ceb746ad
7 changed files with 643 additions and 35 deletions
@@ -229,7 +229,8 @@ Input is a replacement snapshot: booleans `up/down/left/right/a/b/x/y/l/r/start/
select/touch`, signed 32-bit `touchX/touchY`. Omitted fields reset to false/zero.
It preserves the runtime's normal sampling/edge semantics, not UI keyboard events.
Language queries use the capabilities returned by project context. Parameters
Language queries use the capabilities returned by project context. Capability
names are not necessarily callable operation names. Parameters
may contain URI, zero-based UTF-16 position/range/positions, workspace query,
newName, includeDeclaration or task-local itemId for multi-stage queries. The
provider MUST validate the parameters needed by the selected operation and reject
@@ -256,15 +257,55 @@ the application adapter. Studio API/Core use maps, lists and scalar values only.
| `selectionRanges` | `uri`, nonempty `positions` |
| `codeActions` | `uri`, ordered `range`; diagnostics are obtained from the current saved file |
| `incomingCalls`, `outgoingCalls` | task-local `itemId` from a hierarchy result |
| `readExternalSource` | `uri`: a task-owned `prometeu-source:` URI returned by `definition` |
The packaged `studio_language_query` descriptor MUST enumerate all recognized
operation names in `inputSchema.properties.operation.enum`. Its `inputSchema.oneOf`
MUST describe each operation's required `parameters` and additional constraints
(including nonempty `selectionRanges.positions`). Common parameter types and
coordinate rules belong in the shared `parameters` schema. Known additional
parameters tolerated by the adapter remain permitted; irrelevant parameters do
not imply an additional operation. `references.includeDeclaration` defaults to
false, and `workspaceSymbols.query` defaults to the empty string.
The authenticated MCP `studio_project_context` result MUST add `languageQuery`,
derived from that same packaged descriptor, without changing API/Core knowledge:
- `tool`: `studio_language_query`.
- `description` and `parametersSchema`: the shared description and parameter schema.
- `operations`: entries with `operation`, `capability`, `description`,
`requiredParameters`, and the operation's `parametersSchema` constraints. Apply
both the shared and operation-specific schemas to the parameters.
Each descriptor branch records its related context capability as
`x-studio-capability`. These mappings describe recognized operations, not universal
support. Clients MUST consult `languages[].capabilities` separately. In particular,
`callHierarchy` maps to `prepareCallHierarchy`, `incomingCalls` and `outgoingCalls`;
`rename` maps to `prepareRename` and `rename`. `callHierarchy` and `typeHierarchy`
are not valid operation names. `readExternalSource` relates to `lsp` but additionally
requires negotiated `prometeuExternalSources`; `prepareRename` additionally requires
the running server's `renameProvider.prepareProvider`. Connection/initialize
instructions MUST direct clients to this discovery contract, without requiring
checkout code or specifications.
Support MUST be checked against the running server's initialize response before
dispatch. Unknown operations, including currently unsupported type hierarchy,
return `UNSUPPORTED_CAPABILITY`. Context publishes the installed provider's
dispatch. MCP rejects unknown operations and structurally invalid arguments at
tool-schema validation. The language adapter continues to return
`UNSUPPORTED_CAPABILITY` for unknown operations or absent server capabilities.
Context publishes the installed provider's
capabilities, including semantic tokens; hierarchy and rename preparations use
their corresponding server capability. Positions are zero-based UTF-16 offsets,
must fit the saved file and must not split surrogate pairs. Reversed ranges and
missing operation-specific parameters are rejected.
`uri` is a document URI, not a filesystem path: use `file:` for accessible saved
source files in the declared project/dependency scope, or a `prometeu-source:`
identity returned by `definition` in the same task/project. UTF-16 character offsets
are neither UTF-8 byte offsets nor Unicode code-point counts. Start a call hierarchy
with `prepareCallHierarchy(uri, position)`, then use a returned opaque `itemId` for
`incomingCalls` or `outgoingCalls`. Returned hierarchy items may supply new `itemId`
values for further traversal. Item IDs cannot be invented from symbol names or URIs.
The application lifecycle supplies each open project's bound loopback LSP
endpoint. Studio uses OS-assigned ports so different open projects do not compete
for one fixed port. The public LSP configuration default remains unchanged for
@@ -18,6 +18,14 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting
does not grant permission. Use the returned taskId for all work and operate only on this project.
Edit saved project files with your native tools; SDK and external libraries are read-only.
Discover language operations and required parameters in studio_language_query.inputSchema or
studio_project_context.languageQuery. languages[].capabilities describes provider support, not
operation names: callHierarchy maps to prepareCallHierarchy, incomingCalls and outgoingCalls;
rename maps to prepareRename and rename. The running LSP checks effective support on each call.
Use document URIs, not file paths, and zero-based line/character positions in UTF-16 code units.
Begin call hierarchy with prepareCallHierarchy, then use its returned itemId in the same task/project.
Hierarchy itemIds expire on task release/revocation. definition may return a task-owned read-only
prometeu-source: URI; read it with readExternalSource or continue hover/definition in that task.
Validate saved changes with studio_language_query and studio_build_start. Poll studio_operation_get.
Supply a unique clientRequestId per intended build/advance. Recover lost responses by lookup using
clientRequestId; do not blindly repeat frame advancement with a new ID. Cancellation acknowledgement
@@ -2,6 +2,7 @@ package p.studio.app.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import p.studio.api.automation.ProjectKnowledge;
@@ -18,8 +19,12 @@ public final class McpProjectKnowledgeTools {
// Jackson's default Path serializer produces file: URIs; the public contract uses absolute paths.
var paths = new SimpleModule().addSerializer(Path.class, new ToStringSerializer());
var wireMapper = mapper.copy().registerModule(paths);
return Map.of("studio_project_context", arguments -> McpToolResult.success(mapper,
wireMapper.valueToTree(knowledge.context(Path.of(arguments.path("projectRoot").asText())))),
var catalog = new McpToolCatalog(mapper);
return Map.of("studio_project_context", arguments -> {
ObjectNode context = wireMapper.valueToTree(knowledge.context(Path.of(arguments.path("projectRoot").asText())));
context.set("languageQuery", catalog.languageQueryDescription());
return McpToolResult.success(mapper, context);
},
"studio_reference_read", arguments -> McpToolResult.success(mapper, wireMapper.valueToTree(
knowledge.readReference(Path.of(arguments.path("projectRoot").asText()), arguments.path("referenceId").asText(),
integer(arguments, "offset", 0), integer(arguments, "limit", 4000)))));
@@ -39,6 +39,25 @@ public final class McpToolCatalog {
result.remove(List.of("authority", "exampleArguments", "exampleValue"));
return result;
}
/** Shared schema and operation constraints are projected from the advertised contract. */
public ObjectNode languageQueryDescription() {
var definition = (ObjectNode) definition("studio_language_query");
var schema = definition.required("inputSchema");
var result = definition.objectNode().put("tool", "studio_language_query")
.put("description", definition.required("description").asText());
result.set("parametersSchema", schema.required("properties").required("parameters").deepCopy());
var operations = result.putArray("operations");
for (var branch : schema.required("oneOf")) {
var properties = branch.required("properties");
var operation = operations.addObject()
.put("operation", properties.required("operation").required("const").asText())
.put("capability", branch.required("x-studio-capability").asText())
.put("description", branch.required("description").asText());
operation.set("requiredParameters", properties.required("parameters").required("required").deepCopy());
operation.set("parametersSchema", properties.required("parameters").deepCopy());
}
return result;
}
public void validateArguments(String name, JsonNode arguments) {
ContractSchema.validate(definition(name).required("inputSchema"), arguments);
var root = arguments.required("projectRoot").asText();
@@ -4,7 +4,7 @@
{
"name": "studio_project_context",
"authority": "authenticated",
"description": "Read the open project's manifest-driven language, capability, reference and edit-scope context. Includes current authority/cleanup and last-known runtime observations without a task grant; revoked task identities remain invalid.",
"description": "Read the open project's manifest-driven language, capability, reference and edit-scope context. Includes current authority/cleanup and last-known runtime observations without a task grant; revoked task identities remain invalid. languageQuery describes recognized operations and parameter rules derived from the tool catalog; languages[].capabilities describes provider support, not callable operation names. The running server checks effective support on each query.",
"inputSchema": {
"type": "object",
"properties": {
@@ -52,6 +52,10 @@
"description": "Immutable RuntimeObservation: sessionId/buildId, lifecycle, source/observedAt, nullable known progress, lastFrame/captureStale, nativeDetails with per-snapshot provenance, context, unavailable inspections and explicit recovery actions with preconditions. Unknown completedFrames stays null. Recovery never executes automatically."
}
]
},
"languageQuery": {
"type": "object",
"description": "Catalog-derived discovery, not a claim of provider support. tool, description, shared parametersSchema and operations (operation, capability, requiredParameters, description, operation-specific parametersSchema). Apply both parameter schemas. Map capability to languages[].capabilities; effective support is checked against the running server, including prepareProvider and external-source negotiation."
}
}
}
@@ -497,7 +501,7 @@
{
"name": "studio_language_query",
"authority": "task",
"description": "Query project LSP capabilities using saved project files or task-owned read-only external sources. readExternalSource reads an external URI returned by definition; hover and definition can continue inside it. Returns refactoring proposals, never applies edits. Adds analysis and context from the retained didOpen analysis negotiated with prometeuDiagnosticAnalysis v1. Includes saved-source SHA-256 and queryId. 10000 ms execution from admission plus 2000 ms cleanup; language failures use LANGUAGE_QUERY_* or LANGUAGE_SERVER_UNAVAILABLE. Capability fallback is limited with ANALYSIS_DETAILS_UNAVAILABLE. Never infer validity from an empty standard diagnostic array.",
"description": "Query project LSP capabilities using saved project files or task-owned read-only external sources. readExternalSource reads an external URI returned by definition; hover and definition can continue inside it. Returns refactoring proposals, never applies edits. Adds analysis and context from the retained didOpen analysis negotiated with prometeuDiagnosticAnalysis v1. Includes saved-source SHA-256 and queryId. 10000 ms execution from admission plus 2000 ms cleanup; language failures use LANGUAGE_QUERY_* or LANGUAGE_SERVER_UNAVAILABLE. Capability fallback is limited with ANALYSIS_DETAILS_UNAVAILABLE. Never infer validity from an empty standard diagnostic array. Discover exact operation names and their required parameters in inputSchema.oneOf or studio_project_context.languageQuery. Aggregate capabilities such as callHierarchy are not operation names. Recognized operations still require support from the running LSP.",
"inputSchema": {
"type": "object",
"properties": {
@@ -513,32 +517,59 @@
},
"operation": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "Exact operation name from this enum; never pass an aggregate capability such as callHierarchy or typeHierarchy. See oneOf for required parameters and the project context for provider capabilities.",
"enum": [
"readExternalSource",
"diagnostics",
"completion",
"hover",
"signatureHelp",
"definition",
"references",
"documentSymbols",
"workspaceSymbols",
"prepareRename",
"rename",
"codeActions",
"formatting",
"documentLinks",
"foldingRanges",
"selectionRanges",
"prepareCallHierarchy",
"incomingCalls",
"outgoingCalls",
"semanticTokens"
]
},
"parameters": {
"type": "object",
"properties": {
"uri": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "Document URI, not a filesystem path. Use file: for a saved project/dependency source in the declared scope. A prometeu-source: URI must come from definition in the same task/project; external sources permit only readExternalSource, hover and definition and are read-only."
},
"position": {
"type": "object",
"properties": {
"line": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based line index."
},
"character": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based offset in UTF-16 code units within the line; not bytes or Unicode code points."
}
},
"required": [
"line",
"character"
],
"additionalProperties": false
"additionalProperties": false,
"description": "Zero-based line and UTF-16 character offset in the exact saved or task-owned external document; must not split a surrogate pair."
},
"range": {
"type": "object",
@@ -548,43 +579,50 @@
"properties": {
"line": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based line index."
},
"character": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based offset in UTF-16 code units within the line; not bytes or Unicode code points."
}
},
"required": [
"line",
"character"
],
"additionalProperties": false
"additionalProperties": false,
"description": "Zero-based line and UTF-16 character offset in the exact saved or task-owned external document; must not split a surrogate pair."
},
"end": {
"type": "object",
"properties": {
"line": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based line index."
},
"character": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based offset in UTF-16 code units within the line; not bytes or Unicode code points."
}
},
"required": [
"line",
"character"
],
"additionalProperties": false
"additionalProperties": false,
"description": "Zero-based line and UTF-16 character offset in the exact saved or task-owned external document; must not split a surrogate pair."
}
},
"required": [
"start",
"end"
],
"additionalProperties": false
"additionalProperties": false,
"description": "Range in the saved document; end must be at or after start. Both endpoints are zero-based UTF-16 positions."
},
"positions": {
"type": "array",
@@ -593,37 +631,48 @@
"properties": {
"line": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based line index."
},
"character": {
"type": "integer",
"minimum": 0
"minimum": 0,
"description": "Zero-based offset in UTF-16 code units within the line; not bytes or Unicode code points."
}
},
"required": [
"line",
"character"
],
"additionalProperties": false
}
"additionalProperties": false,
"description": "Zero-based line and UTF-16 character offset in the exact saved or task-owned external document; must not split a surrogate pair."
},
"description": "Nonempty list of zero-based UTF-16 positions for selectionRanges."
},
"query": {
"type": "string"
"type": "string",
"description": "Optional workspaceSymbols search text; defaults to the empty string.",
"default": ""
},
"newName": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "Required nonblank replacement name for rename; returns an edit proposal and never writes files."
},
"includeDeclaration": {
"type": "boolean"
"type": "boolean",
"description": "Optional references flag; defaults to false.",
"default": false
},
"itemId": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "Opaque task-local hierarchy identity returned by prepareCallHierarchy or a subsequent incomingCalls/outgoingCalls result. Reuse only within the same task and project; invalid after task release/revocation. Do not substitute a symbol name or URI."
}
},
"required": [],
"additionalProperties": false
"additionalProperties": false,
"description": "Operation-specific inputs described by oneOf. Queries use saved UTF-8 files, never unsaved editor overlays. Position line/character values are zero-based; character counts UTF-16 code units, not bytes or Unicode code points. Positions must fit the document and must not split a surrogate pair. Ranges must be ordered."
}
},
"required": [
@@ -632,7 +681,303 @@
"operation",
"parameters"
],
"additionalProperties": false
"additionalProperties": false,
"oneOf": [
{
"description": "Read the exact read-only external source for a prometeu-source: URI returned by definition in this task. Requires negotiated prometeuExternalSources, not merely lsp support.",
"x-studio-capability": "lsp",
"properties": {
"operation": {
"const": "readExternalSource"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "Analyze the saved document and return its current diagnostics.",
"x-studio-capability": "diagnostics",
"properties": {
"operation": {
"const": "diagnostics"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "Return completion proposals at a saved-document position; never apply edits.",
"x-studio-capability": "completion",
"properties": {
"operation": {
"const": "completion"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Read hover information in a saved document or task-owned external source.",
"x-studio-capability": "hover",
"properties": {
"operation": {
"const": "hover"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Read call signature help at a saved-document position.",
"x-studio-capability": "signatureHelp",
"properties": {
"operation": {
"const": "signatureHelp"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Find definitions in saved files or task-owned external sources. A returned prometeu-source: URI can be read with readExternalSource, hover or definition in the same task.",
"x-studio-capability": "definition",
"properties": {
"operation": {
"const": "definition"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Find references at a saved-document position; includeDeclaration is optional and defaults to false.",
"x-studio-capability": "references",
"properties": {
"operation": {
"const": "references"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "List symbols in the saved document.",
"x-studio-capability": "documentSymbols",
"properties": {
"operation": {
"const": "documentSymbols"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "Search workspace symbols with optional query (default empty string). No uri is required; parameters may be {}.",
"x-studio-capability": "workspaceSymbols",
"properties": {
"operation": {
"const": "workspaceSymbols"
},
"parameters": {
"required": []
}
}
},
{
"description": "Prepare a rename at a saved-document position. Requires rename support with prepareProvider from the running server; aggregate rename support alone is insufficient.",
"x-studio-capability": "rename",
"properties": {
"operation": {
"const": "prepareRename"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Return rename edit proposals with a nonblank newName; never apply edits. SDK and dependency read-only restrictions still apply.",
"x-studio-capability": "rename",
"properties": {
"operation": {
"const": "rename"
},
"parameters": {
"required": [
"uri",
"position",
"newName"
]
}
}
},
{
"description": "Return edit proposals for an ordered saved-document range using current diagnostics. Never execute commands or apply edits.",
"x-studio-capability": "codeActions",
"properties": {
"operation": {
"const": "codeActions"
},
"parameters": {
"required": [
"uri",
"range"
]
}
}
},
{
"description": "Return saved-document formatting edit proposals; never apply edits.",
"x-studio-capability": "formatting",
"properties": {
"operation": {
"const": "formatting"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "List links in the saved document.",
"x-studio-capability": "documentLinks",
"properties": {
"operation": {
"const": "documentLinks"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "List folding ranges in the saved document.",
"x-studio-capability": "foldingRanges",
"properties": {
"operation": {
"const": "foldingRanges"
},
"parameters": {
"required": [
"uri"
]
}
}
},
{
"description": "Return selection ranges for a nonempty list of saved-document positions.",
"x-studio-capability": "selectionRanges",
"properties": {
"operation": {
"const": "selectionRanges"
},
"parameters": {
"required": [
"uri",
"positions"
],
"properties": {
"positions": {
"minItems": 1
}
}
}
}
},
{
"description": "First stage of call hierarchy: prepare at a saved-document position, then pass a returned itemId to incomingCalls or outgoingCalls. callHierarchy is an aggregate capability, not an operation.",
"x-studio-capability": "callHierarchy",
"properties": {
"operation": {
"const": "prepareCallHierarchy"
},
"parameters": {
"required": [
"uri",
"position"
]
}
}
},
{
"description": "Find incoming calls using an itemId returned by a hierarchy result in the same task/project. Returned items provide itemId for further traversal; ids expire when the task ends.",
"x-studio-capability": "callHierarchy",
"properties": {
"operation": {
"const": "incomingCalls"
},
"parameters": {
"required": [
"itemId"
]
}
}
},
{
"description": "Find outgoing calls using an itemId returned by a hierarchy result in the same task/project. Returned items provide itemId for further traversal; ids expire when the task ends.",
"x-studio-capability": "callHierarchy",
"properties": {
"operation": {
"const": "outgoingCalls"
},
"parameters": {
"required": [
"itemId"
]
}
}
},
{
"description": "Read full semantic tokens for the saved document.",
"x-studio-capability": "semanticTokens",
"properties": {
"operation": {
"const": "semanticTokens"
},
"parameters": {
"required": [
"uri"
]
}
}
}
]
},
"outputSchema": {
"type": "object",
@@ -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()) {