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
@@ -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);
}
}