# 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. ## 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. ## 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. ## 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 packaging and real provider resolution are steps 17–18. ## 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 remain phase 4 gates; encoding test pixels in contract tests does not satisfy that integration requirement. ## 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. Step 16's production registry is empty until functional handlers are composed; DEV configuration-copy stays unavailable until step 21. Passing this transport gate is not the phase 3 or final external-agent acceptance gate. API/Core and JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it.