add MCP tool contracts and authenticated local HTTP transport

This commit is contained in:
2026-09-29 07:55:29 +01:00
parent e3c3b2cbb7
commit 9f61f9c07d
18 changed files with 2730 additions and 1 deletions
@@ -239,6 +239,9 @@ that it uses. Capture/build correlation MUST NOT introduce code snapshots.
## 8. Local MCP Admission and Functional Surface
Concrete tool names, input schemas, response envelopes and HTTP lifecycle are
specified in [MCP Tools and Project Knowledge Contract](11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md).
The app MUST host Streamable HTTP at `127.0.0.1:<OS-assigned-port>/mcp` while
Studio is open. It MUST generate a random token per Studio start, require it
on connections, validate Origin and reject unexpected origins. No remote
@@ -0,0 +1,216 @@
# MCP Tools and Project Knowledge Contract
## Status, Scope and Authority
Owner: **studio**, application adapter and neutral automation API. This document
formalizes DEC-0060 B5–B9 and PLN-0139 steps 15–16. It complements
[DEV and Automation](10.%20DEV%20and%20Automation%20Specification.md), which owns
project authority, lifecycle, captures and phase gates. It does not change those
rules or the runtime-owned headless protocol.
The packaged machine-readable input schemas, authority classification and
examples are in `prometeu-app/src/main/resources/mcp/studio-tools-v1.json`.
Contract version is `1.0`. Catalog membership is not runtime availability:
`tools/list` MUST expose only composed handlers, never placeholder implementations.
Steps 17–21 connect the functional providers and DEV configuration assistance;
steps 22–28 provide the real runtime gateway and integrated acceptance.
## 1. Connection Contract
The app hosts `/mcp` on **127.0.0.1 with an OS-assigned port**, using the JSON
response form of MCP Streamable HTTP, protocol revision `2025-06-18`. The
initialization exchange negotiates that supported revision; no compatibility
with other revisions or deprecated HTTP+SSE transport is claimed. An offered
unsupported revision receives the supported revision in `InitializeResult`.
Each start generates a fresh 256-bit random bearer token. Every request MUST
include `Authorization: Bearer <token>`. Missing/wrong credentials return 401.
There is no query-string token, OAuth, cookie authentication, remote bind option,
stdio bridge or wildcard listener. The endpoint has no query parameters.
Native clients may omit `Origin`. If present, it MUST exactly equal the live
endpoint's origin (`http://127.0.0.1:<port>`); `null`, other ports/hosts/schemes
and multiple Origin headers fail. Host MUST match the live loopback authority.
Unexpected origins/hosts return 403. No permissive browser CORS policy is emitted.
Credentials MUST NOT appear in diagnostics, exception messages, object string
representations, generated reports or versioned configuration. Explicit copying
for the external client is provided in step 21, not by logging startup secrets.
Initialization assigns a separate random `Mcp-Session-Id`. Subsequent requests
include this header and the negotiated `MCP-Protocol-Version`. The server can
recover the negotiated version from its connection session if the version header
is absent; an explicitly unsupported header returns 400. Missing required
session returns 400; an unknown/closed session returns 404. The client sends
`notifications/initialized` before tools. `ping` is available after initialization.
POST requires UTF-8 JSON and Accept support for `application/json` and
`text/event-stream`. Responses use JSON, not SSE. GET returns 405. DELETE closes
only the connection session, not project authority. Accepted notifications and
client responses return 202 without a body. Notification/disconnection alone
MUST NOT revoke a task or cancel an operation already returned by operationId.
The transport bounds incoming bodies to 1 MiB, sessions to 128 and request
handling to a bounded worker queue. Oversized bodies return 413; exhausted
session capacity returns 503. Stalled exchanges close after 15 seconds. These
are HTTP resource protections, **not** task expiration or guest/runtime timeouts.
Build/advance MUST return operation identities promptly. A lost response is
resolved by authorized lookup, not by assuming cancellation or replay.
These details follow the official MCP [transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports),
[lifecycle](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle)
and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools)
contracts. Optional SSE, server-initiated requests, sampling, prompts, resource
subscriptions and list-change notifications are not advertised.
## 2. Identity and Admission
All tool inputs require `projectRoot`: an absolute filesystem root resolving to
an open project. UI focus never supplies it. Core services resolve the actual
project, including canonical-path/scope checks; syntactic validation does not
prove authorization.
The authority levels in the packaged catalog are:
- `authenticated`: connection authentication only; project/context/reference reads
are allowed before grant. No task token is returned by discovery.
- `granted`: acquisition validates the prior human grant and atomically creates
the sole task identity. The transport session ID is not that identity.
- `task`: `projectRoot` and `taskId` must identify the current acquired task.
Revalidate before admission, lookup and deduplication, including read-only LSP.
No MCP tool grants human permission or simulates pressing the DEV button.
There are no arbitrary-file read/write, shell, Git or publication tools. Editing
uses the external client's native tools within the context's editable scope.
## 3. v1 Tool Catalog
Fields below supplement `projectRoot`, and `taskId` where authority is `task`.
Input objects reject undeclared fields. IDs are nonempty opaque strings.
| Tool | Authority | Additional input | Successful value |
| --- | --- | --- | --- |
| `studio_project_context` | authenticated | none | Project context in section 5 |
| `studio_reference_read` | authenticated | referenceId; optional offset/limit | Indexed reference page |
| `studio_control_acquire` | granted | none | taskId, state=AGENT_WORKING |
| `studio_control_release` | task | none | state=MANUAL, only after ordered cleanup |
| `studio_language_query` | task | operation, parameters | Supported LSP query/proposal result |
| `studio_build_start` | task | clientRequestId | operationId, clientRequestId, state |
| `studio_headless_boot` | task | buildId | sessionId, buildId; boot uses the task's known build |
| `studio_headless_reset` | task | none | Current session/reset state |
| `studio_headless_set_input` | task | input | Current session acknowledgement |
| `studio_headless_clear_input` | task | none | Current session acknowledgement |
| `studio_headless_advance` | task | clientRequestId, frames | operationId, clientRequestId, state |
| `studio_headless_capture` | task | none | Canonical image and metadata in section 6 |
| `studio_headless_state` | task | none | Current session and runtime state |
| `studio_headless_fault` | task | none | fault object or null, preserving structural fault details |
| `studio_headless_shutdown` | task | none | Session shutdown acknowledgement after managed cleanup |
| `studio_operation_get` | task | exactly one of operationId/clientRequestId | State, known progress, typed result/failure |
| `studio_operation_cancel` | task | operationId | operationId, cancellationRequested |
Boot MUST NOT accept an arbitrary cartridge path. The shared service resolves
buildId to known project artifacts. Runtime limits/capabilities come from the
actual runtime, not fixed MCP promises. Frames is a nonnegative integer (zero
is valid); values beyond effective limits fail rather than being clamped.
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
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
unsupported operations explicitly. Diagnostics, definitions, references and
symbols reuse the existing project LSP. Other queries/refactoring proposals are
exposed only when supported; returned edits MUST respect project versus read-only
SDK/library scope. No query applies filesystem edits.
## 4. Result, Error and Operation Contracts
Successful tools return `isError:false` with structuredContent
`{"status":"ok","value":{...}}`. Domain/admission failures return
`isError:true` with `{"status":"error","error":{"code":"...","message":"..."}}`.
Both include a text content block serializing the same structured data for clients
that do not render structuredContent. Clients use error codes, not parsed prose.
`AutomationFailure.Code` defines domain codes, including project-not-open,
not-granted, invalid-task, busy, unsupported language/capability, missing
reference/documentation, out-of-scope/read-only scope, missing operation/build/
runtime session, duplicate-ID parameter conflict, unavailable/incompatible runtime,
missing frame, exceeded limit, not-cancelable and infrastructure failure.
Unknown methods, malformed JSON-RPC and schema-invalid arguments remain protocol
errors (-32601, -32600/-32700 and -32602); unexpected internals use sanitized
-32603 responses, never request bodies, stack traces or credentials.
Build failure and guest fault are **operation outcomes**, not implicit release.
`TrackedOperation` carries the existing `OperationSnapshot`, clientRequestId,
known progress and either the existing typed build result or runtime outcome.
Unknown requested/completed frame counts are null. Terminal infrastructure
failure/cancellation MUST preserve only known progress. Cancellation acknowledgement
does not assert worker termination or grant manual control.
The wire receipt flattens operationId/state from the neutral operation snapshot.
Polling additionally returns progress and typed result/failure; incomplete results
are null. Build results retain diagnostics/artifact correlation. Runtime results
retain requested/completed frames and distinguish success, guest fault,
termination, cancellation and infrastructure failure. Captured results include
the same MCP image block used by direct capture.
`clientRequestId` deduplication is task-local and in-memory. Same ID plus same
effective parameters returns the same operation; changed parameters fail with
CLIENT_REQUEST_CONFLICT. Operation lookup accepts exactly one key. Revoked,
cross-project or old task identities cannot read/cancel cached work. Neither MCP
JSON-RPC IDs nor runtime requestIds replace this identity. Restart never restores
the registry, replays an advance or recovers authorization.
## 5. Project Knowledge DTOs
Neutral `ProjectKnowledge.Context` contains projectRoot/projectName, languages,
libraries, editableRoots/readOnlyRoots, indexed references and explicit limitations.
Its source is the project manifest and installed providers, never an AI-only file.
Each language includes id/primary, separately identified languageVersion,
compilerVersion and sdkVersion, source extensions/roots, real capabilities and
reference IDs. Version has `value` and `source`; unknown value is null with
source `unknown`. Capability support distinguishes SUPPORTED/UNSUPPORTED/UNKNOWN
and can explain a limitation. Unknown declared language MUST NOT fall back to PBS.
Libraries include identity, known version, roots and whether they belong to the
editable project. External libraries and SDK remain read-only. Reference entries
identify id/title/owner/kind/version; kinds include QUICKSTART, SYNTAX, SEMANTICS,
EXAMPLE, SDK and LIBRARY. Indexed content belongs to its language/SDK owner.
Reference reads take an opaque ID from that index, not a path or arbitrary URI.
Offset defaults to 0; limit defaults to 4000 and accepts 1–16000 Unicode code
points. A page returns referenceId, offset, total, text and nextOffset (null at
end). Invalid pagination fails; unknown/traversal-like IDs cannot escape the
index. Installed packaging and real provider resolution are steps 17–18.
## 6. Image Contract
MCP image content has `type:image`, `mimeType:image/png`, and base64 `data` of
the unchanged `CanonicalCapture.png` bytes. No screenshot, log scraping, temporary
path or network fetch is required. The structured value includes sessionId,
buildId, logicalFrameIndex, frameId, width, height, stridePixels, pixelFormat
`RGBA8888`, mimeType and stale. Stride describes the original framebuffer, not PNG
compression/padding. Logical and render frame counters are independent.
The adapter MUST NOT invent a frame when none exists or substitute another
session's image. The same neutral capture feeds DEV and MCP. Real runtime
production/cross-language equality remain phase 4 gates; encoding test pixels in
contract tests does not satisfy that integration requirement.
## 7. Conformance and Delivery Boundary
Contract tests validate every tool's example, authority level, required project/
task IDs, invalid types/unknown fields, exclusive operation lookup, input ranges,
pagination, result envelopes, PNG bytes and independent frame identities.
HTTP tests use a real loopback listener/client and exercise initialization,
authentication, Origin, endpoint/method/version handling, tool dispatch, malformed
or oversized input, closure, restart and old-token rejection. Provider doubles
exist only in tests. Composition starts/closes transport with Studio.
Step 16's production registry is empty until functional handlers are composed;
DEV configuration-copy stays unavailable until step 21. Passing this transport
gate is not the phase 3 or final external-agent acceptance gate. API/Core and
JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it.
+3 -1
View File
@@ -57,6 +57,7 @@ The current Studio core corpus is:
5. [`8. Project-Local Studio State Specification.md`](8.%20Project-Local%20Studio%20State%20Specification.md)
6. [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md)
7. [`10. DEV and Automation Specification.md`](10.%20DEV%20and%20Automation%20Specification.md)
8. [`11. MCP Tools and Project Knowledge Contract.md`](11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md)
## Reading Order
@@ -68,7 +69,8 @@ Recommended order:
4. assets workspace behavior;
5. project-local Studio state behavior;
6. Studio Core, adapter, composition, and external integration boundaries;
7. DEV authority, document handoff, automation operations/captures and phased integration gates.
7. DEV authority, document handoff, automation operations/captures and phased integration gates;
8. MCP transport/tool schemas and project/language knowledge contracts.
## Current Wave Notes
@@ -290,6 +290,22 @@ public class StudioApplicationConfiguration {
activityHistoryStore);
}
@Bean
p.studio.app.mcp.McpToolCatalog mcpToolCatalog(ObjectMapper mapper) {
return new p.studio.app.mcp.McpToolCatalog(mapper);
}
@Bean
p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper) {
// Providers are connected in PLN-0139 steps 17–20. Never advertise placeholders.
return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, java.util.Map.of());
}
@Bean(initMethod = "start", destroyMethod = "close")
p.studio.app.mcp.LocalMcpServer localMcpServer(ObjectMapper mapper, p.studio.app.mcp.McpToolRegistry tools) {
return new p.studio.app.mcp.LocalMcpServer(mapper, tools);
}
private static Path resolveDefaultProjectsRoot() {
Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
@@ -0,0 +1,48 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashSet;
/** Validator for the deliberately small JSON Schema vocabulary in our packaged schemas.
* Not a general-purpose JSON Schema engine; never accepts client-supplied schemas. */
final class ContractSchema {
private ContractSchema() { }
static void validate(JsonNode schema, JsonNode value) {
if (value == null) fail();
if (schema.has("oneOf")) {
int matches = 0;
for (var branch : schema.get("oneOf")) if (matches(branch, value)) matches++;
if (matches != 1) fail();
}
if (schema.has("not") && matches(schema.get("not"), value)) fail();
if (schema.has("const") && !schema.get("const").equals(value)) fail();
if (schema.has("type")) {
boolean valid = switch (schema.get("type").asText()) {
case "object" -> value.isObject();
case "array" -> value.isArray();
case "string" -> value.isTextual();
case "integer" -> value.isIntegralNumber() && value.canConvertToLong();
case "boolean" -> value.isBoolean();
default -> throw new IllegalStateException("Unsupported packaged schema type");
};
if (!valid) fail();
}
if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail();
if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail();
if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail();
if (schema.has("required")) for (var key : schema.get("required")) if (!value.has(key.asText())) fail();
if (schema.has("properties")) {
var allowed = new HashSet<String>();
schema.get("properties").fields().forEachRemaining(field -> {
allowed.add(field.getKey());
if (value.has(field.getKey())) validate(field.getValue(), value.get(field.getKey()));
});
if (!schema.path("additionalProperties").asBoolean(true)) value.fieldNames().forEachRemaining(key -> { if (!allowed.contains(key)) fail(); });
}
if (schema.has("items")) for (var item : value) validate(schema.get("items"), item);
}
private static boolean matches(JsonNode schema, JsonNode value) {
try { validate(schema, value); return true; } catch (IllegalArgumentException failure) { return false; }
}
private static void fail() { throw new IllegalArgumentException("Arguments do not match the tool contract"); }
}
@@ -0,0 +1,203 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** Local MCP transport only. A connection session never represents a project grant or task. */
public final class LocalMcpServer implements AutoCloseable {
public static final String PROTOCOL_VERSION = "2025-06-18";
private static final int MAX_BODY_BYTES = 1024 * 1024;
private static final int MAX_CONNECTION_SESSIONS = 128;
private final ObjectMapper mapper;
private final McpToolRegistry tools;
private final Map<String, AtomicBoolean> sessions = new ConcurrentHashMap<>();
private final SecureRandom random = new SecureRandom();
private HttpServer server;
private ExecutorService executor;
private ScheduledExecutorService deadlines;
private volatile Connection connection;
public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) {
this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.tools = Objects.requireNonNull(tools);
}
public synchronized void start() throws IOException {
if (server != null) return;
// No configurable bind address: remote and wildcard exposure cannot be enabled accidentally.
var next = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 32);
var workers = new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(32),
Thread.ofPlatform().daemon().name("studio-mcp-", 1).factory(), new ThreadPoolExecutor.AbortPolicy());
var timers = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-deadlines").factory());
try {
connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"), secret());
deadlines = timers;
next.createContext("/mcp", this::handle);
next.setExecutor(workers);
next.start();
executor = workers; server = next;
} catch (RuntimeException failure) {
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
throw failure;
}
}
public Connection connection() {
var current = connection;
if (current == null) throw new IllegalStateException("MCP is not running");
return current;
}
public synchronized boolean isRunning() { return server != null; }
@Override public synchronized void close() {
if (server == null) return;
connection = null; server.stop(0); server = null;
sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow();
}
/** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */
public static final class Connection {
private final URI endpoint;
private final String token;
private Connection(URI endpoint, String token) { this.endpoint = endpoint; this.token = token; }
public URI endpoint() { return endpoint; }
public String authorizationHeader() { return "Bearer " + token; }
@Override public String toString() { return "LocalMcpConnection[endpoint=" + endpoint + ", credentials=REDACTED]"; }
}
private void handle(HttpExchange exchange) throws IOException {
// Bounds stalled body reads and transport responses, not guest simulated time or task lifetime.
var timeout = deadlines.schedule(exchange::close, 15, TimeUnit.SECONDS);
try (exchange) {
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
var current = connection;
if (current == null) { empty(exchange, 503); return; }
if (!"/mcp".equals(exchange.getRequestURI().getRawPath()) || exchange.getRequestURI().getRawQuery() != null) { empty(exchange, 404); return; }
var headers = exchange.getRequestHeaders();
String origin = single(headers, "Origin");
String authority = current.endpoint().getRawAuthority();
if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress()
|| !authority.equals(single(headers, "Host"))
|| origin != null && !("http://" + authority).equals(origin)) { empty(exchange, 403); return; }
String authorization = single(headers, "Authorization");
if (authorization == null || !MessageDigest.isEqual(current.authorizationHeader().getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) {
empty(exchange, 401); return;
}
String version = single(headers, "MCP-Protocol-Version");
if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; }
String sessionId = single(headers, "Mcp-Session-Id");
AtomicBoolean initialized = sessionId == null ? null : sessions.get(sessionId);
if (sessionId != null && initialized == null) { empty(exchange, 404); return; }
String method = exchange.getRequestMethod();
if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
if (method.equals("DELETE")) {
if (sessionId == null) { empty(exchange, 400); return; }
sessions.remove(sessionId); empty(exchange, 200); return; // No project/task release.
}
if (!method.equals("POST")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
if (!accepts(headers, "application/json") || !accepts(headers, "text/event-stream")) { empty(exchange, 406); return; }
String contentType = single(headers, "Content-Type");
if (contentType == null || !contentType.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) { empty(exchange, 415); return; }
byte[] body = exchange.getRequestBody().readNBytes(MAX_BODY_BYTES + 1);
if (body.length > MAX_BODY_BYTES) { empty(exchange, 413); return; }
JsonNode message;
try {
String json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)).toString();
message = mapper.readTree(json);
} catch (IOException invalid) { send(exchange, 400, error(NullNode.instance, -32700, "Invalid JSON")); return; }
if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !message.path("jsonrpc").asText().equals("2.0")
|| message.has("id") && !(message.get("id").isTextual() || message.get("id").isNumber())) {
send(exchange, 400, error(NullNode.instance, -32600, "Invalid request")); return;
}
JsonNode id = message.path("id");
String rpc = message.path("method").asText();
if (!message.path("method").isTextual() || rpc.isBlank() || message.has("result") || message.has("error")) {
// This server issues no requests, but acknowledge well-formed client responses.
if (initialized != null && message.has("id") && !message.has("method") && message.has("result") != message.has("error")) empty(exchange, 202);
else send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32600, "Invalid request"));
return;
}
JsonNode params = message.has("params") ? message.get("params") : mapper.createObjectNode();
if (!params.isObject()) { send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid parameters")); return; }
if (rpc.equals("initialize")) {
if (id.isMissingNode() || initialized != null || !params.path("protocolVersion").isTextual()
|| !params.path("capabilities").isObject() || !params.path("clientInfo").isObject()
|| !params.path("clientInfo").path("name").isTextual() || !params.path("clientInfo").path("version").isTextual()) {
send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return;
}
synchronized (sessions) {
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
sessionId = secret(); sessions.put(sessionId, new AtomicBoolean());
}
exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId);
var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION);
result.putObject("capabilities").putObject("tools").put("listChanged", false);
result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0");
result.put("instructions", "Read project context and indexed references. Human grant in DEV precedes acquisition. Edit saved project files with your native tools, never SDK/external libraries. Validate with LSP/build and explicitly release. Studio revocation does not stop your external file writes. Reconnect with new configuration after Studio restart.");
send(exchange, 200, response(id, result)); return;
}
if (initialized == null) { empty(exchange, 400); return; }
if (id.isMissingNode()) {
if (rpc.equals("notifications/initialized")) initialized.set(true);
// Notifications do not implicitly cancel an already returned operationId or release authority.
empty(exchange, 202); return;
}
if (!initialized.get() && !rpc.equals("ping")) { send(exchange, 200, error(id, -32600, "Initialization required")); return; }
try {
JsonNode result = switch (rpc) {
case "ping" -> mapper.createObjectNode();
case "tools/list" -> {
if (params.has("cursor")) throw new IllegalArgumentException("No further tool page");
yield mapper.createObjectNode().set("tools", tools.descriptors());
}
case "tools/call" -> {
if (!params.path("name").isTextual()) throw new IllegalArgumentException("Missing tool name");
yield tools.call(params.get("name").asText(), params.get("arguments")).wire();
}
default -> null;
};
send(exchange, 200, result == null ? error(id, -32601, "Method not found") : response(id, result));
} catch (IllegalArgumentException invalid) { send(exchange, 200, error(id, -32602, "Invalid tool or parameters")); }
catch (RuntimeException failure) { send(exchange, 200, error(id, -32603, "Internal error")); }
} finally { timeout.cancel(false); }
}
private String secret() { byte[] bytes = new byte[32]; random.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); }
private static String single(Headers headers, String name) {
var values = headers.get(name);
return values == null ? null : values.size() == 1 ? values.getFirst() : "<multiple-headers>";
}
private static boolean accepts(Headers headers, String type) {
return headers.getOrDefault("Accept", List.of()).stream().flatMap(s -> Arrays.stream(s.split(",")))
.anyMatch(range -> {
var parts = range.trim().split(";");
if (!parts[0].trim().equalsIgnoreCase(type)) return false;
for (int index = 1; index < parts.length; index++) {
var parameter = parts[index].trim();
if (parameter.startsWith("q=")) {
try { double q = Double.parseDouble(parameter.substring(2)); if (!(q > 0 && q <= 1)) return false; }
catch (NumberFormatException invalid) { return false; }
}
}
return true;
});
}
private ObjectNode response(JsonNode id, JsonNode result) { var value = mapper.createObjectNode().put("jsonrpc", "2.0"); value.set("id", id); value.set("result", result); return value; }
private ObjectNode error(JsonNode id, int code, String message) { var value = mapper.createObjectNode().put("jsonrpc", "2.0"); value.set("id", id); value.putObject("error").put("code", code).put("message", message); return value; }
private void send(HttpExchange exchange, int status, JsonNode value) throws IOException {
byte[] bytes = mapper.writeValueAsBytes(value);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.sendResponseHeaders(status, bytes.length); exchange.getResponseBody().write(bytes);
}
private static void empty(HttpExchange exchange, int status) throws IOException { exchange.sendResponseHeaders(status, -1); }
}
@@ -0,0 +1,39 @@
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 java.io.IOException;
import java.util.*;
/** Packaged v1 contract, not a claim that every provider has been composed. */
public final class McpToolCatalog {
private final Map<String, JsonNode> definitions;
public McpToolCatalog(ObjectMapper mapper) {
try (var input = getClass().getResourceAsStream("/mcp/studio-tools-v1.json")) {
var root = mapper.readTree(Objects.requireNonNull(input, "Missing MCP contract"));
var loaded = new LinkedHashMap<String, JsonNode>();
for (var tool : root.required("tools")) {
if (loaded.put(tool.required("name").asText(), tool) != null) throw new IllegalStateException("Duplicate MCP tool");
ContractSchema.validate(tool.required("inputSchema"), tool.required("exampleArguments"));
}
definitions = Collections.unmodifiableMap(loaded);
} catch (IOException failure) { throw new IllegalStateException("Cannot read packaged MCP contract", failure); }
}
public Set<String> names() { return definitions.keySet(); }
public JsonNode definition(String name) {
var definition = definitions.get(name);
if (definition == null) throw new IllegalArgumentException("Unknown tool");
return definition.deepCopy();
}
public ObjectNode descriptor(String name) {
var result = (ObjectNode) definition(name);
result.remove(List.of("authority", "exampleArguments", "exampleValue"));
return result;
}
public void validateArguments(String name, JsonNode arguments) {
ContractSchema.validate(definition(name).required("inputSchema"), arguments);
var root = arguments.required("projectRoot").asText();
if (!java.nio.file.Path.of(root).isAbsolute()) throw new IllegalArgumentException("projectRoot must be absolute");
}
}
@@ -0,0 +1,40 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import p.studio.api.automation.AutomationFailure;
import p.studio.api.automation.ControlDeniedException;
import java.util.Map;
import java.util.function.Function;
/** Immutable adapter dispatch. Services, not this transport, own authority and operations. */
public final class McpToolRegistry {
private final McpToolCatalog catalog;
private final ObjectMapper mapper;
private final Map<String, Function<JsonNode, McpToolResult>> handlers;
public McpToolRegistry(McpToolCatalog catalog, ObjectMapper mapper, Map<String, Function<JsonNode, McpToolResult>> handlers) {
this.catalog = catalog; this.mapper = mapper; this.handlers = Map.copyOf(handlers);
handlers.keySet().forEach(catalog::definition);
}
public ArrayNode descriptors() {
var descriptors = mapper.createArrayNode();
catalog.names().stream().filter(handlers::containsKey).forEach(name -> descriptors.add(catalog.descriptor(name)));
return descriptors;
}
public McpToolResult call(String name, JsonNode arguments) {
var handler = handlers.get(name);
if (handler == null) throw new IllegalArgumentException("Unknown or unavailable tool");
catalog.validateArguments(name, arguments);
try { return handler.apply(arguments); }
catch (ControlDeniedException denied) {
var code = switch (denied.status()) {
case INVALID_TASK -> AutomationFailure.Code.INVALID_TASK;
case NOT_GRANTED -> AutomationFailure.Code.NOT_GRANTED;
case CLOSED -> AutomationFailure.Code.CLOSED;
default -> AutomationFailure.Code.BUSY;
};
return McpToolResult.failure(mapper, new AutomationFailure(code, "Project authority rejected the call"));
}
}
}
@@ -0,0 +1,41 @@
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 p.studio.api.automation.AutomationFailure;
import p.studio.api.automation.CanonicalCapture;
import java.util.Base64;
import java.util.Objects;
/** Wire projection only. Images are the same bytes held by the neutral DEV snapshot. */
public final class McpToolResult {
private final ObjectNode wire;
private McpToolResult(ObjectNode wire) { this.wire = wire; }
public ObjectNode wire() { return wire.deepCopy(); }
public static McpToolResult success(ObjectMapper mapper, ObjectNode value) {
return envelope(mapper, mapper.createObjectNode().put("status", "ok").set("value", value.deepCopy()), false);
}
public static McpToolResult failure(ObjectMapper mapper, AutomationFailure failure) {
var data = mapper.createObjectNode().put("status", "error");
data.set("error", mapper.valueToTree(failure));
return envelope(mapper, data, true);
}
public static McpToolResult capture(ObjectMapper mapper, CanonicalCapture capture, boolean stale) {
Objects.requireNonNull(capture);
var metadata = mapper.createObjectNode().put("sessionId", capture.sessionId()).put("buildId", capture.buildId())
.put("logicalFrameIndex", capture.logicalFrameIndex()).put("frameId", capture.frameId())
.put("width", capture.width()).put("height", capture.height()).put("stridePixels", capture.stridePixels())
.put("pixelFormat", "RGBA8888").put("mimeType", "image/png").put("stale", stale);
var result = success(mapper, metadata);
result.wire.withArray("content").addObject().put("type", "image").put("mimeType", "image/png")
.put("data", Base64.getEncoder().encodeToString(capture.png()));
return result;
}
private static McpToolResult envelope(ObjectMapper mapper, JsonNode data, boolean error) {
var wire = mapper.createObjectNode().put("isError", error);
wire.set("structuredContent", data);
wire.putArray("content").addObject().put("type", "text").put("text", data.toString());
return new McpToolResult(wire);
}
}
File diff suppressed because it is too large Load Diff
@@ -21,13 +21,17 @@ class StudioApplicationConfigurationTest {
.headless(true)
.run();
final ExecutorService executor = context.getBean(ExecutorService.class);
final var mcp = context.getBean(p.studio.app.mcp.LocalMcpServer.class);
try (context) {
assertNotNull(context.getBean(StudioUiFactory.class));
assertNotNull(context.getBean(PackerWorkspaceService.class));
assertNotNull(context.getBean(OperationExecutor.class));
assertFalse(context.getClass().getName().contains("WebServer"));
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
assertTrue(context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors().isEmpty());
}
assertTrue(executor.isShutdown());
assertFalse(mcp.isRunning());
}
}
@@ -0,0 +1,133 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import p.studio.api.automation.*;
import static org.junit.jupiter.api.Assertions.*;
class LocalMcpServerTest {
final ObjectMapper mapper = new ObjectMapper();
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
LocalMcpServer server;
String session;
AtomicInteger calls;
@BeforeEach void start() throws Exception {
calls = new AtomicInteger();
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of(
"studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); },
"studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required")))));
server.start();
}
@AfterEach void close() { server.close(); client.close(); }
HttpResponse<String> request(String method, URI uri, String body, String token, String origin, String protocol, String sessionId) throws Exception {
var request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(5))
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json");
if (token != null) request.header("Authorization", token);
if (origin != null) request.header("Origin", origin);
if (protocol != null) request.header("MCP-Protocol-Version", protocol);
if (sessionId != null) request.header("Mcp-Session-Id", sessionId);
return client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
}
HttpResponse<String> post(String body) throws Exception {
return request("POST", server.connection().endpoint(), body, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session);
}
static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; }
void initialize() throws Exception {
var response = post(init()); assertEquals(200, response.statusCode());
session = response.headers().firstValue("Mcp-Session-Id").orElseThrow();
assertEquals(LocalMcpServer.PROTOCOL_VERSION, mapper.readTree(response.body()).path("result").path("protocolVersion").asText());
assertEquals(202, post("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}").statusCode());
}
@Test void lifecycleNegotiatesListsAndCallsOnlyActualHandlers() throws Exception {
initialize();
var listed = mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}").body());
assertEquals(2, listed.path("result").path("tools").size());
var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
assertEquals(200, response.statusCode()); assertEquals(1, calls.get());
assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText());
assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode());
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
}
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode());
assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode());
for (var origin : List.of("null", "https://evil.example", "http://127.0.0.1:1", "http://localhost:" + endpoint.getPort()))
assertEquals(403, request("POST", endpoint, init(), token, origin, null, null).statusCode());
assertEquals(200, request("POST", endpoint, init(), token, "http://" + endpoint.getRawAuthority(), null, null).statusCode());
assertEquals(0, calls.get());
assertFalse(server.connection().toString().contains(token.substring(7)));
}
@Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception {
initialize(); var old = server.connection(); server.close();
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader()));
assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode());
assertEquals(404, post(init()).statusCode());
session = null; initialize();
}
@Test void malformedBodiesVersionsAndToolsCannotReachProviders() throws Exception {
initialize();
assertEquals(400, post("{not json}").statusCode());
assertEquals(400, post("[]").statusCode());
assertEquals(400, post("{\"jsonrpc\":2.0,\"id\":1,\"method\":\"ping\"}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode());
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode());
assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode());
var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}");
assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get());
assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode());
}
@Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception {
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode());
var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt());
assertEquals(405, request("GET", endpoint, null, token, null, null, session).statusCode());
assertEquals(404, request("POST", URI.create(endpoint + "/nested"), init(), token, null, null, null).statusCode());
assertEquals(404, request("POST", URI.create(endpoint + "?token=forbidden"), init(), token, null, null, null).statusCode());
assertEquals(0, calls.get());
}
@Test void authenticatedConnectionDoesNotGrantControl() throws Exception {
initialize();
var denied = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_control_acquire\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
var result = mapper.readTree(denied.body()).path("result");
assertTrue(result.path("isError").asBoolean()); assertEquals("NOT_GRANTED", result.path("structuredContent").path("error").path("code").asText());
}
@Test void hostileHostAndDuplicateOriginAreRejectedEvenWithValidCredentials() throws Exception {
var connection = server.connection();
try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) {
socket.setSoTimeout(3000);
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + connection.authorizationHeader()
+ "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8));
var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine();
assertTrue(status.contains("403"));
}
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example")
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
}
@Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception {
var connection = server.connection();
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build();
assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode());
}
}
@@ -0,0 +1,81 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import p.studio.api.automation.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class McpContractTest {
final ObjectMapper mapper = new ObjectMapper();
final McpToolCatalog catalog = new McpToolCatalog(mapper);
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
assertEquals(17, catalog.names().size());
for (var name : catalog.names()) {
var definition = catalog.definition(name);
catalog.validateArguments(name, definition.get("exampleArguments"));
var result = McpToolResult.success(mapper, (ObjectNode) definition.get("exampleValue"));
ContractSchema.validate(definition.get("outputSchema"), result.wire().get("structuredContent"));
var failure = McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.INVALID_TASK, "Revoked"));
ContractSchema.validate(definition.get("outputSchema"), failure.wire().get("structuredContent"));
assertTrue(Set.of("authenticated", "granted", "task").contains(definition.get("authority").asText()));
assertEquals(definition.get("authority").asText().equals("task"), definition.get("inputSchema").get("properties").has("taskId"));
assertFalse(catalog.descriptor(name).has("exampleArguments"));
}
}
@Test void missingRootTaskUnexpectedFieldsAndWrongTypesAreRejected() {
for (var name : catalog.names()) {
ObjectNode sample = catalog.definition(name).get("exampleArguments").deepCopy();
sample.remove("projectRoot"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample));
sample.put("projectRoot", "relative/root"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample));
sample.put("projectRoot", "/project").put("shell", "forbidden"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample));
sample.remove("shell"); sample.put("projectRoot", 12); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample));
if (sample.has("taskId")) {
sample.put("projectRoot", "/project").remove("taskId");
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments(name, sample));
}
}
}
@Test void lookupIsExclusiveAndFrameInputAndPaginationAreBounded() {
ObjectNode lookup = catalog.definition("studio_operation_get").get("exampleArguments").deepCopy();
lookup.put("clientRequestId", "request"); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_operation_get", lookup));
lookup.remove(List.of("clientRequestId", "operationId")); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_operation_get", lookup));
lookup.put("clientRequestId", "request"); catalog.validateArguments("studio_operation_get", lookup);
ObjectNode advance = catalog.definition("studio_headless_advance").get("exampleArguments").deepCopy();
advance.put("frames", -1); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_advance", advance));
advance.put("frames", 1.5); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_advance", advance));
ObjectNode reference = catalog.definition("studio_reference_read").get("exampleArguments").deepCopy();
reference.put("limit", 0); assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_reference_read", reference));
ObjectNode input = catalog.definition("studio_headless_set_input").get("exampleArguments").deepCopy();
((ObjectNode) input.get("input")).put("touchX", Long.MAX_VALUE);
assertThrows(IllegalArgumentException.class, () -> catalog.validateArguments("studio_headless_set_input", input));
}
@Test void imageBytesAndMetadataArePreservedWithoutFileTransport() throws Exception {
byte[] png = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9l0AAAAASUVORK5CYII=");
var capture = new CanonicalCapture("session", "build", 123, 7, 1, 1, 1, png);
var wire = McpToolResult.capture(mapper, capture, true).wire();
assertArrayEquals(png, Base64.getDecoder().decode(wire.get("content").get(1).get("data").asText()));
assertEquals("image/png", wire.get("content").get(1).get("mimeType").asText());
assertEquals(wire.get("structuredContent").toString(), wire.get("content").get(0).get("text").asText());
var value = wire.get("structuredContent").get("value");
assertEquals(123, value.get("logicalFrameIndex").asLong()); assertEquals(7, value.get("frameId").asLong());
assertTrue(value.get("stale").asBoolean()); assertEquals("RGBA8888", value.get("pixelFormat").asText());
}
@Test void unavailableHandlersAreNotAdvertisedOrInvoked() {
var registry = new McpToolRegistry(catalog, mapper, Map.of());
assertTrue(registry.descriptors().isEmpty());
assertThrows(IllegalArgumentException.class, () -> registry.call("studio_project_context", catalog.definition("studio_project_context").get("exampleArguments")));
}
@Test void neutralLookupProgressAndReferencesDoNotInventUnknownValues() {
assertThrows(IllegalArgumentException.class, () -> new OperationLookup(null, null));
assertThrows(IllegalArgumentException.class, () -> new OperationLookup("id", "request"));
assertThrows(IllegalArgumentException.class, () -> new TrackedOperation.Progress(4L, 5L));
assertNull(new TrackedOperation.Progress(null, null).completedFrames());
assertFalse(ProjectKnowledge.Version.unknown().known());
assertNull(ProjectKnowledge.Version.unknown().value());
assertEquals(1, new ProjectKnowledge.ReferencePage("unicode", 0, 2, 1, "🎮").nextOffset());
assertThrows(IllegalArgumentException.class, () -> new ProjectKnowledge.ReferencePage("invalid", 0, 1, 1, "ab"));
}
}
@@ -9,6 +9,13 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
@AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class)
class StudioBoundaryArchTest {
@ArchTest
static final ArchRule automationTransportStaysInTheApp = noClasses()
.that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..")
.should().dependOnClassesThat().resideInAnyPackage(
"p.studio.app.mcp..", "com.sun.net.httpserver..", "io.modelcontextprotocol..")
.because("DEC-0060 confines MCP and HTTP transport to application adapters");
@ArchTest
static final ArchRule staticContainerCannotReturn = noClasses()
.that().resideInAnyPackage("p.studio..")
@@ -0,0 +1,15 @@
package p.studio.api.automation;
import java.util.Objects;
/** Stable domain failure codes, independent of HTTP status and JSON-RPC errors. */
public record AutomationFailure(Code code, String message) {
public enum Code {
PROJECT_NOT_OPEN, NOT_GRANTED, INVALID_TASK, BUSY, CLOSED, CLEANUP_FAILED,
UNSUPPORTED_LANGUAGE, UNSUPPORTED_CAPABILITY, REFERENCE_NOT_FOUND, DOCUMENTATION_UNAVAILABLE,
OUTSIDE_PROJECT_SCOPE, READ_ONLY_SCOPE, OPERATION_NOT_FOUND, CLIENT_REQUEST_CONFLICT,
RUNTIME_UNAVAILABLE, RUNTIME_INCOMPATIBLE, SESSION_NOT_FOUND, BUILD_NOT_FOUND,
NO_FRAME_AVAILABLE, LIMIT_EXCEEDED, NOT_CANCELABLE, INFRASTRUCTURE_FAILURE
}
public AutomationFailure { Objects.requireNonNull(code); Objects.requireNonNull(message); }
}
@@ -0,0 +1,11 @@
package p.studio.api.automation;
/** Exactly one lookup key, always scoped to a separately validated project/task identity. */
public record OperationLookup(String operationId, String clientRequestId) {
public OperationLookup {
if ((operationId == null) == (clientRequestId == null)
|| (operationId != null && operationId.isBlank())
|| (clientRequestId != null && clientRequestId.isBlank()))
throw new IllegalArgumentException("Supply exactly one nonblank operationId or clientRequestId");
}
}
@@ -0,0 +1,63 @@
package p.studio.api.automation;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
/** Installed, owner-maintained knowledge. Authentication belongs to the calling adapter. */
public interface ProjectKnowledge {
Context context(Path openProjectRoot);
ReferencePage readReference(Path openProjectRoot, String referenceId, int offset, int limit);
record Version(String value, String source) {
public Version {
Objects.requireNonNull(source, "source");
if (source.isBlank() || value != null && value.isBlank()) throw new IllegalArgumentException("Blank version provenance");
}
public boolean known() { return value != null; }
public static Version unknown() { return new Version(null, "unknown"); }
}
enum Support { SUPPORTED, UNSUPPORTED, UNKNOWN }
record Capability(String name, Support support, String limitation) {
public Capability { Objects.requireNonNull(name); Objects.requireNonNull(support); }
}
record Language(String id, boolean primary, Version languageVersion, Version compilerVersion,
Version sdkVersion, List<String> extensions, List<Path> sourceRoots,
List<Capability> capabilities, List<String> referenceIds) {
public Language {
Objects.requireNonNull(id); Objects.requireNonNull(languageVersion);
Objects.requireNonNull(compilerVersion); Objects.requireNonNull(sdkVersion);
extensions = List.copyOf(extensions); sourceRoots = List.copyOf(sourceRoots);
capabilities = List.copyOf(capabilities); referenceIds = List.copyOf(referenceIds);
}
}
enum ReferenceKind { QUICKSTART, SYNTAX, SEMANTICS, EXAMPLE, SDK, LIBRARY }
record Reference(String id, String title, String owner, ReferenceKind kind, Version version) {
public Reference { Objects.requireNonNull(id); Objects.requireNonNull(title); Objects.requireNonNull(owner); Objects.requireNonNull(kind); Objects.requireNonNull(version); }
}
record Library(String id, Version version, List<Path> roots, boolean editable) {
public Library { Objects.requireNonNull(id); Objects.requireNonNull(version); roots = List.copyOf(roots); }
}
record Context(Path projectRoot, String projectName, List<Language> languages,
List<Library> libraries, List<Path> editableRoots, List<Path> readOnlyRoots,
List<Reference> references, List<String> limitations) {
public Context {
projectRoot = Objects.requireNonNull(projectRoot).toAbsolutePath().normalize();
Objects.requireNonNull(projectName);
languages = List.copyOf(languages); libraries = List.copyOf(libraries);
editableRoots = List.copyOf(editableRoots); readOnlyRoots = List.copyOf(readOnlyRoots);
references = List.copyOf(references); limitations = List.copyOf(limitations);
}
}
/** Offsets and limits count Unicode code points, not bytes or UTF-16 code units. */
record ReferencePage(String referenceId, int offset, int total, Integer nextOffset, String text) {
public ReferencePage {
Objects.requireNonNull(referenceId); Objects.requireNonNull(text);
int count = text.codePointCount(0, text.length());
if (offset < 0 || total < offset || count > total - offset
|| (nextOffset == null && count != total - offset)
|| (nextOffset != null && (nextOffset != offset + count || nextOffset >= total || count == 0)))
throw new IllegalArgumentException("Invalid reference page");
}
}
}
@@ -0,0 +1,23 @@
package p.studio.api.automation;
import p.studio.api.operation.OperationSnapshot;
import p.studio.api.shipper.ShipperPrepareResult;
import java.util.Objects;
/** An operation outcome is not task authority. Null result means it is not available yet. */
public record TrackedOperation(OperationSnapshot operation, String clientRequestId, Progress progress,
String buildId, ShipperPrepareResult buildResult, AutomationOutcome runtimeResult, AutomationFailure failure) {
public TrackedOperation {
Objects.requireNonNull(operation); Objects.requireNonNull(clientRequestId); Objects.requireNonNull(progress);
if (clientRequestId.isBlank()) throw new IllegalArgumentException("Empty client request identity");
if (buildResult != null && runtimeResult != null) throw new IllegalArgumentException("Mixed operation result kinds");
}
/** Unknown progress stays null. Never infer completion from cancellation acknowledgement. */
public record Progress(Long requestedFrames, Long completedFrames) {
public Progress {
if (requestedFrames != null && requestedFrames < 0 || completedFrames != null && completedFrames < 0
|| requestedFrames != null && completedFrames != null && completedFrames > requestedFrames)
throw new IllegalArgumentException("Invalid frame progress");
}
}
}