# MCP Tools and Project Knowledge Contract ## 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 [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. 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. Steps 17–21 connect the functional providers and DEV configuration assistance; steps 22–28 provide the real runtime gateway and integrated acceptance. ## 1. Connection Contract The app hosts `/mcp` on **127.0.0.1 with an OS-assigned port**, using the JSON response form of MCP Streamable HTTP, protocol revision `2025-06-18`. The 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. 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. Initialization assigns a separate random `Mcp-Session-Id`. Subsequent requests include this header and the negotiated `MCP-Protocol-Version`. The server can recover the negotiated version from its connection session if the version header is absent; an explicitly unsupported header returns 400. Missing required session returns 400; an unknown/closed session returns 404. The client sends `notifications/initialized` before tools. `ping` is available after initialization. POST requires UTF-8 JSON and Accept support for `application/json` and `text/event-stream`. Responses use JSON, not SSE. GET returns 405. DELETE closes only the connection session, not project authority. Accepted notifications and client responses return 202 without a body. Notification/disconnection alone MUST NOT revoke a task or cancel an operation already returned by operationId. The transport bounds incoming bodies to 1 MiB, sessions to 128 and request handling to a bounded worker queue. Oversized bodies return 413; exhausted session capacity returns 503. Stalled exchanges close after 15 seconds. These are HTTP resource protections, **not** task expiration or guest/runtime timeouts. Build/advance MUST return operation identities promptly. A lost response is resolved by authorized lookup, not by assuming cancellation or replay. These details follow the official MCP [transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports), [lifecycle](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) and [tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) contracts. Optional SSE, server-initiated requests, sampling, prompts, resource subscriptions and list-change notifications are not advertised. ### 1.1 DEV Connection Assistance DEV displays the current endpoint without credentials and provides **Copy MCP configuration** for an open project. The neutral `AgentConnectionGuide` supplies availability and a deliberate clipboard export; JavaFX MUST NOT depend on the HTTP server or keep credentials in labels, diagnostics, project state or history. Connection lifecycle changes refresh availability. A closed project or stopped server cannot export a descriptor. Unloading DEV only unsubscribes presentation listeners; it does not stop the endpoint or revoke project authority. The copied text is a provider-neutral JSON descriptor with `transport` set to `streamable-http`, the live `url`, `headers.Authorization`, canonical `projectRoot` and `instructions`. It is not a promise of a drop-in configuration format for every external client. The developer maps URL/header fields to that client's MCP configuration; a provider-specific wizard remains out of scope. The secret is materialized only for explicit copying and MUST NOT be written to versioned files or logs. Clipboard success/failure feedback MUST NOT repeat credential-bearing content or raw exceptions. The clipboard itself is a deliberate secret export. Copied instructions and MCP initialization guidance direct the client to discover actual tools, read project context and applicable language/SDK/library references, wait for human grant before acquisition, edit saved files within project scope, validate with LSP/build, recover operation receipts by clientRequestId and release explicitly. Missing language support is a reported limitation, not a PBS fallback. They also explain that SDK/external libraries are read-only, revocation cannot stop external file writes, copying grants no authority, and a Studio restart requires fresh endpoint/token configuration. No provider or model is required to test this guidance and the MCP service contract. ## 2. Identity and Admission All tool inputs require `projectRoot`: an absolute filesystem root resolving to an open project. UI focus never supplies it. Core services resolve the actual project, including canonical-path/scope checks; syntactic validation does not 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. - `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. Revalidate before admission, lookup and deduplication, including read-only LSP. No MCP tool grants human permission or simulates pressing the DEV button. There are no arbitrary-file read/write, shell, Git or publication tools. Editing uses the external client's native tools within the context's editable scope. ## 3. v1 Tool Catalog Fields below supplement `projectRoot`, and `taskId` where authority is `task`. Input objects reject undeclared fields. IDs are nonempty opaque strings. | Tool | Authority | Additional input | Successful value | | --- | --- | --- | --- | | `studio_project_context` | authenticated | none | Project context in section 5 | | `studio_reference_read` | authenticated | referenceId; optional offset/limit | Indexed reference page | | `studio_control_acquire` | granted | none | taskId, state=AGENT_WORKING | | `studio_control_release` | task | none | state=MANUAL, only after ordered cleanup | | `studio_language_query` | task | operation, parameters | Supported LSP query/proposal result | | `studio_build_start` | task | clientRequestId | operationId, clientRequestId, state | | `studio_headless_boot` | task | buildId | sessionId, buildId; boot uses the task's known build | | `studio_headless_reset` | task | none | Current session/reset state | | `studio_headless_set_input` | task | input | Current session acknowledgement | | `studio_headless_clear_input` | task | none | Current session acknowledgement | | `studio_headless_advance` | task | clientRequestId, frames | operationId, clientRequestId, state | | `studio_headless_capture` | task | none | Canonical image and metadata in section 6 | | `studio_headless_state` | task | none | Current session and runtime state | | `studio_headless_fault` | task | none | fault object or null, preserving structural fault details | | `studio_headless_shutdown` | task | none | Session shutdown acknowledgement after managed cleanup | | `studio_operation_get` | task | exactly one of operationId/clientRequestId | State, known progress, typed result/failure | | `studio_operation_cancel` | task | operationId | operationId, cancellationRequested | Boot MUST NOT accept an arbitrary cartridge path. The shared service resolves buildId to known project artifacts. Runtime limits/capabilities come from the actual runtime, not fixed MCP promises. Frames is a nonnegative integer (zero is valid); values beyond effective limits fail rather than being clamped. Input is a replacement snapshot: booleans `up/down/left/right/a/b/x/y/l/r/start/ select/touch`, signed 32-bit `touchX/touchY`. Omitted fields reset to false/zero. It preserves the runtime's normal sampling/edge semantics, not UI keyboard events. Language queries use the capabilities returned by project context. Parameters may contain URI, zero-based UTF-16 position/range/positions, workspace query, newName, includeDeclaration or task-local itemId for multi-stage queries. The provider MUST validate the parameters needed by the selected operation and reject unsupported operations explicitly. Diagnostics, definitions, references and symbols reuse the existing project LSP. Other queries/refactoring proposals are exposed only when supported; returned edits MUST respect project versus read-only SDK/library scope. No query applies filesystem edits. ### 3.1 Language Query Operations `studio_language_query` uses the existing project's LSP server via a real client, not a parallel language implementation or a direct call into compiler semantics. Its successful value is `{operation, result, limitations}`. `result` is the JSON projection of the existing LSP response (including null or an empty list when appropriate); LSP union wrappers are unwrapped. Provider classes remain inside the application adapter. Studio API/Core use maps, lists and scalar values only. | Operation | Required parameters beyond projectRoot/taskId | | --- | --- | | `diagnostics`, `documentSymbols`, `documentLinks`, `foldingRanges`, `formatting`, `semanticTokens` | `parameters.uri` | | `hover`, `completion`, `signatureHelp`, `definition`, `references`, `prepareRename`, `prepareCallHierarchy` | `uri`, `position`; references optionally accepts `includeDeclaration` | | `rename` | `uri`, `position`, `newName` | | `workspaceSymbols` | optional `query`; no document URI is needed | | `selectionRanges` | `uri`, nonempty `positions` | | `codeActions` | `uri`, ordered `range`; diagnostics are obtained from the current saved file | | `incomingCalls`, `outgoingCalls` | task-local `itemId` from a hierarchy result | Support MUST be checked against the running server's initialize response before dispatch. Unknown operations, including currently unsupported type hierarchy, return `UNSUPPORTED_CAPABILITY`. Context publishes the installed provider's capabilities, including semantic tokens; hierarchy and rename preparations use their corresponding server capability. Positions are zero-based UTF-16 offsets, must fit the saved file and must not split surrogate pairs. Reversed ranges and missing operation-specific parameters are rejected. The application lifecycle supplies each open project's bound loopback LSP endpoint. Studio uses OS-assigned ports so different open projects do not compete for one fixed port. The public LSP configuration default remains unchanged for other hosts. A manifest language change requires reopening that project's server; the adapter MUST NOT send queries to a server bound to another language/root. Each query uses a short-lived client connection. For document requests, the adapter opens exactly the saved UTF-8 text and waits for that connection's published diagnostics before issuing the semantic query. Other dependency files are read from disk by the existing compiler bridge. A fresh connection prevents reuse of stale overlays from previous requests or the human editor. Unsaved or concurrent external writes remain the developer's responsibility. Queries require the current task, share the project's work admission/cancellation and DEV operation observation, and do not silently queue behind conflicting work. Return/reclaim invalidates the task immediately, waits for worker termination, then clears task-local hierarchy items before manual control is restored. Item IDs from another task or project cannot be used. Client sockets/listeners close on success, failure, timeout or cancellation; project-server shutdown closes its accepted sockets and executor. A lost client does not independently grant control. The adapter bounds connect time to 2 seconds and the LSP exchange to 10 seconds; Core bounds the request worker wait to 12 seconds. Documents are limited to 4 MiB of UTF-8 and task-local hierarchy state to 1024 items. These are adapter resource guards, unrelated to the runtime's deterministic frame/watchdog semantics. Document URIs must resolve to known physical project/dependency source files. Symlink targets are canonicalized before admission. External sources may be queried, but edit-producing queries on read-only roots are rejected. Every URI in returned workspace-edit proposals is checked against the same editable/read-only scope; an unsafe proposal is rejected as a whole. File-operation edits and executable commands are not offered; `workspace/applyEdit` is always refused. No query writes a file. Virtual SDK declarations may not have physical definition locations in the existing LSP; indexed SDK references remain available instead. ## 4. Result, Error and Operation Contracts Successful tools return `isError:false` with structuredContent `{"status":"ok","value":{...}}`. Domain/admission failures return `isError:true` with `{"status":"error","error":{"code":"...","message":"..."}}`. Both include a text content block serializing the same structured data for clients that do not render structuredContent. Clients use error codes, not parsed prose. `AutomationFailure.Code` defines domain codes, including project-not-open, not-granted, invalid-task, busy, unsupported language/capability, missing reference/documentation, out-of-scope/read-only scope, missing operation/build/ runtime session, duplicate-ID parameter conflict, unavailable/incompatible runtime, missing frame, exceeded limit, not-cancelable and infrastructure failure. Unknown methods, malformed JSON-RPC and schema-invalid arguments remain protocol errors (-32601, -32600/-32700 and -32602); unexpected internals use sanitized -32603 responses, never request bodies, stack traces or credentials. Build failure and guest fault are **operation outcomes**, not implicit release. `TrackedOperation` carries the existing `OperationSnapshot`, clientRequestId, known progress and either the existing typed build result or runtime outcome. Unknown requested/completed frame counts are null. Terminal infrastructure failure/cancellation MUST preserve only known progress. Cancellation acknowledgement does not assert worker termination or grant manual control. The wire receipt flattens operationId/state from the neutral operation snapshot. Polling additionally returns progress and typed result/failure; incomplete results are null. Build results retain diagnostics/artifact correlation. Runtime results retain requested/completed frames and distinguish success, guest fault, termination, cancellation and infrastructure failure. Captured results include the same MCP image block used by direct capture. `clientRequestId` deduplication is task-local and in-memory. Same ID plus same effective parameters returns the same operation; changed parameters fail with CLIENT_REQUEST_CONFLICT. Operation lookup accepts exactly one key. Revoked, cross-project or old task identities cannot read/cancel cached work. Neither MCP JSON-RPC IDs nor runtime requestIds replace this identity. Restart never restores the registry, replays an advance or recovers authorization. ### 4.1 Task Work and Correlation `TaskTools` is the neutral service surface; MCP only validates schemas and projects its results. The Core implementation admits work through `AutomationSession.submit` and the existing operation executor, sharing DEV's busy state and cancellation. Acquisition requires the prior human grant. Release reports `MANUAL` only after managed cleanup and document refresh succeed; cleanup failures remain explicit. Admission and request registration are atomic per project. Deduplication uses the operation kind and effective parameters, including requested frames. It is checked after task authority and before busy/active-runtime validation, so a repeated accepted start still resolves its original operation after that work has ended. Rejected starts do not reserve clientRequestIds. Distinct requests cannot silently queue behind busy work. Other projects remain independent. Polling returns `workerTerminated` separately from operation state. `CANCELLED` may acknowledge interruption before the worker exits; it does not permit another conflicting operation or manual control. Final results remain null until worker termination. Progress contains only provider-reported counts and can be unknown. A cooperative final capture is published to DEV before termination while the task is still valid. A revoked task cannot publish a late frame or retrieve cached work. Historical operation images are marked stale when they no longer match DEV's current session/build/frame, or DEV has marked that capture stale. Build executes the same saved-project compiler/packer preparation as manual Shipper, under task admission rather than a manual lease. It checks cancellation between compilation, validation and packaging phases. A successful build receives a task-local buildId; failed builds retain typed diagnostics and do not release control. Before rebuilding, the managed runtime must finish shutdown and detach. Old buildIds are invalidated before overwriting artifacts, including when the new build fails. This is artifact correlation, not source snapshots or recovery. Headless handlers consume a neutral `HeadlessGateway` session port. Boot accepts only a current successful task build; one runtime session may be attached at a time. Input is normalized to a complete replacement snapshot. Advance limits come from that session and are enforced without clamping. Shutdown detaches only after managed cleanup finishes. Runtime process supervision and protocol mapping belong to the application gateway delivered in step 22, not to MCP or the test doubles. Reset leaves the attached process unbooted, marks the previous capture stale and retains its build association. A subsequent explicit `studio_headless_boot` with that same current buildId reboots the known cartridge within the session. Boot without reset while a runtime is attached is rejected as busy. Reset does not change task authority or implicitly start execution. Rebuilding ends and detaches that process, invalidates previous buildIds and requires a fresh explicit boot. Synchronous headless failures finish their worker before returning the error, so a corrective call cannot race the failed worker's admission lock. Task-local operation/build records are discarded after worker termination on return, revocation or project closure. Cleanup failures never restore authority; the records are still discarded after managed work stops. Neither connection disconnect nor polling silence discards an authorized task's records. ## 5. Project Knowledge DTOs Neutral `ProjectKnowledge.Context` contains projectRoot/projectName, languages, libraries, editableRoots/readOnlyRoots, indexed references and explicit limitations. Its source is the project manifest and installed providers, never an AI-only file. Each language includes id/primary, separately identified languageVersion, compilerVersion and sdkVersion, source extensions/roots, real capabilities and reference IDs. Version has `value` and `source`; unknown value is null with source `unknown`. Capability support distinguishes SUPPORTED/UNSUPPORTED/UNKNOWN and can explain a limitation. Unknown declared language MUST NOT fall back to PBS. Libraries include identity, known version, roots and whether they belong to the editable project. External libraries and SDK remain read-only. Reference entries identify id/title/owner/kind/version; kinds include QUICKSTART, SYNTAX, SEMANTICS, EXAMPLE, SDK and LIBRARY. Indexed content belongs to its language/SDK owner. Reference reads take an opaque ID from that index, not a path or arbitrary URI. Offset defaults to 0; limit defaults to 4000 and accepts 1–16000 Unicode code points. A page returns referenceId, offset, total, text and nextOffset (null at end). Invalid pagination fails; unknown/traversal-like IDs cannot escape the index. Installed reference content is resolved through the frontend's owner-maintained reference provider, not a Studio-maintained language specification. ### 5.1 Manifest and Provider Resolution `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 is discoverable only after successful opening and until closure begins. Unregistered/closed roots return `PROJECT_NOT_OPEN`. Each call reads the saved `prometeu.json` and dependency manifests again. Missing or invalid primary manifests fail explicitly instead of returning cached language metadata. Languages are grouped by declared ID, with the primary flag derived from the main manifest. Unknown IDs retain their identity and expose unsupported build/LSP support; no default frontend is consulted. Extensions and source roots come from the installed frontend specification. LSP feature support comes from the same compiler bridge description used by the existing LSP server, not from a duplicated PBS capability list. If that provider cannot describe its LSP, support is UNKNOWN with an explicit limitation. These are installed-provider capabilities, not a promise that the MCP language-query tool is already composed or that any particular source file will compile. Language versions remain unknown when no owner metadata exists. Compiler versions use the installed frontend package's `Implementation-Version` only when present. The requested SDK version has manifest provenance; the context distinguishes versions supported by the installed provider from unsupported requests. Multiple SDK requests for the same language yield an unknown aggregate version, an explicit limitation and separate SDK library entries. These identifiers MUST NOT be substituted for one another. Dependency paths and registry entries use the compiler's existing resolver, including its main-root-relative local path semantics and registry requirement. Discovery does not create a registry, install dependencies or build sources. Unresolved declarations remain visible with empty roots and limitations. Mixed language graphs are described but reported as unsupported for the current build pipeline. Discovery is bounded to 256 projects and 256 declarations per manifest. The editable scope is the canonical project root **minus** read-only roots. Read-only scope takes precedence: external/registry libraries and their transitive dependencies remain protected even when stored beneath the project root or also reachable through a local declaration. Source roots are canonicalized, including symlink targets. SDK entries are always read-only; packaged SDK resources need not have filesystem roots. Scope metadata does not sandbox an external agent's own filesystem tools; the developer remains responsible for those tools and Git. Paths in MCP results are absolute filesystem strings, not `file:` URIs. ### 5.2 Installed References and Pagination An installed frontend MAY implement `FrontendReferenceProvider` through `FrontendProvider.documentation()`. That compiler-side contract supplies indexed, owner-maintained texts for an SDK major and project target. It does not depend on Studio API or MCP. Studio projects these into neutral reference descriptors; full texts MUST NOT be included in project context. Reference IDs are namespaced by language (`:`), unique within the selected project index and opaque to callers. Studio MUST NOT interpret an ID as a filename, URI or URL. PBS packages its numbered specifications and informative quickstart from their owner directory, plus a compilable Game example and actual SDK sources/barrels. A build-generated index binds these texts to the installed frontend using content hashes. Distribution-only reads MUST work without a checkout or network. SDK and 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 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 consultable, not editable through this surface. Pagination counts Unicode code points: an astral character occupies one offset, not two UTF-16 units. Offset 0/limit 4000 are defaults; limit MUST be 1–16000. An offset equal to total returns empty text and null nextOffset. Offsets beyond total, negative offsets, nonintegral values and integers beyond the implementation's signed 32-bit range are invalid parameters, never wrapped/truncated to another page. Missing or unreadable provider documentation yields `DOCUMENTATION_UNAVAILABLE` limitations, not promised references. An uninstalled primary language yields `UNSUPPORTED_LANGUAGE` for reference reads; an available index without the requested ID yields `REFERENCE_NOT_FOUND`. Closed projects yield `PROJECT_NOT_OPEN` before reference lookup. These failures do not grant/revoke task authority. ## 6. Image Contract MCP image content has `type:image`, `mimeType:image/png`, and base64 `data` of the unchanged `CanonicalCapture.png` bytes. No screenshot, log scraping, temporary path or network fetch is required. The structured value includes sessionId, buildId, logicalFrameIndex, frameId, width, height, stridePixels, pixelFormat `RGBA8888`, mimeType and stale. Stride describes the original framebuffer, not PNG compression/padding. Logical and render frame counters are independent. The adapter MUST NOT invent a frame when none exists or substitute another session's image. The same neutral capture feeds DEV and MCP. Real runtime production/cross-language equality is verified by the phase 4 desktop integration gate below; encoding test pixels in contract tests alone does not satisfy it. ## 7. Conformance and Delivery Boundary Contract tests validate every tool's example, authority level, required project/ task IDs, invalid types/unknown fields, exclusive operation lookup, input ranges, pagination, result envelopes, PNG bytes and independent frame identities. HTTP tests use a real loopback listener/client and exercise initialization, authentication, Origin, endpoint/method/version handling, tool dispatch, malformed or oversized input, closure, restart and old-token rejection. Provider doubles exist only in tests. Composition starts/closes transport with Studio. 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 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 actual app composition, project LSP, compiler/packer, saved edits, explicit reset/reboot, build identity invalidation and corrective loops after compile errors/guest faults. Step 24 adds `headlessMcpDesktopTest`: a real HTTP client drives the composed app, installed compiler/packer/LSP and packaged Rust runtime, while the actual JavaFX DEV view observes the shared session. An independent test-only JSONL client runs the same saved cartridge and input timeline in another real process, without the Studio process adapter or capture DTOs. Raw PNG bytes and each capture metadata field match MCP; all decoded framebuffer pixels and the visible identity/stale labels match DEV. State/fault and deterministic reset/fresh-session repetitions are also checked. Rebuilding changes pixels/build identity and visibly marks the old capture stale. Images remain in memory; window screenshots are not evidence. The fixture uses supported project-source LSP definition/symbol navigation and indexed SDK reads. A probe of the installed SDK's `Input.pad()` definition returns an empty result with the current language service; the gate does not claim SDK symbol navigation where no location is returned. This is a language tooling limitation, not a headless or MCP execution fallback. Step 25 extends that real desktop/HTTP gate with active-operation cancellation, connection deletion/reconnection and duplicate receipts, waiting/active revoke, late-call rejection, project closure/reopening and application-context shutdown. A controlled document participant delays refresh acknowledgement to prove that manual control remains blocked until process cleanup and disk refresh complete; it also checks that no revoked frame or old source buffer is applied afterward. The real runtime is killed or suspended in test-owned processes to verify known progress, no implicit restart/replay, forced cleanup and explicit human retry. Compile errors and guest faults are corrected over HTTP within the same task. The normal desktop Debug process starts after release and blocks a new grant. The suspension/manual-Debug scenarios require a POSIX desktop and a free Debug port 7777; the gate never attaches to an existing user's Debug process. The automated client is not an external coding agent. Real-agent compatibility and final packaging acceptance remain later gates. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it.