diff --git a/README.md b/README.md index 35668f82..3c8a0185 100644 --- a/README.md +++ b/README.md @@ -32,25 +32,80 @@ At runtime, the app boots an embedded packer, restores project-local Studio stat ## 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. +Studio includes its own `mcp --project ` mode. Configure the native +client once; project grants and desktop restarts no longer require copying ports +or tokens. The initial integration targets Codex on macOS. -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. Install/stage Studio with its bundled Java runtime (see below). New projects + prepare the local client entry during scaffolding. Opening an existing project + also prepares its enabled integration automatically; Studio starts the shared + MCP server itself. **DEV → Prepare assistant** retries preparation after resolving + a reported setup conflict. Opening a project does not grant agent control. +2. Open the coding client in the project directory. Trust the project and reload + MCP once if the client requests it. Studio does not alter client approval policy. + Tools can initialize/list even before the desktop is open or access is granted. +3. Open the project in Studio and grant control in DEV (save first if prompted). + Active Debug prevents granting. The connector discovers access automatically. +4. The agent acquires a task, consults project/language/SDK references, edits saved + project files with its native tools and validates through LSP/build. SDK and + external libraries remain read-only. +5. Recover uncertain operations by operationId/clientRequestId lookup within the + same task; never replay build/advance blindly. Explicitly release control when + done. Human reclaim also revokes access; stop direct external file edits separately. -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 client invokes the same Studio artifact over stdio. It forwards to Studio's +project-scoped loopback service using protected, transient +`.studio/mcp/connection.json`. The permanent `.codex/config.toml` entry contains +installed Java/classpath/root arguments, not credentials. Both local outputs are +ignored by Git. Unrelated client settings are preserved; tracked or conflicting +Studio entries require deliberate resolution. `.studio/setup.json` preserves +neutral integration intent and existing runtime/editor settings. + +After desktop restart, grant again in DEV. Keep the same client session and +configuration; old task identities and operation receipts are not restored. +DEV displays connection separately from project authority. No project-local +launcher, Python transport script or embedded chat is required. + +### Installation and IntelliJ development + +Build and stage the complete distribution, including its Java runtime: + +```bash +./gradlew :prometeu-app:stageStudioInstallation +``` + +The macOS default is `~/Library/Application Support/Prometeu/Studio/current`. +Staging validates a new version before atomically changing `current`, retaining +older versions for rollback and running processes. Native client registration +uses absolute paths and argument arrays, independent of shell PATH: + +```text +command: /current/runtime/bin/java +args: ["-cp", "/current/lib/*", "p.studio.app.StudioLauncher", "mcp", "--project", ""] +``` + +For development, use an isolated installation: + +```bash +./gradlew :prometeu-app:stageStudioInstallation -PstudioInstallationRoot=/absolute/dev-installation +``` + +In IntelliJ, run/debug `p.studio.app.StudioLauncher` with the `prometeu-app` +runtime classpath and VM option `-Dstudio.installationRoot=/absolute/dev-installation`. +The desktop and client-owned connector are separate JVMs. To debug the latter, +add the development-only VM argument +`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005` +before `-cp` in the local MCP entry, restart that MCP process, then use IntelliJ's +**Remote JVM Debug** on localhost:5005. Do not commit this local configuration. +Because manual edits to the managed entry are protected, restore its original +content before using preparation again. Regular registration never enables JDWP. + +The packaged automated gate checks bundled Java, upgrade/rollback, project paths +with spaces, minimal environment, scaffold/preparation and JavaFX startup: + +```bash +./gradlew :prometeu-app:installedConnectorTest +``` The current production tools cover context, references, task control, LSP, build/pack, operation lookup/cancellation and headless execution (17 tools). @@ -67,7 +122,9 @@ for schemas, authorization, limits and delivery boundaries. | Symptom | Action | | --- | --- | -| Connection rejected after Studio restarts | Copy DEV's configuration again: the token and OS-assigned endpoint are session-local. Do not publish the token. | +| Waiting for access / desktop restarted | Open the project and grant again in DEV. Keep the existing client configuration. | +| Stale connection / incompatible catalog | Grant fresh access, or update the installed Studio when versions differ. Do not edit transient credentials. | +| Preparation conflict | Preserve the existing client settings; resolve a tracked/user-owned/edited Studio table explicitly, then prepare again. | | Acquisition rejected or project busy | Grant control in DEV first; stop manual Debug before granting. Query an existing operation instead of starting another; serialize headless calls. | | `RUNTIME_UNAVAILABLE` or handshake incompatibility | Check the project's configured runtime installation and its packaged headless command. Studio does not download a substitute. | | `NO_FRAME_AVAILABLE` | Advance at least one frame before requesting a capture. | @@ -127,7 +184,7 @@ are not considered fixed by the passing integration tests: regression passes, but the toolchain/target alignment needs separate review. Cross-platform desktop coverage remains a validation boundary, not a confirmed -product defect. Desktop acceptance so far covers macOS ARM64 and Codex CLI only. +product defect. Baseline HTTP desktop acceptance covers macOS ARM64 and Codex CLI only. The integrated stdio flow completed its separate acceptance gates through automated validation and user-confirmed native-client, graphical-launch and IntelliJ checks; see [LSN-0077](discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md) for evidence provenance. The first real Codex CLI acceptance run exercised editing, LSP, build/pack, input, 1,110 frames, native MCP images and explicit release. The developer confirmed the diff --git a/discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md b/discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md new file mode 100644 index 00000000..f6689ed1 --- /dev/null +++ b/discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md @@ -0,0 +1,178 @@ +--- +id: LSN-0077 +ticket: studio-persistent-mcp-connector +title: Integrated Studio MCP Through Stable Setup and Ephemeral Access +created: 2026-09-29 +tags: [studio, mcp, connection, lifecycle, installation] +--- + +# Integrated Studio MCP: Stable Setup, Ephemeral Access + +Owner: **studio**, MCP integration, project lifecycle and local installation. +DSC-0070 / DEC-0061 / PLN-0140 delivered this integration, including the user's +accepted revision for automatic preparation on project open. These identifiers +are historical references; maintained contracts are linked below. Automated +validation and the user's confirmation of final manual acceptance are recorded +separately. + +## Original Problem + +The original integration exposed a new HTTP port and bearer token on each Studio +restart. Developers had to configure their coding client repeatedly. Ad hoc +transport scripts then duplicated initialization, authentication and result +handling, obscuring native MCP tools and images. + +The durable solution separates three lifetimes: installation, connection and +project authority. A stable client registration must not imply durable permission +to edit, and a transport interruption must not replay work. + +## Consolidated Design + +The distributed Studio artifact supports two modes. Normal invocation opens the +desktop. `StudioLauncher mcp --project ` runs a stdio connector +without JavaFX, Spring desktop composition, LSP or a second HTTP server. The coding +client owns that process; developers do not launch it manually for each project. + +The desktop starts one shared loopback HTTP server. Opening a project prepares its +enabled integration automatically through the same neutral port used by scaffold +and the explicit DEV retry. An explicitly disabled integration remains disabled. +Preparation failure is visible in DEV and does not make the project unusable. +Opening a project does not publish credentials or grant control. + +The macOS installation has a stable `current` reference pointing to a validated, +versioned distribution containing dependency JARs and Java. The native client +invokes the absolute installed Java path with a classpath/main/project argument +array. Updating the installation changes the reference, not every project's client +entry. Old versions remain available for rollback and existing processes. + +The tradeoff is an additional lightweight JVM for stdio transport, plus managed +installation lifecycle. In return, there are no per-project launchers or copied +connector binaries, and execution does not depend on an interactive shell PATH. + +## Configuration and Authority Have Different Owners + +| Surface | Lifetime and responsibility | +| --- | --- | +| `.studio/setup.json` | Neutral integration intent; preserves runtime/editor settings | +| `.codex/config.toml` | Local installed command, arguments and canonical project binding; no transient credentials | +| `.studio/mcp/connection.json` | Protected, temporary discovery data published by human grant | +| Core grant/task/operation records | In-memory authority and receipts; never restored from configuration | + +Preparation edits only a managed client entry, validates the result with a TOML +parser and preserves unrelated settings/comments. User-owned, edited or tracked +entries cause explicit conflicts. Initial client trust or reload may still be +required; Studio does not change approval policy. + +Human grant publishes a fresh credential scoped to one canonical project root. +HTTP sessions are bound to that credential, and the server enforces scope even +for knowledge reads. Restricting only the connector would leave a direct HTTP +bypass. Acquisition still creates a separate task identity through shared Core +services. + +## Publication Is Part of the Grant Transaction + +Publication cannot be a best-effort snapshot listener. The neutral lifecycle port +coordinates preparation, publication, activation, invalidation and cleanup: + +1. Save and verify documents under the existing handoff rules. +2. Acquire the OS publication lock and write a private temporary descriptor outside + the authority monitor. +3. Atomically publish, then activate under the grant generation fence. Acquisition + remains unavailable until the transition completes. +4. Abort failed or superseded grants and remove their provisional access. +5. Revoke credentials before asynchronous work cleanup; remove only the owned + publication and release its lock. + +The lock file's inode is retained. Deleting it could let another process lock a +new inode while the first owner still holds the old one. The OS releases the lock +after a crash, allowing safe replacement of stale discovery data. Directories are +0700 and secret-bearing files 0600; Git exclusion alone is not access control. +Cleanup checks publication ownership so an old callback cannot delete newer data. +File cleanup failure must not prevent runtime cancellation. + +## Reconnect Without Replaying Intent + +The stdio connector initializes and lists its packaged catalog before Studio or a +grant is available. It verifies live instance, root and catalog identity before +forwarding. Calls preserve structured results and native image blocks; response +limits are separate from the smaller request limit. + +Discovery and ping may be retried. Build and frame advancement must not be +resubmitted automatically after a lost response. Within the same authorized task, +recover by operationId/clientRequestId lookup. After restart, old in-memory +receipts are unavailable: report an unknown outcome and require a fresh grant/task +and an explicit next intent. Connection liveness and working/manual authority are +separate DEV states. + +## Implementation Findings + +- JSON-RPC numeric IDs must be compared by numeric value. Jackson can represent + the same wire number with different integer node types. +- Grant publication is asynchronous. Tests must await the transition without + blocking the JavaFX thread or assuming a button callback completes filesystem IO. +- `jlink` can generate read-only license files. Normalize staged runtime write + permissions so subsequent Gradle installation updates can replace them. +- An IntelliJ desktop can run from classes without a managed installation. A + generic “preparation incomplete” message hid this prerequisite. The specific + diagnostic now points to `:prometeu-app:stageStudioInstallation` and the optional + `studio.installationRoot` VM setting. +- Preparation belongs to project opening, not only creation or a manual DEV + button. Otherwise existing projects retain unnecessary onboarding friction. +- Capture data larger than 1 MiB must not inherit the request-body cap. The + connector bounds response size and body-read time separately. + +## Verified Results and Acceptance + +The full implementation gate recorded 839 passing tests, 15 existing skips and no +failures, including installation, desktop and real runtime gates. The later +missing-installation diagnostic and automatic-open revision passed their targeted +preparation, Core, app, architecture and runtime suites. Installation staging, +`git diff --check` and `discussion validate` also passed. + +Process tests cover cold initialization, later grant and restart in one connector; +large images; root/session scope; stale identity/catalog rejection; lost build +response with execution count remaining one; unknown old-task receipts; concurrent +publisher JVMs and crash recovery; protected files; grant/close races; TOML +preservation; and stable installed Java across updates. + +On 2026-09-29, after being asked specifically about the outstanding manual gates, +the user confirmed that all were finished. This closes the native Codex +acquire/build/image/release and reconnect-after-restart cycle, installation update +and graphical-client launch, and IntelliJ debugger attachment. The provenance of +this final evidence is **user-reported acceptance**, not an additional automated +run or an independently observed transcript. The implementation's automated +environment was macOS ARM64 with bundled Corretto 21.0.4 and Codex CLI 0.158.0 +installed; that version inspection alone was not treated as native-client proof. + +The prior HTTP-only acceptance from DSC-0068 was not substituted for these gates. +The first accepted integration remains Codex on macOS; other clients/platforms +and the embedded terminal are outside this delivery. + +## Operational Example + +Open the project in Studio. Its enabled client integration is prepared without a +separate per-project Run. Start the coding client in that project and satisfy its +initial trust/reload requirements. Grant access in DEV, acquire the task through +native tools, edit/validate, then release. After Studio restarts, grant again; +keep the client configuration unchanged. An old task is never restored. + +For an IntelliJ desktop, run `p.studio.app.StudioLauncher` with the +`prometeu-app` classpath and Java 21. If a managed installation is missing, stage +it once with `./gradlew :prometeu-app:stageStudioInstallation`. An isolated +installation uses the `studio.installationRoot` desktop VM property. The MCP +stdio process remains client-owned; attach Remote JVM Debug to that process using +an explicit development-only loopback JDWP option. Do not configure the desktop +Run itself with `mcp --project` arguments. + +## References + +- DEC-0061 and PLN-0140: historical source decision and completed implementation + plan for DSC-0070; removed from active workflow during housekeeping. +- [Studio shell and project creation](../../../docs/specs/studio/1.%20Studio%20Shell%20and%20Workspace%20Layout%20Specification.md). +- [Project-local state and discovery](../../../docs/specs/studio/8.%20Project-Local%20Studio%20State%20Specification.md). +- [Core and adapter architecture](../../../docs/specs/studio/9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md). +- [DEV and authority](../../../docs/specs/studio/10.%20DEV%20and%20Automation%20Specification.md). +- [MCP contract and acceptance boundary](../../../docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md). +- [Setup and IntelliJ debugging](../../../README.md). +- [DSC-0068 baseline lesson](../DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md). +- DSC-0071: the separate embedded-terminal discussion; unchanged by this work. diff --git a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md index 2aaf24e7..7d97f1eb 100644 --- a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md +++ b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md @@ -142,3 +142,23 @@ This specification is complete enough when: - workspace and shell responsibilities are clearly separated; - the shell-level expectations for workspace architecture are explicit; - the baseline Studio frame is stable enough for implementation planning. + +## Project Assistant Preparation (DEC-0061) + +Project creation MUST scaffold neutral agent-integration intent in +`.studio/setup.json` and invoke the same preparation port used by existing +projects in DEV. Application infrastructure resolves installed Studio and client +configuration; the wizard/Core MUST NOT serialize provider TOML or launch an +agent. Failed preparation leaves a usable project with actionable incomplete +readiness in DEV, never a false ready claim. Runtime/editor settings and unrelated +client configuration MUST survive. Preparation grants no project control. + +### Automatic preparation when opening a project + +Opening a project MUST prepare its enabled MCP integration using the same neutral +port as scaffold and DEV retry. Desktop composition MUST start the shared loopback +server before project sessions become available; no external command or separate +per-project desktop Run is required. Explicitly disabled integration MUST remain +disabled. Preparation failure MUST remain visible in DEV readiness without blocking +project use. Opening MUST NOT publish credentials or grant/acquire agent control. +The coding client continues to own its configured stdio process and initial trust. diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md index e0a8e881..05c6b562 100644 --- a/docs/specs/studio/10. DEV and Automation Specification.md +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -164,7 +164,7 @@ DEV MUST expose: - the four control states, project identity, current managed operation and diagnostics; - a canonical-image canvas with session/build/logical-frame/render-frame identity and stale status; - a short history of Studio calls, not an independent code history; -- **Copy MCP configuration**, plus short connection/use instructions when the real MCP composition is available. +- **Prepare assistant**, plus short connection/use instructions when the real MCP composition is available. Actions MUST reflect shared service authority. DEV MUST NOT own a duplicate lock or release authority when disposing visual subscriptions. Presentation @@ -177,8 +177,7 @@ in Debug with its existing host/protocol/lifecycle, subject to symmetric guards. “Agent working” means the task has been acquired; it is not a claim to observe all external edits, reasoning or conversation. -Without a real composed MCP endpoint, configuration copy MUST be unavailable -rather than produce a fabricated endpoint or token. Test doubles MAY supply +Preparation MUST report missing installation or configuration conflicts explicitly; it does not depend on a live grant or fabricate endpoint credentials. Test doubles MAY supply operations/captures to isolated tests, never masquerade as product execution. ## 6. Operations and Lost Responses @@ -274,19 +273,18 @@ that it uses. Capture/build correlation MUST NOT introduce code snapshots. Concrete tool names, input schemas, response envelopes and HTTP lifecycle are specified in [MCP Tools and Project Knowledge Contract](11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md). -The app MUST host Streamable HTTP at `127.0.0.1:/mcp` while -Studio is open. It MUST generate a random token per Studio start, require it -on connections, validate Origin and reject unexpected origins. No remote -binding, accounts, OAuth or stdio MCP bridge is part of this baseline. - -Copied configuration MUST contain the actual endpoint/token and MUST NOT be -written to versioned files. Instructions MUST explain that restart requires -refreshing client configuration. Copying configuration and authenticating -MUST NOT grant control. +The desktop MUST host Streamable HTTP at `127.0.0.1:/mcp`. +DEC-0061 adds Studio-owned stdio discovery and one-time preparation as specified +in spec 11. Each human grant publishes a fresh project-scoped credential through +the required lifecycle participant in spec 8. Authentication, project scope and +task identity remain separate checks. There is no global credential bypass. +Restart invalidates old access and requires a fresh human grant, while the native +client's command/configuration remains unchanged. No remote binding, accounts or +OAuth are introduced. Preparation never grants editing authority. | Tool group | Required capabilities | Required authority | | --- | --- | --- | -| Context/references | Project identity, languages, versions, capabilities and paginated references | Authenticated connection; no grant required | +| Context/references | Project identity, languages, versions, capabilities and paginated references | Project credential; no acquired task required | | Control | Acquire task and release control | Prior human grant for acquisition; valid task identity for release | | Language | Existing LSP diagnostics/navigation and supported capabilities | Valid project/task identity | | Build | Compile and pack | Valid project/task identity | @@ -373,7 +371,7 @@ mature gameplay library is not a prerequisite. - Pixel-art generation, full-game libraries, audio capture or deep guest introspection. - Shared editing, isolated worktrees, code snapshots/journals/checkpoints, merge/apply, divergence recovery, undo/rollback or automatic commits/clean-tree gates. - Replacing compiler, Packer, LSP, VM or human Debug semantics; a new general-purpose Studio source editor. -- Remote MCP, accounts/OAuth, stdio MCP bridge, network runtime discovery or provider-specific connection wizard. +- Remote MCP, accounts/OAuth and network runtime discovery. Studio-owned stdio and local Codex preparation are the explicit DEC-0061 additions. - Additional language implementation, persistent operation recovery or automatic task resumption. - Integrated discussion-framework agendas/decisions/plans in the product; those are future work, not this runtime/DEV/MCP contract. @@ -390,3 +388,14 @@ Implementation is conformant only when all phase gates hold and: 7. Lost operation responses cannot duplicate execution; runtime crash cannot trigger replay or implicit authority release. 8. Language context and indexed local references reflect real installed support and work without source checkouts. 9. Manual Debug, architecture boundaries, packaging and real-client integration pass their regression gates. + +## Integrated Connection Revision (DEC-0061) + +Connection and authority MUST be displayed separately. Initialization/ping +liveness determines connection, while Core determines waiting/working/manual +control. A missing descriptor means waiting for access, not proof that Studio is +closed. Preparation reports initial client trust/reload requirements without +modifying approval policy. Revocation removes published access even before +asynchronous worker/runtime cleanup finishes. New grants never restore old task +IDs or receipts. Full integrated native-client acceptance belongs to PLN-0140; +the prior HTTP acceptance alone is insufficient. 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 c9adcc31..59e95041 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 @@ -3,7 +3,7 @@ ## Status, Scope and Authority Owner: **studio**, application adapter and neutral automation API. This document -formalizes DEC-0060 B5–B9 and PLN-0139 steps 15–16. It complements +formalizes DEC-0060 B5–B9 and the integrated connection revision in DEC-0061 (PLN-0140). It complements [DEV and Automation](10.%20DEV%20and%20Automation%20Specification.md), which owns project authority, lifecycle, captures and phase gates. It does not change those rules or the runtime-owned headless protocol. @@ -11,7 +11,7 @@ rules or the runtime-owned headless protocol. The packaged machine-readable input schemas, authority classification and examples are in `prometeu-app/src/main/resources/mcp/studio-tools-v1.json`. Contract version is `1.0`. Catalog membership is not runtime availability: -`tools/list` MUST expose only composed handlers, never placeholder implementations. +HTTP `tools/list` MUST expose only composed handlers, never placeholder implementations. The offline Studio stdio entry MUST advertise the packaged catalog and report unavailable live capabilities explicitly. Steps 17–21 connect the functional providers and DEV configuration assistance; steps 22–28 provide the real runtime gateway and integrated acceptance. @@ -23,18 +23,24 @@ initialization exchange negotiates that supported revision; no compatibility with other revisions or deprecated HTTP+SSE transport is claimed. An offered unsupported revision receives the supported revision in `InitializeResult`. -Each start generates a fresh 256-bit random bearer token. Every request MUST -include `Authorization: Bearer `. Missing/wrong credentials return 401. -There is no query-string token, OAuth, cookie authentication, remote bind option, -stdio bridge or wildcard listener. The endpoint has no query parameters. +Each desktop start generates a new instance identity. Each human project grant +publishes a fresh 256-bit bearer credential scoped to that canonical project root. +Every HTTP request MUST include `Authorization: Bearer `; missing, +wrong or revoked credentials return 401. Initialized HTTP sessions MUST be bound +to that credential/root; mixing another credential with an existing session returns +403. All tools, including knowledge reads, MUST enforce the authenticated root +before dispatch. No instance-wide credential bypass is permitted. + +There is no query-string token, OAuth, cookie authentication, remote bind option +or wildcard listener. The endpoint has no query parameters. Studio also provides +its own stdio mode, described below; it is part of the same artifact. Native clients may omit `Origin`. If present, it MUST exactly equal the live endpoint's origin (`http://127.0.0.1:`); `null`, other ports/hosts/schemes and multiple Origin headers fail. Host MUST match the live loopback authority. Unexpected origins/hosts return 403. No permissive browser CORS policy is emitted. Credentials MUST NOT appear in diagnostics, exception messages, object string -representations, generated reports or versioned configuration. Explicit copying -for the external client is provided in step 21, not by logging startup secrets. +representations, generated reports or versioned configuration. The project discovery file is the only secret-bearing setup output; persistent client configuration and clipboard assistance MUST NOT export secrets. Initialization assigns a separate random `Mcp-Session-Id`. Subsequent requests include this header and the negotiated `MCP-Protocol-Version`. The server can @@ -62,34 +68,87 @@ 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 +### 1.1 Integrated Studio Entry and Offline Catalog -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. +`StudioLauncher mcp --project ` MUST dispatch before JavaFX or +Spring desktop startup. The root MUST be canonicalized once, contain the project +manifest and remain bound for the process lifetime, independently of client cwd. +The mode MUST NOT open a desktop, LSP, runtime or another HTTP listener. It uses +newline-framed UTF-8 JSON-RPC on stdin/stdout; stdout is protocol-only. Requests +are bounded to 1 MiB. EOF closes transport resources without releasing task control. -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. +Initialize, initialized notification, ping and tools/list MUST work before the +desktop, descriptor or grant exists. Offline descriptors come from the same +packaged catalog as HTTP. A deterministic fingerprint covers protocol and tool +schemas. Before forwarding, the connector MUST validate the descriptor, initialize +HTTP, check instance/root/fingerprint metadata, and compare live descriptors with +the packaged catalog. Missing handlers return unsupported capability; incompatible +protocol/schema fails explicitly rather than silently changing the client's tools. -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. +Tool calls MUST preserve structuredContent, text/error blocks and native image +blocks. Response bounds MUST support images above the 1 MiB request limit; the +current response cap is 32 MiB, including a bounded body-read deadline. Network +redirects MUST NOT be followed. The connector MUST reject another project root. + +Discovery runs on calls and bounded background checks. Missing publication means +waiting for access, not proof that the desktop is closed. Distinguish invalid +file/permissions, stale credentials/instance, catalog incompatibility and transport +reconnection. Calls cannot wait indefinitely for a grant. No reconnect path may +resubmit a tool call. An uncertain response MUST retain available clientRequestId +correlation and instruct receipt lookup within the same authorized task. A new +desktop/task has no old receipt registry and requires a fresh human grant. + +### 1.2 Stable Installation and Project Preparation + +The initial delivery targets Codex on macOS. Studio owns a versioned installation +under `~/Library/Application Support/Prometeu/Studio`, with an atomic `current` +reference. Each version includes `lib` dependencies and a compatible Java runtime +under `runtime`. Validate a staged version before switching `current`; retain +previous versions for rollback and already-running processes. Failed validation +MUST leave the existing reference intact. Registered commands MUST work without +an interactive shell PATH, external JDK or developer checkout. + +The client command is the absolute `current/runtime/bin/java`, with argument-array +values `-cp`, `/lib/*`, `p.studio.app.StudioLauncher`, `mcp`, `--project`, +and the canonical root. No project-local executable, generated transport script, +helper binary or separate launcher installation is allowed. The desktop and +connector use the same Studio artifact. JDWP is an explicit development-only JVM +option; IntelliJ attaches to the client-owned connector process separately from +the desktop Debug configuration. + +New-project scaffolding and existing-project preparation MUST use the same neutral +preparation port. `.studio/setup.json` stores integration schema/enabled/profile +intent, preserving runtime/editor settings; it contains no endpoint/credential/task. +Application infrastructure owns `.codex/config.toml` serialization. Its managed +`mcp_servers.prometeu_studio` table stores the stable command, arguments, project +cwd and cold-start timeout. Preserve all unrelated tables, comments, approval +policy and server entries byte-for-byte; validate edits with a TOML parser. +Repetition with identical values MUST be a no-op. User-owned or modified managed +entries and tracked client configuration MUST produce an actionable conflict, +never an overwrite. Keep a protected recovery copy of the previous owned block +without copying unrelated secrets. Precise ignore rules protect machine-local +client configuration and transient discovery without deleting existing rules. + +Preparation MUST report incomplete writes/installations truthfully. Trust/reload +instructions apply to initial client registration only; no client trust or tool +approval may be bypassed. Grant and desktop restart MUST NOT require changing the +client configuration. A clone is prepared locally to resolve its own installation +and project paths. No global client configuration is rewritten. + +### 1.3 DEV Connection Assistance + +DEV MUST expose preparation/readiness through neutral API contracts and show +connection status separately from Core authority. Waiting for access, connected +and reconnecting derive from project-scoped initialization/ping activity with a +bounded liveness window; a retained HTTP session ID alone is insufficient. Working +remains an authority/operation state. DEV MUST NOT invent knowledge of a client +before it connects. A transport drop MUST NOT revoke a task or grant new control. + +Preparation, labels, clipboard, diagnostics and history MUST NOT expose secrets. +Closing/hiding DEV only unsubscribes visual listeners. Human grant/reclaim and +project/application teardown retain their shared Core semantics. Instructions +cover native file edits, project knowledge, grant/acquire, validation, receipt +lookup, images and explicit release without generated transport clients. ## 2. Identity and Admission @@ -101,7 +160,7 @@ prove authorization. The authority levels in the packaged catalog are: - `authenticated`: connection authentication only; project/context/reference reads - are allowed before grant. No task token is returned by discovery. + need no acquired task. HTTP access still requires the project credential published by human grant. Offline catalog discovery returns no task token. - `granted`: acquisition validates the prior human grant and atomically creates the sole task identity. The transport session ID is not that identity. - `task`: `projectRoot` and `taskId` must identify the current acquired task. @@ -335,7 +394,7 @@ reference provider, not a Studio-maintained language specification. `studio_project_context` resolves an exact, canonical root registered by an open project session. It does not use the focused window, accept a source-directory -path as a project root, acquire a manual lease, or require an AI grant. A session +path as a project root, acquire a manual lease, or acquire task authority. The HTTP boundary separately requires the grant-published project credential. A session is discoverable only after successful opening and until closure begins. Unregistered/closed roots return `PROJECT_NOT_OPEN`. @@ -395,8 +454,7 @@ example references identify their SDK major and target; unsupported selections MUST NOT silently reuse another SDK/target. Numbered spec/draft revisions and the reference-index schema revision MUST NOT be reported as language/compiler versions. -`studio_reference_read` is authenticated but does not require a control grant or -task. It resolves the explicit open root and its current saved manifest selection +`studio_reference_read` is authenticated but does not require an acquired task; the transport still requires a grant-published project credential. It resolves the explicit open root and its current saved manifest selection on every read. Changing SDK/target can invalidate previously advertised IDs. Only IDs in that project's installed index can be read, including when other languages/providers are installed globally. SDK and external-library texts remain @@ -442,7 +500,7 @@ The production registry composes all 17 tools as of step 23, including headless handlers bound to the actual `HeadlessProcessGateway`. Missing project runtime configuration fails at boot with `RUNTIME_UNAVAILABLE`; tool discovery does not grant authority or launch a process. No fake runtime is shipped. -DEV configuration-copy is connected as of step 21. The automated HTTP conformance +The former configuration-copy flow is superseded by DEC-0061 permanent preparation and grant-time discovery. 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. The packaged-runtime gate additionally exercises @@ -493,3 +551,26 @@ cycles using the extracted Studio ZIP. The latter verified listener closure and old-credential rejection after restart. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it. Consolidated acceptance evidence and deferred findings live in the DSC-0068 lesson, not in temporary logs. + +### Integrated Connection Acceptance (DEC-0061) + +Prior DSC-0068 native-client evidence covers the original HTTP flow only. The +integrated flow additionally requires a real native Codex session initialized +before grant, unchanged configuration through desktop restart/new grant, native +images/build/release, scaffold and existing-project preparation, installation +update and graphical launch, plus IntelliJ connector attachment. Automated +fixtures cannot substitute for these gates. PLN-0140 completed automated validation +and the user confirmed all outstanding manual gates on 2026-09-29. The manual +confirmation is user-reported acceptance, not an independently observed test run. +[LSN-0077](../../../discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md) +preserves the result and evidence provenance after workflow housekeeping. + +### Automatic preparation when opening a project + +Opening a project MUST prepare its enabled MCP integration using the same neutral +port as scaffold and DEV retry. Desktop composition MUST start the shared loopback +server before project sessions become available; no external command or separate +per-project desktop Run is required. Explicitly disabled integration MUST remain +disabled. Preparation failure MUST remain visible in DEV readiness without blocking +project use. Opening MUST NOT publish credentials or grant/acquire agent control. +The coding client continues to own its configured stdio process and initial trust. diff --git a/docs/specs/studio/8. Project-Local Studio State Specification.md b/docs/specs/studio/8. Project-Local Studio State Specification.md index df5125dc..12c4f75b 100644 --- a/docs/specs/studio/8. Project-Local Studio State Specification.md +++ b/docs/specs/studio/8. Project-Local Studio State Specification.md @@ -79,7 +79,7 @@ The main session-restoration store MUST NOT include: - heavy operational output; - recomputable results that do not represent session restoration state. -Under DEC-0060, automation grants, task/control identities, active runtime sessions and the task-local operation/deduplication registry MUST NOT be persisted or restored through `.studio/state.json` or `.studio/setup.json`. Reopening a project MUST start under manual control. Restoring DEV as the selected workspace is presentation restoration, not permission to resume work. MCP connection credentials MUST NOT be stored in versioned files; they are regenerated on Studio restart. See the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md). +Under DEC-0060, automation grants, task/control identities, active runtime sessions and the task-local operation/deduplication registry MUST NOT be persisted or restored through `.studio/state.json` or `.studio/setup.json`. Reopening a project MUST start under manual control. Restoring DEV as the selected workspace is presentation restoration, not permission to resume work. MCP connection credentials MUST NOT be stored in versioned files; they are regenerated for every project grant and never restored on restart. See the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md). `Project-local activity` and project-local setup may still live under `.studio/`, but they are separate persistence concerns and not part of the main session-restoration store defined here. @@ -105,3 +105,36 @@ This specification is complete enough when: - accepted and excluded categories are explicit; - load, restore, save, and fallback timing are explicit; - and the ownership boundary with `StudioProjectSession` is normatively locked. + +## Integrated MCP Discovery (DEC-0061) + +`.studio/setup.json` MUST carry neutral `agentIntegration` intent with +`schemaVersion:1`, `enabled` and `clientProfile`. Preserve runtime and editor +fields. This intent is configuration, not readiness or authorization. Machine-local +resolved client configuration is a separate preparation output. + +The transient descriptor is `.studio/mcp/connection.json`, limited to 16 KiB. +Schema v1 requires integral `schemaVersion:1` and nonempty string `instanceId`, +`projectRoot`, `endpoint`, `credential`, `catalogFingerprint`. Root MUST match the +connector's canonical root. Endpoint MUST be `http://127.0.0.1:/mcp`, with +no userinfo, query, fragment or redirect. Grant/task IDs and receipts are forbidden. + +On macOS `.studio/mcp` MUST be owned by the current user with mode 0700; +descriptor, lock and temporary files MUST be 0600 before secrets are written. +Reject symlinked/unsafe paths and tracked descriptor targets. Add precise ignore +rules idempotently without changing unrelated project permissions or files. + +Ownership MUST use an OS-held lock on the stable `publication.lock` inode; do +not delete the lock file on ordinary cleanup. A second live publisher fails. A +crashed process releases its lock through the OS; a new owner may atomically +replace stale content. Write a protected same-directory temporary file and +atomically rename it. Cleanup checks both instance and publication generation +so an old callback cannot remove newer discovery data. + +Publication is a required grant lifecycle participant, not a swallowed observer. +Prepare/publish occur outside the Core monitor; authority activation uses a +generation fence. Acquisition cannot succeed until publication and grant both +commit. Failure aborts credentials/files and reports a failed grant. Revoke/close +invalidate credentials before asynchronous work cleanup, then remove owned +publication and release ownership. File cleanup failure MUST NOT prevent runtime +cancellation. An already-admitted release response MUST remain deliverable. diff --git a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md index aabb8d0e..d9d220da 100644 --- a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +++ b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md @@ -114,9 +114,9 @@ The JavaFX module MUST NOT directly invoke compiler implementations, `p.packer`, Spring Boot MUST be used only by `prometeu-app` for desktop composition and lifecycle. `WebApplicationType.NONE` remains a valid composition mode with an explicitly managed local HTTP adapter. Conformance MUST NOT impose an unconditional absence of a web server that would forbid the DEC-0060 MCP exception. -The sole accepted HTTP-server use is an in-process MCP Streamable HTTP endpoint at `127.0.0.1:/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a random per-Studio-start token, validate Origin and reject unexpected origins, and stop with Studio. Connection authentication MUST NOT grant project/task authority. The token MUST NOT be stored in versioned files, and restart requires refreshed client configuration. +The sole accepted HTTP-server use is an in-process MCP Streamable HTTP endpoint at `127.0.0.1:/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a fresh grant-published project credential, validate project/session scope and Origin, and stop with Studio. Connection authentication MUST NOT grant project/task authority. Credentials MUST NOT be stored in versioned files. Restart requires a fresh human grant, while the stable client configuration remains unchanged. -This exception does not authorize a web UI, remote binding, general-purpose web application, accounts, OAuth, or a stdio MCP bridge. HTTP/MCP dependencies MUST NOT enter API/Core or the JavaFX adapter. Spring Data, Spring AI and durable event infrastructure remain outside the accepted architecture. +This exception does not authorize a web UI, remote binding, general-purpose web application, accounts or OAuth. DEC-0061 explicitly adds the Studio-owned stdio mode and local client preparation. HTTP/MCP dependencies MUST NOT enter API/Core or the JavaFX adapter. Spring Data, Spring AI and durable event infrastructure remain outside the accepted architecture. Spring configuration MAY create core services, infrastructure adapters, and a JavaFX composition factory. It MUST NOT use field injection, context lookup, broad service bags, or a replacement static container. @@ -178,3 +178,17 @@ The architecture is conformant only when all of the following hold together: - migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite; - redesigning compiler, Packer, LSP, or runtime semantics; - introducing microservices or durable event infrastructure. + +## Integrated MCP Connection Boundary (DEC-0061) + +The same Studio application artifact MUST support `mcp --project` over stdio +before desktop composition. It connects to the existing loopback HTTP adapter; +it MUST NOT implement separate authority, operations, language services or runtime +semantics. Offline catalog loading does not initialize the desktop graph. + +API exposes neutral preparation/readiness and connection-publication lifecycle +ports. Core orchestrates save, publication commit/abort, grant, revocation and +shutdown through those ports. Application infrastructure owns credentials, file +locks/atomic discovery, HTTP identity checks, TOML preparation and managed +installation/runtime packaging. JavaFX consumes neutral status and actions only. +Filesystem publication MUST NOT run under a long-held authority monitor. diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index f3ae8b27..1b172f22 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -84,3 +84,14 @@ Normative reminders: - the Studio backend is exposed through neutral API contracts shared by JavaFX and the local MCP adapter, without duplicated authority or orchestration; - Spring Boot remains the desktop composition root with the narrow DEC-0060 local MCP HTTP exception; Spring Modulith still verifies the JavaFX-free `p.studio.core` boundary; - `p.studio.Container`, `AppContainer`, and the mixed `prometeu-studio` module are not valid final architecture. + +## Integrated MCP connection + +DEC-0061 revises the baseline with Studio-owned `mcp --project` mode, grant-time +project discovery, scoped HTTP credentials, one-time scaffold/preparation and a +stable installation with bundled Java. Specs 8–11 define the lifecycle and +transport boundaries; spec 1 defines project creation. PLN-0140 is complete; +automated results and user-confirmed manual acceptance are consolidated in +[LSN-0077](../../../discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md). +The earlier HTTP evidence was not substituted for these gates. The embedded +terminal remains separate. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e55198f6..ee11348c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,6 +12,7 @@ spring-boot = "3.5.16" spring-modulith = "1.4.13" [libraries] +tomlj = { group = "org.tomlj", name = "tomlj", version = "1.1.1" } javafx-controls = { group = "org.openjfx", name = "javafx-controls", version.ref = "javafx" } javafx-fxml = { group = "org.openjfx", name = "javafx-fxml", version.ref = "javafx" } richtextfx = { group = "org.fxmisc.richtext", name = "richtextfx", version.ref = "richtextfx" } diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 8df792af..735d89c5 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -4,6 +4,7 @@ plugins { } dependencies { + implementation(libs.tomlj) implementation(project(":prometeu-infra")) implementation(project(":prometeu-lsp:prometeu-lsp-api")) implementation(project(":prometeu-lsp:prometeu-lsp-v1")) @@ -26,6 +27,36 @@ application { mainClass = "p.studio.app.StudioLauncher" } +val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) } +val studioRuntime = layout.buildDirectory.dir("studio-runtime") +val assembleStudioRuntime by tasks.registering(Exec::class) { + val jdk = studioJava.get().metadata.installationPath.asFile + inputs.property("jdk", jdk.absolutePath) + outputs.dir(studioRuntime) + doFirst { delete(studioRuntime) } + // jlink license files can be read-only; Gradle Sync must be able to refresh the installed image. + doLast { + studioRuntime.get().asFile.walkTopDown().filter { it.isFile }.forEach { + check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" } + } + } + commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files", + "--no-man-pages", "--output", studioRuntime.get().asFile) +} +distributions { + main { contents { from(assembleStudioRuntime) { into("runtime") } } } +} +tasks.register("stageStudioInstallation") { + group = "application" + description = "Stages and validates the bundled Studio/Java installation; no project launcher is created." + dependsOn(tasks.named("installDist")) + classpath = sourceSets["main"].runtimeClasspath + mainClass = "p.studio.app.install.ManagedStudioInstallation" + args(layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath, + providers.gradleProperty("studioInstallationRoot").getOrElse( + "${System.getProperty("user.home")}/Library/Application Support/Prometeu/Studio")) +} + javafx { version = libs.versions.javafx.get() modules("javafx.controls", "javafx.fxml") @@ -77,3 +108,20 @@ tasks.register("headlessMcpDesktopTest") { systemProperty("java.awt.headless", "false") systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) } + +// Subprocess tests exercise the actual Studio main and OS ownership boundaries. +tasks.withType().configureEach { + systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath) +} + +tasks.named("test") { exclude("**/InstalledConnectorTest.class") } +tasks.register("installedConnectorTest") { + group = "verification" + description = "Validates installed Java, stable updates, project preparation and JavaFX startup (requires a display)." + dependsOn(tasks.named("installDist")) + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/InstalledConnectorTest.class") + systemProperty("studio.test.distribution", layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath) +} 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 69aec83e..020cec9a 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -230,13 +230,16 @@ public class StudioApplicationConfiguration { @Bean(destroyMethod = "close") DefaultProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, - p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) { - return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations); + p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations, + p.studio.api.automation.AutomationConnectionLifecycle connections, + p.studio.api.automation.AgentIntegrationPreparation preparation) { + return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations, connections, preparation); } @Bean - ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) { - return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore); + ProjectCatalog projectCatalog(ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore, + p.studio.api.automation.AgentIntegrationPreparation preparation) { + return new ProjectCatalogService(resolveDefaultProjectsRoot(), mapper, setupStore, preparation); } @Bean @@ -340,10 +343,19 @@ public class StudioApplicationConfiguration { return new p.studio.app.mcp.LocalMcpServer(mapper, tools); } + @Bean + p.studio.api.automation.AutomationConnectionLifecycle connectionLifecycle(p.studio.app.mcp.LocalMcpServer server, ObjectMapper mapper) { + return new p.studio.app.mcp.ProjectConnectionPublisher(server, mapper); + } + @Bean + p.studio.api.automation.AgentIntegrationPreparation agentPreparation(ObjectMapper mapper) { + return new p.studio.app.mcp.StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper); + } @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); + p.studio.core.project.ProjectAccessRegistry projects, ObjectMapper mapper, + p.studio.api.automation.AgentIntegrationPreparation preparation) { + return new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, preparation); } private static Path resolveDefaultProjectsRoot() { diff --git a/prometeu-app/src/main/java/p/studio/app/StudioLauncher.java b/prometeu-app/src/main/java/p/studio/app/StudioLauncher.java index 8ca6ca55..791c43be 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioLauncher.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioLauncher.java @@ -7,6 +7,11 @@ public final class StudioLauncher { } public static void main(String[] args) { + if (args.length > 0 && "mcp".equals(args[0])) { + try { p.studio.app.mcp.stdio.StudioMcpStdio.main(args); } + catch (Exception failure) { System.err.println("Studio MCP could not start. Check --project, the manifest and installation."); System.exit(1); } + return; + } Application.launch(App.class, args); } } diff --git a/prometeu-app/src/main/java/p/studio/app/install/ManagedStudioInstallation.java b/prometeu-app/src/main/java/p/studio/app/install/ManagedStudioInstallation.java new file mode 100644 index 00000000..e81a66c8 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/install/ManagedStudioInstallation.java @@ -0,0 +1,55 @@ +package p.studio.app.install; + +import java.io.IOException; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** One versioned application installation; client entries always refer to current. */ +public final class ManagedStudioInstallation { + public static final class MissingInstallation extends IOException { + public MissingInstallation() { + super("Studio installation is missing. In the Studio checkout, run ./gradlew :prometeu-app:stageStudioInstallation, then prepare the assistant again. If using an isolated installation, set -Dstudio.installationRoot to that installation in the desktop VM options."); + } + } + private ManagedStudioInstallation() { } + public static Path defaultRoot() { + return Path.of(System.getProperty("studio.installationRoot", Path.of(System.getProperty("user.home"), + "Library", "Application Support", "Prometeu", "Studio").toString())).toAbsolutePath(); + } + public static void ensureAvailable(Path base) throws Exception { + if (Files.isExecutable(base.resolve("current/runtime/bin/java")) && Files.isDirectory(base.resolve("current/lib"))) return; + Path location = Path.of(ManagedStudioInstallation.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + if (!Files.isRegularFile(location) || !Files.isDirectory(location.getParent().getParent().resolve("runtime"))) + throw new MissingInstallation(); + install(location.getParent().getParent(), base); + } + public static synchronized Path install(Path source, Path base) throws Exception { + source = source.toRealPath(); Files.createDirectories(base.resolve("versions")); + Path version = base.resolve("versions").resolve(UUID.randomUUID().toString()); + Files.createDirectory(version); + for (String part : List.of("lib", "runtime")) { + if (!Files.isDirectory(source.resolve(part))) throw new IOException("Incomplete Studio distribution"); + try (var paths = Files.walk(source.resolve(part))) { + for (Path from : paths.toList()) { + Path to = version.resolve(source.relativize(from)); + if (Files.isDirectory(from)) Files.createDirectories(to); + else Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES); + } + } + } + var process = new ProcessBuilder(version.resolve("runtime/bin/java").toString(), "-cp", version.resolve("lib/*").toString(), + "p.studio.app.install.StudioInstallationProbe").redirectError(ProcessBuilder.Redirect.DISCARD).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Installation validation timed out"); } + if (process.exitValue() != 0) throw new IOException("Installation validation failed"); + Path link = base.resolve(".current-" + UUID.randomUUID()); + try { Files.createSymbolicLink(link, base.toAbsolutePath().relativize(version.toAbsolutePath())); + Files.move(link, base.resolve("current"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { Files.deleteIfExists(link); } + return version; + } + public static void main(String[] args) throws Exception { + if (args.length != 2) throw new IllegalArgumentException("distribution and installation root required"); + install(Path.of(args[0]), Path.of(args[1])); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/install/StudioInstallationProbe.java b/prometeu-app/src/main/java/p/studio/app/install/StudioInstallationProbe.java new file mode 100644 index 00000000..cdbb87b0 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/install/StudioInstallationProbe.java @@ -0,0 +1,12 @@ +package p.studio.app.install; + +/** Packaging health check; it never starts the GUI or opens projects. */ +public final class StudioInstallationProbe { + public static void main(String[] args) throws Exception { + var catalog = new p.studio.app.mcp.McpToolCatalog(new com.fasterxml.jackson.databind.ObjectMapper()); + if (catalog.names().isEmpty()) throw new IllegalStateException("Missing catalog"); + for (String type : java.util.List.of("javafx.application.Application", "javafx.fxml.FXMLLoader", + "p.studio.app.App", "java.net.http.HttpClient", "com.sun.net.httpserver.HttpServer", "org.tomlj.Toml")) + Class.forName(type, false, StudioInstallationProbe.class.getClassLoader()); + } +} 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 a9b19dee..5588589e 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 @@ -20,7 +20,22 @@ public final class LocalMcpServer implements AutoCloseable { private static final int MAX_CONNECTION_SESSIONS = 128; private final ObjectMapper mapper; private final McpToolRegistry tools; - private final Map sessions = new ConcurrentHashMap<>(); + private record Session(ProjectCredentials.Credential credential, AtomicBoolean initialized, java.util.concurrent.atomic.AtomicLong lastSeen) { } + private final Map sessions = new ConcurrentHashMap<>(); + private final ProjectCredentials credentials = new ProjectCredentials(); + private volatile String instanceId; + public ProjectCredentials credentials() { return credentials; } + public String instanceId() { return instanceId; } + public synchronized void activateCredential(String instance, ProjectCredentials.Credential credential) { + if (server == null || !Objects.equals(instanceId, instance)) throw new IllegalStateException("Studio instance changed"); + credential.activate(); + } + public String catalogFingerprint() { return tools.catalogFingerprint(); } + public boolean connected(java.nio.file.Path root) { + long now = System.nanoTime(); + return sessions.values().stream().anyMatch(s -> s.initialized.get() && s.credential.active() && s.credential.root().equals(root) + && now - s.lastSeen.get() < TimeUnit.SECONDS.toNanos(10)); + } private final SecureRandom random = new SecureRandom(); private HttpServer server; private ExecutorService executor; @@ -42,7 +57,8 @@ public final class LocalMcpServer implements AutoCloseable { this.tools = Objects.requireNonNull(tools); } - public synchronized void start() throws IOException { + public void start() throws IOException { + synchronized (this) { if (server != null) return; // No configurable bind address: remote and wildcard exposure cannot be enabled accidentally. var next = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 32); @@ -50,17 +66,20 @@ public final class LocalMcpServer implements AutoCloseable { Thread.ofPlatform().daemon().name("studio-mcp-", 1).factory(), new ThreadPoolExecutor.AbortPolicy()); var timers = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-deadlines").factory()); try { - connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp"), secret()); + instanceId = UUID.randomUUID().toString(); + connection = new Connection(URI.create("http://127.0.0.1:" + next.getAddress().getPort() + "/mcp")); deadlines = timers; next.createContext("/mcp", this::handle); next.setExecutor(workers); next.start(); + timers.scheduleWithFixedDelay(() -> connectionListeners.forEach(LocalMcpServer::notifyConnectionListener), 2, 2, TimeUnit.SECONDS); executor = workers; server = next; - connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } catch (RuntimeException failure) { next.stop(0); workers.shutdownNow(); timers.shutdownNow(); connection = null; throw failure; } + } + connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } public Connection connection() { var current = connection; @@ -68,20 +87,20 @@ public final class LocalMcpServer implements AutoCloseable { return current; } public synchronized boolean isRunning() { return server != null; } - @Override public synchronized void close() { + @Override public void close() { + synchronized (this) { if (server == null) return; connection = null; server.stop(0); server = null; - sessions.clear(); executor.shutdownNow(); deadlines.shutdownNow(); + sessions.clear(); credentials.clear(); executor.shutdownNow(); deadlines.shutdownNow(); + } connectionListeners.forEach(LocalMcpServer::notifyConnectionListener); } - /** Only explicit connection/configuration consumers may obtain the bearer token; never log it. */ + /** Public endpoint metadata contains no credential. */ public static final class Connection { private final URI endpoint; - private final String token; - private Connection(URI endpoint, String token) { this.endpoint = endpoint; this.token = token; } + private Connection(URI endpoint) { this.endpoint = endpoint; } public URI endpoint() { return endpoint; } - public String authorizationHeader() { return "Bearer " + token; } @Override public String toString() { return "LocalMcpConnection[endpoint=" + endpoint + ", credentials=REDACTED]"; } } @@ -101,13 +120,17 @@ public final class LocalMcpServer implements AutoCloseable { || !authority.equals(single(headers, "Host")) || origin != null && !("http://" + authority).equals(origin)) { empty(exchange, 403); return; } String authorization = single(headers, "Authorization"); - if (authorization == null || !MessageDigest.isEqual(current.authorizationHeader().getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) { + var credential = credentials.authenticate(authorization); + if (credential == null) { empty(exchange, 401); return; } String version = single(headers, "MCP-Protocol-Version"); if (version != null && !PROTOCOL_VERSION.equals(version)) { empty(exchange, 400); return; } String sessionId = single(headers, "Mcp-Session-Id"); - AtomicBoolean initialized = sessionId == null ? null : sessions.get(sessionId); + var session = sessionId == null ? null : sessions.get(sessionId); + if (session != null && session.credential != credential) { empty(exchange, 403); return; } + AtomicBoolean initialized = session == null ? null : session.initialized; + if (session != null) session.lastSeen.set(System.nanoTime()); if (sessionId != null && initialized == null) { empty(exchange, 404); return; } String method = exchange.getRequestMethod(); if (method.equals("GET")) { exchange.getResponseHeaders().set("Allow", "POST, DELETE"); empty(exchange, 405); return; } @@ -148,14 +171,16 @@ public final class LocalMcpServer implements AutoCloseable { send(exchange, 400, error(id.isMissingNode() ? NullNode.instance : id, -32602, "Invalid initialization")); return; } synchronized (sessions) { + sessions.values().removeIf(s -> !s.credential.active()); if (sessions.size() >= MAX_CONNECTION_SESSIONS) { empty(exchange, 503); return; } - sessionId = secret(); sessions.put(sessionId, new AtomicBoolean()); + sessionId = secret(); sessions.put(sessionId, new Session(credential, new AtomicBoolean(), new java.util.concurrent.atomic.AtomicLong(System.nanoTime()))); } exchange.getResponseHeaders().set("Mcp-Session-Id", sessionId); 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", McpConnectionGuide.INSTRUCTIONS); + result.putObject("_meta").put("instanceId", instanceId).put("projectRoot", credential.root().toString()).put("catalogFingerprint", tools.catalogFingerprint()); send(exchange, 200, response(id, result)); return; } if (initialized == null) { empty(exchange, 400); return; } @@ -174,7 +199,18 @@ public final class LocalMcpServer implements AutoCloseable { } case "tools/call" -> { if (!params.path("name").isTextual()) throw new IllegalArgumentException("Missing tool name"); - yield tools.call(params.get("name").asText(), params.get("arguments")).wire(); + var arguments = params.get("arguments"); + if (arguments == null || !arguments.path("projectRoot").isTextual()) throw new IllegalArgumentException("Missing root"); + java.nio.file.Path requested; + try { requested = java.nio.file.Path.of(arguments.path("projectRoot").asText()); + if (!requested.isAbsolute()) throw new IllegalArgumentException("Relative root"); + requested = requested.toRealPath(); + } catch (java.io.IOException | RuntimeException invalid) { throw new IllegalArgumentException("Invalid root"); } + if (!credential.active() || !credential.root().equals(requested)) { + yield McpToolResult.failure(mapper, new p.studio.api.automation.AutomationFailure( + p.studio.api.automation.AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Connection is bound to another project or no longer authorized")).wire(); + } + yield tools.call(params.get("name").asText(), arguments).wire(); } default -> null; }; 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 index ac096304..baa0d117 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpConnectionGuide.java @@ -7,12 +7,11 @@ 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. */ +/** Projects connection liveness and permanent setup independently of task authority. */ 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. + Use the Studio tools for this project. Wait for the developer to grant access in DEV, then acquire control. + The installed Studio connector discovers the connection automatically; do not write transport scripts or copy tokens. 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. @@ -26,25 +25,42 @@ public final class McpConnectionGuide implements AgentConnectionGuide { 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. + After Studio restart, wait for a fresh human grant. The connector reconnects automatically; old task identities are invalid. """; private final LocalMcpServer server; private final ProjectAccessRegistry projects; private final ObjectMapper mapper; + private final p.studio.api.automation.AgentIntegrationPreparation preparation; public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper) { - this.server = server; this.projects = projects; this.mapper = mapper; + this(server, projects, mapper, new StudioAgentPreparation(p.studio.app.install.ManagedStudioInstallation.defaultRoot(), mapper)); } + public McpConnectionGuide(LocalMcpServer server, ProjectAccessRegistry projects, ObjectMapper mapper, + p.studio.api.automation.AgentIntegrationPreparation preparation) { + this.server = server; this.projects = projects; this.mapper = mapper; this.preparation = preparation; + } + @Override public boolean supportsPreparation() { return true; } @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(); + return "Run the installed Studio in mcp --project mode for " + canonical + "\n" + INSTRUCTIONS; + } + @Override public p.studio.api.automation.AgentIntegrationPreparation.Result prepare(Path root) { + return preparation.prepare(projects.requireOpenRoot(root)); + } + @Override public p.studio.api.automation.AgentIntegrationPreparation.Result preparationStatus(Path root) { + return preparation.status(projects.requireOpenRoot(root)); + } + @Override public State state(Path root) { + try { + Path canonical = projects.requireOpenRoot(root); + if (!server.isRunning()) return State.UNAVAILABLE; + if (server.connected(canonical)) return State.CONNECTED; + var control = projects.requireAutomation(canonical).snapshot().state(); + return control == p.studio.api.automation.ControlState.AGENT_WORKING ? State.RECONNECTING : State.WAITING_FOR_ACCESS; + } catch (RuntimeException unavailable) { return State.UNAVAILABLE; } } @Override public OperationSubscription subscribe(Runnable changed) { return server.onConnectionChanged(changed); } } diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java index 559a9665..1dcfcc55 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolCatalog.java @@ -21,6 +21,14 @@ public final class McpToolCatalog { } catch (IOException failure) { throw new IllegalStateException("Cannot read packaged MCP contract", failure); } } public Set names() { return definitions.keySet(); } + public String fingerprint() { + try { + var digest = java.security.MessageDigest.getInstance("SHA-256"); + digest.update(LocalMcpServer.PROTOCOL_VERSION.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + definitions.keySet().stream().sorted().forEach(name -> digest.update(descriptor(name).toString().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + return java.util.HexFormat.of().formatHex(digest.digest()); + } catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } + } public JsonNode definition(String name) { var definition = definitions.get(name); if (definition == null) throw new IllegalArgumentException("Unknown tool"); diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java index 0849ab02..7082f526 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpToolRegistry.java @@ -22,6 +22,7 @@ public final class McpToolRegistry { catalog.names().stream().filter(handlers::containsKey).forEach(name -> descriptors.add(catalog.descriptor(name))); return descriptors; } + public String catalogFingerprint() { return catalog.fingerprint(); } public McpToolResult call(String name, JsonNode arguments) { var handler = handlers.get(name); if (handler == null) throw new IllegalArgumentException("Unknown or unavailable tool"); diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionFiles.java b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionFiles.java new file mode 100644 index 00000000..5b35ab37 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionFiles.java @@ -0,0 +1,79 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.*; +import java.io.IOException; +import java.net.URI; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import static java.nio.file.LinkOption.NOFOLLOW_LINKS; + +/** Local discovery data is untrusted until paths, permissions and live identity are verified. */ +public final class ProjectConnectionFiles { + public static final String RELATIVE = ".studio/mcp/connection.json"; + private static final Set FILE_MODE = PosixFilePermissions.fromString("rw-------"); + private ProjectConnectionFiles() { } + public static Path directory(Path root) throws IOException { + Path studio = root.resolve(".studio"), directory = studio.resolve("mcp"); + safeDirectory(studio, false); safeDirectory(directory, true); return directory; + } + private static void safeDirectory(Path path, boolean privateDirectory) throws IOException { + if (!Files.exists(path, NOFOLLOW_LINKS)) Files.createDirectory(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + if (Files.isSymbolicLink(path) || !Files.isDirectory(path, NOFOLLOW_LINKS)) throw new IOException("Unsafe connection directory"); + if (privateDirectory) requirePrivate(path, true); + } + public static void requirePrivate(Path path, boolean directory) throws IOException { + if (Files.isSymbolicLink(path) || !(directory ? Files.isDirectory(path, NOFOLLOW_LINKS) : Files.isRegularFile(path, NOFOLLOW_LINKS))) + throw new IOException("Unsafe connection file"); + var expected = directory ? PosixFilePermissions.fromString("rwx------") : FILE_MODE; + if (!Files.getPosixFilePermissions(path, NOFOLLOW_LINKS).equals(expected) + || !Files.getOwner(path, NOFOLLOW_LINKS).equals(Files.getOwner(Path.of(System.getProperty("user.home"))))) + throw new IOException("Connection permissions must be restricted to the current user"); + } + public static void atomicPrivateWrite(Path target, byte[] bytes) throws IOException { + if (Files.exists(target, NOFOLLOW_LINKS)) requirePrivate(target, false); + var temp = Files.createTempFile(target.getParent(), ".connection-", ".tmp", PosixFilePermissions.asFileAttribute(FILE_MODE)); + try { Files.write(temp, bytes); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } + finally { Files.deleteIfExists(temp); } + } + public static boolean tracked(Path root, String relative) throws IOException { + try { + var process = new ProcessBuilder("git", "-C", root.toString(), "ls-files", "-z", "--", relative).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + if (!process.waitFor(5, TimeUnit.SECONDS)) { process.destroyForcibly(); throw new IOException("Git check timed out"); } + if (process.exitValue() != 0 && process.exitValue() != 128) throw new IOException("Cannot verify file tracking"); + return process.getInputStream().read() != -1; + } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Git check interrupted"); } + } + public static void ignore(Path root, String relative) throws IOException { + Path path = root.resolve(".gitignore"); + if (Files.isSymbolicLink(path)) throw new IOException("Unsafe ignore file"); + String old = Files.exists(path) ? Files.readString(path) : ""; + String rule = "/" + relative; + if (old.lines().anyMatch(rule::equals)) return; + Files.writeString(path, old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + rule + "\n"); + } + public static Descriptor read(Path root, ObjectMapper mapper) throws IOException { + Path path = root.resolve(RELATIVE); + if (Files.isSymbolicLink(root.resolve(".studio"))) throw new IOException("Unsafe discovery path"); + requirePrivate(path.getParent(), true); requirePrivate(path, false); + byte[] bytes; + try (var input = Files.newInputStream(path, NOFOLLOW_LINKS)) { bytes = input.readNBytes(16 * 1024 + 1); } + if (bytes.length > 16 * 1024) throw new IOException("Connection descriptor too large"); + var json = mapper.readTree(bytes); + if (json == null || !json.path("schemaVersion").isIntegralNumber() || !json.path("schemaVersion").canConvertToInt() || json.path("schemaVersion").asInt(-1) != 1) throw new IOException("Unsupported connection schema"); + for (String field : Set.of("instanceId", "projectRoot", "endpoint", "credential", "catalogFingerprint")) + if (!json.path(field).isTextual() || json.path(field).asText().isBlank()) throw new IOException("Invalid connection descriptor"); + try { + if (!Path.of(json.path("projectRoot").asText()).equals(root)) throw new IOException("Connection project mismatch"); + URI endpoint = URI.create(json.path("endpoint").asText()); + if (!"http".equals(endpoint.getScheme()) || !"127.0.0.1".equals(endpoint.getHost()) || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 || !"/mcp".equals(endpoint.getRawPath()) || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null || endpoint.getUserInfo() != null) throw new IOException("Invalid loopback endpoint"); + return new Descriptor(endpoint, json.path("instanceId").asText(), json.path("credential").asText(), json.path("catalogFingerprint").asText()); + } catch (IllegalArgumentException invalid) { throw new IOException("Invalid connection descriptor"); } + } + public record Descriptor(URI endpoint, String instanceId, String credential, String catalogFingerprint) { + @Override public String toString() { return "ProjectConnectionDescriptor[REDACTED]"; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionPublisher.java b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionPublisher.java new file mode 100644 index 00000000..e8928791 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectConnectionPublisher.java @@ -0,0 +1,52 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.AutomationConnectionLifecycle; +import java.nio.channels.*; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; + +/** The lock inode outlives a publication. Its OS lock, not a stale PID/file, establishes ownership. */ +public final class ProjectConnectionPublisher implements AutomationConnectionLifecycle { + private final LocalMcpServer server; + private final ObjectMapper mapper; + public ProjectConnectionPublisher(LocalMcpServer server, ObjectMapper mapper) { this.server = server; this.mapper = mapper; } + @Override public Publication prepare(Path projectRoot) throws Exception { + Path root = projectRoot.toRealPath(); + final String instance = server.instanceId(); + final var endpoint = server.connection().endpoint(); + if (ProjectConnectionFiles.tracked(root, ProjectConnectionFiles.RELATIVE)) throw new IllegalStateException("Connection file is tracked"); + ProjectConnectionFiles.ignore(root, ".studio/mcp/"); + Path directory = ProjectConnectionFiles.directory(root), lockPath = directory.resolve("publication.lock"); + if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)) ProjectConnectionFiles.requirePrivate(lockPath, false); + var channel = FileChannel.open(lockPath, Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS), + PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + FileLock lock; + try { lock = channel.tryLock(); if (lock == null) throw new AutomationConnectionLifecycle.OwnershipConflict(); } + catch (OverlappingFileLockException conflict) { channel.close(); throw new AutomationConnectionLifecycle.OwnershipConflict(); } + catch (Exception conflict) { channel.close(); throw conflict; } + var credential = server.credentials().prepare(root); + return new Publication() { + private boolean published, closed; + public void publish() throws Exception { + var value = mapper.createObjectNode().put("schemaVersion", 1).put("instanceId", instance) + .put("projectRoot", root.toString()).put("endpoint", endpoint.toString()) + .put("credential", credential.secret()).put("catalogFingerprint", server.catalogFingerprint()); + ProjectConnectionFiles.atomicPrivateWrite(directory.resolve("connection.json"), mapper.writeValueAsBytes(value)); published = true; + } + public void activate() { server.activateCredential(instance, credential); } + public void invalidate() { credential.invalidate(); } + public synchronized void close() throws Exception { + if (closed) return; closed = true; invalidate(); + try { + if (published && Files.exists(directory.resolve("connection.json"), LinkOption.NOFOLLOW_LINKS)) { + var current = ProjectConnectionFiles.read(root, mapper); + if (instance.equals(current.instanceId()) && credential.secret().equals(current.credential())) + Files.delete(directory.resolve("connection.json")); + } + } finally { try { lock.release(); } finally { channel.close(); } } + } + }; + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/ProjectCredentials.java b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectCredentials.java new file mode 100644 index 00000000..b2457c1c --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/ProjectCredentials.java @@ -0,0 +1,42 @@ +package p.studio.app.mcp; + +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** Memory-only authentication; never a substitute for the Core grant/task checks. */ +public final class ProjectCredentials { + private final Map credentials = new ConcurrentHashMap<>(); + public Credential prepare(Path root) { + byte[] bytes = new byte[32]; new SecureRandom().nextBytes(bytes); + var credential = new Credential(root, Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + credentials.put(credential.secret, credential); return credential; + } + public Credential authenticate(String header) { + if (header == null || !header.startsWith("Bearer ")) return null; + String token = header.substring(7); + var found = credentials.get(token); + return found != null && found.active && MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8), + found.secret.getBytes(StandardCharsets.UTF_8)) ? found : null; + } + public void clear() { credentials.values().forEach(Credential::invalidate); credentials.clear(); } + public final class Credential { + private final Path root; + private final String secret; + private volatile boolean active; + private boolean invalidated; + private Credential(Path root, String secret) { this.root = root; this.secret = secret; } + public Path root() { return root; } + public String secret() { return secret; } + public synchronized void activate() { + if (invalidated) throw new IllegalStateException("Credential invalidated"); + active = true; + } + public synchronized void invalidate() { active = false; invalidated = true; credentials.remove(secret, this); } + public boolean active() { return active; } + @Override public String toString() { return "ProjectCredential[REDACTED]"; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/StudioAgentPreparation.java b/prometeu-app/src/main/java/p/studio/app/mcp/StudioAgentPreparation.java new file mode 100644 index 00000000..e221302d --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/StudioAgentPreparation.java @@ -0,0 +1,124 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.AgentIntegrationPreparation; +import p.studio.app.install.ManagedStudioInstallation; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.nio.charset.StandardCharsets; +import java.util.*; +import org.tomlj.Toml; + +/** Only the managed entry is edited; unrelated client configuration remains byte-for-byte intact. */ +public final class StudioAgentPreparation implements AgentIntegrationPreparation { + private final Path installation; + private final ObjectMapper mapper; + private final Map preparationFailures = new java.util.concurrent.ConcurrentHashMap<>(); + private static final String BEGIN = "# Studio managed MCP entry "; + private static final String END = "# End Studio managed MCP entry\n"; + public StudioAgentPreparation(Path installation, ObjectMapper mapper) { this.installation = installation; this.mapper = mapper; } + @Override public synchronized Result prepare(Path projectRoot) { + var result = prepareLocal(projectRoot); + Path key = preparationKey(projectRoot); + if (result.ready()) preparationFailures.remove(key); else preparationFailures.put(key, result); + return result; + } + private Result prepareLocal(Path projectRoot) { + try { + Path root = projectRoot.toRealPath(); + if (!Files.isRegularFile(root.resolve("prometeu.json"))) return new Result(false, "Project manifest not found."); + if (ProjectConnectionFiles.tracked(root, ".codex/config.toml")) + return new Result(false, "Client configuration is tracked. Keep machine-specific registration local before preparing this project."); + Path directory = root.resolve(".codex"), config = directory.resolve("config.toml"); + if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(config)) return new Result(false, "Client configuration path is unsafe."); + String old = Files.exists(config) ? Files.readString(config) : ""; + String next = merge(old, entry(root)); + ManagedStudioInstallation.ensureAvailable(installation); + Files.createDirectories(directory); + ProjectConnectionFiles.ignore(root, ".codex/config.toml"); + ProjectConnectionFiles.ignore(root, ".studio/mcp/"); + if (!old.equals(next)) { + int previous = old.indexOf(BEGIN); + if (previous >= 0) { + ProjectConnectionFiles.ignore(root, ".codex/.studio-mcp.previous.toml"); + String owned = old.substring(previous, old.indexOf(END, previous) + END.length()); + ProjectConnectionFiles.atomicPrivateWrite(directory.resolve(".studio-mcp.previous.toml"), owned.getBytes(StandardCharsets.UTF_8)); + } + Path temporary = Files.createTempFile(directory, ".studio-config-", ".tmp", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + try { Files.writeString(temporary, next); Files.move(temporary, config, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } + finally { Files.deleteIfExists(temporary); } + } + Path studio = root.resolve(".studio"); + if (Files.isSymbolicLink(studio)) throw new IllegalStateException("Unsafe setup directory"); + Files.createDirectories(studio); + Path setup = studio.resolve("setup.json"); + if (Files.isSymbolicLink(setup)) throw new IllegalStateException("Unsafe setup file"); + var value = Files.exists(setup) ? mapper.readTree(Files.readAllBytes(setup)) : mapper.createObjectNode(); + if (!(value instanceof com.fasterxml.jackson.databind.node.ObjectNode object)) throw new IllegalStateException("Invalid setup"); + object.putObject("agentIntegration").put("schemaVersion", 1).put("enabled", true).put("clientProfile", "codex"); + String setupText = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object); + if (!Files.exists(setup) || !Files.readString(setup).equals(setupText)) { + Path temporary = Files.createTempFile(studio, ".setup-", ".tmp"); + try { Files.writeString(temporary, setupText); Files.move(temporary, setup, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } + finally { Files.deleteIfExists(temporary); } + } + return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Then grant access in DEV; no token copying or restart reconfiguration is needed."); + } catch (ManagedStudioInstallation.MissingInstallation missing) { return new Result(false, missing.getMessage()); } + catch (Conflict conflict) { return new Result(false, conflict.getMessage()); } + catch (Exception failure) { return new Result(false, "Preparation incomplete. Check the Studio installation and project/configuration permissions; existing client settings were not deliberately replaced."); } + } + @Override public Result status(Path projectRoot) { + var failure = preparationFailures.get(preparationKey(projectRoot)); + if (failure != null) return failure; + try { + Path root = projectRoot.toRealPath(), config = root.resolve(".codex/config.toml"); + if (Files.isSymbolicLink(config.getParent()) || Files.isSymbolicLink(config)) + return new Result(false, "Unsafe client configuration path. Prepare the assistant after resolving it."); + if (!Files.isRegularFile(config)) return new Result(false, "Assistant setup is incomplete. Prepare the assistant for this project."); + String old = Files.readString(config); + if (!old.equals(merge(old, entry(root))) || !Files.isExecutable(installation.resolve("current/runtime/bin/java"))) + return new Result(false, "Assistant setup is incomplete. Prepare the assistant from an installed Studio."); + return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested."); + } catch (Conflict conflict) { return new Result(false, conflict.getMessage()); } + catch (Exception unavailable) { return new Result(false, "Assistant setup could not be verified. Prepare the assistant again."); } + } + private static Path preparationKey(Path root) { + try { return root.toRealPath(); } + catch (java.io.IOException missing) { return root.toAbsolutePath().normalize(); } + } + public String entry(Path root) throws Exception { + Path current = installation.resolve("current").toAbsolutePath(); + return "[mcp_servers.prometeu_studio]\ncommand = " + quote(current.resolve("runtime/bin/java").toString()) + + "\nargs = " + mapper.writeValueAsString(List.of("-cp", current.resolve("lib/*").toString(), "p.studio.app.StudioLauncher", "mcp", "--project", root.toString())) + + "\ncwd = " + quote(root.toString()) + "\nstartup_timeout_sec = 20\ntool_timeout_sec = 90\n"; + } + private String quote(String text) throws Exception { return mapper.writeValueAsString(text); } + static String merge(String old, String entry) throws Exception { + if (Toml.parse(old).hasErrors()) throw new Conflict("Existing client TOML is invalid; repair it before preparation."); + String block = BEGIN + hash(entry) + "\n" + entry + END; + int start = old.indexOf(BEGIN), end = old.indexOf(END); + String next; + if (start >= 0) { + int body = old.indexOf('\n', start) + 1; + if (start > 0 && old.charAt(start - 1) != '\n' || body == 0 || end < body || old.indexOf(BEGIN, body) >= 0 || !old.substring(start + BEGIN.length(), body - 1).equals(hash(old.substring(body, end)))) + throw new Conflict("The Studio MCP entry was edited. Resolve the managed-entry conflict explicitly."); + next = old.substring(0, start) + block + old.substring(end + END.length()); + } else { + if (end >= 0 || Toml.parse(old).contains("mcp_servers.prometeu_studio")) throw new Conflict("A user-owned Studio MCP entry already exists; resolve it explicitly."); + next = old + (old.isEmpty() || old.endsWith("\n") ? "" : "\n") + block; + } + if (Toml.parse(next).hasErrors()) throw new Conflict("Client configuration conflicts with the Studio entry; nothing was overwritten."); + var actual = Toml.parse(next).getTable("mcp_servers.prometeu_studio"); + var expected = Toml.parse(entry).getTable("mcp_servers.prometeu_studio"); + if (actual == null || expected == null || !actual.keySet().equals(expected.keySet()) + || !Objects.equals(actual.getString("command"), expected.getString("command")) + || !Objects.equals(actual.getString("cwd"), expected.getString("cwd")) + || !Objects.equals(actual.getLong("startup_timeout_sec"), expected.getLong("startup_timeout_sec")) + || !Objects.equals(actual.getLong("tool_timeout_sec"), expected.getLong("tool_timeout_sec")) + || actual.getArray("args") == null || !actual.getArray("args").toList().equals(expected.getArray("args").toList())) + throw new Conflict("The managed Studio table conflicts with other client settings; resolve it explicitly."); + return next; + } + private static String hash(String text) throws Exception { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); } + private static final class Conflict extends Exception { Conflict(String text) { super(text); } } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpConnection.java b/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpConnection.java new file mode 100644 index 00000000..fbb428ec --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpConnection.java @@ -0,0 +1,170 @@ +package p.studio.app.mcp.stdio; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.ObjectNode; +import p.studio.app.mcp.*; +import java.io.*; +import java.net.http.*; +import java.nio.file.*; +import java.time.Duration; +import java.util.*; + +/** Owns only HTTP transport. Never retries a tools/call or creates task authority. */ +final class StudioMcpConnection implements AutoCloseable { + private final Path root; + private final ObjectMapper mapper; + private final McpToolCatalog catalog; + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).followRedirects(HttpClient.Redirect.NEVER).build(); + private ProjectConnectionFiles.Descriptor descriptor; + private String session; + private Set available = Set.of(); + // Diagnostic correlation only: Core remains the sole validator of task authority. + private final LinkedHashMap observedTaskInstances = new LinkedHashMap<>(); + private long sequence; + private volatile String status = "WAITING_FOR_ACCESS"; + StudioMcpConnection(Path root, ObjectMapper mapper, McpToolCatalog catalog) { this.root = root; this.mapper = mapper; this.catalog = catalog; } + String status() { return status; } + synchronized void probe() { + try { connect(); exchange("ping", mapper.createObjectNode(), true, 3); status = "CONNECTED"; } + catch (Exception failure) { disconnect(); } + } + synchronized JsonNode call(String tool, JsonNode arguments) { + boolean dispatched = false; + try { + catalog.validateArguments(tool, arguments); + try { + if (!Path.of(arguments.path("projectRoot").asText()).toRealPath().equals(root)) + return failure("OUTSIDE_PROJECT_SCOPE", "The connector is bound to another project."); + } catch (IOException inaccessible) { return failure("INVALID_REQUEST", "Project root cannot be resolved."); } + connect(); + String taskInstance = observedTaskInstances.get(arguments.path("taskId").asText()); + if (tool.equals("studio_operation_get") && taskInstance != null && !taskInstance.equals(descriptor.instanceId())) + return failure("OUTCOME_UNKNOWN", "Studio restarted; this task's in-memory receipts are unavailable. Obtain a fresh grant/task and decide the next intent explicitly; do not replay the old operation."); + if (!available.contains(tool)) return failure("UNSUPPORTED_CAPABILITY", "The live Studio does not provide this tool."); + var params = mapper.createObjectNode().put("name", tool).set("arguments", arguments); + dispatched = true; + var response = exchange("tools/call", params, true, 70); + if (response.has("error")) throw new ProtocolFailure(response.get("error")); + status = "CONNECTED"; + var result = response.required("result"); + if (tool.equals("studio_control_acquire") && !result.path("isError").asBoolean()) { + String task = result.path("structuredContent").path("value").path("taskId").asText(); + if (!task.isBlank()) { + observedTaskInstances.put(task, descriptor.instanceId()); + if (observedTaskInstances.size() > 64) observedTaskInstances.remove(observedTaskInstances.keySet().iterator().next()); + } + } + return result; + } catch (ProtocolFailure protocol) { throw protocol; + } catch (IllegalArgumentException invalid) { + return failure("INVALID_REQUEST", "Invalid tool arguments or project root."); + } catch (Exception unavailable) { + disconnect(); + var result = failure(dispatched ? "OUTCOME_UNKNOWN" : status, + dispatched ? "Response unavailable; do not replay. For the same authorized task, look up operationId/clientRequestId. After Studio restart, obtain a new grant; old receipts may be unavailable." + : guidance()); + if (dispatched && arguments != null && arguments.path("clientRequestId").isTextual()) + ((ObjectNode) result.path("structuredContent").path("error")).put("clientRequestId", arguments.path("clientRequestId").asText()); + ((ObjectNode) result.path("content").get(0)).put("text", result.path("structuredContent").toString()); + return result; + } + } + private String guidance() { + return switch (status) { + case "VERSION_INCOMPATIBLE" -> "Studio and its installed connector are incompatible; update the installation."; + case "STALE_CONNECTION" -> "Connection credentials are stale or invalid; grant access again in DEV."; + case "INVALID_DESCRIPTOR" -> "Project connection data or permissions are invalid; prepare the project again."; + default -> "Open Studio and this project, then grant access in DEV. The connection will be discovered without restarting this client."; + }; + } + private void connect() throws Exception { + ProjectConnectionFiles.Descriptor next; + try { next = ProjectConnectionFiles.read(root, mapper); } + catch (NoSuchFileException absent) { status = "WAITING_FOR_ACCESS"; throw absent; } + catch (IOException invalid) { + status = Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)) ? "INVALID_DESCRIPTOR" : "WAITING_FOR_ACCESS"; + throw invalid; + } + if (!catalog.fingerprint().equals(next.catalogFingerprint())) { status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible catalog"); } + if (session != null && next.equals(descriptor)) return; + descriptor = next; session = null; status = "RECONNECTING"; + var params = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION); + params.putObject("capabilities"); params.putObject("clientInfo").put("name", "studio-project-connector").put("version", "1"); + var result = exchange("initialize", params, true, 5).required("result"); + if (!LocalMcpServer.PROTOCOL_VERSION.equals(result.path("protocolVersion").asText()) + || !catalog.fingerprint().equals(result.path("_meta").path("catalogFingerprint").asText())) { + status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible protocol"); + } + if (!next.instanceId().equals(result.path("_meta").path("instanceId").asText()) + || !root.toString().equals(result.path("_meta").path("projectRoot").asText())) { + status = "STALE_CONNECTION"; throw new IOException("Wrong instance"); + } + exchange("notifications/initialized", mapper.createObjectNode(), false, 5); + var descriptors = exchange("tools/list", mapper.createObjectNode(), true, 5).path("result").path("tools"); + if (!descriptors.isArray()) throw new IOException("Invalid catalog"); + var names = new HashSet(); + for (var tool : descriptors) { + String name = tool.path("name").asText(); + if (!catalog.names().contains(name) || !catalog.descriptor(name).equals(tool) || !names.add(name)) { + status = "VERSION_INCOMPATIBLE"; throw new IOException("Incompatible tools"); + } + } + available = Set.copyOf(names); status = "CONNECTED"; + } + private JsonNode exchange(String method, JsonNode params, boolean responseExpected, int seconds) throws Exception { + var message = mapper.createObjectNode().put("jsonrpc", "2.0").put("method", method); + if (responseExpected) message.put("id", ++sequence); + message.set("params", params); + var request = HttpRequest.newBuilder(descriptor.endpoint()).timeout(Duration.ofSeconds(seconds)) + .header("Authorization", "Bearer " + descriptor.credential()).header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", LocalMcpServer.PROTOCOL_VERSION); + if (session != null) request.header("Mcp-Session-Id", session); + var pending = client.sendAsync(request.POST(HttpRequest.BodyPublishers.ofString(message.toString())).build(), + info -> boundedBody()); + HttpResponse response; + try { response = pending.get(seconds, java.util.concurrent.TimeUnit.SECONDS); } + catch (Exception failure) { pending.cancel(true); throw failure; } + if (response.statusCode() != 200 && response.statusCode() != 202) { + if (response.statusCode() == 401 || response.statusCode() == 403 || response.statusCode() == 404) status = "STALE_CONNECTION"; + throw new IOException("Connection rejected"); + } + response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> session = value); + if (method.equals("initialize") && session == null) throw new IOException("Missing session identity"); + if (!responseExpected) return mapper.nullNode(); + var json = mapper.readTree(response.body()); + if (json == null || !"2.0".equals(json.path("jsonrpc").asText()) || !json.path("id").isIntegralNumber() || !message.get("id").bigIntegerValue().equals(json.path("id").bigIntegerValue()) + || json.has("result") == json.has("error")) throw new IOException("Invalid response"); + return json; + } + private static HttpResponse.BodySubscriber boundedBody() { + return new HttpResponse.BodySubscriber<>() { + final HttpResponse.BodySubscriber delegate = HttpResponse.BodySubscribers.ofByteArray(); + java.util.concurrent.Flow.Subscription subscription; + long bytes; + public java.util.concurrent.CompletionStage getBody() { return delegate.getBody(); } + public void onSubscribe(java.util.concurrent.Flow.Subscription value) { subscription = value; delegate.onSubscribe(value); } + public void onNext(List buffers) { + for (var buffer : buffers) bytes += buffer.remaining(); + if (bytes > 32L * 1024 * 1024) { subscription.cancel(); delegate.onError(new IOException("Response too large")); } + else delegate.onNext(buffers); + } + public void onError(Throwable failure) { delegate.onError(failure); } + public void onComplete() { delegate.onComplete(); } + }; + } + + private ObjectNode failure(String code, String message) { + var value = mapper.createObjectNode().put("isError", true); + var data = value.putObject("structuredContent").put("status", "error"); + data.putObject("error").put("code", code).put("message", message); + value.putArray("content").addObject().put("type", "text").put("text", data.toString()); + return value; + } + static final class ProtocolFailure extends RuntimeException { + final JsonNode error; + ProtocolFailure(JsonNode error) { super("Studio protocol error"); this.error = error.deepCopy(); } + } + + private void disconnect() { if (status.equals("CONNECTED")) status = "RECONNECTING"; session = null; available = Set.of(); } + @Override public void close() { client.shutdownNow(); } +} diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpStdio.java b/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpStdio.java new file mode 100644 index 00000000..43184b7a --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/stdio/StudioMcpStdio.java @@ -0,0 +1,83 @@ +package p.studio.app.mcp.stdio; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.*; +import p.studio.app.mcp.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.concurrent.*; + +/** A mode of Studio itself; no JavaFX, Spring, HTTP listener or agent runtime is started here. */ +public final class StudioMcpStdio { + private StudioMcpStdio() { } + public static void main(String[] args) throws Exception { + if (args.length != 3 || !"mcp".equals(args[0]) || !"--project".equals(args[1]) || !Path.of(args[2]).isAbsolute()) + throw new IllegalArgumentException("Usage: mcp --project "); + Path root = Path.of(args[2]).toRealPath(); + if (!Files.isRegularFile(root.resolve("prometeu.json"))) throw new IllegalArgumentException("Project manifest not found"); + run(root, System.in, System.out); + } + public static void run(Path root, InputStream input, OutputStream output) throws Exception { + var mapper = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + mapper.getFactory().setStreamReadConstraints(com.fasterxml.jackson.core.StreamReadConstraints.builder().maxStringLength(32 * 1024 * 1024).build()); + var catalog = new McpToolCatalog(mapper); + var timer = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("studio-mcp-discovery").factory()); + try (var connection = new StudioMcpConnection(root, mapper, catalog)) { + timer.scheduleWithFixedDelay(connection::probe, 0, 2, TimeUnit.SECONDS); + boolean initialized = false, negotiated = false; + var line = new ByteArrayOutputStream(); int next; + while ((next = input.read()) != -1) { + if (next != '\n') { + if (line.size() >= 1024 * 1024) throw new IOException("MCP request exceeds limit"); + line.write(next); continue; + } + JsonNode message; + try { message = mapper.readTree(StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(line.toByteArray())).toString()); } + catch (Exception malformed) { line.reset(); write(output, error(mapper, mapper.nullNode(), -32700, "Invalid JSON")); continue; } + line.reset(); + if (message == null || !message.isObject() || !message.path("jsonrpc").isTextual() || !"2.0".equals(message.path("jsonrpc").asText()) + || !message.path("method").isTextual() || message.has("id") && !(message.path("id").isTextual() || message.path("id").isIntegralNumber())) { + write(output, error(mapper, mapper.nullNode(), -32600, "Invalid request")); continue; + } + String method = message.path("method").asText(); + if (!message.has("id")) { if (negotiated && "notifications/initialized".equals(method)) initialized = true; continue; } + var id = message.get("id"); JsonNode result; + if (method.equals("initialize") && !negotiated) { + var params = message.path("params"); + if (!params.path("protocolVersion").isTextual() || !params.path("capabilities").isObject() || !params.path("clientInfo").isObject()) { + write(output, error(mapper, id, -32602, "Invalid initialization")); continue; + } + var value = mapper.createObjectNode().put("protocolVersion", LocalMcpServer.PROTOCOL_VERSION); + value.putObject("capabilities").putObject("tools").put("listChanged", false); + value.putObject("serverInfo").put("name", "prometeu-studio").put("version", "1"); + value.put("instructions", McpConnectionGuide.INSTRUCTIONS + "\nProject root: " + root); + result = value; negotiated = true; + } else if (!initialized) { write(output, error(mapper, id, -32600, "Initialization required")); continue; } + else if (method.equals("ping")) result = mapper.createObjectNode(); + else if (method.equals("tools/list")) { + var value = mapper.createObjectNode(); var tools = value.putArray("tools"); + catalog.names().forEach(name -> tools.add(catalog.descriptor(name))); result = value; + } else if (method.equals("tools/call")) { + String tool = message.path("params").path("name").asText(); + var arguments = message.path("params").path("arguments"); + try { catalog.validateArguments(tool, arguments); } + catch (IllegalArgumentException invalid) { write(output, error(mapper, id, -32602, "Invalid tool arguments")); continue; } + try { result = connection.call(tool, arguments); } + catch (StudioMcpConnection.ProtocolFailure protocol) { + var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("error", protocol.error); + write(output, reply); continue; + } + } else { write(output, error(mapper, id, -32601, "Method not found")); continue; } + var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); reply.set("result", result); write(output, reply); + } + } finally { timer.shutdownNow(); } + } + private static JsonNode error(ObjectMapper mapper, JsonNode id, int code, String text) { + var reply = mapper.createObjectNode().put("jsonrpc", "2.0"); reply.set("id", id); + reply.putObject("error").put("code", code).put("message", text); return reply; + } + private static void write(OutputStream output, JsonNode value) throws IOException { + output.write(value.toString().getBytes(StandardCharsets.UTF_8)); output.write('\n'); output.flush(); + } +} 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 eeb2d185..f73a72f8 100644 --- a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -40,6 +40,12 @@ class DevDesktopTest { completed.get(10, TimeUnit.SECONDS); } + static void awaitWaiting(AutomationSession authority) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (authority.snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(5); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + } + @Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception { var pool = Executors.newSingleThreadExecutor(); var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); @@ -70,6 +76,9 @@ class DevDesktopTest { assertEquals(1, subscriptions.get()); assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled()); ((Button) dev[0].rootNode().lookup("#dev-grant")).fire(); + }); + awaitWaiting(authority); + fx(() -> { assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get()); assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); @@ -96,8 +105,8 @@ class DevDesktopTest { locale.setLocale(java.util.Locale.forLanguageTag("pt-BR")); host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get()); authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH); - assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); }); + awaitWaiting(authority); } finally { fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); }); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow(); @@ -120,56 +129,39 @@ class DevDesktopTest { }); } - @Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception { + @Test void preparesConnectionWithoutGrantAndRemainsAvailableWhenTransportStops() throws Exception { var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); var projects = new p.studio.core.project.ProjectAccessRegistry(); - var savedClipboard = new java.util.HashMap(); - var copied = new java.util.concurrent.atomic.AtomicReference(); + var prepared = new CompletableFuture(); var view = new DevWorkspace[1]; var stage = new Stage[1]; try (var pool = Executors.newSingleThreadExecutor(); var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry( new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); - var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper); + var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper, project -> { + prepared.complete(null); + return new p.studio.api.automation.AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once."); + }); server.start(); try { fx(() -> { - var clipboard = javafx.scene.input.Clipboard.getSystemClipboard(); - clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type))); var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root); view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide); stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show(); view[0].load(); - var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); - button.fire(); copied.set(clipboard.getString()); - assertEquals(ControlState.MANUAL, authority.snapshot().state()); - assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText()); - assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) - .noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader()))); + var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); button.fire(); }); - var first = mapper.readTree(copied.get()); - assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText())); - assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText()); + prepared.get(5, TimeUnit.SECONDS); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); server.close(); - fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); + fx(() -> assertFalse(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); server.start(); authority.grant(false).toCompletableFuture().join(); - fx(() -> { - var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); - button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString()); - assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); - }); - var next = mapper.readTree(copied.get()); - assertFalse(first.path("headers").equals(next.path("headers"))); - assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText())); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); } finally { - fx(() -> { - if (view[0] != null) view[0].unLoad(); - if (stage[0] != null) stage[0].close(); - javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard); - }); + fx(() -> { if (view[0] != null) view[0].unLoad(); if (stage[0] != null) stage[0].close(); }); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close(); } } diff --git a/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java b/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java new file mode 100644 index 00000000..9e234370 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/install/InstalledConnectorTest.java @@ -0,0 +1,79 @@ +package p.studio.app.install; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.app.mcp.StudioAgentPreparation; +import p.studio.core.project.*; +import p.studio.api.project.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.*; + +class InstalledConnectorTest { + @TempDir Path temporary; + @Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception { + Path base = temporary.resolve("Application Support/Studio"); + Path source = Path.of(System.getProperty("studio.test.distribution")); + Path first = ManagedStudioInstallation.install(source, base); + var mapper = new ObjectMapper(); + var preparation = new StudioAgentPreparation(base, mapper); + var catalog = new ProjectCatalogService(temporary, mapper, new ProjectLocalStudioSetupStore(mapper), preparation); + var scaffold = catalog.createProject(new ProjectCreationRequest("Scaffold Game", temporary, "pbs", 1, ProjectTarget.Game, "src", 8, "/my/runtime")); + assertTrue(preparation.status(scaffold.rootPath()).ready()); + Path existing = Files.createDirectory(temporary.resolve("Existing Project")); + Files.copy(scaffold.rootPath().resolve("prometeu.json"), existing.resolve("prometeu.json")); + Files.createDirectory(existing.resolve(".studio")); + Files.writeString(existing.resolve(".studio/setup.json"), "{\"runtimePath\":\"/preserved/runtime\",\"custom\":42}"); + Files.createDirectory(existing.resolve(".codex")); + String custom = "# preserve\napproval_policy = \"on-request\"\n[mcp_servers.other]\ncommand = \"other\"\n"; + Files.writeString(existing.resolve(".codex/config.toml"), custom); + assertTrue(preparation.prepare(existing).ready()); + var config = existing.resolve(".codex/config.toml"); + String stable = Files.readString(config); var modified = Files.getLastModifiedTime(config); + assertTrue(stable.startsWith(custom)); assertTrue(preparation.prepare(existing).ready()); + assertEquals(stable, Files.readString(config)); assertEquals(modified, Files.getLastModifiedTime(config)); + var setup = mapper.readTree(Files.readString(existing.resolve(".studio/setup.json"))); + assertEquals(42, setup.path("custom").asInt()); assertEquals("/preserved/runtime", setup.path("runtimePath").asText()); + assertFalse(Files.exists(existing.resolve(".studio/mcp/connection.json"))); + runConnector(base, existing); + Path second = ManagedStudioInstallation.install(source, base); + assertNotEquals(first, second); assertTrue(Files.isDirectory(first)); + assertEquals(second.toRealPath(), base.resolve("current").toRealPath()); + assertEquals(stable, Files.readString(config)); runConnector(base, existing); + assertThrows(Exception.class, () -> ManagedStudioInstallation.install(existing, base)); + assertEquals(second.toRealPath(), base.resolve("current").toRealPath()); runConnector(base, existing); + // Test fixture only: installed runtime/lib must load and start JavaFX, without checkout application classes. + String fixtures = Path.of(DesktopProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString(); + var desktop = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*") + java.io.File.pathSeparator + fixtures, + DesktopProbe.class.getName()).redirectError(temporary.resolve("desktop.stderr").toFile()).start(); + try { assertTrue(desktop.waitFor(20, TimeUnit.SECONDS)); assertEquals(0, desktop.exitValue(), Files.readString(temporary.resolve("desktop.stderr"))); } + finally { desktop.destroyForcibly(); } + } + void runConnector(Path base, Path root) throws Exception { + var process = minimal(base.resolve("current/runtime/bin/java").toString(), "-cp", base.resolve("current/lib/*").toString(), + "p.studio.app.StudioLauncher", "mcp", "--project", root.toRealPath().toString()).start(); + try { + String input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"installed-test\",\"version\":\"1\"}}}\n"; + process.getOutputStream().write(input.getBytes(java.nio.charset.StandardCharsets.UTF_8)); process.getOutputStream().close(); + assertTrue(process.waitFor(15, TimeUnit.SECONDS)); assertEquals(0, process.exitValue()); + assertEquals("prometeu-studio", new ObjectMapper().readTree(process.getInputStream()).path("result").path("serverInfo").path("name").asText()); + } finally { process.destroyForcibly(); } + } + ProcessBuilder minimal(String... args) { + var builder = new ProcessBuilder(args).directory(temporary.toFile()); + builder.environment().clear(); builder.environment().put("PATH", "/usr/bin:/bin"); builder.environment().put("HOME", System.getProperty("user.home")); + return builder; + } + public static class DesktopProbe { + public static void main(String[] args) { + javafx.application.Platform.startup(() -> { + try { + var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX"))); + stage.show(); stage.close(); System.exit(0); + } catch (Throwable failure) { System.exit(2); } + }); + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java index ea648396..615c57ff 100644 --- a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java +++ b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.*; class AutomationLspQueriesTest { + String httpAuthorization; @TempDir Path temporary; final ObjectMapper mapper = new ObjectMapper(); final ExecutorService workers = Executors.newCachedThreadPool(); @@ -134,6 +135,8 @@ class AutomationLspQueriesTest { try (var server = new p.studio.app.mcp.LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) { server.start(); + var credential = server.credentials().prepare(root.toRealPath()); + credential.activate(); httpAuthorization = "Bearer " + credential.secret(); var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize"); var setup = initialize.putObject("params").put("protocolVersion", "2025-06-18"); setup.putObject("capabilities"); setup.putObject("clientInfo").put("name", "language-test").put("version", "1"); @@ -155,7 +158,7 @@ class AutomationLspQueriesTest { private java.net.http.HttpResponse post(java.net.http.HttpClient client, p.studio.app.mcp.LocalMcpServer server, String connection, JsonNode body) throws Exception { var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(15)) - .header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json") + .header("Authorization", httpAuthorization).header("Content-Type", "application/json") .header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18"); if (connection != null) request.header("Mcp-Session-Id", connection); return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString()); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java index 037a57fc..d42d1880 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/LocalMcpServerTest.java @@ -15,6 +15,12 @@ class LocalMcpServerTest { final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build(); LocalMcpServer server; String session; + @org.junit.jupiter.api.io.TempDir java.nio.file.Path root; + String authorization; + void authorize(java.nio.file.Path project) throws Exception { + var credential = server.credentials().prepare(project.toRealPath()); + credential.activate(); authorization = "Bearer " + credential.secret(); + } AtomicInteger calls; @BeforeEach void start() throws Exception { @@ -22,7 +28,7 @@ class LocalMcpServerTest { server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of( "studio_project_context", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("projectRoot", args.get("projectRoot").asText())); }, "studio_control_acquire", args -> McpToolResult.failure(mapper, new AutomationFailure(AutomationFailure.Code.NOT_GRANTED, "Human grant required"))))); - server.start(); + server.start(); authorize(root); } @AfterEach void close() { server.close(); client.close(); } HttpResponse request(String method, URI uri, String body, String token, String origin, String protocol, String sessionId) throws Exception { @@ -35,7 +41,7 @@ class LocalMcpServerTest { return client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString()); } HttpResponse post(String body) throws Exception { - return request("POST", server.connection().endpoint(), body, server.connection().authorizationHeader(), null, LocalMcpServer.PROTOCOL_VERSION, session); + return request("POST", server.connection().endpoint(), body.replace("/project", root.toRealPath().toString()), authorization, null, LocalMcpServer.PROTOCOL_VERSION, session); } static String init() { return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1\"},\"capabilities\":{}}}"; } void initialize() throws Exception { @@ -51,11 +57,11 @@ class LocalMcpServerTest { var response = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"/project\"}}}"); assertEquals(200, response.statusCode()); assertEquals(1, calls.get()); assertEquals("ok", mapper.readTree(response.body()).path("result").path("structuredContent").path("status").asText()); - assertEquals(200, request("DELETE", server.connection().endpoint(), null, server.connection().authorizationHeader(), null, null, session).statusCode()); + assertEquals(200, request("DELETE", server.connection().endpoint(), null, authorization, null, null, session).statusCode()); assertEquals(404, post("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}").statusCode()); } @Test void authAndOriginAreCheckedBeforeProtocolOrTools() throws Exception { - var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader(); + var endpoint = server.connection().endpoint(); var token = authorization; assertEquals("127.0.0.1", endpoint.getHost()); assertTrue(endpoint.getPort() > 0); assertEquals(401, request("POST", endpoint, init(), null, null, null, null).statusCode()); assertEquals(401, request("POST", endpoint, init(), "Bearer wrong", null, null, null).statusCode()); @@ -66,10 +72,10 @@ class LocalMcpServerTest { assertFalse(server.connection().toString().contains(token.substring(7))); } @Test void restartChangesCredentialsInvalidatesConnectionsAndDoesNotPersistThem() throws Exception { - initialize(); var old = server.connection(); server.close(); + initialize(); var old = authorization; server.close(); assertFalse(server.isRunning()); assertThrows(IllegalStateException.class, server::connection); - server.start(); assertFalse(old.authorizationHeader().equals(server.connection().authorizationHeader())); - assertEquals(401, request("POST", server.connection().endpoint(), init(), old.authorizationHeader(), null, null, null).statusCode()); + server.start(); authorize(root); assertFalse(old.equals(authorization)); + assertEquals(401, request("POST", server.connection().endpoint(), init(), old, null, null, null).statusCode()); assertEquals(404, post(init()).statusCode()); session = null; initialize(); } @@ -81,13 +87,13 @@ class LocalMcpServerTest { assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"method\":123}").statusCode()); assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"id\":2,\"method\":\"ping\"}").statusCode()); assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"} {}").statusCode()); - assertEquals(400, request("POST", server.connection().endpoint(), init(), server.connection().authorizationHeader(), null, "unknown", session).statusCode()); + assertEquals(400, request("POST", server.connection().endpoint(), init(), authorization, null, "unknown", session).statusCode()); var bad = post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"studio_project_context\",\"arguments\":{\"projectRoot\":\"relative\"}}}"); assertEquals(-32602, mapper.readTree(bad.body()).path("error").path("code").intValue()); assertEquals(0, calls.get()); assertEquals(413, post(" ".repeat(1024 * 1024 + 1)).statusCode()); } @Test void exactEndpointNoSseAndInitializationAreEnforced() throws Exception { - var endpoint = server.connection().endpoint(); var token = server.connection().authorizationHeader(); + var endpoint = server.connection().endpoint(); var token = authorization; assertEquals(400, post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").statusCode()); var initialized = post(init()); session = initialized.headers().firstValue("Mcp-Session-Id").orElseThrow(); assertEquals(-32600, mapper.readTree(post("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}").body()).path("error").path("code").asInt()); @@ -117,7 +123,7 @@ class LocalMcpServerTest { server.close(); server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, McpProjectKnowledgeTools.handlers(knowledge, mapper))); - server.start(); + server.start(); authorize(root); initialize(); var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call"); call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", root.toString()); @@ -153,13 +159,13 @@ class LocalMcpServerTest { var connection = server.connection(); try (var socket = new java.net.Socket("127.0.0.1", connection.endpoint().getPort())) { socket.setSoTimeout(3000); - String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + connection.authorizationHeader() + String request = "POST /mcp HTTP/1.1\r\nHost: evil.example\r\nAuthorization: " + authorization + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; socket.getOutputStream().write(request.getBytes(java.nio.charset.StandardCharsets.UTF_8)); var status = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())).readLine(); assertTrue(status.contains("403")); } - var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization) .header("Origin", "http://" + connection.endpoint().getRawAuthority()).header("Origin", "https://evil.example") .POST(HttpRequest.BodyPublishers.ofString(init())).build(); assertEquals(403, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); @@ -167,13 +173,29 @@ class LocalMcpServerTest { @Test void contentNegotiationAcceptsWeightedTypesAndRejectsInvalidUtf8() throws Exception { var connection = server.connection(); - var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + var request = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization) .header("Accept", "application/json;q=1, text/event-stream;q=0.5").header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(init())).build(); assertEquals(200, client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); - var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", connection.authorizationHeader()) + var invalid = HttpRequest.newBuilder(connection.endpoint()).header("Authorization", authorization) .header("Accept", "application/json, text/event-stream").header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofByteArray(new byte[]{(byte) 0xc3, (byte) 0x28})).build(); assertEquals(400, client.send(invalid, HttpResponse.BodyHandlers.discarding()).statusCode()); } + @Test void projectCredentialsCannotCrossRootsOrReuseAnotherSession() throws Exception { + initialize(); + var other = java.nio.file.Files.createDirectory(root.resolve("other")).toRealPath(); + var credential = server.credentials().prepare(other); credential.activate(); + var wire = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\"}"; + assertEquals(403, request("POST", server.connection().endpoint(), wire, "Bearer " + credential.secret(), null, + LocalMcpServer.PROTOCOL_VERSION, session).statusCode()); + var call = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 5).put("method", "tools/call"); + call.putObject("params").put("name", "studio_project_context").putObject("arguments").put("projectRoot", other.toString()); + var reply = mapper.readTree(post(call.toString()).body()); + assertEquals("OUTSIDE_PROJECT_SCOPE", reply.path("result").path("structuredContent").path("error").path("code").asText()); + assertEquals(0, calls.get()); + server.credentials().authenticate(authorization).invalidate(); + assertEquals(401, post(wire).statusCode()); + } + } 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 index b1f8d0fc..bf6bf5ac 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpConnectionGuideTest.java @@ -15,38 +15,34 @@ import static org.junit.jupiter.api.Assertions.*; class McpConnectionGuideTest { @TempDir Path root; - @Test void exportsLiveProjectDescriptorWithoutGrantAndTracksRestartWithoutRetainingSecrets() throws Exception { + @Test void preparationIsStableAndSeparateFromAuthority() throws Exception { var mapper = new ObjectMapper(); var projects = new ProjectAccessRegistry(); try (var workers = Executors.newSingleThreadExecutor(); var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers)); var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); - var guide = new McpConnectionGuide(server, projects, mapper); - assertTrue(guide.endpoint().isEmpty()); - assertThrows(IllegalStateException.class, () -> guide.configuration(root)); - var notifications = new AtomicInteger(); - var subscription = guide.subscribe(notifications::incrementAndGet); - server.start(); assertEquals(2, notifications.get()); - var descriptor = mapper.readTree(guide.configuration(root)); - assertEquals(server.connection().endpoint().toString(), descriptor.path("url").asText()); - assertEquals(root.toRealPath().toString(), descriptor.path("projectRoot").asText()); - // Do not put bearer credentials into assertion diagnostics. - assertTrue(server.connection().authorizationHeader().equals(descriptor.path("headers").path("Authorization").asText())); - assertFalse(guide.toString().contains(descriptor.path("headers").path("Authorization").asText())); + var prepared = new AtomicInteger(); + var canonical = root.toRealPath(); + var guide = new McpConnectionGuide(server, projects, mapper, project -> { + assertEquals(canonical, project); prepared.incrementAndGet(); + return new AgentIntegrationPreparation.Result(true, "Prepared; trust/reload once."); + }); + assertEquals(AgentConnectionGuide.State.UNAVAILABLE, guide.state(root)); + var stable = guide.configuration(root); + assertTrue(guide.prepare(root).ready()); assertEquals(1, prepared.get()); assertEquals(ControlState.MANUAL, authority.snapshot().state()); assertNull(authority.snapshot().task()); + server.start(); + assertEquals(AgentConnectionGuide.State.WAITING_FOR_ACCESS, guide.state(root)); + assertFalse(stable.contains("Bearer")); for (var instruction : List.of("studio_project_context", "studio_reference_read", "studio_control_acquire", "studio_control_release", "studio_language_query", "studio_build_start", "clientRequestId", "read-only", "restart", "native file writes")) - assertTrue(descriptor.path("instructions").asText().contains(instruction)); - var old = server.connection(); server.close(); assertEquals(3, notifications.get()); assertTrue(guide.endpoint().isEmpty()); - server.start(); assertEquals(4, notifications.get()); - var fresh = mapper.readTree(guide.configuration(root)); - assertTrue(fresh.path("headers").path("Authorization").asText().equals(server.connection().authorizationHeader())); - assertFalse(fresh.path("headers").path("Authorization").asText().equals(old.authorizationHeader())); + assertTrue(stable.contains(instruction)); + server.close(); server.start(); assertEquals(stable, guide.configuration(root)); assertThrows(AutomationException.class, () -> guide.configuration(root.resolve("unopened"))); authority.closeAsync().toCompletableFuture().join(); assertThrows(AutomationException.class, () -> guide.configuration(root)); - registration.close(); subscription.close(); server.close(); assertEquals(4, notifications.get()); + registration.close(); } } } 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 bcc31e44..1dce2afb 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 @@ -20,6 +20,7 @@ import java.util.function.*; import static org.junit.jupiter.api.Assertions.*; class McpTaskToolsTest { + String httpAuthorization; @TempDir Path root; final ObjectMapper mapper = new ObjectMapper(); final ExecutorService workers = Executors.newCachedThreadPool(); @@ -243,6 +244,8 @@ class McpTaskToolsTest { compose(shipper); try (var server = new LocalMcpServer(mapper, tools); var client = java.net.http.HttpClient.newHttpClient()) { server.start(); + var credential = server.credentials().prepare(root.toRealPath()); + credential.activate(); httpAuthorization = "Bearer " + credential.secret(); var initialize = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize"); var params = initialize.putObject("params").put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "task-test").put("version", "1"); @@ -281,6 +284,8 @@ class McpTaskToolsTest { try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers)); var client = java.net.http.HttpClient.newHttpClient()) { server.start(); + var credential = server.credentials().prepare(root.toRealPath()); + credential.activate(); httpAuthorization = "Bearer " + credential.secret(); var unauthorized = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}")) .timeout(java.time.Duration.ofSeconds(5)).build(); assertEquals(401, client.send(unauthorized, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode()); @@ -315,7 +320,7 @@ class McpTaskToolsTest { var captured = httpCall(client, server, first, "studio_headless_capture", args()); value(captured); assertArrayEquals(session.snapshot().capture().png(), Base64.getDecoder().decode(captured.path("content").get(1).path("data").asText())); var deleted = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).DELETE() - .header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", first).build(); + .header("Authorization", httpAuthorization).header("Mcp-Session-Id", first).build(); assertEquals(200, client.send(deleted, java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode()); assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); String reconnected = connect(client, server); @@ -367,7 +372,7 @@ class McpTaskToolsTest { } java.net.http.HttpResponse post(java.net.http.HttpClient client, LocalMcpServer server, String connection, JsonNode body) throws Exception { var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()).timeout(java.time.Duration.ofSeconds(10)) - .header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json") + .header("Authorization", httpAuthorization).header("Content-Type", "application/json") .header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18"); if (connection != null) request.header("Mcp-Session-Id", connection); return client.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build(), java.net.http.HttpResponse.BodyHandlers.ofString()); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java new file mode 100644 index 00000000..c7371644 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/ProjectConnectionPublisherTest.java @@ -0,0 +1,115 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; + +class ProjectConnectionPublisherTest { + @TempDir Path temporary; + final ObjectMapper mapper = new ObjectMapper(); + LocalMcpServer server; + Path root; + @BeforeEach void start() throws Exception { + root = temporary.toRealPath(); + server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of())); server.start(); + } + @AfterEach void stop() { server.close(); } + @Test void publishesPrivatelyOnlyActivatesExplicitlyAndCleansUpOwnedGeneration() throws Exception { + Files.writeString(root.resolve(".gitignore"), "# existing\n/build/\n"); + var publisher = new ProjectConnectionPublisher(server, mapper); + var publication = publisher.prepare(root); + publication.publish(); + var descriptor = ProjectConnectionFiles.read(root, mapper); + assertNull(server.credentials().authenticate("Bearer " + descriptor.credential())); + publication.activate(); + assertEquals(root, server.credentials().authenticate("Bearer " + descriptor.credential()).root()); + var file = root.resolve(ProjectConnectionFiles.RELATIVE); + assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(file)); + assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(file.getParent())); + assertFalse(descriptor.toString().contains(descriptor.credential())); + assertThrows(Exception.class, () -> publisher.prepare(root)); + publication.invalidate(); assertNull(server.credentials().authenticate("Bearer " + descriptor.credential())); + publication.close(); assertFalse(Files.exists(file)); assertTrue(Files.exists(file.resolveSibling("publication.lock"))); + try (var next = publisher.prepare(root)) { + next.publish(); next.activate(); publication.close(); + assertTrue(Files.exists(file)); + assertNotEquals(descriptor.credential(), ProjectConnectionFiles.read(root, mapper).credential()); + } + assertEquals("# existing\n/build/\n/.studio/mcp/\n", Files.readString(root.resolve(".gitignore"))); + } + @Test void unsafePathsAndPermissionsNeverPublishSecrets() throws Exception { + Path destination = Files.createDirectory(root.resolve("outside")); + Files.createSymbolicLink(root.resolve(".studio"), destination); + assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root)); + assertFalse(Files.exists(destination.resolve("mcp"))); + Files.delete(root.resolve(".studio")); + Path directory = ProjectConnectionFiles.directory(root); + Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("rwxr-xr-x")); + assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root)); + } + @Test void malformedDescriptorsNeverSupplyAnArbitraryEndpoint() throws Exception { + try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) { + publication.publish(); + Path path = root.resolve(ProjectConnectionFiles.RELATIVE); + var valid = mapper.readTree(Files.readString(path)); + for (String endpoint : java.util.List.of("https://example.com/mcp", "http://127.0.0.1:123/mcp?x=1", "http://localhost:123/mcp")) { + var bad = valid.deepCopy(); ((com.fasterxml.jackson.databind.node.ObjectNode) bad).put("endpoint", endpoint); + Files.writeString(path, bad.toString()); assertThrows(Exception.class, () -> ProjectConnectionFiles.read(root, mapper)); + } + Files.writeString(path, valid.toString()); + } + } + @Test void osLockRejectsAnotherJvmAndCrashAllowsRecoveryWithoutUnlinkingLock() throws Exception { + Process owner = ownerProcess(); + try { + assertEquals("READY", java.util.concurrent.CompletableFuture.supplyAsync(() -> { + try { return owner.inputReader().readLine(); } catch (java.io.IOException failure) { throw new java.io.UncheckedIOException(failure); } + }).get(10, java.util.concurrent.TimeUnit.SECONDS)); + var lock = root.resolve(".studio/mcp/publication.lock"); + var inode = Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey(); + Process conflict = ownerProcess(); + try { assertTrue(conflict.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(2, conflict.exitValue()); } + finally { conflict.destroyForcibly(); } + owner.destroyForcibly(); assertTrue(owner.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)); + assertTrue(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE))); + try (var recovered = new ProjectConnectionPublisher(server, mapper).prepare(root)) { + recovered.publish(); recovered.activate(); + assertEquals(server.instanceId(), ProjectConnectionFiles.read(root, mapper).instanceId()); + assertEquals(inode, Files.readAttributes(lock, java.nio.file.attribute.BasicFileAttributes.class).fileKey()); + } + } finally { owner.destroyForcibly(); } + } + @Test void trackedDiscoveryTargetIsRejectedWithoutWritingCredentials() throws Exception { + var directory = ProjectConnectionFiles.directory(root); + var target = directory.resolve("connection.json"); Files.writeString(target, "tracked placeholder"); + for (var command : java.util.List.of(java.util.List.of("git", "init", "-q"), java.util.List.of("git", "add", "-f", ProjectConnectionFiles.RELATIVE))) { + var process = new ProcessBuilder(command).directory(root.toFile()).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + assertTrue(process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS)); assertEquals(0, process.exitValue()); + } + assertThrows(Exception.class, () -> new ProjectConnectionPublisher(server, mapper).prepare(root)); + assertEquals("tracked placeholder", Files.readString(target)); + assertFalse(Files.exists(directory.resolve("publication.lock"))); + } + + private Process ownerProcess() throws Exception { + return new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin/java").toString(), "-cp", + System.getProperty("studio.test.classpath"), Owner.class.getName(), root.toString()) + .redirectError(ProcessBuilder.Redirect.DISCARD).start(); + } + public static class Owner { + public static void main(String[] args) throws Exception { + var mapper = new ObjectMapper(); + try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of()))) { + server.start(); + try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(Path.of(args[0]))) { + publication.publish(); publication.activate(); System.out.println("READY"); System.out.flush(); System.in.read(); + } catch (Exception conflict) { System.exit(2); } + } + } + } + +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/StudioAgentPreparationTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/StudioAgentPreparationTest.java new file mode 100644 index 00000000..8d7a0213 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/StudioAgentPreparationTest.java @@ -0,0 +1,36 @@ +package p.studio.app.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import static org.junit.jupiter.api.Assertions.*; + +class StudioAgentPreparationTest { + @TempDir Path temporary; + @Test void preservesUnrelatedTomlAndRejectsUserOwnedOrEditedEntry() throws Exception { + var preparation = new StudioAgentPreparation(temporary.resolve("Application Support/Studio"), new ObjectMapper()); + String entry = preparation.entry(temporary.toRealPath()); + String custom = "# keep exactly\napproval_policy = \"on-request\"\n[mcp_servers.custom]\ncommand = \"custom\"\n"; + String merged = StudioAgentPreparation.merge(custom, entry); + assertTrue(merged.startsWith(custom)); assertEquals(merged, StudioAgentPreparation.merge(merged, entry)); + assertFalse(merged.contains("credential")); assertFalse(merged.contains("connection.json")); + assertThrows(Exception.class, () -> StudioAgentPreparation.merge("[mcp_servers.prometeu_studio]\ncommand=\"mine\"\n", entry)); + assertThrows(Exception.class, () -> StudioAgentPreparation.merge(merged.replace("startup_timeout_sec = 20", "startup_timeout_sec = 30"), entry)); + String updated = StudioAgentPreparation.merge(merged, preparation.entry(temporary.resolve("another project"))); + assertTrue(updated.startsWith(custom)); assertTrue(updated.contains("another project")); + } + @Test void absentInstallationReportsIncompleteAndDoesNotModifyClientConfig() throws Exception { + Files.writeString(temporary.resolve("prometeu.json"), "{}"); + Files.createDirectory(temporary.resolve(".codex")); + Path config = temporary.resolve(".codex/config.toml"); Files.writeString(config, "# preserve\n"); + var preparation = new StudioAgentPreparation(temporary.resolve("missing"), new ObjectMapper()); + var result = preparation.prepare(temporary); + assertFalse(result.ready()); assertEquals("# preserve\n", Files.readString(config)); + assertTrue(result.message().contains("Studio installation is missing")); + assertTrue(result.message().contains(":prometeu-app:stageStudioInstallation")); + assertTrue(result.message().contains("-Dstudio.installationRoot")); + assertFalse(Files.exists(temporary.resolve(".studio/mcp"))); + assertEquals(result, preparation.status(temporary.toRealPath())); + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java new file mode 100644 index 00000000..b9f2cf71 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java @@ -0,0 +1,204 @@ +package p.studio.app.mcp.stdio; + +import com.fasterxml.jackson.databind.*; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.app.mcp.*; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +class StudioMcpStdioTest { + @TempDir Path temporary; + final ObjectMapper mapper = new ObjectMapper(); + Path root; + @BeforeEach void project() throws Exception { root = temporary.toRealPath(); Files.writeString(root.resolve("prometeu.json"), "{}"); } + LocalMcpServer server(AtomicInteger calls, String image) { + return new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, Map.of("studio_project_context", args -> { + calls.incrementAndGet(); + return McpToolResult.successWithCapture(mapper, mapper.createObjectNode().put("projectRoot", args.path("projectRoot").asText()), + new p.studio.api.automation.CanonicalCapture("session", "build", 1, 1, 1, 1, 1, Base64.getDecoder().decode(image)), false); + }))); + } + @Test void coldProcessDiscoversLaterGrantPreservesLargeImagesAndSurvivesRestart() throws Exception { + var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100); + try (var process = new Connector(root); var server = server(count, pixels)) { + process.initialize(); + assertEquals(17, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size()); + var waiting = process.call("studio_project_context", root); + assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText()); + assertFalse(Files.exists(root.resolve(".studio"))); + server.start(); + var publisher = new ProjectConnectionPublisher(server, mapper); + try (var publication = publisher.prepare(root)) { + publication.publish(); publication.activate(); + var result = process.call("studio_project_context", root); + assertFalse(result.path("isError").asBoolean(), result.path("structuredContent").toString()); + assertEquals(pixels, result.path("content").get(1).path("data").asText()); + assertEquals(root.toString(), result.path("structuredContent").path("value").path("projectRoot").asText()); + Path other = Files.createDirectory(root.resolve("other")); + assertEquals("OUTSIDE_PROJECT_SCOPE", process.call("studio_project_context", other).path("structuredContent").path("error").path("code").asText()); + assertEquals(1, count.get()); + } + server.close(); server.start(); + assertEquals("WAITING_FOR_ACCESS", process.call("studio_project_context", root).path("structuredContent").path("error").path("code").asText()); + try (var fresh = publisher.prepare(root)) { + fresh.publish(); fresh.activate(); + assertFalse(process.call("studio_project_context", root).path("isError").asBoolean()); + assertEquals(2, count.get()); + } + } + } + @Test void invalidArgumentsAndMalformedLinesDoNotLaunchDesktopOrBreakCorrelation() throws Exception { + try (var connector = new Connector(root)) { + connector.send("{bad json}"); + assertEquals(-32700, connector.read().path("error").path("code").asInt()); + connector.initialize(); + assertEquals(-32601, connector.request("no-method", mapper.createObjectNode()).path("error").path("code").asInt()); + assertTrue(connector.request("ping", mapper.createObjectNode()).has("result")); + } + var process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", "relative") + .redirectError(ProcessBuilder.Redirect.DISCARD).start(); + assertTrue(process.waitFor(10, TimeUnit.SECONDS)); assertNotEquals(0, process.exitValue()); + assertEquals(0, process.getInputStream().readAllBytes().length); + } + @Test void lostBuildResponseIsNotReplayedAndReceiptCanBeLookedUpAfterReconnect() throws Exception { + var builds = new AtomicInteger(); var mapper = this.mapper; + var handlers = Map.>of( + "studio_build_start", args -> { builds.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1")); }, + "studio_operation_get", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "op-1"))); + try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers)); + var transport = java.net.http.HttpClient.newHttpClient()) { + server.start(); + var proxy = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0); + var dropped = new java.util.concurrent.atomic.AtomicBoolean(); + proxy.createContext("/mcp", exchange -> { + try (exchange) { + var bytes = exchange.getRequestBody().readAllBytes(); + var incoming = mapper.readTree(bytes); + var request = java.net.http.HttpRequest.newBuilder(server.connection().endpoint()); + for (String header : List.of("Authorization", "Content-Type", "Accept", "Mcp-Session-Id", "MCP-Protocol-Version")) { + String value = exchange.getRequestHeaders().getFirst(header); if (value != null) request.header(header, value); + } + var response = transport.send(request.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(bytes)).build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray()); + if (incoming.path("params").path("name").asText().equals("studio_build_start") && dropped.compareAndSet(false, true)) { + exchange.sendResponseHeaders(200, 100); return; // Committed tool, intentionally incomplete transport response. + } + response.headers().firstValue("Mcp-Session-Id").ifPresent(value -> exchange.getResponseHeaders().set("Mcp-Session-Id", value)); + exchange.sendResponseHeaders(response.statusCode(), response.body().length == 0 ? -1 : response.body().length); + exchange.getResponseBody().write(response.body()); + } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } + }); + proxy.start(); + try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root); + var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) { + publication.publish(); publication.activate(); + var path = root.resolve(ProjectConnectionFiles.RELATIVE); + var descriptor = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(Files.readString(path)); + descriptor.put("endpoint", "http://127.0.0.1:" + proxy.getAddress().getPort() + "/mcp"); Files.writeString(path, descriptor.toString()); + var args = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", "task").put("clientRequestId", "intent-1"); + var unknown = connection.call("studio_build_start", args); + assertEquals("OUTCOME_UNKNOWN", unknown.path("structuredContent").path("error").path("code").asText()); + assertEquals("intent-1", unknown.path("structuredContent").path("error").path("clientRequestId").asText()); + connection.probe(); assertEquals(1, builds.get()); + var recovered = connection.call("studio_operation_get", args); + assertEquals("op-1", recovered.path("structuredContent").path("value").path("operationId").asText()); + assertEquals(1, builds.get()); + } finally { proxy.stop(0); } + } + } + + @Test void restartedInstanceCannotClaimRecoveryOfOldTaskReceipts() throws Exception { + var calls = new AtomicInteger(); + var handlers = Map.>of( + "studio_control_acquire", args -> McpToolResult.success(mapper, mapper.createObjectNode().put("taskId", UUID.randomUUID().toString())), + "studio_operation_get", args -> { calls.incrementAndGet(); return McpToolResult.success(mapper, mapper.createObjectNode().put("operationId", "fresh")); }); + try (var server = new LocalMcpServer(mapper, new McpToolRegistry(new McpToolCatalog(mapper), mapper, handlers)); + var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) { + server.start(); var publisher = new ProjectConnectionPublisher(server, mapper); + String task; + try (var publication = publisher.prepare(root)) { + publication.publish(); publication.activate(); + task = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString())) + .path("structuredContent").path("value").path("taskId").asText(); + } + server.close(); server.start(); + try (var publication = publisher.prepare(root)) { + publication.publish(); publication.activate(); + var old = mapper.createObjectNode().put("projectRoot", root.toString()).put("taskId", task).put("clientRequestId", "old"); + assertEquals("OUTCOME_UNKNOWN", connection.call("studio_operation_get", old).path("structuredContent").path("error").path("code").asText()); + assertEquals(0, calls.get()); + String fresh = connection.call("studio_control_acquire", mapper.createObjectNode().put("projectRoot", root.toString())) + .path("structuredContent").path("value").path("taskId").asText(); + old.put("taskId", fresh); + assertFalse(connection.call("studio_operation_get", old).path("isError").asBoolean()); assertEquals(1, calls.get()); + } + } + } + + @Test void staleIdentityAndCatalogMismatchAreRejectedBeforeToolDispatch() throws Exception { + var calls = new AtomicInteger(); + try (var server = server(calls, "AAAA")) { + server.start(); + try (var publication = new ProjectConnectionPublisher(server, mapper).prepare(root)) { + publication.publish(); publication.activate(); + Path path = root.resolve(ProjectConnectionFiles.RELATIVE); + String valid = Files.readString(path); + try { + for (String field : List.of("instanceId", "catalogFingerprint")) { + var invalid = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(valid); invalid.put(field, "outdated"); + Files.writeString(path, invalid.toString()); + try (var connection = new StudioMcpConnection(root, mapper, new McpToolCatalog(mapper))) { + var result = connection.call("studio_project_context", mapper.createObjectNode().put("projectRoot", root.toString())); + assertEquals(field.equals("instanceId") ? "STALE_CONNECTION" : "VERSION_INCOMPATIBLE", + result.path("structuredContent").path("error").path("code").asText()); + } + } + assertEquals(0, calls.get()); + } finally { Files.writeString(path, valid); } + } + } + } + + static String java() { return Path.of(System.getProperty("java.home"), "bin/java").toString(); } + static String classpath() { return System.getProperty("studio.test.classpath"); } + final class Connector implements AutoCloseable { + final Process process; + final BufferedReader reader; + final BufferedWriter writer; + final ExecutorService reads = Executors.newSingleThreadExecutor(); + final Path errors; + int sequence; + Connector(Path project) throws Exception { + errors = Files.createTempFile(temporary, "stdio-", ".stderr"); + process = new ProcessBuilder(java(), "-cp", classpath(), "p.studio.app.StudioLauncher", "mcp", "--project", project.toString()) + .directory(temporary.toFile()).redirectError(errors.toFile()).start(); + reader = process.inputReader(); writer = process.outputWriter(); + } + void send(String value) throws Exception { writer.write(value); writer.newLine(); writer.flush(); } + JsonNode read() throws Exception { + String line = reads.submit(reader::readLine).get(15, TimeUnit.SECONDS); + assertNotNull(line, Files.readString(errors)); return mapper.readTree(line); + } + JsonNode request(String method, JsonNode params) throws Exception { + var value = mapper.createObjectNode().put("jsonrpc", "2.0").put("id", ++sequence).put("method", method); value.set("params", params); + send(value.toString()); var response = read(); assertEquals(sequence, response.path("id").asInt()); return response; + } + void initialize() throws Exception { + var params = mapper.createObjectNode().put("protocolVersion", "2025-06-18"); params.putObject("capabilities"); params.putObject("clientInfo").put("name", "process-test").put("version", "1"); + assertEquals("2025-06-18", request("initialize", params).path("result").path("protocolVersion").asText()); + send("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"); + } + JsonNode call(String name, Path root) throws Exception { + var params = mapper.createObjectNode().put("name", name); params.putObject("arguments").put("projectRoot", root.toString()); + return request("tools/call", params).path("result"); + } + public void close() throws Exception { + try { writer.close(); assertTrue(process.waitFor(10, TimeUnit.SECONDS), "EOF must terminate the connector"); assertEquals(0, process.exitValue(), Files.readString(errors)); } + finally { process.destroyForcibly(); reads.shutdownNow(); } + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java index fd1fc7a3..7160f424 100644 --- a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessMcpDesktopTest.java @@ -39,6 +39,7 @@ class HeadlessMcpDesktopTest { LocalMcpServer server; HttpClient client; String connection, task, build, session; + String authorization = "Bearer unavailable"; Path installation, source; DevWorkspace dev; Stage stage; @@ -76,9 +77,9 @@ class HeadlessMcpDesktopTest { stage = new Stage(); stage.setTitle("Real MCP / headless / DEV conformance"); stage.setScene(new Scene((javafx.scene.Parent) dev.rootNode(), 1000, 800)); stage.show(); dev.load(); }); - connect(); } void connect() throws Exception { + authorization = "Bearer " + p.studio.app.mcp.ProjectConnectionFiles.read(root, mapper).credential(); connection = null; var initialize = request("initialize"); var params = initialize.putObject("params").put("protocolVersion", "2025-06-18"); @@ -96,8 +97,15 @@ class HeadlessMcpDesktopTest { assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive), "No managed runtime may survive the test"); } - void acquire() throws Exception { + void grant() throws Exception { fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (project.automation().snapshot().state() != ControlState.WAITING_FOR_AGENT && System.nanoTime() < deadline) Thread.sleep(10); + assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state()); + connect(); + } + void acquire() throws Exception { + grant(); task = value(call("studio_control_acquire", args())).path("taskId").asText(); } void prepareLongRun() throws Exception { @@ -121,7 +129,7 @@ class HeadlessMcpDesktopTest { prepareLongRun(); var receipt = startRunning("cancel-me"); var delete = HttpRequest.newBuilder(server.connection().endpoint()).DELETE() - .header("Authorization", server.connection().authorizationHeader()).header("Mcp-Session-Id", connection).build(); + .header("Authorization", authorization).header("Mcp-Session-Id", connection).build(); assertEquals(200, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode()); client.close(); client = HttpClient.newHttpClient(); connect(); assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); @@ -159,7 +167,7 @@ class HeadlessMcpDesktopTest { refreshEntered.get(10, TimeUnit.SECONDS); assertEquals(ControlState.RETURNING_CONTROL, project.automation().snapshot().state()); assertFalse(project.automation().snapshot().manualAllowed()); - assertEquals("INVALID_TASK", call("studio_operation_get", args().put("clientRequestId", "revoked")).path("structuredContent").path("error").path("code").asText()); + assertEquals(401, post(request("ping")).statusCode()); assertSame(lastCapture, project.automation().snapshot().capture(), "Revoked work must not publish a late frame"); refreshGate.complete(null); assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); @@ -169,19 +177,19 @@ class HeadlessMcpDesktopTest { } @Test void waitingRevokeProjectCloseAndReopenNeverRestoreAuthority() throws Exception { - fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); + grant(); fx(() -> ((Button) dev.rootNode().lookup("#dev-reclaim")).fire()); assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); - assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText()); + assertEquals(401, post(request("ping")).statusCode()); prepareLongRun(); startRunning("close-project"); fx(dev::unLoad); assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state(), "DEV does not own task lifetime"); project.close(); assertTrue(owned.stream().noneMatch(ProcessHandle::isAlive)); - assertEquals("PROJECT_NOT_OPEN", call("studio_operation_get", args().put("clientRequestId", "close-project")).path("structuredContent").path("error").path("code").asText()); + assertEquals(401, post(request("ping")).statusCode()); project = app.getBean(ProjectSessionFactory.class).open(project.projectReference()); assertEquals(ControlState.MANUAL, project.automation().snapshot().state()); - assertEquals("INVALID_TASK", call("studio_build_start", args().put("clientRequestId", "late")).path("structuredContent").path("error").path("code").asText()); + assertEquals(401, post(request("ping")).statusCode()); } @Test void applicationContextShutdownClosesActiveProjectAndRuntime() throws Exception { @@ -270,13 +278,13 @@ class HeadlessMcpDesktopTest { } @Test void fullHttpLoopMatchesRawRuntimePixelsAndDisplayedDevAcrossResetAndRebuild() throws Exception { + assertEquals(401, post(request("ping")).statusCode()); + grant(); assertEquals(17, mapper.readTree(post(request("tools/list")).body()).path("result").path("tools").size()); assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs")); value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100))); var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000))); assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference"); - assertEquals("NOT_GRANTED", call("studio_control_acquire", args()).path("structuredContent").path("error").path("code").asText()); - fx(() -> ((Button) dev.rootNode().lookup("#dev-grant")).fire()); assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state()); task = value(call("studio_control_acquire", args())).path("taskId").asText(); assertFalse(task.isBlank()); @@ -442,7 +450,7 @@ class HeadlessMcpDesktopTest { } HttpResponse post(JsonNode body) throws Exception { var request = HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15)) - .header("Authorization", server.connection().authorizationHeader()).header("Content-Type", "application/json") + .header("Authorization", authorization).header("Content-Type", "application/json") .header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", "2025-06-18"); if (connection != null) request.header("Mcp-Session-Id", connection); return client.send(request.POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(), HttpResponse.BodyHandlers.ofString()); 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 index 1019562e..1219ef2b 100644 --- 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 @@ -4,10 +4,15 @@ import p.studio.api.operation.OperationSubscription; import java.nio.file.Path; import java.util.Optional; -/** Connection assistance only. Copying credentials never grants project authority. */ +/** Connection assistance only. Preparation never grants project authority. */ public interface AgentConnectionGuide { + enum State { UNAVAILABLE, WAITING_FOR_ACCESS, CONNECTED, RECONNECTING } + default boolean supportsPreparation() { return false; } + default State state(Path root) { return endpoint().isPresent() ? State.WAITING_FOR_ACCESS : State.UNAVAILABLE; } + default AgentIntegrationPreparation.Result prepare(Path root) { return new AgentIntegrationPreparation.Result(false, "Preparation unavailable"); } + default AgentIntegrationPreparation.Result preparationStatus(Path root) { return new AgentIntegrationPreparation.Result(false, ""); } Optional endpoint(); - /** Explicit secret-bearing export for the clipboard; never persist or log this string. */ + /** Permanent registration guidance only; never returns credentials. */ String configuration(Path openProjectRoot); OperationSubscription subscribe(Runnable changed); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentIntegrationPreparation.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentIntegrationPreparation.java new file mode 100644 index 00000000..7968c830 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AgentIntegrationPreparation.java @@ -0,0 +1,13 @@ +package p.studio.api.automation; + +import java.nio.file.Path; + +/** Machine-local client setup, independent of granting project authority. */ +public interface AgentIntegrationPreparation { + Result prepare(Path projectRoot); + default Result status(Path projectRoot) { return new Result(false, "Prepare the assistant for this project."); } + record Result(boolean ready, String message) { } + static AgentIntegrationPreparation unavailable() { + return root -> new Result(false, "Prepare the assistant from an installed Studio."); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationConnectionLifecycle.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationConnectionLifecycle.java new file mode 100644 index 00000000..03a0bca9 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationConnectionLifecycle.java @@ -0,0 +1,28 @@ +package p.studio.api.automation; + +import java.nio.file.Path; + +/** Required grant participant. Preparation/publication may do IO; activation/invalidation must not. */ +public interface AutomationConnectionLifecycle { + Publication prepare(Path projectRoot) throws Exception; + + final class OwnershipConflict extends Exception { + public OwnershipConflict() { super("Another Studio instance owns this project's connection. Reclaim or close it before granting here."); } + } + + interface Publication extends AutoCloseable { + void publish() throws Exception; + void activate(); + void invalidate(); + @Override void close() throws Exception; + } + + static AutomationConnectionLifecycle none() { + return root -> new Publication() { + public void publish() { } + public void activate() { } + public void invalidate() { } + public void close() { } + }; + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java index a8544e28..32f82f1a 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java @@ -1,6 +1,6 @@ package p.studio.api.automation; public record ControlResult(Status status, TaskIdentity task, String diagnostic) { - public enum Status { GRANTED, ACQUIRED, RETURNED, BUSY, DIRTY_DOCUMENTS, SAVE_FAILED, NOT_GRANTED, INVALID_TASK, CLOSED, CLEANUP_FAILED } + public enum Status { GRANTED, ACQUIRED, RETURNED, BUSY, DIRTY_DOCUMENTS, SAVE_FAILED, CONNECTION_FAILED, CONNECTION_CONFLICT, NOT_GRANTED, INVALID_TASK, CLOSED, CLEANUP_FAILED } public boolean success() { return status == Status.GRANTED || status == Status.ACQUIRED || status == Status.RETURNED; } public static ControlResult of(Status status, String message) { return new ControlResult(status, null, message); } } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/project/ProjectLocalStudioSetup.java b/prometeu-studio-api/src/main/java/p/studio/api/project/ProjectLocalStudioSetup.java index 22f54e0b..d05ec799 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/project/ProjectLocalStudioSetup.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/project/ProjectLocalStudioSetup.java @@ -2,14 +2,23 @@ package p.studio.api.project; public record ProjectLocalStudioSetup( String prometeuRuntimePath, - EditorIndentationSetup editorIndentation) { + EditorIndentationSetup editorIndentation, + AgentIntegrationSetup agentIntegration) { + public ProjectLocalStudioSetup(String runtimePath, EditorIndentationSetup indentation) { + this(runtimePath, indentation, AgentIntegrationSetup.defaults()); + } public ProjectLocalStudioSetup { + agentIntegration = agentIntegration == null ? AgentIntegrationSetup.defaults() : agentIntegration; prometeuRuntimePath = normalizeText(prometeuRuntimePath); editorIndentation = editorIndentation == null ? EditorIndentationSetup.defaults() : editorIndentation.normalize(); } + public record AgentIntegrationSetup(int schemaVersion, boolean enabled, String clientProfile) { + public static AgentIntegrationSetup defaults() { return new AgentIntegrationSetup(1, true, "codex"); } + } + public static ProjectLocalStudioSetup defaults() { return new ProjectLocalStudioSetup(null, EditorIndentationSetup.defaults()); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectCatalogService.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectCatalogService.java index 774865b3..13cbbb8d 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectCatalogService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectCatalogService.java @@ -23,8 +23,15 @@ public final class ProjectCatalogService implements ProjectCatalog { private final Path projectsRoot; private final ObjectMapper mapper; private final ProjectLocalStudioSetupStore setupStore; + private final p.studio.api.automation.AgentIntegrationPreparation integration; public ProjectCatalogService(Path projectsRoot, ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) { + this(projectsRoot, mapper, setupStore, p.studio.api.automation.AgentIntegrationPreparation.unavailable()); + } + + public ProjectCatalogService(Path projectsRoot, ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore, + p.studio.api.automation.AgentIntegrationPreparation integration) { + this.integration = Objects.requireNonNull(integration); this.projectsRoot = Objects.requireNonNull(projectsRoot, "projectsRoot").toAbsolutePath().normalize(); this.mapper = Objects.requireNonNull(mapper, "mapper").copy() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); @@ -103,6 +110,7 @@ public final class ProjectCatalogService implements ProjectCatalog { } catch (IOException exception) { throw new UncheckedIOException(exception); } + integration.prepare(root); // Readiness is queried by DEV; project creation remains usable on setup failure. return openProject(root); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java index ca19bbc5..522c9d28 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java @@ -11,6 +11,9 @@ import java.util.function.Consumer; public final class DefaultAutomationSession implements AutomationSession { private final Path root; private final OperationExecutor executor; + private final AutomationConnectionLifecycle connections; + private AutomationConnectionLifecycle.Publication connection; + private CompletableFuture publicationIdle = CompletableFuture.completedFuture(null); private final List> listeners = new CopyOnWriteArrayList<>(); private final List documents = new CopyOnWriteArrayList<>(); private final Deque calls = new ArrayDeque<>(); @@ -34,8 +37,13 @@ public final class DefaultAutomationSession implements AutomationSession { private CompletableFuture manualIdle = CompletableFuture.completedFuture(null); public DefaultAutomationSession(Path root, OperationExecutor executor) { + this(root, executor, AutomationConnectionLifecycle.none()); + } + + public DefaultAutomationSession(Path root, OperationExecutor executor, AutomationConnectionLifecycle connections) { this.root = root.toAbsolutePath().normalize(); this.executor = Objects.requireNonNull(executor); + this.connections = Objects.requireNonNull(connections); } public synchronized ManualLease enterManual() { @@ -101,15 +109,7 @@ public final class DefaultAutomationSession implements AutomationSession { if (found && !save) return result(ControlResult.Status.DIRTY_DOCUMENTS, "Save all and grant, or cancel"); CompletionStage saved = CompletableFuture.completedFuture(null); if (found) for (var participant : participants) saved = saved.thenCompose(v -> participant.saveAll()); - return saved.thenCompose(v -> verifySaved(participants)).thenApply(v -> { - synchronized (this) { - if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); - if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active"); - state = ControlState.WAITING_FOR_AGENT; - record("grant"); - return ControlResult.of(ControlResult.Status.GRANTED, ""); - } - }); + return saved.thenCompose(v -> verifySaved(participants)).thenApplyAsync(v -> publishGrant(attempt)); }).exceptionally(f -> ControlResult.of(ControlResult.Status.SAVE_FAILED, message(f))) .thenApply(outcome -> { synchronized (this) { @@ -121,6 +121,39 @@ public final class DefaultAutomationSession implements AutomationSession { }); } + private ControlResult publishGrant(long attempt) { + AutomationConnectionLifecycle.Publication prepared = null; + boolean committed = false; + CompletableFuture publishing = null; + try { + synchronized (this) { + if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + publishing = publicationIdle = new CompletableFuture<>(); + } + prepared = connections.prepare(root); + prepared.publish(); + synchronized (this) { + if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active"); + prepared.activate(); + connection = prepared; committed = true; + state = ControlState.WAITING_FOR_AGENT; + record("grant"); + return ControlResult.of(ControlResult.Status.GRANTED, ""); + } + } catch (AutomationConnectionLifecycle.OwnershipConflict conflict) { + return ControlResult.of(ControlResult.Status.CONNECTION_CONFLICT, conflict.getMessage()); + } catch (Exception failure) { + return ControlResult.of(ControlResult.Status.CONNECTION_FAILED, "Assistant connection could not be published: check project access, installation and publication conflicts."); + } finally { + if (!committed && prepared != null) { + prepared.invalidate(); + try { prepared.close(); } catch (Exception ignored) { /* Credential is already invalid. */ } + } + if (publishing != null) publishing.complete(null); + } + } + private CompletionStage verifySaved(List participants) { CompletionStage check = CompletableFuture.completedFuture(null); for (var p : participants) check = check.thenCompose(v -> p.hasUnsavedChanges().thenAccept(dirty -> { @@ -131,7 +164,7 @@ public final class DefaultAutomationSession implements AutomationSession { @Override public synchronized ControlResult acquire() { if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed"); - if (state != ControlState.WAITING_FOR_AGENT) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required"); + if (state != ControlState.WAITING_FOR_AGENT || handoffPending) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required"); task = new TaskIdentity(root, UUID.randomUUID().toString()); state = ControlState.AGENT_WORKING; record("acquire"); publish(); return new ControlResult(ControlResult.Status.ACQUIRED, task, ""); @@ -155,23 +188,29 @@ public final class DefaultAutomationSession implements AutomationSession { final ManagedHeadlessSession ownedRuntime; final List cancellations; final List participants; - final CompletableFuture idle; + final CompletableFuture idle, publisherIdle; final List cleanups; + final AutomationConnectionLifecycle.Publication publication; synchronized (this) { if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current"); if (closing) closed = true; if (returning != null && !returning.isDone()) return returning; - if (!closing && state == ControlState.MANUAL) return result(ControlResult.Status.RETURNED, ""); + if (!closing && state == ControlState.MANUAL && !handoffPending) return result(ControlResult.Status.RETURNED, ""); state = ControlState.RETURNING_CONTROL; task = null; generation++; handoffPending = false; record(closing ? "close" : "reclaim"); stale = capture != null; result = returning = new CompletableFuture<>(); - operation = active; ownedRuntime = runtime; idle = manualIdle; + operation = active; ownedRuntime = runtime; idle = manualIdle; publisherIdle = publicationIdle; cancellations = closing ? List.copyOf(manualCancellation) : List.of(); participants = closing ? List.of() : List.copyOf(documents); cleanups = List.copyOf(taskCleanup); taskCleanup.clear(); + publication = connection; connection = null; + if (publication != null) publication.invalidate(); publish(); } // Never call another service while holding the authority monitor: Debug owns its own lock. + CompletionStage publicationCleanup; + try { if (publication != null) publication.close(); publicationCleanup = CompletableFuture.completedFuture(null); } + catch (Exception failure) { publicationCleanup = CompletableFuture.failedFuture(new IllegalStateException("Connection cleanup failed; access is revoked")); } CompletionStage cleanup; try { for (var cancellation : cancellations) cancellation.run(); @@ -179,14 +218,14 @@ public final class DefaultAutomationSession implements AutomationSession { CompletionStage stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination(); CompletionStage shutdown = CompletableFuture.completedFuture(null); if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); } - cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle); + cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle, publisherIdle, publicationCleanup.toCompletableFuture()); cleanup = cleanup.whenComplete((v, failure) -> cleanups.forEach(Runnable::run)); // Closing disposes documents; an explicit return must refresh them before unlocking. for (var p : participants) cleanup = cleanup.thenCompose(v -> { synchronized (this) { if (closed) return CompletableFuture.completedFuture(null); } return p.refreshFromDisk(); }); - } catch (RuntimeException failure) { cleanup = CompletableFuture.failedFuture(failure); } + } catch (Exception failure) { cleanup = CompletableFuture.failedFuture(failure); } cleanup.whenComplete((v, failure) -> { synchronized (this) { if (failure == null) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index fbeb88f7..0e824205 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -17,15 +17,35 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory private final LspLifecyclePort lsp; private final p.studio.core.project.ProjectAccessRegistry access; private final p.studio.api.operation.OperationExecutor operations; + private final p.studio.api.automation.AutomationConnectionLifecycle connections; + private final p.studio.api.automation.AgentIntegrationPreparation preparation; public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore, ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations) { + this(stateStore, setupStore, lsp, access, operations, p.studio.api.automation.AutomationConnectionLifecycle.none()); + } + + public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore, + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations, + p.studio.api.automation.AutomationConnectionLifecycle connections) { + this(stateStore, setupStore, lsp, access, operations, connections, + p.studio.api.automation.AgentIntegrationPreparation.unavailable()); + } + + public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore, + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations, + p.studio.api.automation.AutomationConnectionLifecycle connections, + p.studio.api.automation.AgentIntegrationPreparation preparation) { + this.preparation = Objects.requireNonNull(preparation); this.stateStore = Objects.requireNonNull(stateStore, "stateStore"); this.setupStore = Objects.requireNonNull(setupStore, "setupStore"); this.lsp = Objects.requireNonNull(lsp, "lsp"); this.access = Objects.requireNonNull(access); this.operations = Objects.requireNonNull(operations); + this.connections = Objects.requireNonNull(connections); } @Override @@ -33,8 +53,10 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory if (closed) throw new IllegalStateException("Project sessions are closing"); final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference"); final var setup = setupStore.load(project); + // Preparation reports readiness independently; opening never grants agent authority. + if (setup.agentIntegration().enabled()) preparation.prepare(project.rootPath()); final var state = stateStore.load(project); - var automation = new DefaultAutomationSession(project.rootPath(), operations); + var automation = new DefaultAutomationSession(project.rootPath(), operations, connections); var ready = new java.util.concurrent.atomic.AtomicBoolean(); var registration = access.register(project.rootPath(), automation::enterManual, () -> ready.get() && !automation.snapshot().closed(), automation); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java index 155d07aa..a217942e 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -18,6 +18,46 @@ class DefaultAutomationSessionTest { ControlResult await(CompletionStage result) { return result.toCompletableFuture().join(); } TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); } + @Test void publicationIsRequiredAndCloseWaitsForAbortedPublicationWithoutHoldingMonitor() throws Exception { + var entered = new CountDownLatch(1); var proceed = new CountDownLatch(1); + var active = new java.util.concurrent.atomic.AtomicBoolean(); var cleaned = new java.util.concurrent.atomic.AtomicBoolean(); + var s = new DefaultAutomationSession(root, operations, ignored -> new AutomationConnectionLifecycle.Publication() { + public void publish() throws Exception { entered.countDown(); assertTrue(proceed.await(5, TimeUnit.SECONDS)); } + public void activate() { active.set(true); } + public void invalidate() { active.set(false); } + public void close() { cleaned.set(true); } + }); + var grant = s.grant(false).toCompletableFuture(); + assertTrue(entered.await(5, TimeUnit.SECONDS)); + assertEquals(NOT_GRANTED, s.acquire().status()); + var closing = s.closeAsync().toCompletableFuture(); + assertFalse(closing.isDone()); assertTrue(s.snapshot().closed()); + proceed.countDown(); + assertEquals(CLOSED, grant.get(5, TimeUnit.SECONDS).status()); + assertEquals(RETURNED, closing.get(5, TimeUnit.SECONDS).status()); + assertTrue(cleaned.get()); assertFalse(active.get()); + } + @Test void failedPublicationCannotGrantAndCleanupFailureStillCancelsWork() { + var s = new DefaultAutomationSession(root, operations, ignored -> { throw new java.io.IOException("private details"); }); + assertEquals(CONNECTION_FAILED, await(s.grant(false)).status()); + assertTrue(s.snapshot().manualAllowed()); assertEquals(NOT_GRANTED, s.acquire().status()); + assertFalse(s.snapshot().diagnostics().toString().contains("private details")); + var active = new java.util.concurrent.atomic.AtomicBoolean(); + var next = new DefaultAutomationSession(root, operations, ignored -> new AutomationConnectionLifecycle.Publication() { + public void publish() { } + public void activate() { active.set(true); } + public void invalidate() { active.set(false); } + public void close() throws Exception { throw new java.io.IOException("file failure"); } + }); + var task = start(next); + next.submit(task, "running", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null)); + var returned = next.reclaim().toCompletableFuture(); + assertFalse(active.get()); assertTrue(operations.last.cancelled); assertFalse(returned.isDone()); + operations.last.finish(); + assertEquals(CLEANUP_FAILED, returned.join().status()); + assertTrue(await(next.reclaim()).success()); + } + @Test void terminationObserversCanSubmitTheNextOperation() { var s = session(); var task = start(s); var first = s.submit(task, "first", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null)); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java index 93ad9f8b..9d33b71e 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java @@ -107,6 +107,40 @@ final class DefaultProjectSessionTest { registration.unsubscribe(); } + @Test void openingPreparesIntegrationAndRemainsManualEvenWhenPreparationIsIncomplete() { + var mapper = new ObjectMapper(); var calls = new java.util.ArrayList(); + var published = new java.util.concurrent.atomic.AtomicInteger(); + try (var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), + new ProjectLocalStudioSetupStore(mapper), new RecordingLsp(), new p.studio.core.project.ProjectAccessRegistry(), + new p.studio.core.support.ControlledOperations(), root -> { + published.incrementAndGet(); throw new AssertionError("Opening must not publish credentials"); + }, root -> { + calls.add(root); return new p.studio.api.automation.AgentIntegrationPreparation.Result(false, "Installation missing"); + })) { + var first = factory.open(project()); + assertEquals(java.util.List.of(project().rootPath()), calls); + assertTrue(first.automation().snapshot().manualAllowed()); + assertNull(first.automation().snapshot().task()); assertEquals(0, published.get()); + first.close(); + var reopened = factory.open(project()); + assertEquals(2, calls.size()); assertTrue(reopened.automation().snapshot().manualAllowed()); + } + } + + @Test void explicitDisabledIntegrationIsPreservedOnOpen() { + var mapper = new ObjectMapper(); var setup = new ProjectLocalStudioSetupStore(mapper); + setup.save(project(), new p.studio.api.project.ProjectLocalStudioSetup(null, null, + new p.studio.api.project.ProjectLocalStudioSetup.AgentIntegrationSetup(1, false, "codex"))); + try (var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup, + new RecordingLsp(), new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations(), + p.studio.api.automation.AutomationConnectionLifecycle.none(), root -> { + throw new AssertionError("Disabled integration must not be prepared automatically"); + })) { + assertTrue(factory.open(project()).automation().snapshot().manualAllowed()); + assertFalse(setup.load(project()).agentIntegration().enabled()); + } + } + private static final class RecordingLsp implements LspLifecyclePort { int boots; int shutdowns; 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 b208e31e..d328367f 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 @@ -4,6 +4,7 @@ import lombok.Getter; public enum I18n { WORKSPACE_DEV("workspace.dev"), + DEV_MCP_WAITING("dev.mcpWaiting"), DEV_MCP_CONNECTED("dev.mcpConnected"), DEV_MCP_RECONNECTING("dev.mcpReconnecting"), 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"), 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 f3585aac..763c732d 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 @@ -33,6 +33,7 @@ public final class DevWorkspace extends Workspace { private OperationSubscription subscription; private long generation; private CanonicalCapture rendered; + private boolean preparing; private final javafx.beans.value.ChangeListener localeListener; public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) { @@ -53,7 +54,7 @@ public final class DevWorkspace extends Workspace { reclaim.setOnAction(e -> automation.reclaim()); configuration.setId("dev-mcp-config"); configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); - configuration.setOnAction(e -> copyConfiguration()); + configuration.setOnAction(e -> prepareConfiguration()); availability.setId("dev-mcp-endpoint"); availability.setWrapText(true); copyStatus.setId("dev-mcp-copy-status"); Label instructions = new Label(); instructions.setWrapText(true); @@ -82,12 +83,17 @@ public final class DevWorkspace extends Workspace { if (subscription != null) return; i18n.localeProperty().addListener(localeListener); long subscribed = ++generation; + java.util.concurrent.CompletableFuture.supplyAsync(() -> connectionGuide.preparationStatus(projectRoot)) + .whenComplete((result, failure) -> Platform.runLater(() -> { + if (generation == subscribed && !preparing && copyStatus.getText().isEmpty()) + copyStatus.setText(failure == null ? result.message() : i18n.text(I18n.DEV_CONFIG_FAILED)); + })); subscription = automation.subscribe(snapshot -> { 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(); } }; + Runnable update = () -> { if (generation == subscribed) { updateConnection(); } }; if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); }); } @@ -127,20 +133,25 @@ public final class DevWorkspace extends Workspace { } } private void updateConnection() { - var endpoint = connectionGuide.endpoint(); - configuration.setDisable(automation.snapshot().closed() || endpoint.isEmpty()); - availability.setText(endpoint.orElseGet(() -> i18n.text(I18n.DEV_MCP_UNAVAILABLE))); + configuration.setDisable(preparing || automation.snapshot().closed() || !connectionGuide.supportsPreparation()); + availability.setText(i18n.text(switch (connectionGuide.state(projectRoot)) { + case UNAVAILABLE -> I18n.DEV_MCP_UNAVAILABLE; + case WAITING_FOR_ACCESS -> I18n.DEV_MCP_WAITING; + case CONNECTED -> I18n.DEV_MCP_CONNECTED; + case RECONNECTING -> I18n.DEV_MCP_RECONNECTING; + })); } - 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(); - } + private void prepareConfiguration() { + if (preparing) return; + preparing = true; + long requested = generation; + configuration.setDisable(true); + java.util.concurrent.CompletableFuture.supplyAsync(() -> connectionGuide.prepare(projectRoot)) + .whenComplete((result, failure) -> Platform.runLater(() -> { + preparing = false; + if (generation != requested) return; + copyStatus.setText(failure == null ? result.message() : 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 50376187..219a0684 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -360,11 +360,11 @@ workspace.debug=Debug workspace.dev=DEV dev.grant=Grant control to AI dev.reclaim=Interrupt and reclaim control -dev.copyConfig=Copy MCP configuration +dev.copyConfig=Prepare assistant 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.mcpInstructions=Prepare the assistant once for this project. Start the agent here, then grant access in DEV. Studio discovers the connection automatically, including after restart and a new grant. dev.configCopied=Connection descriptor and project instructions copied. Contains a private token. -dev.configFailed=Could not copy the current connection configuration. +dev.configFailed=Assistant preparation failed. Check the installation and project settings. 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 @@ -377,3 +377,6 @@ dev.history=Recent Studio calls dev.noFrame=No runtime capture dev.staleFrame=Stale capture — previous build or execution dev.currentFrame=Canonical runtime capture +dev.mcpWaiting=Assistant connection: waiting for access or connection +dev.mcpConnected=Assistant connected +dev.mcpReconnecting=Assistant reconnecting 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 dd23428c..b8b0052a 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 @@ -31,11 +31,11 @@ workspace.debug.status.stopped=Parado workspace.dev=DEV dev.grant=Ceder controle à IA dev.reclaim=Interromper e retomar controle -dev.copyConfig=Copiar configuração MCP +dev.copyConfig=Preparar assistente 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.mcpInstructions=Prepare o assistente uma vez neste projeto. Inicie o agente aqui e conceda acesso no DEV. A conexão é descoberta automaticamente, inclusive após reiniciar e conceder acesso novamente. 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.configFailed=Falha ao preparar assistente. Confira a instalação e as configurações do projeto. 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 @@ -48,3 +48,6 @@ dev.history=Chamadas recentes ao Studio dev.noFrame=Nenhuma captura do runtime dev.staleFrame=Captura desatualizada — build ou execução anterior dev.currentFrame=Captura canônica do runtime +dev.mcpWaiting=Conexão do assistente: aguardando acesso ou conexão +dev.mcpConnected=Assistente conectado +dev.mcpReconnecting=Assistente reconectando