fix(mcp): reclaim transport sessions and preserve recovery correlation
This commit is contained in:
@@ -55,6 +55,23 @@ only the connection session, not project authority. Accepted notifications and
|
|||||||
client responses return 202 without a body. Notification/disconnection alone
|
client responses return 202 without a body. Notification/disconnection alone
|
||||||
MUST NOT revoke a task or cancel an operation already returned by operationId.
|
MUST NOT revoke a task or cancel an operation already returned by operationId.
|
||||||
|
|
||||||
|
The integrated connector MUST attempt authenticated DELETE before discarding a
|
||||||
|
known HTTP session on close, failed-connection recovery or descriptor replacement.
|
||||||
|
It MUST use that session's original endpoint and credential, bound cleanup to two
|
||||||
|
seconds and preserve the original outcome if cleanup fails. Closing is idempotent;
|
||||||
|
a closed connector MUST NOT reconnect through subsequent calls or background probes.
|
||||||
|
DELETE MUST NOT be substituted with task release or replay of a tool call.
|
||||||
|
|
||||||
|
The server MUST reclaim connection sessions after 60 seconds without transport
|
||||||
|
activity, as well as sessions whose credentials are inactive. A request already
|
||||||
|
being handled protects its session from idle expiration; completion renews the
|
||||||
|
idle period. Maintenance runs periodically and expired sessions are reclaimed
|
||||||
|
before session admission. Connector pings renew activity. Idle expiration returns
|
||||||
|
404 on subsequent use of the expired identity and never revokes project/task
|
||||||
|
authority, cancels admitted work or deletes task-local operation receipts. Clients
|
||||||
|
may initialize another connection and look up an existing receipt under the same
|
||||||
|
still-authorized task. The 128-session limit still applies to live connections.
|
||||||
|
|
||||||
The transport bounds incoming bodies to 1 MiB, sessions to 128 and request
|
The transport bounds incoming bodies to 1 MiB, sessions to 128 and request
|
||||||
handling to a bounded worker queue. Oversized bodies return 413; exhausted
|
handling to a bounded worker queue. Oversized bodies return 413; exhausted
|
||||||
session capacity returns 503. Stalled exchanges close after 15 seconds. These
|
session capacity returns 503. Stalled exchanges close after 15 seconds. These
|
||||||
@@ -97,6 +114,9 @@ reconnection. Calls cannot wait indefinitely for a grant. No reconnect path may
|
|||||||
resubmit a tool call. An uncertain response MUST retain available clientRequestId
|
resubmit a tool call. An uncertain response MUST retain available clientRequestId
|
||||||
correlation and instruct receipt lookup within the same authorized task. A new
|
correlation and instruct receipt lookup within the same authorized task. A new
|
||||||
desktop/task has no old receipt registry and requires a fresh human grant.
|
desktop/task has no old receipt registry and requires a fresh human grant.
|
||||||
|
Connector-generated uncertain-outcome errors carry that correlation in
|
||||||
|
`error.details.clientRequestId`, within the advertised output schema; the text
|
||||||
|
content block MUST serialize the identical structured envelope.
|
||||||
|
|
||||||
### 1.2 Stable Installation and Project Preparation
|
### 1.2 Stable Installation and Project Preparation
|
||||||
|
|
||||||
|
|||||||
@@ -18,9 +18,18 @@ public final class LocalMcpServer implements AutoCloseable {
|
|||||||
public static final String PROTOCOL_VERSION = "2025-06-18";
|
public static final String PROTOCOL_VERSION = "2025-06-18";
|
||||||
private static final int MAX_BODY_BYTES = 1024 * 1024;
|
private static final int MAX_BODY_BYTES = 1024 * 1024;
|
||||||
private static final int MAX_CONNECTION_SESSIONS = 128;
|
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 ObjectMapper mapper;
|
||||||
private final McpToolRegistry tools;
|
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 Map<String, Session> sessions = new ConcurrentHashMap<>();
|
||||||
private final ProjectCredentials credentials = new ProjectCredentials();
|
private final ProjectCredentials credentials = new ProjectCredentials();
|
||||||
private volatile String instanceId;
|
private volatile String instanceId;
|
||||||
@@ -32,9 +41,11 @@ public final class LocalMcpServer implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
public String catalogFingerprint() { return tools.catalogFingerprint(); }
|
public String catalogFingerprint() { return tools.catalogFingerprint(); }
|
||||||
public boolean connected(java.nio.file.Path root) {
|
public boolean connected(java.nio.file.Path root) {
|
||||||
long now = System.nanoTime();
|
synchronized (sessions) {
|
||||||
return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root)
|
long now = nanoTime.getAsLong();
|
||||||
&& now - s.lastSeen.get() < TimeUnit.SECONDS.toNanos(10));
|
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 final SecureRandom random = new SecureRandom();
|
||||||
private HttpServer server;
|
private HttpServer server;
|
||||||
@@ -52,9 +63,24 @@ public final class LocalMcpServer implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) {
|
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)
|
this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
|
||||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||||
this.tools = Objects.requireNonNull(tools);
|
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 {
|
public void start() throws IOException {
|
||||||
@@ -72,7 +98,7 @@ public final class LocalMcpServer implements AutoCloseable {
|
|||||||
next.createContext("/mcp", this::handle);
|
next.createContext("/mcp", this::handle);
|
||||||
next.setExecutor(workers);
|
next.setExecutor(workers);
|
||||||
next.start();
|
next.start();
|
||||||
timers.scheduleWithFixedDelay(() -> connectionListeners.forEach(LocalMcpServer::notifyConnectionListener), 2, 2, TimeUnit.SECONDS);
|
timers.scheduleWithFixedDelay(this::maintainConnections, 2, 2, TimeUnit.SECONDS);
|
||||||
executor = workers; server = next;
|
executor = workers; server = next;
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null;
|
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 {
|
private void handle(HttpExchange exchange) throws IOException {
|
||||||
// Bounds stalled body reads and transport responses, not guest simulated time or task lifetime.
|
// Bounds stalled body reads and transport responses, not guest simulated time or task lifetime.
|
||||||
var timeout = deadlines.schedule(exchange::close, 15, TimeUnit.SECONDS);
|
var timeout = deadlines.schedule(exchange::close, 15, TimeUnit.SECONDS);
|
||||||
|
Session admittedSession = null;
|
||||||
try (exchange) {
|
try (exchange) {
|
||||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
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");
|
String version = single(headers, "MCP-Protocol-Version");
|
||||||
if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; }
|
if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; }
|
||||||
String sessionId = single(headers, "Mcp-Session-Id");
|
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; }
|
if (session != null && session.credential != credential) { empty(exchange, 403); return; }
|
||||||
AtomicBoolean initialized = session == null ? null : session.initialized;
|
AtomicBoolean initialized = session == null ? null : session.initialized;
|
||||||
if (session != null) session.lastSeen.set(System.nanoTime());
|
|
||||||
if (sessionId != null && initialized == null) { empty(exchange, 404); return; }
|
if (sessionId != null && initialized == null) { empty(exchange, 404); return; }
|
||||||
String method = exchange.getRequestMethod();
|
String method = exchange.getRequestMethod();
|
||||||
if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; }
|
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;
|
send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return;
|
||||||
}
|
}
|
||||||
synchronized (sessions) {
|
synchronized (sessions) {
|
||||||
sessions.values().removeIf(s -> !s.credential.active());
|
expireSessions(nanoTime.getAsLong());
|
||||||
if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; }
|
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);
|
exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId);
|
||||||
var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION);
|
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));
|
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 (IllegalArgumentException invalid) { send(exchange, 200, error(id, -32602, "Invalid tool or parameters")); }
|
||||||
catch (RuntimeException failure) { send(exchange, 200, error(id, -32603, "Internal error")); }
|
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 String secret() { byte[] bytes = new byte[32]; random.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); }
|
||||||
private static String single(Headers headers, String name) {
|
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.
|
// Diagnostic correlation only: Core remains the sole validator of task authority.
|
||||||
private final LinkedHashMap<String, String> observedTaskInstances = new LinkedHashMap<>();
|
private final LinkedHashMap<String, String> observedTaskInstances = new LinkedHashMap<>();
|
||||||
private long sequence;
|
private long sequence;
|
||||||
|
private boolean closed;
|
||||||
private volatile String status = "WAITING_FOR_ACCESS";
|
private volatile String status = "WAITING_FOR_ACCESS";
|
||||||
StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; }
|
StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; }
|
||||||
String status() { return status; }
|
String status() { return status; }
|
||||||
synchronized void probe() {
|
synchronized void probe() {
|
||||||
|
if (closed) return;
|
||||||
try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; }
|
try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; }
|
||||||
catch (Exception failure) { disconnect(); }
|
catch (Exception failure) { disconnect(); }
|
||||||
}
|
}
|
||||||
synchronized JsonNode call(String tool, JsonNode arguments) {
|
synchronized JsonNode call(String tool, JsonNode arguments) {
|
||||||
|
if (closed) return failure("CLOSED", "The connector is closed.");
|
||||||
boolean dispatched = false;
|
boolean dispatched = false;
|
||||||
try {
|
try {
|
||||||
catalog.validateArguments(tool, arguments);
|
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."
|
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());
|
: guidance());
|
||||||
if (dispatched && arguments != null && arguments.path("clientRequestId").isTextual())
|
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());
|
((ObjectNode) result.path("content").get(0)).put("text", result.path("structuredContent").toString());
|
||||||
return result;
|
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 (!catalog.fingerprint().equals(next.catalogFingerprint())) { status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible catalog"); }
|
||||||
if (session != null && next.equals(descriptor)) return;
|
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);
|
var params = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION);
|
||||||
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1");
|
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1");
|
||||||
var result = exchange("initialize", params, true, 5).required("result");
|
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(); }
|
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(); }
|
private void disconnect() {
|
||||||
@Override public void close() { client.shutdownNow(); }
|
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(); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import java.net.http.*;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import java.util.concurrent.*;
|
||||||
import p.studio.api.automation.*;
|
import p.studio.api.automation.*;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
@@ -61,6 +63,105 @@ class LocalMcpServerTest {
|
|||||||
assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode());
|
assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode());
|
||||||
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
|
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void useClock(AtomicLong clock, Map<String, java.util.function.Function<com.fasterxml.jackson.databind.JsonNode, McpToolResult>> handlers) throws Exception {
|
||||||
|
server.close();
|
||||||
|
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers), clock::get);
|
||||||
|
server.start(); authorize(root); session = null;
|
||||||
|
}
|
||||||
|
private HttpResponse<String> ping(String id) throws Exception {
|
||||||
|
return request("POST", server.connection().endpoint(), "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}",
|
||||||
|
authorization, null, LocalMcpServer.PROTOCOL_VERSION, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void abandonedSessionsExpireWithoutEvictingActiveSessionsAtCapacity() throws Exception {
|
||||||
|
var clock = new AtomicLong(); useClock(clock, Map.of());
|
||||||
|
String first = null, live = null;
|
||||||
|
for (int index = 0; index < 128; index++) {
|
||||||
|
var response = post(init()); assertEquals(200, response.statusCode());
|
||||||
|
live = response.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||||
|
if (first == null) first = live;
|
||||||
|
}
|
||||||
|
assertEquals(503, post(init()).statusCode(), "128 live sessions must still enforce the resource limit");
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(59));
|
||||||
|
assertEquals(200, ping(live).statusCode());
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(60));
|
||||||
|
assertEquals(200, post(init()).statusCode(), "Expired orphans must free slots before admission");
|
||||||
|
assertEquals(404, ping(first).statusCode());
|
||||||
|
assertEquals(200, ping(live).statusCode(), "Authenticated transport activity must renew a session");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void inFlightRequestsSurviveIdleExpiryAndCompletionRenewsTheSession() throws Exception {
|
||||||
|
var clock = new AtomicLong(); var entered = new CountDownLatch(1); var release = new CountDownLatch(1);
|
||||||
|
useClock(clock, Map.of("studio_project_context", args -> {
|
||||||
|
entered.countDown();
|
||||||
|
try { if (!release.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("Fixture timeout"); }
|
||||||
|
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IllegalStateException(interrupted); }
|
||||||
|
return McpToolResult.success(mapper, mapper.createObjectNode());
|
||||||
|
}));
|
||||||
|
initialize(); String original = session;
|
||||||
|
var call = CompletableFuture.supplyAsync(() -> {
|
||||||
|
try { return post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}"); }
|
||||||
|
catch (Exception failure) { throw new CompletionException(failure); }
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
assertTrue(entered.await(3, TimeUnit.SECONDS));
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(61));
|
||||||
|
assertEquals(200, request("POST", server.connection().endpoint(), init(), authorization, null, null, null).statusCode());
|
||||||
|
assertEquals(200, ping(original).statusCode(), "A running request must protect its transport session");
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(122));
|
||||||
|
release.countDown(); assertEquals(200, call.get(3, TimeUnit.SECONDS).statusCode());
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(181));
|
||||||
|
assertEquals(200, ping(original).statusCode(), "Completion, not only admission, must renew idle time");
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(241));
|
||||||
|
assertEquals(404, ping(original).statusCode());
|
||||||
|
} finally { release.countDown(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void transportExpiryAndDeletePreserveTheTaskAndBuildReceipt() throws Exception {
|
||||||
|
java.nio.file.Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"game\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
|
||||||
|
var workers = Executors.newCachedThreadPool(); var clock = new AtomicLong(); var builds = new AtomicInteger();
|
||||||
|
var authority = new p.studio.core.session.DefaultAutomationSession(root.toRealPath(), new p.studio.app.operation.ExecutorOperationExecutor(workers));
|
||||||
|
var access = new p.studio.core.project.ProjectAccessRegistry();
|
||||||
|
access.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
|
||||||
|
var projects = new p.studio.core.project.ProjectCatalogService(root.getParent(), mapper, new p.studio.core.project.ProjectLocalStudioSetupStore(mapper));
|
||||||
|
var tasks = new p.studio.core.session.DefaultTaskTools(access, projects, (project, sink) -> {
|
||||||
|
builds.incrementAndGet();
|
||||||
|
return p.studio.api.shipper.ShipperPrepareResult.failed(List.of(), List.of("Controlled compile rejection"));
|
||||||
|
}, Optional.empty());
|
||||||
|
try {
|
||||||
|
useClock(clock, McpTaskTools.handlers(tasks, mapper, false));
|
||||||
|
assertTrue(authority.grant(false).toCompletableFuture().get(3, TimeUnit.SECONDS).success());
|
||||||
|
initialize();
|
||||||
|
var base = mapper.createObjectNode().put("projectRoot", root.toString());
|
||||||
|
var acquired = rpcTool("studio_control_acquire", base);
|
||||||
|
String task = acquired.path("structuredContent").path("value").path("taskId").asText();
|
||||||
|
assertFalse(task.isBlank());
|
||||||
|
base.put("taskId", task).put("clientRequestId", "one-build");
|
||||||
|
String operation = rpcTool("studio_build_start", base).path("structuredContent").path("value").path("operationId").asText();
|
||||||
|
var terminated = tasks.operation(root, task, new OperationLookup(operation, null));
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
|
||||||
|
while (!terminated.workerTerminated() && System.nanoTime() < deadline) {
|
||||||
|
Thread.sleep(5); terminated = tasks.operation(root, task, new OperationLookup(operation, null));
|
||||||
|
}
|
||||||
|
assertTrue(terminated.workerTerminated());
|
||||||
|
clock.set(TimeUnit.SECONDS.toNanos(60)); assertEquals(404, ping(session).statusCode());
|
||||||
|
session = null; initialize();
|
||||||
|
assertEquals(operation, rpcTool("studio_operation_get", base).path("structuredContent").path("value").path("operationId").asText());
|
||||||
|
assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode());
|
||||||
|
session = null; initialize();
|
||||||
|
assertEquals(operation, rpcTool("studio_operation_get", base).path("structuredContent").path("value").path("operationId").asText());
|
||||||
|
assertEquals(task, authority.snapshot().task().value()); assertEquals(1, builds.get());
|
||||||
|
} finally { authority.closeAsync().toCompletableFuture().get(3, TimeUnit.SECONDS); workers.shutdownNow(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private com.fasterxml.jackson.databind.JsonNode rpcTool(String name, com.fasterxml.jackson.databind.node.ObjectNode arguments) throws Exception {
|
||||||
|
var message = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 3).put("method", "tools/call");
|
||||||
|
message.putObject("params").put("name", name).set("arguments", arguments);
|
||||||
|
var result = mapper.readTree(post(message.toString()).body()).path("result");
|
||||||
|
McpContractAssertions.assertValidResult(new McpToolCatalog(mapper), name, result);
|
||||||
|
assertFalse(result.path("isError").asBoolean(), result.toString()); return result;
|
||||||
|
}
|
||||||
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
|
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
|
||||||
var endpoint = server.connection().endpoint(); var token = authorization;
|
var endpoint = server.connection().endpoint(); var token = authorization;
|
||||||
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
|
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package p.studio.app.mcp;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** Validate actual connector output with the same packaged contract as discovery. */
|
||||||
|
public final class McpContractAssertions {
|
||||||
|
private McpContractAssertions() { }
|
||||||
|
|
||||||
|
public static void assertValidResult(McpToolCatalog catalog, String tool, JsonNode result) {
|
||||||
|
assertDoesNotThrow(() -> ContractSchema.validate(catalog.definition(tool).required("outputSchema"),
|
||||||
|
result.required("structuredContent")), tool);
|
||||||
|
assertEquals(result.required("structuredContent").toString(), result.path("content").get(0).path("text").asText());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import java.util.*;
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static p.studio.app.mcp.McpContractAssertions.assertValidResult;
|
||||||
|
|
||||||
@org.junit.jupiter.api.Tag("integration")
|
@org.junit.jupiter.api.Tag("integration")
|
||||||
class StudioMcpStdioTest {
|
class StudioMcpStdioTest {
|
||||||
@@ -67,7 +68,14 @@ class StudioMcpStdioTest {
|
|||||||
assertEquals(0, process.getInputStream().readAllBytes().length);
|
assertEquals(0, process.getInputStream().readAllBytes().length);
|
||||||
}
|
}
|
||||||
@Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception {
|
@Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception {
|
||||||
|
lostBuildResponse(false);
|
||||||
|
}
|
||||||
|
@Test void failedSessionDeletionDoesNotHideLostResponseOrReplayWork() throws Exception {
|
||||||
|
lostBuildResponse(true);
|
||||||
|
}
|
||||||
|
private void lostBuildResponse(boolean rejectDelete) throws Exception {
|
||||||
var builds = new AtomicInteger(); var mapper = this.mapper;
|
var builds = new AtomicInteger(); var mapper = this.mapper;
|
||||||
|
var deletes = new AtomicInteger();
|
||||||
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
||||||
"studio_build_start", args -> { builds.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")); },
|
"studio_build_start", args -> { builds.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")); },
|
||||||
"studio_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")));
|
"studio_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")));
|
||||||
@@ -78,13 +86,17 @@ class StudioMcpStdioTest {
|
|||||||
var dropped = new java.util.concurrent.atomic.AtomicBoolean();
|
var dropped = new java.util.concurrent.atomic.AtomicBoolean();
|
||||||
proxy.createContext("/mcp", exchange -> {
|
proxy.createContext("/mcp", exchange -> {
|
||||||
try (exchange) {
|
try (exchange) {
|
||||||
|
if (exchange.getRequestMethod().equals("DELETE")) {
|
||||||
|
deletes.incrementAndGet();
|
||||||
|
if (rejectDelete) { exchange.sendResponseHeaders(503, -1); return; }
|
||||||
|
}
|
||||||
var bytes = exchange.getRequestBody().readAllBytes();
|
var bytes = exchange.getRequestBody().readAllBytes();
|
||||||
var incoming = mapper.readTree(bytes);
|
var incoming = bytes.length == 0 ? mapper.nullNode() : mapper.readTree(bytes);
|
||||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint());
|
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint());
|
||||||
for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) {
|
for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) {
|
||||||
String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value);
|
String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value);
|
||||||
}
|
}
|
||||||
var response = transport.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray());
|
var response = transport.send(request.method(exchange.getRequestMethod(), java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray());
|
||||||
if (incoming.path("params").path("name").asText().equals("studio_build_start") && dropped.compareAndSet(false, true)) {
|
if (incoming.path("params").path("name").asText().equals("studio_build_start") && dropped.compareAndSet(false, true)) {
|
||||||
exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response.
|
exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response.
|
||||||
}
|
}
|
||||||
@@ -103,7 +115,10 @@ class StudioMcpStdioTest {
|
|||||||
var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1");
|
var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1");
|
||||||
var unknown = connection.call("studio_build_start", args);
|
var unknown = connection.call("studio_build_start", args);
|
||||||
assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText());
|
assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText());
|
||||||
assertEquals("intent-1", unknown.path("structuredContent").path("error").path("clientRequestId").asText());
|
assertEquals("intent-1", unknown.path("structuredContent").path("error").path("details").path("clientRequestId").asText());
|
||||||
|
assertFalse(unknown.path("structuredContent").path("error").has("clientRequestId"));
|
||||||
|
assertValidResult(new McpToolCatalog(mapper), "studio_build_start", unknown);
|
||||||
|
assertEquals(1, deletes.get(), "Discarding a failed connection must attempt DELETE exactly once");
|
||||||
connection.probe(); assertEquals(1, builds.get());
|
connection.probe(); assertEquals(1, builds.get());
|
||||||
var recovered = connection.call("studio_operation_get", args);
|
var recovered = connection.call("studio_operation_get", args);
|
||||||
assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText());
|
assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText());
|
||||||
@@ -112,6 +127,140 @@ class StudioMcpStdioTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test void moreThan128ClosedConnectorsReuseCapacityAndCloseCannotReconnect() throws Exception {
|
||||||
|
var calls = new AtomicInteger(); var catalog = new McpToolCatalog(mapper);
|
||||||
|
try (var server = server(calls, "AAAA")) {
|
||||||
|
server.start();
|
||||||
|
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||||
|
publication.publish(); publication.activate();
|
||||||
|
for (int index = 0; index < 132; index++) {
|
||||||
|
try (var connection = new StudioMcpConnection(root, mapper, catalog)) {
|
||||||
|
var args = mapper.createObjectNode().put("projectRoot", root.toString());
|
||||||
|
var result = connection.call("studio_project_context", args);
|
||||||
|
assertFalse(result.path("isError").asBoolean(), "Connection " + index + ": " + result);
|
||||||
|
connection.close(); connection.close(); connection.probe();
|
||||||
|
var closed = connection.call("studio_project_context", args);
|
||||||
|
assertEquals("CLOSED", closed.path("structuredContent").path("error").path("code").asText());
|
||||||
|
assertValidResult(catalog, "studio_project_context", closed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(132, calls.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void moreThan128LostResponsesCanReconnectWithoutLeakingSessionsOrReplayingCalls() throws Exception {
|
||||||
|
var calls = new AtomicInteger(); var deletes = new AtomicInteger();
|
||||||
|
try (var server = server(calls, "AAAA"); var transport = java.net.http.HttpClient.newHttpClient()) {
|
||||||
|
server.start();
|
||||||
|
var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
proxy.createContext("/mcp", exchange -> {
|
||||||
|
try (exchange) {
|
||||||
|
var bytes = exchange.getRequestBody().readAllBytes();
|
||||||
|
var message = bytes.length == 0 ? mapper.nullNode() : mapper.readTree(bytes);
|
||||||
|
if (exchange.getRequestMethod().equals("DELETE")) deletes.incrementAndGet();
|
||||||
|
var response = forward(server, transport, exchange, bytes);
|
||||||
|
if (message.path("method").asText().equals("tools/call")) {
|
||||||
|
assertEquals(200, response.statusCode());
|
||||||
|
exchange.sendResponseHeaders(200, 100); return; // Lose an already executed read result.
|
||||||
|
}
|
||||||
|
relay(exchange, response);
|
||||||
|
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
|
||||||
|
});
|
||||||
|
proxy.start();
|
||||||
|
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root);
|
||||||
|
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||||
|
publication.publish(); publication.activate(); pointAtProxy(proxy);
|
||||||
|
for (int index = 0; index < 132; index++) {
|
||||||
|
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
|
||||||
|
assertEquals("OUTCOME_UNKNOWN", result.path("structuredContent").path("error").path("code").asText(), "Reconnect " + index);
|
||||||
|
assertValidResult(new McpToolCatalog(mapper), "studio_project_context", result);
|
||||||
|
}
|
||||||
|
assertEquals(132, calls.get(), "Each intentional call executes only once");
|
||||||
|
assertEquals(132, deletes.get());
|
||||||
|
} finally { proxy.stop(0); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void stalledDeleteIsBoundedAndDoesNotPreventIdempotentClose() throws Exception {
|
||||||
|
var calls = new AtomicInteger(); var deletes = new AtomicInteger(); var release = new CountDownLatch(1);
|
||||||
|
try (var server = server(calls, "AAAA"); var transport = java.net.http.HttpClient.newHttpClient()) {
|
||||||
|
server.start();
|
||||||
|
var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
proxy.createContext("/mcp", exchange -> {
|
||||||
|
try (exchange) {
|
||||||
|
if (exchange.getRequestMethod().equals("DELETE")) {
|
||||||
|
deletes.incrementAndGet(); release.await(6, TimeUnit.SECONDS);
|
||||||
|
exchange.sendResponseHeaders(200, -1); return;
|
||||||
|
}
|
||||||
|
relay(exchange, forward(server, transport, exchange, exchange.getRequestBody().readAllBytes()));
|
||||||
|
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
|
||||||
|
});
|
||||||
|
proxy.start();
|
||||||
|
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root);
|
||||||
|
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||||
|
publication.publish(); publication.activate(); pointAtProxy(proxy);
|
||||||
|
assertFalse(connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString())).path("isError").asBoolean());
|
||||||
|
long started = System.nanoTime();
|
||||||
|
assertDoesNotThrow(connection::close);
|
||||||
|
assertTrue(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(4), "DELETE has a two-second budget");
|
||||||
|
connection.close(); connection.probe(); assertEquals(1, deletes.get());
|
||||||
|
assertEquals(1, calls.get());
|
||||||
|
} finally { release.countDown(); proxy.stop(0); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void descriptorReplacementDeletesThroughTheOriginalEndpoint() throws Exception {
|
||||||
|
var calls = new AtomicInteger(); var firstDeletes = new AtomicInteger(); var secondDeletes = new AtomicInteger();
|
||||||
|
try (var server = server(calls, "AAAA"); var transport = java.net.http.HttpClient.newHttpClient()) {
|
||||||
|
server.start();
|
||||||
|
var first = relayProxy(server, transport, firstDeletes); var second = relayProxy(server, transport, secondDeletes);
|
||||||
|
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root);
|
||||||
|
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||||
|
publication.publish(); publication.activate(); pointAtProxy(first);
|
||||||
|
var args = mapper.createObjectNode().put("projectRoot", root.toString());
|
||||||
|
assertFalse(connection.call("studio_project_context", args).path("isError").asBoolean());
|
||||||
|
pointAtProxy(second);
|
||||||
|
assertFalse(connection.call("studio_project_context", args).path("isError").asBoolean());
|
||||||
|
assertEquals(1, firstDeletes.get()); assertEquals(0, secondDeletes.get());
|
||||||
|
connection.close(); assertEquals(1, secondDeletes.get()); assertEquals(2, calls.get());
|
||||||
|
} finally { first.stop(0); second.stop(0); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static com.sun.net.httpserver.HttpServer relayProxy(LocalMcpServer server, java.net.http.HttpClient transport,
|
||||||
|
AtomicInteger deletes) throws IOException {
|
||||||
|
var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
proxy.createContext("/mcp", exchange -> {
|
||||||
|
try (exchange) {
|
||||||
|
if (exchange.getRequestMethod().equals("DELETE")) deletes.incrementAndGet();
|
||||||
|
relay(exchange, forward(server, transport, exchange, exchange.getRequestBody().readAllBytes()));
|
||||||
|
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
|
||||||
|
});
|
||||||
|
proxy.start(); return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void pointAtProxy(com.sun.net.httpserver.HttpServer proxy) throws Exception {
|
||||||
|
var path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||||
|
var descriptor = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(Files.readString(path));
|
||||||
|
descriptor.put("endpoint", "http://127.0.0.1:" + proxy.getAddress().getPort() + "/mcp");
|
||||||
|
Files.writeString(path, descriptor.toString());
|
||||||
|
}
|
||||||
|
private static java.net.http.HttpResponse<byte[]> forward(LocalMcpServer server, java.net.http.HttpClient transport,
|
||||||
|
com.sun.net.httpserver.HttpExchange exchange, byte[] bytes) throws IOException, InterruptedException {
|
||||||
|
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint());
|
||||||
|
for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) {
|
||||||
|
String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value);
|
||||||
|
}
|
||||||
|
return transport.send(request.method(exchange.getRequestMethod(), java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(),
|
||||||
|
java.net.http.HttpResponse.BodyHandlers.ofByteArray());
|
||||||
|
}
|
||||||
|
private static void relay(com.sun.net.httpserver.HttpExchange exchange, java.net.http.HttpResponse<byte[]> response) throws IOException {
|
||||||
|
response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> exchange.getResponseHeaders().set("Mcp-Session-Id", value));
|
||||||
|
exchange.sendResponseHeaders(response.statusCode(), response.body().length == 0 ? -1 : response.body().length);
|
||||||
|
exchange.getResponseBody().write(response.body());
|
||||||
|
}
|
||||||
|
|
||||||
@Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception {
|
@Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception {
|
||||||
var calls = new AtomicInteger();
|
var calls = new AtomicInteger();
|
||||||
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
||||||
@@ -156,6 +305,7 @@ class StudioMcpStdioTest {
|
|||||||
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
|
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
|
||||||
assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE",
|
assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE",
|
||||||
result.path("structuredContent").path("error").path("code").asText());
|
result.path("structuredContent").path("error").path("code").asText());
|
||||||
|
assertValidResult(new McpToolCatalog(mapper), "studio_project_context", result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertEquals(0, calls.get());
|
assertEquals(0, calls.get());
|
||||||
@@ -195,7 +345,9 @@ class StudioMcpStdioTest {
|
|||||||
}
|
}
|
||||||
JsonNode call(String name, Path root) throws Exception {
|
JsonNode call(String name, Path root) throws Exception {
|
||||||
var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString());
|
var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString());
|
||||||
return request("tools/call", params).path("result");
|
var result = request("tools/call", params).path("result");
|
||||||
|
assertValidResult(new McpToolCatalog(mapper), name, result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
public void close() throws Exception {
|
public void close() throws Exception {
|
||||||
try { writer.close(); assertTrue(process.waitFor(10, TimeUnit.SECONDS), "EOF must terminate the connector"); assertEquals(0, process.exitValue(), Files.readString(errors)); }
|
try { writer.close(); assertTrue(process.waitFor(10, TimeUnit.SECONDS), "EOF must terminate the connector"); assertEquals(0, process.exitValue(), Files.readString(errors)); }
|
||||||
|
|||||||
Reference in New Issue
Block a user