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 sessions = new ConcurrentHashMap<>(); private final SecureRandom random = new SecureRandom(); private HttpServer server; private ExecutorService executor; private ScheduledExecutorService deadlines; private volatile Connection connection; private final java.util.List connectionListeners = new CopyOnWriteArrayList<>(); public p.studio.api.operation.OperationSubscription onConnectionChanged(Runnable listener) { connectionListeners.add(listener); notifyConnectionListener(listener); return () -> connectionListeners.remove(listener); } private static void notifyConnectionListener(Runnable listener) { try { listener.run(); } catch (RuntimeException ignored) { /* Observation cannot change lifecycle. */ } } 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; connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } 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(); connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } /** 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", McpConnectionGuide.INSTRUCTIONS); 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() : ""; } 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); } }