fix(mcp): reclaim transport sessions and preserve recovery correlation
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

This commit is contained in:
2026-11-27 00:00:54 +00:00
parent fccfeca39d
commit a2494e7d70
6 changed files with 381 additions and 18 deletions
@@ -18,9 +18,18 @@ 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 static final long SESSION_IDLE_NANOS = TimeUnit.SECONDS.toNanos(60);
private final ObjectMapper mapper;
private final McpToolRegistry tools;
private record Session(ProjectCredentials.Credential credential, AtomicBoolean initialized, java.util.concurrent.atomic.AtomicLong lastSeen) { }
private final java.util.function.LongSupplier nanoTime;
/** Activity is guarded by sessions, independently of project/task authority. */
private static final class Session {
final ProjectCredentials.Credential credential;
final AtomicBoolean initialized = new AtomicBoolean();
long lastSeen;
int activeRequests;
Session(ProjectCredentials.Credential credential, long now) { this.credential = credential; lastSeen = now; }
}
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
private final ProjectCredentials credentials = new ProjectCredentials();
private volatile String instanceId;
@@ -32,9 +41,11 @@ public final class LocalMcpServer implements AutoCloseable {
}
public String catalogFingerprint() { return tools.catalogFingerprint(); }
public boolean connected(java.nio.file.Path root) {
long now = System.nanoTime();
return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root)
&& now - s.lastSeen.get() < TimeUnit.SECONDS.toNanos(10));
synchronized (sessions) {
long now = nanoTime.getAsLong();
return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root)
&& now - s.lastSeen < TimeUnit.SECONDS.toNanos(10));
}
}
private final SecureRandom random = new SecureRandom();
private HttpServer server;
@@ -52,9 +63,24 @@ public final class LocalMcpServer implements AutoCloseable {
}
public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) {
this(mapper, tools, System::nanoTime);
}
LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools, java.util.function.LongSupplier nanoTime) {
this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.tools = Objects.requireNonNull(tools);
this.nanoTime = Objects.requireNonNull(nanoTime);
}
private void expireSessions(long now) {
// Callers hold sessions: admission, renewal and expiry must be atomic.
sessions.values().removeIf(s -> !s.credential.active()
|| s.activeRequests == 0 && now - s.lastSeen >= SESSION_IDLE_NANOS);
}
private void maintainConnections() {
synchronized (sessions) { expireSessions(nanoTime.getAsLong()); }
connectionListeners.forEach(LocalMcpServer::notifyConnectionListener);
}
public void start() throws IOException {
@@ -72,7 +98,7 @@ public final class LocalMcpServer implements AutoCloseable {
next.createContext("/mcp", this::handle);
next.setExecutor(workers);
next.start();
timers.scheduleWithFixedDelay(() -> connectionListeners.forEach(LocalMcpServer::notifyConnectionListener), 2, 2, TimeUnit.SECONDS);
timers.scheduleWithFixedDelay(this::maintainConnections, 2, 2, TimeUnit.SECONDS);
executor = workers; server = next;
} catch (RuntimeException failure) {
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
@@ -107,6 +133,7 @@ public final class LocalMcpServer implements AutoCloseable {
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);
Session admittedSession = null;
try (exchange) {
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
@@ -127,10 +154,19 @@ public final class LocalMcpServer implements AutoCloseable {
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");
var session = sessionId == null ? null : sessions.get(sessionId);
final Session session;
synchronized (sessions) {
long now = nanoTime.getAsLong();
expireSessions(now);
session = sessionId == null ? null : sessions.get(sessionId);
if (session != null && session.credential == credential) {
session.activeRequests++;
session.lastSeen = now;
admittedSession = session;
}
}
if (session != null && session.credential != credential) { empty(exchange, 403); return; }
AtomicBoolean initialized = session == null ? null : session.initialized;
if (session != null) session.lastSeen.set(System.nanoTime());
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; }
@@ -171,9 +207,9 @@ public final class LocalMcpServer implements AutoCloseable {
send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return;
}
synchronized (sessions) {
sessions.values().removeIf(s -> !s.credential.active());
expireSessions(nanoTime.getAsLong());
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
sessionId = secret(); sessions.put(sessionId, new Session(credential, new AtomicBoolean(), new java.util.concurrent.atomic.AtomicLong(System.nanoTime())));
sessionId = secret(); sessions.put(sessionId, new Session(credential, nanoTime.getAsLong()));
}
exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId);
var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION);
@@ -217,7 +253,13 @@ public final class LocalMcpServer implements AutoCloseable {
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); }
} finally {
timeout.cancel(false);
if (admittedSession != null) synchronized (sessions) {
admittedSession.lastSeen = nanoTime.getAsLong();
admittedSession.activeRequests--;
}
}
}
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) {
@@ -21,14 +21,17 @@ final class StudioMcpConnection implements AutoCloseable {
// Diagnostic correlation only: Core remains the sole validator of task authority.
private final LinkedHashMap<String, String> observedTaskInstances = new LinkedHashMap<>();
private long sequence;
private boolean closed;
private volatile String status = "WAITING_FOR_ACCESS";
StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; }
String status() { return status; }
synchronized void probe() {
if (closed) return;
try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; }
catch (Exception failure) { disconnect(); }
}
synchronized JsonNode call(String tool, JsonNode arguments) {
if (closed) return failure("CLOSED", "The connector is closed.");
boolean dispatched = false;
try {
catalog.validateArguments(tool, arguments);
@@ -64,7 +67,8 @@ final class StudioMcpConnection implements AutoCloseable {
dispatched ? "Response unavailable; do not replay. For the same authorized task, look up operationId/clientRequestId. After Studio restart, obtain a new grant; old receipts may be unavailable."
: guidance());
if (dispatched && arguments != null && arguments.path("clientRequestId").isTextual())
((ObjectNode) result.path("structuredContent").path("error")).put("clientRequestId", arguments.path("clientRequestId").asText());
((ObjectNode) result.path("structuredContent").path("error")).putObject("details")
.put("clientRequestId", arguments.path("clientRequestId").asText());
((ObjectNode) result.path("content").get(0)).put("text", result.path("structuredContent").toString());
return result;
}
@@ -87,7 +91,8 @@ final class StudioMcpConnection implements AutoCloseable {
}
if (!catalog.fingerprint().equals(next.catalogFingerprint())) { status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible catalog"); }
if (session != null && next.equals(descriptor)) return;
descriptor = next; session = null; status = "RECONNECTING";
disconnect();
descriptor = next; status = "RECONNECTING";
var params = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1");
var result = exchange("initialize", params, true, 5).required("result");
@@ -165,6 +170,33 @@ final class StudioMcpConnection implements AutoCloseable {
ProtocolFailure(JsonNode error) { super("Studio protocol error"); this.error = error.deepCopy(); }
}
private void disconnect() { if (status.equals("CONNECTED")) status = "RECONNECTING"; session = null; available = Set.of(); }
@Override public void close() { client.shutdownNow(); }
private void disconnect() {
if (status.equals("CONNECTED")) status = "RECONNECTING";
String previous = session;
session = null;
available = Set.of();
if (previous == null || descriptor == null) return;
// A transport session is disposable; deleting it never releases the Core task.
// Use the old descriptor, even when discovery has found another instance.
java.util.concurrent.CompletableFuture<?> pending = null;
try {
var request = HttpRequest.newBuilder(descriptor.endpoint()).timeout(Duration.ofSeconds(2))
.header("Authorization", "Bearer " + descriptor.credential())
.header("Mcp-Session-Id", previous).header("MCP-Protocol-Version", LocalMcpServer.PROTOCOL_VERSION)
.DELETE().build();
pending = client.sendAsync(request, HttpResponse.BodyHandlers.discarding());
pending.get(2, java.util.concurrent.TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
if (pending != null) pending.cancel(true);
Thread.currentThread().interrupt();
} catch (Exception unavailable) {
if (pending != null) pending.cancel(true); // Idle expiry recovers unreachable sessions.
}
}
@Override public synchronized void close() {
if (closed) return;
closed = true;
try { disconnect(); }
finally { client.shutdownNow(); }
}
}