diff --git a/README.md b/README.md index 0a339e57..65a6da41 100644 --- a/README.md +++ b/README.md @@ -21,14 +21,47 @@ The root project is a monorepo with these main areas: ## Current Product Shape -The Studio shell currently organizes the product around three workspaces: +The Studio shell currently organizes the product around four workspaces: - Assets - Debug +- DEV (external-agent authorization and observation) - Shipper At runtime, the app boots an embedded packer, restores project-local Studio state, and opens the Studio launcher window. Project creation currently scaffolds a Prometeu workspace with `prometeu.json`, `src/`, `assets/`, `build/`, `cartridge/`, `.workspace/`, and local Studio metadata. +## External Coding Agents (MCP) + +Open a project and select **DEV → Copy MCP configuration**. The copied JSON is a +provider-neutral connection descriptor: use its `url` and `headers.Authorization` +in your external client's Streamable HTTP MCP setup, and provide its `projectRoot` +and instructions to the agent. Adapt the configuration syntax to your client; +there is no embedded chat or provider-specific setup wizard. + +Keep the descriptor/token private and out of versioned files and logs. The endpoint +is local to this computer. After restarting Studio, copy it again and update the +client: both the port and token are ephemeral. Copying or connecting does not +authorize edits or start a task. + +1. Connect, discover tools, read project context and applicable language/SDK references. +2. In DEV, grant control (save all first if prompted). Active Debug prevents granting. +3. The agent acquires a task, edits saved project files using its own tools, and + validates through LSP/build. SDK and external libraries are consultable, read-only. +4. Poll operations by operationId or clientRequestId. Recover a lost start receipt + by lookup; never retry frame advancement blindly with a new ID. +5. The agent explicitly releases control. To interrupt, use DEV's reclaim button + and stop the external client separately: Studio cannot prevent its direct file writes. + +The current production tools cover context, references, task control, LSP, +build/pack and operation lookup/cancellation. Headless tool handlers are tested, +but remain undiscoverable until the real runtime gateway is composed. DEV is an +observation panel, not manual Play/input for the agent's session; **Debug** retains +the human testing workflow. Edits are preserved on cancellation; Git/review/recovery +remain the developer's responsibility. + +See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) +for schemas, authorization, limits and delivery boundaries. + ## Requirements - JDK 21 or newer recommended for local development diff --git a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md index c1f30af0..5758e392 100644 --- a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md +++ b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md @@ -62,6 +62,35 @@ and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tool contracts. Optional SSE, server-initiated requests, sampling, prompts, resource subscriptions and list-change notifications are not advertised. +### 1.1 DEV Connection Assistance + +DEV displays the current endpoint without credentials and provides **Copy MCP +configuration** for an open project. The neutral `AgentConnectionGuide` supplies +availability and a deliberate clipboard export; JavaFX MUST NOT depend on the +HTTP server or keep credentials in labels, diagnostics, project state or history. +Connection lifecycle changes refresh availability. A closed project or stopped +server cannot export a descriptor. Unloading DEV only unsubscribes presentation +listeners; it does not stop the endpoint or revoke project authority. + +The copied text is a provider-neutral JSON descriptor with `transport` set to +`streamable-http`, the live `url`, `headers.Authorization`, canonical `projectRoot` +and `instructions`. It is not a promise of a drop-in configuration format for +every external client. The developer maps URL/header fields to that client's MCP +configuration; a provider-specific wizard remains out of scope. The secret is +materialized only for explicit copying and MUST NOT be written to versioned files +or logs. Clipboard success/failure feedback MUST NOT repeat credential-bearing +content or raw exceptions. The clipboard itself is a deliberate secret export. + +Copied instructions and MCP initialization guidance direct the client to discover +actual tools, read project context and applicable language/SDK/library references, +wait for human grant before acquisition, edit saved files within project scope, +validate with LSP/build, recover operation receipts by clientRequestId and release +explicitly. Missing language support is a reported limitation, not a PBS fallback. +They also explain that SDK/external libraries are read-only, revocation cannot +stop external file writes, copying grants no authority, and a Studio restart +requires fresh endpoint/token configuration. No provider or model is required +to test this guidance and the MCP service contract. + ## 2. Identity and Admission All tool inputs require `projectRoot`: an absolute filesystem root resolving to @@ -405,6 +434,9 @@ and `studio_language_query`, plus control acquire/release, build start and opera get/cancel as of step 20 (eight tools). Headless handlers are implemented and tested against the neutral port, but are advertised only when a real `HeadlessGateway` is composed in the integration phase. No fake runtime is shipped. -DEV configuration-copy stays unavailable until step 21. Passing this transport -gate is not the phase 3 or final external-agent acceptance gate. API/Core and +DEV configuration-copy is connected as of step 21. The automated HTTP conformance +gate exercises all 17 tool contracts using real project knowledge/LSP and test-only +build/runtime ports; a separate HTTP test uses the real compiler/packer. This +completes MCP-phase conformance, not real-process or external-agent acceptance. +API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it. diff --git a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java index eb57a3b1..461849ca 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -281,13 +281,13 @@ public class StudioApplicationConfiguration { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, - activityHistoryStore); + activityHistoryStore, connectionGuide); } @Bean @@ -335,6 +335,12 @@ public class StudioApplicationConfiguration { return new p.studio.app.mcp.LocalMcpServer(mapper, tools); } + @Bean + p.studio.api.automation.AgentConnectionGuide connectionGuide(p.studio.app.mcp.LocalMcpServer server, + p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper) { + return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper); + } + private static Path resolveDefaultProjectsRoot() { Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); while (cursor != null) { diff --git a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java index 898eef58..19d30390 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java @@ -56,6 +56,7 @@ public final class StudioUiFactory { private final SceneBankWorkflow sceneBankWorkflow; private final WindowStateStore windowStateStore; private final ProjectActivityHistoryStore activityHistoryStore; + private final p.studio.api.automation.AgentConnectionGuide connectionGuide; public StudioUiFactory( ProjectCatalog projectCatalog, @@ -82,7 +83,8 @@ public final class StudioUiFactory { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { + this.connectionGuide = Objects.requireNonNull(connectionGuide); this.projectCatalog = Objects.requireNonNull(projectCatalog, "projectCatalog"); this.knownProjects = Objects.requireNonNull(knownProjects, "knownProjects"); this.languageCatalog = Objects.requireNonNull(languageCatalog, "languageCatalog"); @@ -116,6 +118,6 @@ public final class StudioUiFactory { assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, - activityHistoryStore); + activityHistoryStore, connectionGuide); } } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java index b1b96e78..a9b19dee 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/LocalMcpServer.java @@ -26,6 +26,15 @@ public final class LocalMcpServer implements AutoCloseable { private ExecutorService executor; private ScheduledExecutorService deadlines; private volatile Connection connection; + private final java.util.List connectionListeners = new CopyOnWriteArrayList<>(); + + public p.studio.api.operation.OperationSubscription onConnectionChanged(Runnable listener) { + connectionListeners.add(listener); notifyConnectionListener(listener); + return () -> connectionListeners.remove(listener); + } + private static void notifyConnectionListener(Runnable listener) { + try { listener.run(); } catch (RuntimeException ignored) { /* Observation cannot change lifecycle. */ } + } public LocalMcpServer(ObjectMapper mapper, McpToolRegistry tools) { this.mapper = mapper.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) @@ -47,6 +56,7 @@ public final class LocalMcpServer implements AutoCloseable { next.setExecutor(workers); next.start(); executor = workers; server = next; + connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } catch (RuntimeException failure) { next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null; throw failure; @@ -62,6 +72,7 @@ public final class LocalMcpServer implements AutoCloseable { if (server == null) return; connection = null; server.stop(0); server = null; sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow(); + connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } /** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */ @@ -144,7 +155,7 @@ public final class LocalMcpServer implements AutoCloseable { var result = mapper.createObjectNode().put("protocolVersion", PROTOCOL_VERSION); result.putObject("capabilities").putObject("tools").put("listChanged", false); result.putObject("serverInfo").put("name", "prometeu-studio-mcp").put("version", "1.0"); - result.put("instructions", "Read project context and indexed references. Human grant in DEV precedes acquisition. Edit saved project files with your native tools, never SDK/external libraries. Validate with LSP/build and explicitly release. Studio revocation does not stop your external file writes. Reconnect with new configuration after Studio restart."); + result.put("instructions", McpConnectionGuide.INSTRUCTIONS); send(exchange, 200, response(id, result)); return; } if (initialized == null) { empty(exchange, 400); return; } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java new file mode 100644 index 00000000..ac096304 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java @@ -0,0 +1,50 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.AgentConnectionGuide; +import p.studio.api.operation.OperationSubscription; +import p.studio.core.project.ProjectAccessRegistry; +import java.nio.file.Path; +import java.util.Optional; + +/** Builds a provider-neutral connection descriptor from the live server, only on explicit export. */ +public final class McpConnectionGuide implements AgentConnectionGuide { + public static final String INSTRUCTIONS = """ + Configure your external coding client's MCP connection using the url and Authorization header below. + This is a provider-neutral descriptor, not a provider-specific configuration file. + Keep the token private; do not commit this descriptor, write it into project files or include it in logs. + Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult + studio_reference_read for the declared languages, SDK and libraries before editing as needed. + Do not assume PBS or another language when support/documentation is missing; report the limitation. + Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting + does not grant permission. Use the returned taskId for all work and operate only on this project. + Edit saved project files with your native tools; SDK and external libraries are read-only. + Validate saved changes with studio_language_query and studio_build_start. Poll studio_operation_get. + Supply a unique clientRequestId per intended build/advance. Recover lost responses by lookup using + clientRequestId; do not blindly repeat frame advancement with a new ID. Cancellation acknowledgement + is not worker termination. Use only tools/capabilities actually advertised by this running Studio. + Observe headless images/state when those tools are available, and explicitly studio_control_release + when finished. On revocation stop external edits too: Studio cannot stop your native file writes. + Existing edits are preserved. Git/review/recovery remain the developer's responsibility. + Recopy and update your client's connection after Studio restart: endpoint and token are ephemeral. + """; + private final LocalMcpServer server; + private final ProjectAccessRegistry projects; + private final ObjectMapper mapper; + public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) { + this.server = server; this.projects = projects; this.mapper = mapper; + } + @Override public Optional endpoint() { + try { return Optional.of(server.connection().endpoint().toString()); } + catch (IllegalStateException unavailable) { return Optional.empty(); } + } + @Override public String configuration(Path root) { + Path canonical = projects.requireOpenRoot(root); + var live = server.connection(); + var value = mapper.createObjectNode().put("transport", "streamable-http").put("url", live.endpoint().toString()); + value.putObject("headers").put("Authorization", live.authorizationHeader()); + value.put("projectRoot", canonical.toString()).put("instructions", INSTRUCTIONS); + return value.toPrettyString(); + } + @Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java index a44980ea..eeb2d185 100644 --- a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -120,6 +120,61 @@ class DevDesktopTest { }); } + @Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception { + var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + var projects = new p.studio.core.project.ProjectAccessRegistry(); + var savedClipboard = new java.util.HashMap(); + var copied = new java.util.concurrent.atomic.AtomicReference(); + 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); + 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 first = mapper.readTree(copied.get()); + assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText())); + assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText()); + server.close(); + fx(() -> assertTrue(((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())); + 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); + }); + authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close(); + } + } + } + @Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception { fx(() -> { var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect"); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java new file mode 100644 index 00000000..b1f8d0fc --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java @@ -0,0 +1,52 @@ +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 p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +class McpConnectionGuideTest { + @TempDir Path root; + @Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() 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())); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); + assertNull(authority.snapshot().task()); + 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())); + 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()); + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java index 575b3440..bebead92 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -238,6 +238,97 @@ class McpTaskToolsTest { } } } + @Test void allToolGroupsConformOverHttpWithRealLspAndTestOnlyRuntime() throws Exception { + Path source = Files.createDirectories(root.resolve("src")).resolve("main.pbs"); + Files.writeString(source, "fn main() -> int { return 1; }\n"); + var lifecycle = new p.studio.lsp.services.LspServerLifecycleImpl(); + var lsp = new p.studio.app.lsp.LspLifecycleAdapter(lifecycle); + var project = catalog.openProject(root); lsp.boot(project); + var knowledge = new p.studio.app.compiler.CompilerProjectKnowledge(access, catalog, mapper); + var language = new p.studio.core.language.TaskLanguageQueries(access, + new p.studio.app.lsp.AutomationLspQueries(lifecycle, catalog, knowledge, mapper)); + var handlers = new LinkedHashMap<>(McpTaskTools.handlers(service, mapper, true)); + handlers.putAll(McpProjectKnowledgeTools.handlers(knowledge, mapper)); + handlers.putAll(McpLanguageTools.handlers(language, mapper)); + try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers)); + var client = java.net.http.HttpClient.newHttpClient()) { + server.start(); + 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()); + String first = connect(client, server), second = connect(client, server); + var list = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/list"); + assertEquals(17, mapper.readTree(post(client, server, first, list).body()).path("result").path("tools").size()); + var context = value(httpCall(client, server, first, "studio_project_context", rootOnly())); + assertTrue(context.path("languages").toString().contains("pbs")); + value(httpCall(client, server, first, "studio_reference_read", rootOnly().put("referenceId", "pbs:quickstart").put("limit", 100))); + error("NOT_GRANTED", httpCall(client, server, first, "studio_control_acquire", rootOnly())); + error("INVALID_TASK", httpCall(client, server, first, "studio_build_start", args().put("taskId", "missing").put("clientRequestId", "denied"))); + session.grant(false).toCompletableFuture().join(); + var a = workers.submit(() -> httpCall(client, server, first, "studio_control_acquire", rootOnly())); + var b = workers.submit(() -> httpCall(client, server, second, "studio_control_acquire", rootOnly())); + var results = List.of(a.get(5, TimeUnit.SECONDS), b.get(5, TimeUnit.SECONDS)); + assertEquals(1, results.stream().filter(r -> !r.path("isError").asBoolean()).count()); + task = value(results.stream().filter(r -> !r.path("isError").asBoolean()).findFirst().orElseThrow()).path("taskId").asText(); + var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString()); + value(httpCall(client, server, first, "studio_language_query", query)); + Files.writeString(source, "fn main( {"); + assertFalse(value(httpCall(client, server, first, "studio_language_query", query)).path("result").isEmpty()); + Files.writeString(source, "fn main() -> int { return 2; }\n"); + value(httpCall(client, server, first, "studio_language_query", query)); + httpCall(client, server, first, "studio_build_start", args().put("clientRequestId", "conformance-build")); + var build = httpCompleted(client, server, first, "conformance-build"); + value(httpCall(client, server, first, "studio_headless_boot", args().put("buildId", build.path("result").path("buildId").asText()))); + for (var op : List.of("reset", "clear_input", "state", "fault")) value(httpCall(client, server, first, "studio_headless_" + op, args())); + value(httpCall(client, server, first, "studio_headless_set_input", args().set("input", mapper.createObjectNode().put("a", true)))); + value(httpCall(client, server, first, "studio_headless_advance", args().put("clientRequestId", "conformance-advance").put("frames", 5))); + var advanced = httpCompleted(client, server, first, "conformance-advance"); + assertEquals("SUCCEEDED", advanced.path("result").path("status").asText()); + 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(); + assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode()); + assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); + String reconnected = connect(client, server); + assertEquals(advanced.path("operationId"), value(httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance"))).path("operationId")); + runtime.kind = AutomationOutcome.Kind.GUEST_FAULT; + value(httpCall(client, server, reconnected, "studio_headless_advance", args().put("clientRequestId", "guest").put("frames", 2))); + assertEquals("GUEST_FAULT", httpCompleted(client, server, reconnected, "guest").path("result").path("status").asText()); + value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", advanced.path("operationId").asText()))); + runtime.hold = true; + String pending = value(httpCall(client, server, reconnected, "studio_headless_advance", + args().put("clientRequestId", "cancel-over-http").put("frames", 50))).path("operationId").asText(); + assertTrue(value(httpCall(client, server, reconnected, "studio_operation_cancel", args().put("operationId", pending))) + .path("cancellationRequested").asBoolean()); + runtime.gate.countDown(); + assertEquals("CANCELLED", httpCompleted(client, server, reconnected, "cancel-over-http").path("state").asText()); + value(httpCall(client, server, reconnected, "studio_headless_shutdown", args())); + value(httpCall(client, server, reconnected, "studio_control_release", args())); + error("INVALID_TASK", httpCall(client, server, reconnected, "studio_operation_get", args().put("clientRequestId", "conformance-advance"))); + session.grant(false).toCompletableFuture().join(); + task = value(httpCall(client, server, reconnected, "studio_control_acquire", rootOnly())).path("taskId").asText(); + session.reclaim().toCompletableFuture().join(); + error("INVALID_TASK", httpCall(client, server, reconnected, "studio_build_start", args().put("clientRequestId", "late"))); + } finally { lsp.shutdown(project); } + } + String connect(java.net.http.HttpClient client, LocalMcpServer server) throws Exception { + 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", "conformance-test").put("version", "1"); + String connection = post(client, server, null, initialize).headers().firstValue("Mcp-Session-Id").orElseThrow(); + assertEquals(202, post(client, server, connection, mapper.createObjectNode().put("jsonrpc", "2.0").put("method", "notifications/initialized")).statusCode()); + return connection; + } + JsonNode httpCompleted(java.net.http.HttpClient client, LocalMcpServer server, String connection, String request) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + var result = value(httpCall(client, server, connection, "studio_operation_get", args().put("clientRequestId", request))); + if (result.path("workerTerminated").asBoolean()) return result; + Thread.sleep(5); + } while (System.nanoTime() < deadline); + throw new AssertionError("Operation did not terminate"); + } 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); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java new file mode 100644 index 00000000..1019562e --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentConnectionGuide.java @@ -0,0 +1,21 @@ +package p.studio.api.automation; + +import p.studio.api.operation.OperationSubscription; +import java.nio.file.Path; +import java.util.Optional; + +/** Connection assistance only. Copying credentials never grants project authority. */ +public interface AgentConnectionGuide { + Optional endpoint(); + /** Explicit secret-bearing export for the clipboard; never persist or log this string. */ + String configuration(Path openProjectRoot); + OperationSubscription subscribe(Runnable changed); + + static AgentConnectionGuide unavailable() { + return new AgentConnectionGuide() { + public Optional endpoint() { return Optional.empty(); } + public String configuration(Path root) { throw new IllegalStateException("Connection unavailable"); } + public OperationSubscription subscribe(Runnable changed) { changed.run(); return () -> {}; } + }; + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java index b6926533..b208e31e 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java @@ -6,6 +6,7 @@ public enum I18n { WORKSPACE_DEV("workspace.dev"), DEV_GRANT("dev.grant"), DEV_RECLAIM("dev.reclaim"), DEV_COPY_CONFIG("dev.copyConfig"), DEV_MCP_UNAVAILABLE("dev.mcpUnavailable"), DEV_EXTERNAL_WARNING("dev.externalWarning"), + DEV_MCP_INSTRUCTIONS("dev.mcpInstructions"), DEV_CONFIG_COPIED("dev.configCopied"), DEV_CONFIG_FAILED("dev.configFailed"), DEV_MANUAL("dev.manual"), DEV_WAITING("dev.waiting"), DEV_WORKING("dev.working"), DEV_RETURNING("dev.returning"), DEV_SAVE_GRANT("dev.saveGrant"), DEV_UNSAVED("dev.unsaved"), DEV_DIAGNOSTICS("dev.diagnostics"), DEV_HISTORY("dev.history"), diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java index 9600f564..867bc98a 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java @@ -66,7 +66,7 @@ public final class MainView extends BorderPane { final AssetColorSchemaFactory assetColorSchemaFactory, final TiledAssetService tiledAssetService, final SceneBankWorkflow sceneBankWorkflow, - final ProjectActivityHistoryStore activityHistoryStore) { + final ProjectActivityHistoryStore activityHistoryStore, final p.studio.api.automation.AgentConnectionGuide connectionGuide) { initializing = true; this.eventBus = eventBus; this.projectSession = projectSession; @@ -98,7 +98,7 @@ public final class MainView extends BorderPane { host.register(new DebugWorkspace(projectReference, projectSession.executionSession(), i18n, eventBus)); final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus); host.register(shipperWorkspace); - host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus)); + host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus, connectionGuide)); documentRegistration = projectSession.automation().registerDocuments(assetWorkspace.documentHandoff()); p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(assetWorkspace.rootNode(), () -> projectSession.automation().snapshot().manualAllowed()); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java index c4e25bdc..c48966db 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java @@ -70,6 +70,7 @@ public final class StudioWindowCoordinator implements AutoCloseable { private final TiledAssetService tiledAssetService; private final SceneBankWorkflow sceneBankWorkflow; private final ProjectActivityHistoryStore activityHistoryStore; + private final p.studio.api.automation.AgentConnectionGuide connectionGuide; private final Object lifecycleMonitor = new Object(); private volatile boolean closed; private volatile ProjectSession pendingProjectSession; @@ -104,7 +105,8 @@ public final class StudioWindowCoordinator implements AutoCloseable { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore) { + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { + this.connectionGuide = Objects.requireNonNull(connectionGuide); this.launcherStage = Objects.requireNonNull(launcherStage, "launcherStage"); this.projectCatalogService = Objects.requireNonNull(projectCatalogService, "projectCatalogService"); this.knownProjectsService = Objects.requireNonNull(knownProjectsService, "knownProjectsService"); @@ -263,7 +265,7 @@ public final class StudioWindowCoordinator implements AutoCloseable { executor, theme, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, - activityHistoryStore); + activityHistoryStore, connectionGuide); this.projectSession = projectSession; final Scene scene = new Scene(mainView, PROJECT_WIDTH, PROJECT_HEIGHT); scene.getStylesheets().add(theme.getDefaultTheme()); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java index 05810691..b1fe3936 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java @@ -25,13 +25,23 @@ public final class DevWorkspace extends Workspace { private final TextArea diagnostics = new TextArea(), history = new TextArea(); private final ImageView canvas = new ImageView(); private final Button grant = new Button(), reclaim = new Button(); + private final Button configuration = new Button(); + private final Label availability = new Label(), copyStatus = new Label(); + private final AgentConnectionGuide connectionGuide; + private final java.nio.file.Path projectRoot; + private OperationSubscription connectionSubscription; private OperationSubscription subscription; private long generation; private CanonicalCapture rendered; private final javafx.beans.value.ChangeListener localeListener; public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) { + this(project, automation, i18n, events, AgentConnectionGuide.unavailable()); + } + public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events, + AgentConnectionGuide connectionGuide) { super(project, events); this.automation = automation; this.i18n = i18n; + this.connectionGuide = java.util.Objects.requireNonNull(connectionGuide); projectRoot = project.rootPath(); localeListener = (o, before, after) -> apply(this.automation.snapshot()); scroll.setFitToWidth(true); root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace"); @@ -40,9 +50,13 @@ public final class DevWorkspace extends Workspace { reclaim.textProperty().bind(i18n.bind(I18n.DEV_RECLAIM)); grant.setOnAction(e -> grant(false)); reclaim.setOnAction(e -> automation.reclaim()); - Button configuration = new Button(); configuration.setId("dev-mcp-config"); - configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); configuration.setDisable(true); - Label availability = new Label(); availability.textProperty().bind(i18n.bind(I18n.DEV_MCP_UNAVAILABLE)); + configuration.setId("dev-mcp-config"); + configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); + configuration.setOnAction(e -> copyConfiguration()); + availability.setId("dev-mcp-endpoint"); availability.setWrapText(true); + copyStatus.setId("dev-mcp-copy-status"); + Label instructions = new Label(); instructions.setWrapText(true); + instructions.textProperty().bind(i18n.bind(I18n.DEV_MCP_INSTRUCTIONS)); Label warning = new Label(); warning.setWrapText(true); warning.textProperty().bind(i18n.bind(I18n.DEV_EXTERNAL_WARNING)); canvas.setPreserveRatio(true); canvas.setSmooth(false); canvas.setFitWidth(640); canvas.setFitHeight(360); @@ -50,7 +64,7 @@ public final class DevWorkspace extends Workspace { diagnostics.setEditable(false); diagnostics.setPrefRowCount(3); history.setEditable(false); history.setPrefRowCount(5); root.getChildren().addAll(new Label(project.name() + " — " + project.rootPath()), - state, new HBox(10, grant, reclaim, configuration), availability, warning, + state, new HBox(10, grant, reclaim, configuration), availability, copyStatus, instructions, warning, operation, imageStatus, imagePane, identity, pane(I18n.DEV_DIAGNOSTICS, diagnostics), pane(I18n.DEV_HISTORY, history)); apply(automation.snapshot()); @@ -71,11 +85,16 @@ public final class DevWorkspace extends Workspace { Runnable update = () -> { if (generation == subscribed) apply(snapshot); }; if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); }); + connectionSubscription = connectionGuide.subscribe(() -> { + Runnable update = () -> { if (generation == subscribed) { copyStatus.setText(""); updateConnection(); } }; + if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); + }); } @Override public void unLoad() { generation++; i18n.localeProperty().removeListener(localeListener); if (subscription != null) { subscription.unsubscribe(); subscription = null; } + if (connectionSubscription != null) { connectionSubscription.unsubscribe(); connectionSubscription = null; } } private void grant(boolean save) { automation.grant(save).whenComplete((result, failure) -> Platform.runLater(() -> { @@ -89,6 +108,7 @@ public final class DevWorkspace extends Workspace { })); } private void apply(AutomationSnapshot snapshot) { + updateConnection(); var view = DevWorkspaceProjection.from(snapshot); state.setText(i18n.text(switch (view.state()) { case MANUAL -> I18n.DEV_MANUAL; @@ -105,4 +125,21 @@ public final class DevWorkspace extends Workspace { canvas.setImage(rendered == null ? null : new Image(new ByteArrayInputStream(rendered.png()))); } } + private void updateConnection() { + var endpoint = connectionGuide.endpoint(); + configuration.setDisable(automation.snapshot().closed() || endpoint.isEmpty()); + availability.setText(endpoint.orElseGet(() -> i18n.text(I18n.DEV_MCP_UNAVAILABLE))); + } + private void copyConfiguration() { + try { + if (automation.snapshot().closed()) throw new IllegalStateException("Project closed"); + var content = new javafx.scene.input.ClipboardContent(); + content.putString(connectionGuide.configuration(projectRoot)); + boolean copied = javafx.scene.input.Clipboard.getSystemClipboard().setContent(content); + copyStatus.setText(i18n.text(copied ? I18n.DEV_CONFIG_COPIED : I18n.DEV_CONFIG_FAILED)); + } catch (RuntimeException unavailable) { + // Never render exception payloads or credential-bearing configuration in diagnostics. + copyStatus.setText(i18n.text(I18n.DEV_CONFIG_FAILED)); updateConnection(); + } + } } diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties index 6ee9a196..50376187 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -361,7 +361,10 @@ workspace.dev=DEV dev.grant=Grant control to AI dev.reclaim=Interrupt and reclaim control dev.copyConfig=Copy MCP configuration -dev.mcpUnavailable=MCP connection is not available yet. This stage provides project control and observation. +dev.mcpUnavailable=MCP connection is unavailable. +dev.mcpInstructions=Copy the connection descriptor into your external client's MCP setup (adapt its format if needed). Connect → read project/language references → acquire after a human grant → edit saved files and validate with LSP/build → release. Copying does not grant control. Keep the token private and out of versioned files; recopy after restarting Studio. Only listed tools are available. +dev.configCopied=Connection descriptor and project instructions copied. Contains a private token. +dev.configFailed=Could not copy the current connection configuration. dev.externalWarning=Reclaiming control stops Studio-managed work, not direct writes by your external agent. Stop that client separately. Existing edits are preserved. dev.manual=Manual control dev.waiting=Waiting for agent — project control granted diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties index ff673d74..dd23428c 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties @@ -32,7 +32,10 @@ workspace.dev=DEV dev.grant=Ceder controle à IA dev.reclaim=Interromper e retomar controle dev.copyConfig=Copiar configuração MCP -dev.mcpUnavailable=A conexão MCP ainda não está disponível. Esta etapa oferece controle do projeto e acompanhamento. +dev.mcpUnavailable=A conexão MCP está indisponível. +dev.mcpInstructions=Copie o descritor de conexão para a configuração MCP do cliente externo (adapte o formato se necessário). Conecte → consulte projeto/linguagens/referências → adquira após cessão humana → edite arquivos salvos e valide com LSP/build → devolva. Copiar não cede controle. Mantenha o token privado e fora de arquivos versionados; copie novamente após reiniciar o Studio. Somente as ferramentas listadas estão disponíveis. +dev.configCopied=Descritor de conexão e instruções do projeto copiados. Contém um token privado. +dev.configFailed=Não foi possível copiar a configuração atual de conexão. dev.externalWarning=Retomar controle encerra o trabalho gerenciado pelo Studio, não as escritas diretas do agente externo. Pare esse cliente separadamente. As alterações existentes são preservadas. dev.manual=Controle manual dev.waiting=Aguardando agente — controle do projeto cedido