expose task control and deduplicated operations through MCP

This commit is contained in:
2026-09-29 10:26:19 +01:00
parent c1834bad1f
commit 20bbbd26bd
14 changed files with 775 additions and 12 deletions
@@ -176,7 +176,7 @@ public class StudioApplicationConfiguration {
}
@Bean
Shipper shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
StudioShipperService shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper,
OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
return new StudioShipperService(compiler, packer, mapper, operations, access);
}
@@ -313,12 +313,20 @@ public class StudioApplicationConfiguration {
return new p.studio.core.language.TaskLanguageQueries(projects, language);
}
@Bean
p.studio.api.automation.TaskTools taskTools(p.studio.core.project.ProjectAccessRegistry projects,
ProjectCatalog catalog, p.studio.core.shipper.SavedProjectPreparation shipper,
java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
return new p.studio.core.session.DefaultTaskTools(projects, catalog, shipper, headless);
}
@Bean
p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper,
p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language) {
// Control/build/runtime/operation providers are connected in PLN-0139 step 20.
p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language,
p.studio.api.automation.TaskTools tasks, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper));
handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper));
handlers.putAll(p.studio.app.mcp.McpTaskTools.handlers(tasks, mapper, headless.isPresent()));
return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers);
}
@@ -0,0 +1,97 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.studio.api.automation.*;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
/** Wire projection only; task authority, work and deduplication remain in Core. */
public final class McpTaskTools {
private McpTaskTools() {}
public static Map<String, Function<JsonNode, McpToolResult>> handlers(TaskTools tools, ObjectMapper mapper, boolean headlessAvailable) {
var handlers = new LinkedHashMap<String, Function<JsonNode, McpToolResult>>();
handlers.put("studio_control_acquire", args -> control(mapper, tools.acquire(root(args))));
handlers.put("studio_control_release", args -> control(mapper, tools.release(root(args), task(args)).toCompletableFuture().join()));
handlers.put("studio_build_start", args -> receipt(mapper, tools.build(root(args), task(args), args.path("clientRequestId").asText())));
handlers.put("studio_operation_get", args -> operation(mapper, tools.operation(root(args), task(args),
new OperationLookup(args.path("operationId").asText(null), args.path("clientRequestId").asText(null)))));
handlers.put("studio_operation_cancel", args -> McpToolResult.success(mapper, mapper.createObjectNode()
.put("operationId", args.path("operationId").asText())
.put("cancellationRequested", tools.cancel(root(args), task(args), args.path("operationId").asText()))));
if (headlessAvailable) {
handlers.put("studio_headless_advance", args -> {
if (!args.path("frames").canConvertToLong()) throw new IllegalArgumentException("frames exceeds integer range");
return receipt(mapper, tools.advance(root(args), task(args), args.path("clientRequestId").asText(), args.path("frames").longValue()));
});
for (var action : TaskTools.HeadlessAction.values()) {
handlers.put("studio_headless_" + action.name().toLowerCase(Locale.ROOT), args -> {
Map<String, Object> input = action == TaskTools.HeadlessAction.SET_INPUT ? input(args.path("input")) : Map.of();
var result = tools.headless(root(args), task(args), action, args.path("buildId").asText(null), input);
return result.capture() != null ? McpToolResult.capture(mapper, result.capture(), false)
: McpToolResult.success(mapper, mapper.valueToTree(result.values()));
});
}
}
return handlers;
}
private static Map<String, Object> input(JsonNode input) {
var normalized = new LinkedHashMap<String, Object>();
for (var name : List.of("up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select", "touch"))
normalized.put(name, input.path(name).asBoolean(false));
normalized.put("touchX", input.path("touchX").asInt(0));
normalized.put("touchY", input.path("touchY").asInt(0));
return Map.copyOf(normalized);
}
private static McpToolResult control(ObjectMapper mapper, ControlResult result) {
if (!result.success()) {
var code = switch (result.status()) {
case CLEANUP_FAILED -> AutomationFailure.Code.CLEANUP_FAILED;
case CLOSED -> AutomationFailure.Code.CLOSED;
case INVALID_TASK -> AutomationFailure.Code.INVALID_TASK;
case NOT_GRANTED -> AutomationFailure.Code.NOT_GRANTED;
default -> AutomationFailure.Code.BUSY;
};
return McpToolResult.failure(mapper, new AutomationFailure(code, result.diagnostic()));
}
var value = mapper.createObjectNode().put("state", result.task() == null ? "MANUAL" : "AGENT_WORKING");
if (result.task() != null) value.put("taskId", result.task().value());
return McpToolResult.success(mapper, value);
}
private static ObjectNode identity(ObjectMapper mapper, TrackedOperation operation) {
return mapper.createObjectNode().put("operationId", operation.operation().id().value())
.put("clientRequestId", operation.clientRequestId()).put("state", operation.operation().state().name());
}
private static McpToolResult receipt(ObjectMapper mapper, TrackedOperation operation) { return McpToolResult.success(mapper, identity(mapper, operation)); }
private static McpToolResult operation(ObjectMapper mapper, TrackedOperation operation) {
var value = identity(mapper, operation);
value.put("workerTerminated", operation.workerTerminated());
value.set("progress", mapper.valueToTree(operation.progress()));
value.set("failure", mapper.valueToTree(operation.failure()));
value.putNull("result");
if (operation.buildResult() != null) {
var build = operation.buildResult();
var result = value.putObject("result").put("kind", "build").put("status", build.status().name());
result.put("buildId", operation.buildId());
result.put("manifestPath", build.manifestPath() == null ? null : build.manifestPath().toString());
result.set("emittedArtifacts", mapper.valueToTree(build.emittedArtifacts().stream().map(Path::toString).toList()));
result.set("diagnostics", mapper.valueToTree(build.diagnostics()));
var logs = result.putArray("logs");
build.logs().forEach(log -> logs.addObject().put("source", log.source().name()).put("severity", log.severity().name())
.put("message", log.message()).put("timestamp", log.timestamp().toString()));
}
CanonicalCapture capture = null;
if (operation.runtimeResult() != null) {
var runtime = operation.runtimeResult();
var result = value.putObject("result").put("kind", "runtime").put("status", runtime.kind().name())
.put("requestedFrames", runtime.requestedFrames()).put("completedFrames", runtime.completedFrames());
result.set("diagnostics", mapper.valueToTree(runtime.diagnostics()));
capture = runtime.capture();
}
return McpToolResult.successWithCapture(mapper, value, capture, operation.captureStale());
}
private static Path root(JsonNode args) { return Path.of(args.path("projectRoot").asText()); }
private static String task(JsonNode args) { return args.path("taskId").asText(); }
}
@@ -32,6 +32,14 @@ public final class McpToolResult {
.put("data", Base64.getEncoder().encodeToString(capture.png()));
return result;
}
public static McpToolResult successWithCapture(ObjectMapper mapper, ObjectNode value, CanonicalCapture capture, boolean stale) {
if (capture == null) return success(mapper, value);
var image = capture(mapper, capture, stale);
value.set("capture", image.wire.path("structuredContent").path("value"));
var result = success(mapper, value);
result.wire.withArray("content").add(image.wire.withArray("content").get(1).deepCopy());
return result;
}
private static McpToolResult envelope(ObjectMapper mapper, JsonNode data, boolean error) {
var wire = mapper.createObjectNode().put("isError", error);
wire.set("structuredContent", data);
@@ -30,10 +30,12 @@ class StudioApplicationConfigurationTest {
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(3, tools.size());
org.junit.jupiter.api.Assertions.assertEquals(8, tools.size());
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_language_query", tools.get(2).path("name").asText());
assertTrue(tools.toString().contains("studio_language_query"));
assertTrue(tools.toString().contains("studio_build_start"));
assertFalse(tools.toString().contains("studio_headless_boot"));
}
assertTrue(executor.isShutdown());
assertFalse(mcp.isRunning());
@@ -0,0 +1,287 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.automation.*;
import p.studio.api.operation.*;
import p.studio.api.shipper.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.core.project.*;
import p.studio.core.runtime.HeadlessGateway;
import p.studio.core.session.*;
import p.studio.core.shipper.SavedProjectPreparation;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
class McpTaskToolsTest {
@TempDir Path root;
final ObjectMapper mapper = new ObjectMapper();
final ExecutorService workers = Executors.newCachedThreadPool();
final ProjectAccessRegistry access = new ProjectAccessRegistry();
final AtomicInteger builds = new AtomicInteger();
final CountDownLatch buildEntered = new CountDownLatch(1), buildGate = new CountDownLatch(1);
volatile boolean holdBuild, failBuild, infrastructureFailure;
DefaultAutomationSession session;
DefaultTaskTools service;
ProjectCatalogService catalog;
McpToolRegistry tools;
FakeRuntime runtime;
String task;
@BeforeEach void setup() throws Exception {
root = root.toRealPath();
Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"game\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
catalog = new ProjectCatalogService(root.getParent(), mapper, new ProjectLocalStudioSetupStore(mapper));
session = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers));
access.register(root, session::enterManual, () -> !session.snapshot().closed(), session);
compose((project, sink) -> {
builds.incrementAndGet(); buildEntered.countDown();
if (holdBuild) awaitGate(buildGate);
if (infrastructureFailure) throw new IllegalStateException("test failure");
return failBuild ? ShipperPrepareResult.failed(List.of(), List.of("compile error"))
: new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS, List.of(), root.resolve("build/manifest.json"), List.of(), List.of());
});
}
void compose(SavedProjectPreparation preparation) {
service = new DefaultTaskTools(access, catalog, preparation, Optional.of((project, buildId, build) -> {
runtime = new FakeRuntime(buildId); return runtime;
}));
tools = new McpToolRegistry(new McpToolCatalog(mapper), mapper, McpTaskTools.handlers(service, mapper, true));
}
@AfterEach void close() throws Exception {
buildGate.countDown();
if (runtime != null) runtime.gate.countDown();
session.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
workers.shutdownNow();
}
ObjectNode args() { var args = mapper.createObjectNode().put("projectRoot", root.toString()); if (task != null) args.put("taskId", task); return args; }
ObjectNode rootOnly() { return mapper.createObjectNode().put("projectRoot", root.toString()); }
JsonNode call(String name, ObjectNode args) { return tools.call(name, args).wire(); }
JsonNode value(JsonNode response) { assertFalse(response.path("isError").asBoolean(), response.toString()); return response.path("structuredContent").path("value"); }
void error(String code, JsonNode response) { assertEquals(code, response.path("structuredContent").path("error").path("code").asText(), response.toString()); }
void acquire() { session.grant(false).toCompletableFuture().join(); task = value(call("studio_control_acquire", rootOnly())).path("taskId").asText(); }
JsonNode poll(String request) { return value(call("studio_operation_get", args().put("clientRequestId", request))); }
JsonNode completed(String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
JsonNode result;
do { result = poll(request); if (!List.of("RUNNING", "PENDING").contains(result.path("state").asText())) return result; Thread.sleep(5); }
while (System.nanoTime() < deadline);
fail("Operation did not finish: " + result); return null;
}
String buildAndBoot() throws Exception {
call("studio_build_start", args().put("clientRequestId", "build"));
String id = completed("build").path("result").path("buildId").asText();
value(call("studio_headless_boot", args().put("buildId", id)));
return id;
}
@Test void grantIsHumanOnlyAndDuplicateBuildsShareOneOperationAcrossRacingClients() throws Exception {
error("NOT_GRANTED", call("studio_control_acquire", rootOnly()));
acquire(); holdBuild = true;
var start = new CountDownLatch(1);
var results = new ArrayList<Future<String>>();
for (int n = 0; n < 20; n++) results.add(workers.submit(() -> {
start.await(); return value(call("studio_build_start", args().put("clientRequestId", "same"))).path("operationId").asText();
}));
start.countDown();
var ids = new HashSet<String>(); for (var result : results) ids.add(result.get(2, TimeUnit.SECONDS));
assertEquals(1, ids.size()); assertTrue(buildEntered.await(2, TimeUnit.SECONDS)); assertEquals(1, builds.get());
assertEquals(ids.iterator().next(), poll("same").path("operationId").asText()); // lost receipt lookup
error("BUSY", call("studio_build_start", args().put("clientRequestId", "different")));
error("CLIENT_REQUEST_CONFLICT", call("studio_headless_advance", args().put("clientRequestId", "same").put("frames", 1)));
assertThrows(ControlDeniedException.class, session::enterManual);
buildGate.countDown(); assertEquals("SUCCESS", completed("same").path("result").path("status").asText());
value(call("studio_build_start", args().put("clientRequestId", "same"))); assertEquals(1, builds.get());
}
@Test void failuresRetainAuthorityAndFreshTaskOrServiceDoesNotRecoverOldOperations() throws Exception {
acquire(); failBuild = true;
value(call("studio_build_start", args().put("clientRequestId", "bad")));
var result = completed("bad"); assertEquals("FAILED", result.path("result").path("status").asText());
assertTrue(result.path("result").path("diagnostics").toString().contains("compile error"));
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
failBuild = false; infrastructureFailure = true;
value(call("studio_build_start", args().put("clientRequestId", "infra")));
assertEquals("INFRASTRUCTURE_FAILURE", completed("infra").path("failure").path("code").asText());
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
String old = task;
value(call("studio_control_release", args()));
error("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "bad")));
acquire(); assertNotEquals(old, task);
error("OPERATION_NOT_FOUND", call("studio_operation_get", args().put("clientRequestId", "bad")));
var restarted = new DefaultTaskTools(access, catalog, (p, s) -> { throw new AssertionError("No replay"); }, Optional.empty());
assertEquals(AutomationFailure.Code.OPERATION_NOT_FOUND, assertThrows(AutomationException.class,
() -> restarted.operation(root, task, new OperationLookup(null, "bad"))).failure().code());
}
@Test void headlessHandlersShareCanonicalPixelsWithDevAndNeverRepeatAnAdvance() throws Exception {
acquire(); buildAndBoot();
value(call("studio_headless_set_input", args().set("input", mapper.createObjectNode().put("a", true))));
assertEquals(true, runtime.input.get("a")); assertEquals(false, runtime.input.get("up")); assertEquals(0, runtime.input.get("touchY"));
var receipt = value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5)));
var result = completed("advance"); assertEquals(1, runtime.advances.get());
assertEquals(5, result.path("progress").path("completedFrames").asInt());
assertEquals(receipt.path("operationId"), value(call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 5))).path("operationId"));
error("CLIENT_REQUEST_CONFLICT", call("studio_headless_advance", args().put("clientRequestId", "advance").put("frames", 6)));
var wire = call("studio_operation_get", args().put("clientRequestId", "advance"));
assertEquals("image", wire.path("content").get(1).path("type").asText());
assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(wire.path("content").get(1).path("data").asText()));
assertEquals(900, result.path("capture").path("frameId").asInt());
assertEquals(5, result.path("capture").path("logicalFrameIndex").asInt());
value(call("studio_headless_capture", args()));
for (var operation : List.of("state", "fault", "clear_input", "reset")) value(call("studio_headless_" + operation, args()));
assertTrue(session.snapshot().stale());
assertTrue(poll("advance").path("capture").path("stale").asBoolean());
value(call("studio_headless_shutdown", args())); assertTrue(runtime.stopped);
error("SESSION_NOT_FOUND", call("studio_headless_state", args()));
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void runtimeFaultAndBoundsDoNotRevokeTaskAndRebuildStopsRuntimeFirst() throws Exception {
acquire(); String oldBuild = buildAndBoot(); runtime.kind = AutomationOutcome.Kind.GUEST_FAULT;
value(call("studio_headless_advance", args().put("clientRequestId", "fault").put("frames", 2)));
assertEquals("GUEST_FAULT", completed("fault").path("result").path("status").asText());
error("LIMIT_EXCEEDED", call("studio_headless_advance", args().put("clientRequestId", "large").put("frames", 601)));
error("BUSY", call("studio_headless_boot", args().put("buildId", oldBuild)));
value(call("studio_build_start", args().put("clientRequestId", "rebuild")));
String next = completed("rebuild").path("result").path("buildId").asText(); assertTrue(runtime.stopped);
error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", oldBuild)));
value(call("studio_headless_boot", args().put("buildId", next)));
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void cancellationPreservesKnownProgressAndReclaimWaitsForWorkerTermination() throws Exception {
acquire(); buildAndBoot(); runtime.hold = true;
String operation = value(call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50))).path("operationId").asText();
assertTrue(runtime.entered.await(2, TimeUnit.SECONDS));
assertEquals(2, poll("long").path("progress").path("completedFrames").asInt());
assertTrue(value(call("studio_operation_cancel", args().put("operationId", operation))).path("cancellationRequested").asBoolean());
assertEquals(2, poll("long").path("progress").path("completedFrames").asInt());
assertEquals("CANCELLED", poll("long").path("state").asText());
assertFalse(poll("long").path("workerTerminated").asBoolean());
error("BUSY", call("studio_build_start", args().put("clientRequestId", "blocked")));
var returnControl = session.reclaim().toCompletableFuture(); assertFalse(returnControl.isDone());
error("INVALID_TASK", call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50)));
error("INVALID_TASK", call("studio_operation_cancel", args().put("operationId", operation)));
runtime.gate.countDown(); assertTrue(returnControl.get(2, TimeUnit.SECONDS).success());
assertTrue(session.snapshot().manualAllowed()); assertTrue(runtime.stopped);
}
@Test void anotherProjectCannotReadCachedWorkAndNoGatewayIsAdvertisedAsAvailable() throws Exception {
acquire(); buildAndBoot();
Path other = Files.createDirectory(root.resolve("other"));
var another = new DefaultAutomationSession(other, new ExecutorOperationExecutor(workers));
access.register(other, another::enterManual, () -> true, another);
another.grant(false).toCompletableFuture().join(); String otherTask = another.acquire().task().value();
error("INVALID_TASK", call("studio_operation_get", args().put("projectRoot", other.toString()).put("clientRequestId", "build")));
error("OPERATION_NOT_FOUND", call("studio_operation_get", args().put("projectRoot", other.toString()).put("taskId", otherTask).put("clientRequestId", "build")));
assertFalse(McpTaskTools.handlers(service, mapper, false).containsKey("studio_headless_boot"));
another.closeAsync().toCompletableFuture().join();
}
@Test void cooperativeCancellationPublishesTheSameFinalKnownCaptureWithoutReleasingAuthority() throws Exception {
acquire(); buildAndBoot(); runtime.hold = true;
String operation = value(call("studio_headless_advance", args().put("clientRequestId", "cancelled").put("frames", 50))).path("operationId").asText();
assertTrue(runtime.entered.await(2, TimeUnit.SECONDS));
value(call("studio_operation_cancel", args().put("operationId", operation)));
runtime.gate.countDown();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
while (!poll("cancelled").path("workerTerminated").asBoolean() && System.nanoTime() < deadline) Thread.sleep(5);
var result = poll("cancelled");
assertTrue(result.path("workerTerminated").asBoolean());
assertEquals("CANCELLED", result.path("result").path("status").asText());
assertEquals(2, result.path("progress").path("completedFrames").asInt());
assertFalse(result.path("capture").path("stale").asBoolean());
assertEquals(2, session.snapshot().capture().logicalFrameIndex());
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
assertFalse(value(call("studio_operation_cancel", args().put("operationId", operation))).path("cancellationRequested").asBoolean());
}
@Test void realHttpBuildUsesExistingCompilerAndPackerAndRecoversReceiptByClientId() throws Exception {
var docs = p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game);
for (var reference : docs) if (reference.id().startsWith("pbs:example:game:1:")) {
Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length()));
Files.createDirectories(file.getParent()); Files.writeString(file, reference.text());
}
try (var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) {
var shipper = new p.studio.core.shipper.StudioShipperService(new p.studio.app.compiler.CompilerBuildGatewayAdapter(),
packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers), access);
compose(shipper);
try (var server = new LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) {
server.start();
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");
String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow();
post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized"));
error("NOT_GRANTED", httpCall(client, server, connection, "studio_control_acquire", rootOnly()));
session.grant(false).toCompletableFuture().join();
task = value(httpCall(client, server, connection, "studio_control_acquire", rootOnly())).path("taskId").asText();
assertThrows(ControlDeniedException.class, () -> shipper.prepare(catalog.openProject(root), ignored -> {}));
// Discard the initial response, as a client with a lost receipt would do.
httpCall(client, server, connection, "studio_build_start", args().put("clientRequestId", "http-build"));
var result = completed("http-build");
assertEquals("SUCCESS", result.path("result").path("status").asText(), result.toString());
assertTrue(Files.isRegularFile(Path.of(result.path("result").path("manifestPath").asText())));
var recovered = value(httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", "http-build")));
assertEquals(result.path("operationId"), recovered.path("operationId"));
assertEquals(result.path("operationId"), value(httpCall(client, server, connection, "studio_build_start", args().put("clientRequestId", "http-build"))).path("operationId"));
value(httpCall(client, server, connection, "studio_control_release", args()));
error("INVALID_TASK", httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", "http-build")));
assertTrue(session.snapshot().manualAllowed());
}
}
}
JsonNode httpCall(java.net.http.HttpClient client, LocalMcpServer server, String connection, String name, ObjectNode arguments) throws Exception {
var request = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", UUID.randomUUID().toString()).put("method", "tools/call");
request.putObject("params").put("name", name).set("arguments", arguments);
var response = post(client, server, connection, request);
assertEquals(200, response.statusCode(), response.body());
var body = mapper.readTree(response.body()); assertFalse(body.has("error"), body.toString());
return body.path("result");
}
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("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());
}
static void awaitGate(CountDownLatch gate) {
boolean interrupted = false;
while (true) { try { gate.await(); break; } catch (InterruptedException ignored) { interrupted = true; } }
if (interrupted) Thread.currentThread().interrupt();
}
final class FakeRuntime implements HeadlessGateway.Session {
final String id = UUID.randomUUID().toString(), build;
final AtomicInteger advances = new AtomicInteger();
final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1);
volatile boolean stopped, hold, cancelled;
volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED;
Map<String, Object> input;
FakeRuntime(String build) { this.build = build; }
public String sessionId() { return id; }
public void cancel() { cancelled = true; }
public CompletionStage<Void> shutdown() { stopped = true; return CompletableFuture.completedFuture(null); }
public long maxFramesPerAdvance() { return 600; }
CanonicalCapture capture(long logical) { return new CanonicalCapture(id, build, logical, 900, 1, 1, 1,
Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1kAAAAASUVORK5CYII=")); }
public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map<String, Object> input) {
this.input = input;
return new TaskTools.HeadlessReply(Map.of("sessionId", id), action == TaskTools.HeadlessAction.CAPTURE ? capture(5) : null);
}
public AutomationOutcome advance(long frames, Consumer<TrackedOperation.Progress> progress) {
advances.incrementAndGet(); progress.accept(new TrackedOperation.Progress(frames, Math.min(2, frames))); entered.countDown();
if (hold) awaitGate(gate);
long completed = cancelled ? Math.min(2, frames) : frames;
return new AutomationOutcome(cancelled ? AutomationOutcome.Kind.CANCELLED : kind, frames, completed, List.of(), capture(completed));
}
}
}