Launch the JavaFX 2 project shell on Java 25 with an interactive viewport, managed Play lifecycle and project mutation guards. Preserve headless/MCP and save compatibility, and qualify exact runtime executable bundles. Separate unit JaCoCo gates from opt-in integration suites and use the internal Pong fixture for the headless visual pilot. Move maintenance and native conformance tools into tooling; retain the VS Code extension and update current navigation links. Validation: tooling make verify passed, including 1064 Studio unit tests, JaCoCo thresholds and 22 headless integration tests.
227 lines
18 KiB
Java
227 lines
18 KiB
Java
package p.studio.app.mcp;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import org.junit.jupiter.api.*;
|
|
import java.net.URI;
|
|
import java.net.http.*;
|
|
import java.time.Duration;
|
|
import java.util.*;
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
import p.studio.api.automation.*;
|
|
import static org.junit.jupiter.api.Assertions.*;
|
|
|
|
@org.junit.jupiter.api.Tag("integration")
|
|
class LocalMcpServerTest {
|
|
final ObjectMapper mapper = new ObjectMapper();
|
|
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 {
|
|
calls = new AtomicInteger();
|
|
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(); 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 {
|
|
var request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(5))
|
|
.header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json");
|
|
if (token != null) request.header("Authorization", token);
|
|
if (origin != null) request.header("Origin", origin);
|
|
if (protocol != null) request.header("MCP-Protocol-Version", protocol);
|
|
if (sessionId != null) request.header("Mcp-Session-Id", sessionId);
|
|
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.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 {
|
|
var response = post(init()); assertEquals(200, response.statusCode());
|
|
session = response.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
|
assertEquals(LocalMcpServer.PROTOCOL_VERSION, mapper.readTree(response.body()).path("result").path("protocolVersion").asText());
|
|
assertEquals(202, post("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}").statusCode());
|
|
}
|
|
@Test void lifecycleNegotiatesListsAndCallsOnlyActualHandlers() throws Exception {
|
|
initialize();
|
|
var listed = mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}").body());
|
|
assertEquals(2, listed.path("result").path("tools").size());
|
|
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, 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 = 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());
|
|
for (var origin : List.of("null", "https://evil.example", "http://127.0.0.1:1", "http://localhost:" + endpoint.getPort()))
|
|
assertEquals(403, request("POST", endpoint, init(), token, origin, null, null).statusCode());
|
|
assertEquals(200, request("POST", endpoint, init(), token, "http://" + endpoint.getRawAuthority(), null, null).statusCode());
|
|
assertEquals(0, calls.get());
|
|
assertFalse(server.connection().toString().contains(token.substring(7)));
|
|
}
|
|
@Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception {
|
|
initialize(); var old = authorization; server.close();
|
|
assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection);
|
|
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();
|
|
}
|
|
@Test void malformedBodiesVersionsAndToolsCannotReachProviders() throws Exception {
|
|
initialize();
|
|
assertEquals(400, post("{not json}").statusCode());
|
|
assertEquals(400, post("[]").statusCode());
|
|
assertEquals(400, post("{\"jsonrpc\":2.0,\"id\":1,\"method\":\"ping\"}").statusCode());
|
|
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(), 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 = 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());
|
|
assertEquals(405, request("GET", endpoint, null, token, null, null, session).statusCode());
|
|
assertEquals(404, request("POST", URI.create(endpoint + "/nested"), init(), token, null, null, null).statusCode());
|
|
assertEquals(404, request("POST", URI.create(endpoint + "?token=forbidden"), init(), token, null, null, null).statusCode());
|
|
assertEquals(0, calls.get());
|
|
}
|
|
@Test void authenticatedConnectionDoesNotGrantControl() throws Exception {
|
|
initialize();
|
|
var denied = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_control_acquire\",\"arguments\":{\"projectRoot\":\"/project\"}}}");
|
|
var result = mapper.readTree(denied.body()).path("result");
|
|
assertTrue(result.path("isError").asBoolean()); assertEquals("NOT_GRANTED", result.path("structuredContent").path("error").path("code").asText());
|
|
}
|
|
|
|
@Test void realContextHandlerReadsAnOpenProjectWithoutGrantAndRejectsItAfterClose(
|
|
@org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary) throws Exception {
|
|
var root = temporary.toRealPath();
|
|
java.nio.file.Files.writeString(root.resolve("prometeu.json"), """
|
|
{"name":"HTTP context","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
|
|
""");
|
|
var open = new p.studio.core.project.ProjectAccessRegistry();
|
|
var registration = open.register(root, () -> { throw new AssertionError("Context must not acquire manual control"); }, () -> true);
|
|
var catalog = new p.studio.core.project.ProjectCatalogService(root, mapper,
|
|
new p.studio.core.project.ProjectLocalStudioSetupStore(mapper));
|
|
var knowledge = new p.studio.app.compiler.CompilerProjectKnowledge(open, catalog, mapper);
|
|
server.close();
|
|
server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper,
|
|
McpProjectKnowledgeTools.handlers(knowledge, mapper)));
|
|
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());
|
|
var wire = mapper.readTree(post(call.toString()).body()).path("result");
|
|
assertFalse(wire.path("isError").asBoolean());
|
|
var value = wire.path("structuredContent").path("value");
|
|
assertEquals(root.toString(), value.path("projectRoot").asText());
|
|
assertEquals(root.toString(), value.path("editableRoots").get(0).asText());
|
|
assertEquals("pbs", value.path("languages").get(0).path("id").asText());
|
|
assertTrue(value.path("languages").get(0).path("languageVersion").path("value").isNull());
|
|
assertFalse(java.nio.file.Files.exists(root.resolve(".studio")));
|
|
var params = (com.fasterxml.jackson.databind.node.ObjectNode) call.path("params");
|
|
params.put("name", "studio_reference_read");
|
|
var arguments = (com.fasterxml.jackson.databind.node.ObjectNode) params.path("arguments");
|
|
arguments.put("referenceId", "pbs:quickstart");
|
|
var page = mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("value");
|
|
assertEquals(0, page.path("offset").asInt());
|
|
assertEquals(4000, page.path("text").asText().codePointCount(0, page.path("text").asText().length()));
|
|
assertEquals(4000, page.path("nextOffset").asInt());
|
|
arguments.put("offset", 4294967296L);
|
|
assertEquals(-32602, mapper.readTree(post(call.toString()).body()).path("error").path("code").asInt());
|
|
arguments.remove("offset");
|
|
arguments.put("referenceId", "../../prometeu.json");
|
|
var missing = mapper.readTree(post(call.toString()).body()).path("result");
|
|
assertEquals("REFERENCE_NOT_FOUND", missing.path("structuredContent").path("error").path("code").asText());
|
|
registration.unsubscribe();
|
|
var denied = mapper.readTree(post(call.toString()).body()).path("result");
|
|
assertTrue(denied.path("isError").asBoolean());
|
|
assertEquals("PROJECT_NOT_OPEN", denied.path("structuredContent").path("error").path("code").asText());
|
|
}
|
|
|
|
@Test void hostileHostAndDuplicateOriginAreRejectedEvenWithValidCredentials() throws Exception {
|
|
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: " + 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", 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());
|
|
}
|
|
|
|
@Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception {
|
|
var connection = server.connection();
|
|
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", 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());
|
|
}
|
|
|
|
@Test void evidenceImagesUseAuthenticatedEndpointAndCannotReuseRevokedTasksOrCrossProjectIds() throws Exception {
|
|
root=root.toRealPath();var pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
|
var authority=new p.studio.core.session.DefaultAutomationSession(root,new p.studio.app.operation.ExecutorOperationExecutor(pool));
|
|
var projects=new p.studio.core.project.ProjectAccessRegistry();projects.register(root,authority::enterManual,()->!authority.snapshot().closed(),authority);
|
|
var codec=new p.studio.app.evidence.PngEvidenceCodec();var tools=new p.studio.core.session.DefaultEvidenceTools(projects,null,new p.studio.app.evidence.FileEvidenceStore(mapper),codec);
|
|
byte[] png=codec.encode(new Evidence.Pixels(1,1,new byte[]{1,2,3,(byte)255}));
|
|
var source=root.resolve("reference.png");java.nio.file.Files.write(source,png);
|
|
var artifact=tools.importReference(root,null,"human-import",source,null).artifacts().getFirst();
|
|
try {
|
|
server.close();server=new LocalMcpServer(mapper,new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpEvidenceTools.handlers(tools,mapper)));
|
|
server.start();authorize(root);session=null;initialize();
|
|
authority.grant(false).toCompletableFuture().get(5,java.util.concurrent.TimeUnit.SECONDS);String task=authority.acquire().task().value();
|
|
var call=mapper.createObjectNode().put("jsonrpc","2.0").put("id",2).put("method","tools/call");
|
|
var args=call.putObject("params").put("name","studio_evidence_image").putObject("arguments").put("projectRoot",root.toString()).put("taskId",task).put("artifactId",artifact.id());
|
|
assertEquals(401,request("POST",server.connection().endpoint(),call.toString(),null,null,LocalMcpServer.PROTOCOL_VERSION,session).statusCode());
|
|
var result=mapper.readTree(post(call.toString()).body()).path("result");assertFalse(result.path("isError").asBoolean());
|
|
assertArrayEquals(png,Base64.getDecoder().decode(result.path("content").get(1).path("data").asText()));
|
|
args.put("projectRoot",java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath().toString());
|
|
assertEquals("OUTSIDE_PROJECT_SCOPE",mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("error").path("code").asText());
|
|
args.put("projectRoot",root.toString());authority.release(authority.snapshot().task()).toCompletableFuture().get(5,java.util.concurrent.TimeUnit.SECONDS);
|
|
assertEquals("INVALID_TASK",mapper.readTree(post(call.toString()).body()).path("result").path("structuredContent").path("error").path("code").asText());
|
|
} finally {authority.closeAsync().toCompletableFuture().join();pool.shutdownNow();}
|
|
}
|
|
|
|
}
|