add MCP tool contracts and authenticated local HTTP transport
This commit is contained in:
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user