feat(studio): integrate project MCP setup and lifecycle
This commit is contained in:
@@ -40,6 +40,12 @@ class DevDesktopTest {
|
||||
completed.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
static void awaitWaiting(AutomationSession authority) throws Exception {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (authority.snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(5);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
}
|
||||
|
||||
@Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception {
|
||||
var pool = Executors.newSingleThreadExecutor();
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
@@ -70,6 +76,9 @@ class DevDesktopTest {
|
||||
assertEquals(1, subscriptions.get());
|
||||
assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled());
|
||||
((Button) dev[0].rootNode().lookup("#dev-grant")).fire();
|
||||
});
|
||||
awaitWaiting(authority);
|
||||
fx(() -> {
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
@@ -96,8 +105,8 @@ class DevDesktopTest {
|
||||
locale.setLocale(java.util.Locale.forLanguageTag("pt-BR"));
|
||||
host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get());
|
||||
authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
});
|
||||
awaitWaiting(authority);
|
||||
} finally {
|
||||
fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); });
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow();
|
||||
@@ -120,56 +129,39 @@ class DevDesktopTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception {
|
||||
@Test void preparesConnectionWithoutGrantAndRemainsAvailableWhenTransportStops() throws Exception {
|
||||
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
var projects = new p.studio.core.project.ProjectAccessRegistry();
|
||||
var savedClipboard = new java.util.HashMap<javafx.scene.input.DataFormat, Object>();
|
||||
var copied = new java.util.concurrent.atomic.AtomicReference<String>();
|
||||
var prepared = new CompletableFuture<Void>();
|
||||
var view = new DevWorkspace[1]; var stage = new Stage[1];
|
||||
try (var pool = Executors.newSingleThreadExecutor();
|
||||
var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry(
|
||||
new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) {
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool));
|
||||
var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
|
||||
var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper);
|
||||
var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, project -> {
|
||||
prepared.complete(null);
|
||||
return new p.studio.api.automation.AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once.");
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
fx(() -> {
|
||||
var clipboard = javafx.scene.input.Clipboard.getSystemClipboard();
|
||||
clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type)));
|
||||
var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root);
|
||||
view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide);
|
||||
stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show();
|
||||
view[0].load();
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
|
||||
button.fire(); copied.set(clipboard.getString());
|
||||
assertEquals(ControlState.MANUAL, authority.snapshot().state());
|
||||
assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText());
|
||||
assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label)
|
||||
.noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader())));
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); button.fire();
|
||||
});
|
||||
var first = mapper.readTree(copied.get());
|
||||
assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText()));
|
||||
assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText());
|
||||
prepared.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(ControlState.MANUAL, authority.snapshot().state());
|
||||
server.close();
|
||||
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
fx(() -> assertFalse(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
server.start(); authority.grant(false).toCompletableFuture().join();
|
||||
fx(() -> {
|
||||
var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled());
|
||||
button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
});
|
||||
var next = mapper.readTree(copied.get());
|
||||
assertFalse(first.path("headers").equals(next.path("headers")));
|
||||
assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText()));
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state());
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled()));
|
||||
} finally {
|
||||
fx(() -> {
|
||||
if (view[0] != null) view[0].unLoad();
|
||||
if (stage[0] != null) stage[0].close();
|
||||
javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard);
|
||||
});
|
||||
fx(() -> { if (view[0] != null) view[0].unLoad(); if (stage[0] != null) stage[0].close(); });
|
||||
authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package p.studio.app.install;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.app.mcp.StudioAgentPreparation;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.api.project.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class InstalledConnectorTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception {
|
||||
Path base = temporary.resolve("Application Support/Studio");
|
||||
Path source = Path.of(System.getProperty("studio.test.distribution"));
|
||||
Path first = ManagedStudioInstallation.install(source, base);
|
||||
var mapper = new ObjectMapper();
|
||||
var preparation = new StudioAgentPreparation(base, mapper);
|
||||
var catalog = new ProjectCatalogService(temporary, mapper, new ProjectLocalStudioSetupStore(mapper), preparation);
|
||||
var scaffold = catalog.createProject(new ProjectCreationRequest("Scaffold Game", temporary, "pbs", 1, ProjectTarget.Game, "src", 8, "/my/runtime"));
|
||||
assertTrue(preparation.status(scaffold.rootPath()).ready());
|
||||
Path existing = Files.createDirectory(temporary.resolve("Existing Project"));
|
||||
Files.copy(scaffold.rootPath().resolve("prometeu.json"), existing.resolve("prometeu.json"));
|
||||
Files.createDirectory(existing.resolve(".studio"));
|
||||
Files.writeString(existing.resolve(".studio/setup.json"), "{\"runtimePath\":\"/preserved/runtime\",\"custom\":42}");
|
||||
Files.createDirectory(existing.resolve(".codex"));
|
||||
String custom = "# preserve\napproval_policy = \"on-request\"\n[mcp_servers.other]\ncommand = \"other\"\n";
|
||||
Files.writeString(existing.resolve(".codex/config.toml"), custom);
|
||||
assertTrue(preparation.prepare(existing).ready());
|
||||
var config = existing.resolve(".codex/config.toml");
|
||||
String stable = Files.readString(config); var modified = Files.getLastModifiedTime(config);
|
||||
assertTrue(stable.startsWith(custom)); assertTrue(preparation.prepare(existing).ready());
|
||||
assertEquals(stable, Files.readString(config)); assertEquals(modified, Files.getLastModifiedTime(config));
|
||||
var setup = mapper.readTree(Files.readString(existing.resolve(".studio/setup.json")));
|
||||
assertEquals(42, setup.path("custom").asInt()); assertEquals("/preserved/runtime", setup.path("runtimePath").asText());
|
||||
assertFalse(Files.exists(existing.resolve(".studio/mcp/connection.json")));
|
||||
runConnector(base, existing);
|
||||
Path second = ManagedStudioInstallation.install(source, base);
|
||||
assertNotEquals(first, second); assertTrue(Files.isDirectory(first));
|
||||
assertEquals(second.toRealPath(), base.resolve("current").toRealPath());
|
||||
assertEquals(stable, Files.readString(config)); runConnector(base, existing);
|
||||
assertThrows(Exception.class, () -> ManagedStudioInstallation.install(existing, base));
|
||||
assertEquals(second.toRealPath(), base.resolve("current").toRealPath()); runConnector(base, existing);
|
||||
// Test fixture only: installed runtime/lib must load and start JavaFX, without checkout application classes.
|
||||
String fixtures = Path.of(DesktopProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
|
||||
var desktop = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*") + java.io.File.pathSeparator + fixtures,
|
||||
DesktopProbe.class.getName()).redirectError(temporary.resolve("desktop.stderr").toFile()).start();
|
||||
try { assertTrue(desktop.waitFor(20, TimeUnit.SECONDS)); assertEquals(0, desktop.exitValue(), Files.readString(temporary.resolve("desktop.stderr"))); }
|
||||
finally { desktop.destroyForcibly(); }
|
||||
}
|
||||
void runConnector(Path base, Path root) throws Exception {
|
||||
var process = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*").toString(),
|
||||
"p.studio.app.StudioLauncher", "mcp", "--project", root.toRealPath().toString()).start();
|
||||
try {
|
||||
String input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"installed-test\",\"version\":\"1\"}}}\n";
|
||||
process.getOutputStream().write(input.getBytes(java.nio.charset.StandardCharsets.UTF_8)); process.getOutputStream().close();
|
||||
assertTrue(process.waitFor(15, TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
|
||||
assertEquals("prometeu-studio", new ObjectMapper().readTree(process.getInputStream()).path("result").path("serverInfo").path("name").asText());
|
||||
} finally { process.destroyForcibly(); }
|
||||
}
|
||||
ProcessBuilder minimal(String... args) {
|
||||
var builder = new ProcessBuilder(args).directory(temporary.toFile());
|
||||
builder.environment().clear(); builder.environment().put("PATH", "/usr/bin:/bin"); builder.environment().put("HOME", System.getProperty("user.home"));
|
||||
return builder;
|
||||
}
|
||||
public static class DesktopProbe {
|
||||
public static void main(String[] args) {
|
||||
javafx.application.Platform.startup(() -> {
|
||||
try {
|
||||
var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX")));
|
||||
stage.show(); stage.close(); System.exit(0);
|
||||
} catch (Throwable failure) { System.exit(2); }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AutomationLspQueriesTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ExecutorService workers = Executors.newCachedThreadPool();
|
||||
@@ -134,6 +135,8 @@ class AutomationLspQueriesTest {
|
||||
try (var server = new p.studio.app.mcp.LocalMcpServer(mapper, tools);
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
|
||||
var setup = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
setup.putObject("capabilities"); setup.putObject("clientInfo").put("name", "language-test").put("version", "1");
|
||||
@@ -155,7 +158,7 @@ class AutomationLspQueriesTest {
|
||||
private java.net.http.HttpResponse<String> post(java.net.http.HttpClient client, p.studio.app.mcp.LocalMcpServer server,
|
||||
String connection, JsonNode body) throws Exception {
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(15))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", httpAuthorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
@@ -15,6 +15,12 @@ class LocalMcpServerTest {
|
||||
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
LocalMcpServer server;
|
||||
String session;
|
||||
@org.junit.jupiter.api.io.TempDir java.nio.file.Path root;
|
||||
String authorization;
|
||||
void authorize(java.nio.file.Path project) throws Exception {
|
||||
var credential = server.credentials().prepare(project.toRealPath());
|
||||
credential.activate(); authorization = "Bearer " + credential.secret();
|
||||
}
|
||||
AtomicInteger calls;
|
||||
|
||||
@BeforeEach void start() throws Exception {
|
||||
@@ -22,7 +28,7 @@ class LocalMcpServerTest {
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of(
|
||||
"studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); },
|
||||
"studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required")))));
|
||||
server.start();
|
||||
server.start(); authorize(root);
|
||||
}
|
||||
@AfterEach void close() { server.close(); client.close(); }
|
||||
HttpResponse<String> request(String method, URI uri, String body, String token, String origin, String protocol, String sessionId) throws Exception {
|
||||
@@ -35,7 +41,7 @@ class LocalMcpServerTest {
|
||||
return client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
HttpResponse<String> post(String body) throws Exception {
|
||||
return request("POST", server.connection().endpoint(), body, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session);
|
||||
return request("POST", server.connection().endpoint(), body.replace("/project", root.toRealPath().toString()), authorization, null, LocalMcpServer.PROTOCOL_VERSION, session);
|
||||
}
|
||||
static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; }
|
||||
void initialize() throws Exception {
|
||||
@@ -51,11 +57,11 @@ class LocalMcpServerTest {
|
||||
var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
|
||||
assertEquals(200, response.statusCode()); assertEquals(1, calls.get());
|
||||
assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText());
|
||||
assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode());
|
||||
assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode());
|
||||
assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode());
|
||||
}
|
||||
@Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception {
|
||||
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
|
||||
var endpoint = server.connection().endpoint(); var token = authorization;
|
||||
assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0);
|
||||
assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode());
|
||||
assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode());
|
||||
@@ -66,10 +72,10 @@ class LocalMcpServerTest {
|
||||
assertFalse(server.connection().toString().contains(token.substring(7)));
|
||||
}
|
||||
@Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception {
|
||||
initialize(); var old = server.connection(); server.close();
|
||||
initialize(); var old = authorization; server.close();
|
||||
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
|
||||
server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader()));
|
||||
assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode());
|
||||
server.start(); authorize(root); assertFalse(old.equals(authorization));
|
||||
assertEquals(401, request("POST", server.connection().endpoint(), init(), old, null, null, null).statusCode());
|
||||
assertEquals(404, post(init()).statusCode());
|
||||
session = null; initialize();
|
||||
}
|
||||
@@ -81,13 +87,13 @@ class LocalMcpServerTest {
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode());
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode());
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode());
|
||||
assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode());
|
||||
assertEquals(400, request("POST", server.connection().endpoint(), init(), authorization, null, "unknown", session).statusCode());
|
||||
var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}");
|
||||
assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get());
|
||||
assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode());
|
||||
}
|
||||
@Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception {
|
||||
var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader();
|
||||
var endpoint = server.connection().endpoint(); var token = authorization;
|
||||
assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode());
|
||||
var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt());
|
||||
@@ -117,7 +123,7 @@ class LocalMcpServerTest {
|
||||
server.close();
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper,
|
||||
McpProjectKnowledgeTools.handlers(knowledge, mapper)));
|
||||
server.start();
|
||||
server.start(); authorize(root);
|
||||
initialize();
|
||||
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call");
|
||||
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString());
|
||||
@@ -153,13 +159,13 @@ class LocalMcpServerTest {
|
||||
var connection = server.connection();
|
||||
try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) {
|
||||
socket.setSoTimeout(3000);
|
||||
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + connection.authorizationHeader()
|
||||
String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + authorization
|
||||
+ "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine();
|
||||
assertTrue(status.contains("403"));
|
||||
}
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
|
||||
assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
@@ -167,13 +173,29 @@ class LocalMcpServerTest {
|
||||
|
||||
@Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception {
|
||||
var connection = server.connection();
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(init())).build();
|
||||
assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader())
|
||||
var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization)
|
||||
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build();
|
||||
assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
}
|
||||
@Test void projectCredentialsCannotCrossRootsOrReuseAnotherSession() throws Exception {
|
||||
initialize();
|
||||
var other = java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath();
|
||||
var credential = server.credentials().prepare(other); credential.activate();
|
||||
var wire = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\"}";
|
||||
assertEquals(403, request("POST", server.connection().endpoint(), wire, "Bearer " + credential.secret(), null,
|
||||
LocalMcpServer.PROTOCOL_VERSION, session).statusCode());
|
||||
var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 5).put("method", "tools/call");
|
||||
call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", other.toString());
|
||||
var reply = mapper.readTree(post(call.toString()).body());
|
||||
assertEquals("OUTSIDE_PROJECT_SCOPE", reply.path("result").path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(0, calls.get());
|
||||
server.credentials().authenticate(authorization).invalidate();
|
||||
assertEquals(401, post(wire).statusCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,38 +15,34 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class McpConnectionGuideTest {
|
||||
@TempDir Path root;
|
||||
@Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() throws Exception {
|
||||
@Test void preparationIsStableAndSeparateFromAuthority() throws Exception {
|
||||
var mapper = new ObjectMapper(); var projects = new ProjectAccessRegistry();
|
||||
try (var workers = Executors.newSingleThreadExecutor();
|
||||
var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) {
|
||||
var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers));
|
||||
var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority);
|
||||
var guide = new McpConnectionGuide(server, projects, mapper);
|
||||
assertTrue(guide.endpoint().isEmpty());
|
||||
assertThrows(IllegalStateException.class, () -> guide.configuration(root));
|
||||
var notifications = new AtomicInteger();
|
||||
var subscription = guide.subscribe(notifications::incrementAndGet);
|
||||
server.start(); assertEquals(2, notifications.get());
|
||||
var descriptor = mapper.readTree(guide.configuration(root));
|
||||
assertEquals(server.connection().endpoint().toString(), descriptor.path("url").asText());
|
||||
assertEquals(root.toRealPath().toString(), descriptor.path("projectRoot").asText());
|
||||
// Do not put bearer credentials into assertion diagnostics.
|
||||
assertTrue(server.connection().authorizationHeader().equals(descriptor.path("headers").path("Authorization").asText()));
|
||||
assertFalse(guide.toString().contains(descriptor.path("headers").path("Authorization").asText()));
|
||||
var prepared = new AtomicInteger();
|
||||
var canonical = root.toRealPath();
|
||||
var guide = new McpConnectionGuide(server, projects, mapper, project -> {
|
||||
assertEquals(canonical, project); prepared.incrementAndGet();
|
||||
return new AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once.");
|
||||
});
|
||||
assertEquals(AgentConnectionGuide.State.UNAVAILABLE, guide.state(root));
|
||||
var stable = guide.configuration(root);
|
||||
assertTrue(guide.prepare(root).ready()); assertEquals(1, prepared.get());
|
||||
assertEquals(ControlState.MANUAL, authority.snapshot().state());
|
||||
assertNull(authority.snapshot().task());
|
||||
server.start();
|
||||
assertEquals(AgentConnectionGuide.State.WAITING_FOR_ACCESS, guide.state(root));
|
||||
assertFalse(stable.contains("Bearer"));
|
||||
for (var instruction : List.of("studio_project_context", "studio_reference_read", "studio_control_acquire", "studio_control_release",
|
||||
"studio_language_query", "studio_build_start", "clientRequestId", "read-only", "restart", "native file writes"))
|
||||
assertTrue(descriptor.path("instructions").asText().contains(instruction));
|
||||
var old = server.connection(); server.close(); assertEquals(3, notifications.get()); assertTrue(guide.endpoint().isEmpty());
|
||||
server.start(); assertEquals(4, notifications.get());
|
||||
var fresh = mapper.readTree(guide.configuration(root));
|
||||
assertTrue(fresh.path("headers").path("Authorization").asText().equals(server.connection().authorizationHeader()));
|
||||
assertFalse(fresh.path("headers").path("Authorization").asText().equals(old.authorizationHeader()));
|
||||
assertTrue(stable.contains(instruction));
|
||||
server.close(); server.start(); assertEquals(stable, guide.configuration(root));
|
||||
assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened")));
|
||||
authority.closeAsync().toCompletableFuture().join();
|
||||
assertThrows(AutomationException.class, () -> guide.configuration(root));
|
||||
registration.close(); subscription.close(); server.close(); assertEquals(4, notifications.get());
|
||||
registration.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class McpTaskToolsTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ExecutorService workers = Executors.newCachedThreadPool();
|
||||
@@ -243,6 +244,8 @@ class McpTaskToolsTest {
|
||||
compose(shipper);
|
||||
try (var server = new LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize");
|
||||
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
params.putObject("capabilities"); params.putObject("clientInfo").put("name", "task-test").put("version", "1");
|
||||
@@ -281,6 +284,8 @@ class McpTaskToolsTest {
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
server.start();
|
||||
var credential = server.credentials().prepare(root.toRealPath());
|
||||
credential.activate(); httpAuthorization = "Bearer " + credential.secret();
|
||||
var unauthorized = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}"))
|
||||
.timeout(java.time.Duration.ofSeconds(5)).build();
|
||||
assertEquals(401, client.send(unauthorized, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
@@ -315,7 +320,7 @@ class McpTaskToolsTest {
|
||||
var captured = httpCall(client, server, first, "studio_headless_capture", args()); value(captured);
|
||||
assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(captured.path("content").get(1).path("data").asText()));
|
||||
var deleted = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", first).build();
|
||||
.header("Authorization", httpAuthorization).header("Mcp-Session-Id", first).build();
|
||||
assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
|
||||
String reconnected = connect(client, server);
|
||||
@@ -367,7 +372,7 @@ class McpTaskToolsTest {
|
||||
}
|
||||
java.net.http.HttpResponse<String> post(java.net.http.HttpClient client, LocalMcpServer server, String connection, JsonNode body) throws Exception {
|
||||
var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(10))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", httpAuthorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectConnectionPublisherTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
LocalMcpServer server;
|
||||
Path root;
|
||||
@BeforeEach void start() throws Exception {
|
||||
root = temporary.toRealPath();
|
||||
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of())); server.start();
|
||||
}
|
||||
@AfterEach void stop() { server.close(); }
|
||||
@Test void publishesPrivatelyOnlyActivatesExplicitlyAndCleansUpOwnedGeneration() throws Exception {
|
||||
Files.writeString(root.resolve(".gitignore"), "# existing\n/build/\n");
|
||||
var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
var publication = publisher.prepare(root);
|
||||
publication.publish();
|
||||
var descriptor = ProjectConnectionFiles.read(root, mapper);
|
||||
assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
|
||||
publication.activate();
|
||||
assertEquals(root, server.credentials().authenticate("Bearer " + descriptor.credential()).root());
|
||||
var file = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(file));
|
||||
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(file.getParent()));
|
||||
assertFalse(descriptor.toString().contains(descriptor.credential()));
|
||||
assertThrows(Exception.class, () -> publisher.prepare(root));
|
||||
publication.invalidate(); assertNull(server.credentials().authenticate("Bearer " + descriptor.credential()));
|
||||
publication.close(); assertFalse(Files.exists(file)); assertTrue(Files.exists(file.resolveSibling("publication.lock")));
|
||||
try (var next = publisher.prepare(root)) {
|
||||
next.publish(); next.activate(); publication.close();
|
||||
assertTrue(Files.exists(file));
|
||||
assertNotEquals(descriptor.credential(), ProjectConnectionFiles.read(root, mapper).credential());
|
||||
}
|
||||
assertEquals("# existing\n/build/\n/.studio/mcp/\n", Files.readString(root.resolve(".gitignore")));
|
||||
}
|
||||
@Test void unsafePathsAndPermissionsNeverPublishSecrets() throws Exception {
|
||||
Path destination = Files.createDirectory(root.resolve("outside"));
|
||||
Files.createSymbolicLink(root.resolve(".studio"), destination);
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
assertFalse(Files.exists(destination.resolve("mcp")));
|
||||
Files.delete(root.resolve(".studio"));
|
||||
Path directory = ProjectConnectionFiles.directory(root);
|
||||
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("rwxr-xr-x"));
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
}
|
||||
@Test void malformedDescriptorsNeverSupplyAnArbitraryEndpoint() throws Exception {
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
publication.publish();
|
||||
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
var valid = mapper.readTree(Files.readString(path));
|
||||
for (String endpoint : java.util.List.of("https://example.com/mcp", "http://127.0.0.1:123/mcp?x=1", "http://localhost:123/mcp")) {
|
||||
var bad = valid.deepCopy(); ((com.fasterxml.jackson.databind.node.ObjectNode) bad).put("endpoint", endpoint);
|
||||
Files.writeString(path, bad.toString()); assertThrows(Exception.class, () -> ProjectConnectionFiles.read(root, mapper));
|
||||
}
|
||||
Files.writeString(path, valid.toString());
|
||||
}
|
||||
}
|
||||
@Test void osLockRejectsAnotherJvmAndCrashAllowsRecoveryWithoutUnlinkingLock() throws Exception {
|
||||
Process owner = ownerProcess();
|
||||
try {
|
||||
assertEquals("READY", java.util.concurrent.CompletableFuture.supplyAsync(() -> {
|
||||
try { return owner.inputReader().readLine(); } catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); }
|
||||
}).get(10, java.util.concurrent.TimeUnit.SECONDS));
|
||||
var lock = root.resolve(".studio/mcp/publication.lock");
|
||||
var inode = Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey();
|
||||
Process conflict = ownerProcess();
|
||||
try { assertTrue(conflict.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(2, conflict.exitValue()); }
|
||||
finally { conflict.destroyForcibly(); }
|
||||
owner.destroyForcibly(); assertTrue(owner.waitFor(10, java.util.concurrent.TimeUnit.SECONDS));
|
||||
assertTrue(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)));
|
||||
try (var recovered = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
recovered.publish(); recovered.activate();
|
||||
assertEquals(server.instanceId(), ProjectConnectionFiles.read(root, mapper).instanceId());
|
||||
assertEquals(inode, Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey());
|
||||
}
|
||||
} finally { owner.destroyForcibly(); }
|
||||
}
|
||||
@Test void trackedDiscoveryTargetIsRejectedWithoutWritingCredentials() throws Exception {
|
||||
var directory = ProjectConnectionFiles.directory(root);
|
||||
var target = directory.resolve("connection.json"); Files.writeString(target, "tracked placeholder");
|
||||
for (var command : java.util.List.of(java.util.List.of("git", "init", "-q"), java.util.List.of("git", "add", "-f", ProjectConnectionFiles.RELATIVE))) {
|
||||
var process = new ProcessBuilder(command).directory(root.toFile()).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
assertTrue(process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(0, process.exitValue());
|
||||
}
|
||||
assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root));
|
||||
assertEquals("tracked placeholder", Files.readString(target));
|
||||
assertFalse(Files.exists(directory.resolve("publication.lock")));
|
||||
}
|
||||
|
||||
private Process ownerProcess() throws Exception {
|
||||
return new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin/java").toString(), "-cp",
|
||||
System.getProperty("studio.test.classpath"), Owner.class.getName(), root.toString())
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
}
|
||||
public static class Owner {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var mapper = new ObjectMapper();
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) {
|
||||
server.start();
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(Path.of(args[0]))) {
|
||||
publication.publish(); publication.activate(); System.out.println("READY"); System.out.flush(); System.in.read();
|
||||
} catch (Exception conflict) { System.exit(2); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StudioAgentPreparationTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void preservesUnrelatedTomlAndRejectsUserOwnedOrEditedEntry() throws Exception {
|
||||
var preparation = new StudioAgentPreparation(temporary.resolve("Application Support/Studio"), new ObjectMapper());
|
||||
String entry = preparation.entry(temporary.toRealPath());
|
||||
String custom = "# keep exactly\napproval_policy = \"on-request\"\n[mcp_servers.custom]\ncommand = \"custom\"\n";
|
||||
String merged = StudioAgentPreparation.merge(custom, entry);
|
||||
assertTrue(merged.startsWith(custom)); assertEquals(merged, StudioAgentPreparation.merge(merged, entry));
|
||||
assertFalse(merged.contains("credential")); assertFalse(merged.contains("connection.json"));
|
||||
assertThrows(Exception.class, () -> StudioAgentPreparation.merge("[mcp_servers.prometeu_studio]\ncommand=\"mine\"\n", entry));
|
||||
assertThrows(Exception.class, () -> StudioAgentPreparation.merge(merged.replace("startup_timeout_sec = 20", "startup_timeout_sec = 30"), entry));
|
||||
String updated = StudioAgentPreparation.merge(merged, preparation.entry(temporary.resolve("another project")));
|
||||
assertTrue(updated.startsWith(custom)); assertTrue(updated.contains("another project"));
|
||||
}
|
||||
@Test void absentInstallationReportsIncompleteAndDoesNotModifyClientConfig() throws Exception {
|
||||
Files.writeString(temporary.resolve("prometeu.json"), "{}");
|
||||
Files.createDirectory(temporary.resolve(".codex"));
|
||||
Path config = temporary.resolve(".codex/config.toml"); Files.writeString(config, "# preserve\n");
|
||||
var preparation = new StudioAgentPreparation(temporary.resolve("missing"), new ObjectMapper());
|
||||
var result = preparation.prepare(temporary);
|
||||
assertFalse(result.ready()); assertEquals("# preserve\n", Files.readString(config));
|
||||
assertTrue(result.message().contains("Studio installation is missing"));
|
||||
assertTrue(result.message().contains(":prometeu-app:stageStudioInstallation"));
|
||||
assertTrue(result.message().contains("-Dstudio.installationRoot"));
|
||||
assertFalse(Files.exists(temporary.resolve(".studio/mcp")));
|
||||
assertEquals(result, preparation.status(temporary.toRealPath()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package p.studio.app.mcp.stdio;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.app.mcp.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StudioMcpStdioTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
Path root;
|
||||
@BeforeEach void project() throws Exception { root = temporary.toRealPath(); Files.writeString(root.resolve("prometeu.json"), "{}"); }
|
||||
LocalMcpServer server(AtomicInteger calls, String image) {
|
||||
return new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of("studio_project_context", args -> {
|
||||
calls.incrementAndGet();
|
||||
return McpToolResult.successWithCapture(mapper, mapper.createObjectNode().put("projectRoot", args.path("projectRoot").asText()),
|
||||
new p.studio.api.automation.CanonicalCapture("session", "build", 1, 1, 1, 1, 1, Base64.getDecoder().decode(image)), false);
|
||||
})));
|
||||
}
|
||||
@Test void coldProcessDiscoversLaterGrantPreservesLargeImagesAndSurvivesRestart() throws Exception {
|
||||
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
|
||||
try (var process = new Connector(root); var server = server(count, pixels)) {
|
||||
process.initialize();
|
||||
assertEquals(17, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
|
||||
var waiting = process.call("studio_project_context", root);
|
||||
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
|
||||
assertFalse(Files.exists(root.resolve(".studio")));
|
||||
server.start();
|
||||
var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
var result = process.call("studio_project_context", root);
|
||||
assertFalse(result.path("isError").asBoolean(), result.path("structuredContent").toString());
|
||||
assertEquals(pixels, result.path("content").get(1).path("data").asText());
|
||||
assertEquals(root.toString(), result.path("structuredContent").path("value").path("projectRoot").asText());
|
||||
Path other = Files.createDirectory(root.resolve("other"));
|
||||
assertEquals("OUTSIDE_PROJECT_SCOPE", process.call("studio_project_context", other).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(1, count.get());
|
||||
}
|
||||
server.close(); server.start();
|
||||
assertEquals("WAITING_FOR_ACCESS", process.call("studio_project_context", root).path("structuredContent").path("error").path("code").asText());
|
||||
try (var fresh = publisher.prepare(root)) {
|
||||
fresh.publish(); fresh.activate();
|
||||
assertFalse(process.call("studio_project_context", root).path("isError").asBoolean());
|
||||
assertEquals(2, count.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test void invalidArgumentsAndMalformedLinesDoNotLaunchDesktopOrBreakCorrelation() throws Exception {
|
||||
try (var connector = new Connector(root)) {
|
||||
connector.send("{bad json}");
|
||||
assertEquals(-32700, connector.read().path("error").path("code").asInt());
|
||||
connector.initialize();
|
||||
assertEquals(-32601, connector.request("no-method", mapper.createObjectNode()).path("error").path("code").asInt());
|
||||
assertTrue(connector.request("ping", mapper.createObjectNode()).has("result"));
|
||||
}
|
||||
var process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", "relative")
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
assertTrue(process.waitFor(10, TimeUnit.SECONDS)); assertNotEquals(0, process.exitValue());
|
||||
assertEquals(0, process.getInputStream().readAllBytes().length);
|
||||
}
|
||||
@Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception {
|
||||
var builds = new AtomicInteger(); var mapper = this.mapper;
|
||||
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_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")));
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
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);
|
||||
var dropped = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
proxy.createContext("/mcp", exchange -> {
|
||||
try (exchange) {
|
||||
var bytes = exchange.getRequestBody().readAllBytes();
|
||||
var incoming = mapper.readTree(bytes);
|
||||
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);
|
||||
}
|
||||
var response = transport.send(request.POST(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)) {
|
||||
exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response.
|
||||
}
|
||||
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());
|
||||
} 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();
|
||||
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());
|
||||
var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1");
|
||||
var unknown = connection.call("studio_build_start", args);
|
||||
assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals("intent-1", unknown.path("structuredContent").path("error").path("clientRequestId").asText());
|
||||
connection.probe(); assertEquals(1, builds.get());
|
||||
var recovered = connection.call("studio_operation_get", args);
|
||||
assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText());
|
||||
assertEquals(1, builds.get());
|
||||
} finally { proxy.stop(0); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception {
|
||||
var calls = new AtomicInteger();
|
||||
var handlers = Map.<String, java.util.function.Function<JsonNode, McpToolResult>>of(
|
||||
"studio_control_acquire", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("taskId", UUID.randomUUID().toString())),
|
||||
"studio_operation_get", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "fresh")); });
|
||||
try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers));
|
||||
var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||
server.start(); var publisher = new ProjectConnectionPublisher(server, mapper);
|
||||
String task;
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
task = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
|
||||
.path("structuredContent").path("value").path("taskId").asText();
|
||||
}
|
||||
server.close(); server.start();
|
||||
try (var publication = publisher.prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
var old = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", task).put("clientRequestId", "old");
|
||||
assertEquals("OUTCOME_UNKNOWN", connection.call("studio_operation_get", old).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(0, calls.get());
|
||||
String fresh = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString()))
|
||||
.path("structuredContent").path("value").path("taskId").asText();
|
||||
old.put("taskId", fresh);
|
||||
assertFalse(connection.call("studio_operation_get", old).path("isError").asBoolean()); assertEquals(1, calls.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void staleIdentityAndCatalogMismatchAreRejectedBeforeToolDispatch() throws Exception {
|
||||
var calls = new AtomicInteger();
|
||||
try (var server = server(calls, "AAAA")) {
|
||||
server.start();
|
||||
try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) {
|
||||
publication.publish(); publication.activate();
|
||||
Path path = root.resolve(ProjectConnectionFiles.RELATIVE);
|
||||
String valid = Files.readString(path);
|
||||
try {
|
||||
for (String field : List.of("instanceId", "catalogFingerprint")) {
|
||||
var invalid = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(valid); invalid.put(field, "outdated");
|
||||
Files.writeString(path, invalid.toString());
|
||||
try (var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) {
|
||||
var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString()));
|
||||
assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE",
|
||||
result.path("structuredContent").path("error").path("code").asText());
|
||||
}
|
||||
}
|
||||
assertEquals(0, calls.get());
|
||||
} finally { Files.writeString(path, valid); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String java() { return Path.of(System.getProperty("java.home"), "bin/java").toString(); }
|
||||
static String classpath() { return System.getProperty("studio.test.classpath"); }
|
||||
final class Connector implements AutoCloseable {
|
||||
final Process process;
|
||||
final BufferedReader reader;
|
||||
final BufferedWriter writer;
|
||||
final ExecutorService reads = Executors.newSingleThreadExecutor();
|
||||
final Path errors;
|
||||
int sequence;
|
||||
Connector(Path project) throws Exception {
|
||||
errors = Files.createTempFile(temporary, "stdio-", ".stderr");
|
||||
process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", project.toString())
|
||||
.directory(temporary.toFile()).redirectError(errors.toFile()).start();
|
||||
reader = process.inputReader(); writer = process.outputWriter();
|
||||
}
|
||||
void send(String value) throws Exception { writer.write(value); writer.newLine(); writer.flush(); }
|
||||
JsonNode read() throws Exception {
|
||||
String line = reads.submit(reader::readLine).get(15, TimeUnit.SECONDS);
|
||||
assertNotNull(line, Files.readString(errors)); return mapper.readTree(line);
|
||||
}
|
||||
JsonNode request(String method, JsonNode params) throws Exception {
|
||||
var value = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", ++sequence).put("method", method); value.set("params", params);
|
||||
send(value.toString()); var response = read(); assertEquals(sequence, response.path("id").asInt()); return response;
|
||||
}
|
||||
void initialize() throws Exception {
|
||||
var params = mapper.createObjectNode().put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "process-test").put("version", "1");
|
||||
assertEquals("2025-06-18", request("initialize", params).path("result").path("protocolVersion").asText());
|
||||
send("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}");
|
||||
}
|
||||
JsonNode call(String name, Path root) throws Exception {
|
||||
var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString());
|
||||
return request("tools/call", params).path("result");
|
||||
}
|
||||
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)); }
|
||||
finally { process.destroyForcibly(); reads.shutdownNow(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ class HeadlessMcpDesktopTest {
|
||||
LocalMcpServer server;
|
||||
HttpClient client;
|
||||
String connection, task, build, session;
|
||||
String authorization = "Bearer unavailable";
|
||||
Path installation, source;
|
||||
DevWorkspace dev;
|
||||
Stage stage;
|
||||
@@ -76,9 +77,9 @@ class HeadlessMcpDesktopTest {
|
||||
stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance");
|
||||
stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load();
|
||||
});
|
||||
connect();
|
||||
}
|
||||
void connect() throws Exception {
|
||||
authorization = "Bearer " + p.studio.app.mcp.ProjectConnectionFiles.read(root, mapper).credential();
|
||||
connection = null;
|
||||
var initialize = request("initialize");
|
||||
var params = initialize.putObject("params").put("protocolVersion", "2025-06-18");
|
||||
@@ -96,8 +97,15 @@ class HeadlessMcpDesktopTest {
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test");
|
||||
}
|
||||
|
||||
void acquire() throws Exception {
|
||||
void grant() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (project.automation().snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(10);
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
|
||||
connect();
|
||||
}
|
||||
void acquire() throws Exception {
|
||||
grant();
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
}
|
||||
void prepareLongRun() throws Exception {
|
||||
@@ -121,7 +129,7 @@ class HeadlessMcpDesktopTest {
|
||||
prepareLongRun();
|
||||
var receipt = startRunning("cancel-me");
|
||||
var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE()
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build();
|
||||
.header("Authorization", authorization).header("Mcp-Session-Id", connection).build();
|
||||
assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
client.close(); client = HttpClient.newHttpClient(); connect();
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state());
|
||||
@@ -159,7 +167,7 @@ class HeadlessMcpDesktopTest {
|
||||
refreshEntered.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state());
|
||||
assertFalse(project.automation().snapshot().manualAllowed());
|
||||
assertEquals("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame");
|
||||
refreshGate.complete(null);
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
@@ -169,19 +177,19 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
|
||||
@Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception {
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
grant();
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
prepareLongRun(); startRunning("close-project");
|
||||
fx(dev::unLoad);
|
||||
assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime");
|
||||
project.close();
|
||||
assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive));
|
||||
assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
project = app.getBean(ProjectSessionFactory.class).open(project.projectReference());
|
||||
assertEquals(ControlState.MANUAL, project.automation().snapshot().state());
|
||||
assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText());
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
}
|
||||
|
||||
@Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception {
|
||||
@@ -270,13 +278,13 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
|
||||
@Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception {
|
||||
assertEquals(401, post(request("ping")).statusCode());
|
||||
grant();
|
||||
assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size());
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
|
||||
assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference");
|
||||
assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText());
|
||||
fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire());
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
assertFalse(task.isBlank());
|
||||
@@ -442,7 +450,7 @@ class HeadlessMcpDesktopTest {
|
||||
}
|
||||
HttpResponse<String> post(JsonNode body) throws Exception {
|
||||
var request = HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15))
|
||||
.header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json")
|
||||
.header("Authorization", authorization).header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18");
|
||||
if (connection != null) request.header("Mcp-Session-Id", connection);
|
||||
return client.send(request.POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
Reference in New Issue
Block a user