diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md new file mode 100644 index 000000000..175853ecf --- /dev/null +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -0,0 +1,30 @@ +# Operating Recoup Records through the API + +A Recoup Records operator signs in with an ordinary Recoup account, selects a label workspace they can already access and gives the agent a job. The first write milestone records a `needs_changes` release-metadata review and independently reopens its receipt. The subsequent durable workflow opens private catalog correction cases for eligible recordings, continues after chat closure and verifies each saved case. Qualify both milestones on a disposable label containing synthetic recordings. [First verified write](https://github.com/recoupable/api/issues/1308) · [Durable API jobs](https://github.com/recoupable/api/issues/1315) · [Private case access](https://github.com/recoupable/api/issues/1316) + +## Authority and instructions + +| Component | Responsibility | +| --- | --- | +| Sign-in | Authenticate the existing Recoup account through the connection's supported flow. Preserve its organization membership, resource access, OAuth audience and granted scopes. On the existing REST surface the credential identifies the account. For organization-scoped work, carry the selected organization into the API call and validate membership and resource access there. The shared REST authentication helper returns no organization when none is supplied. The personal, one-hour `mcp:read` registration profile remains read-only. [REST authentication](../../lib/auth/validateAuthContext.ts) · [OAuth access](../../lib/oauth/resolveOAuthAccess.ts) · [Personal registration](../agent-registration.md) | +| MCP and agent | On a qualified host with native Skills enabled, the host lists the account’s permitted skills and makes their names and descriptions available to the agent before the first prompt. It can keep the file manifest locally. It reads the selected guide and any required files only when the task calls for them. On a host without native Skills, a topic `search` can surface the guide alongside the relevant API operation. Open it with `search({skill})`, or browse with `search({})`. Use `execute` to compose the permitted operations and return a compact answer. The host supplies authenticated context outside the generated program. The API alone decides business authorization, including any approval the underlying operation already requires. | +| Recoup API | Apply the existing account, workspace, entitlement, recipient, quote, spending and resource checks appropriate to each operation, on every entry point. Return an actionable denial, existing approval/quote requirement, or receipt for an accepted action. A host or downstream provider may also require interaction. Show the actual reason and continue through the supported flow. | +| Durable job | When an operation needs to outlive the chat, use an API-owned job or workflow that records the initiating account, workspace, admitted job, idempotency key, checkpoints and result. Before subsequent effects and on result access, enforce the owning operation's current permissions. If the supported authorization expires and cannot be refreshed or revalidated, pause and request reconnection. Establish what survived the restart using the original job record. | + +A Recoup Records operator can say “check this week's releases” or designate an existing catalog handbook. For a handbook-guided job, the API records the assigning account, organization or workspace, assignment ID, source, document ID, authorized version and content digest. Retain an immutable snapshot or a retrievable immutable version. Before the first effect and after restart, resolve any host-supplied reference against this trusted assignment record and recheck the account's current access. Hold affected work if the reference, version or digest differs, the content cannot be verified, or its authorization is withdrawn. The assigning account can deliberately select a different handbook by updating the assignment. Optional recurring jobs can reuse these instructions. The owning API still decides access, spend and required approvals. [Job acceptance](https://github.com/recoupable/api/issues/1315) + +## The durable catalog job + +Ask the agent to open one private correction case for each recording whose current release evidence shows a missing recording identifier (ISRC). For example, if the fixture has three confirmed gaps, one already has a case, and another track's lookup failed, the expected change is two new cases. The two new cases cite their source versions, the existing case remains unique, and the failed lookup stays unresolved. The work involves no messages, provider registrations or spending. + +Today Recoup distinguishes an observed missing ISRC from a failed lookup, partial coverage and stale source versions. Its existing REST Context route and standard MCP can save and reopen workspace-scoped cases with expected revisions and idempotency keys. A saved case is a private workpaper. The current delegated OAuth profile excludes case save, read and list. Ordinary sign-in identifies the user, and the existing credential and route still determine which operations work. An authenticated account alone does not prove that a particular connector already supports the job. [Release observations](../../lib/context/planning/readReleaseTrackObservations.ts) · [Case contract](../../lib/context/README.md#catalog-case-artifacts-catd-29) · [OAuth exclusions](../mcp-oauth-tool-qualification.md) + +To qualify the direct connection, expose the authorized case operations for its normal sign-in path through the owning API. Reuse the scoped case processor, enforce workspace membership, validate recording and evidence versions, preserve revision conflicts, and keep withdrawal and redaction behavior on later reads. Document existing grants that lack the necessary access. Keep the OpenAI Directory's separately reviewed catalog surface within its published capabilities. Rights registration, distribution and collections each need their own API/provider operation and observed outcome. + +## Installed end-to-end acceptance + +1. Seed two isolated organizations and a catalog large enough to paginate. Include confirmed gaps, already-handled records, a failed lookup, conflicting evidence and a withdrawn source. Sign in with an ordinary test account that already has the pilot label's required access. Compare direct code mode with the same underlying REST operation on equivalent fixture state. Use named MCP as a control where its current credential is eligible. On a fresh native connection, verify that only permitted skill names and descriptions reach the agent before the first prompt, with zero file reads. Give the operator’s release-check request without naming a guide or prompting a search. Observe whether the agent selects the relevant guide from its description and reads it on demand. On the fallback host, search the same topic, verify distinct guide and operation previews, and open the exact guide with `search({skill})`. Repeat on both hosts outside the guide’s audience. The hidden entry must disappear and guide reads must produce zero business effects. +2. Create a real case through the direct connection with zero extra setup or prompts beyond sign-in for this already permitted private action. Independently reopen it through an account-authorized read path and verify workspace, recording, saved revision and source evidence. Count expected and actual new cases, unresolved findings, duplicates, wrong-tenant effects and human interruptions. +3. Close the initiating chat during a durable job, restart its worker, and submit a duplicate business key. An unchanged retry finds the original job; different work under the same key conflicts. Change a source version before a queued write and verify the job rechecks its evidence. Remove workspace access before another queued effect and verify that it stops. Preserve unknown external outcomes for reconciliation. +4. Exercise a separate existing operation with a real API-mandated approval or quote. Verify that the client receives the same requirement as an equivalent authorized API caller, and that it cannot cause the effect without satisfying that requirement. After the authorized approver records a decision at the owning API, check `execute({runId})` only observes. Explicit `execute({runId,resume:true})` can finish the exact approved outstanding step and continue the saved checkpoint. If the API applied it already, the run must reuse that receipt without another effect. Race two explicit resumes and independently verify one effect under the original decision. Record real host-imposed prompts separately from API decisions. Publish only sanitized task outcomes, receipt references, interruptions and cost per verified case. +5. Designate one of two valid handbooks in the same fixture organization. At initial dispatch and after restart, supply the other handbook, a different tenant's reference, a changed version and a withdrawn source. Each affected action stays pending or denied with zero writes. The originally designated, currently authorized version resumes successfully. Run an inline assignment separately to verify ordinary one-off work starts directly after sign-in. diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md new file mode 100644 index 000000000..36cccea6e --- /dev/null +++ b/docs/plans/mcp-code-mode-baseline.md @@ -0,0 +1,60 @@ +# Recoup MCP migration baseline + +Measured November 27, 2026 from API main `ff33a113d3fcb40813b41b61007ebc724b199e51`. The full delegated catalog contained 95 descriptors, including 94 visible to the model. The legacy SDK returned **32,466 reference tokens** of descriptor JSON. The modern adapter returned **31,971** for the same names. Both figures are historical measurements of the existing named registries at the pinned source revision. A host can defer descriptors, reformat them, truncate them or cache prompt prefixes. Actual first-turn model input and billed tokens require host or provider telemetry. [API revision](https://github.com/recoupable/api/tree/ff33a113d3fcb40813b41b61007ebc724b199e51) · [Full catalog test](../../lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts) + +## Measured discovery sizes + +Each cell gives UTF-8 bytes / tokens. The payload is compact JSON of `{"tools":[…]}`, before HTTP compression. “Visible” removes the one explicitly app-only tool. The selected-context profile has no gallery. Both credentials in the standard row share a registry. The ingestion flag adds one multi-operation descriptor. The development-only entitlement calculator was disabled in every row. + +| Registry | Registered / visible | Legacy, full | Legacy, visible | Modern, full | Modern, visible | +| --- | ---: | ---: | ---: | ---: | ---: | +| Standard API key or Privy | 84 / 83 | 106,087 / 29,580 | 105,417 / 29,422 | 145,838 / 44,243 | 145,203 / 44,092 | +| Standard, ingestion enabled | 85 / 84 | 107,132 / 29,783 | 106,462 / 29,625 | 154,509 / 47,058 | 153,874 / 46,907 | +| Limited personal OAuth | 8 / 7 | 4,864 / 1,236 | 4,194 / 1,078 | 4,584 / 1,189 | 3,949 / 1,038 | +| Full OAuth | 95 / 94 | 114,407 / 32,466 | 113,737 / 32,308 | 111,082 / 31,971 | 110,447 / 31,820 | +| Selected-context OAuth | 27 / 27 | 32,293 / 10,832 | 32,293 / 10,832 | 31,348 / 10,696 | 31,348 / 10,696 | + +The November 29 **design fixture** advertises exactly `search` and `execute` in both profiles. The compact `tools/list` result measures **3,697 bytes / 937 tokens** for read-only execution and **4,456 / 1,110** for action-capable execution. The latter is 96.5% smaller than the historical 31,820-token full OAuth model-visible list. These figures cover tool descriptors alone. On a qualified native Skills host, separately measure the full `skills/list` manifest bytes on the wire and the tokens for authorized names and descriptions exposed to the agent before its first prompt. Record host instructions and total first-turn input where observable. Verify zero startup reads of `SKILL.md` or packaged files. Measure fallback search previews and later file reads in the turn that requests them. [Proposed descriptors](mcp-code-mode-tools.json) · [Wire fixture verifier](verify-mcp-code-mode.py) + +The connected Codex Recoup connector independently exposed 94 tool names in this session. Its compact JSON array of host-normalized names, descriptions and TypeScript declarations occupied 73,648 bytes. This observation provides a host-side inventory check. Model input telemetry was unavailable. The public protected-resource document returned the canonical MCP audience and the three published scopes. The public Docs discovery card independently advertised a documentation-only MCP with two tools. [Resource metadata](https://api.recoupable.dev/.well-known/oauth-protected-resource/mcp) · [Docs server card](https://docs.recoupable.dev/.well-known/mcp/server-card.json) + +### Reproduce the figures + +1. Use the API revision above and its locked dependencies. The legacy client/server use `@modelcontextprotocol/sdk` 1.26.0. The modern server uses `@modelcontextprotocol/server` 2.4.0. Start from the working `fullOAuthCatalog.test.ts` fixture, its mock providers and linked in-memory transports. Register the actual callbacks without invoking them. +2. Apply the route's registration composition. Use `registerAllTools` for standard, `registerOAuthTools` for limited and `registerFullOAuthTools` for full. Pass `"selected_context"` to the full registrar for selected grants. For all except selected add `registerRecoupExtension` and `registerRecoupSkillsTool`. For standard use `INGESTION_ENABLED=false` and then `true`. A direct limited registry test that adds only the extension omits the production route's skills fallback. [Route](../../app/mcp/route.ts) · [Limited scope mapping](../../lib/mcp/oauth/limitedOAuthToolScopes.ts) +3. Legacy measurement uses `await client.listTools()`. For modern measurement pass the same registration callback through `createModernRecoupHandler`, using its native skills flag for all except selected. Issue a local Fetch request using the request fixture's `2026-07-28`, `Mcp-Method: tools/list`, client capabilities and protocol-version metadata. Follow all cursors and append returned tools in order. Each measured profile fit on one page. The local harness used synthetic auth info, an empty skills directory and a placeholder HTML resource body. Discovery with either transport reads no gallery HTML or skill file contents. The existing full OAuth test and both profile measurements passed without a business call. [Modern adapter](../../lib/mcp/skills/createModernRecoupHandler.ts) · [Modern request fixture](../../app/mcp/__tests__/oauthRoute.test.ts) +4. For each list serialize `JSON.stringify({tools})`, without whitespace or a trailing newline, and measure `Buffer.byteLength(serialized, "utf8")`. Count `len(tiktoken.get_encoding("o200k_base").encode(serialized))` with tiktoken 0.14.0. Repeat after filtering descriptors with `_meta.ui.visibility` equal to `["app"]`. The full-OAuth SHA-256 digest before filtering was `72de73a133c6160d6d2b182bad87830449be60b4eec2bd8cc4813e45f2fc8264` for legacy and `7c5a1d3f87498bc6a3ce4a43a693c4e67cd6e86d3d7281bcb49eb8f6cbce164a` for modern. Digests preserve SDK property order. + +## Current callers and authorization + +- **Remote business MCP.** `/mcp` verifies a bearer as delegated OAuth, Privy or an API key. It selects the catalog based on the verified credential, grant and selected context. The legacy and modern adapters are dispatched by protocol headers. The full delegated adapter strips caller owner input, validates inputs, rechecks client/grant/account and scopes, and separately applies task, catalog, organization, recipient and room checks. It mints account-bound video locators and returns only authorized task-run fields. Current full OAuth budgets are 120 calls per account and 30 per account/tool each minute. In a code program these limits must apply to each underlying operation as well as any outer execution quota. [Authorization](../../lib/mcp/verifyApiKey.ts) · [Full registration](../../lib/mcp/oauth/registerFullOAuthTools.ts) · [Preparation](../../lib/mcp/oauth/prepareFullOAuthTool.ts) · [Execution](../../lib/mcp/oauth/executeFullOAuthTool.ts) · [Rate limits](../../lib/mcp/oauth/checkFullOAuthRateLimit.ts) +- **Limited and selected grants.** Limited discovery contains five personal business tools, a skills tool and two gallery launchers. Scope challenges and execution enforce three read and two write capabilities. The selected-context grant has 27 frozen Context actions, current selected organization authorization, and separate data projections. A new catalog entry must never expand this consent. Standard-only ingestion, credential export, registration preflight, professional roster, streams/tracking and retained-evidence/case operations require explicit treatment. [Limited adapter](../../lib/mcp/oauth/registerOAuthTools.ts) · [Selected actions](../../lib/oauth/selectedContextActions.ts) · [Selected authorizer](../../lib/mcp/oauth/createSelectedContextAuthorizer.ts) · [Full registry exclusions](../../lib/mcp/oauth/registerFullOAuthTools.ts) +- **REST.** `validateAuthContext` requires exactly one of a REST API key or bearer authentication and implements account override and organization checks. Its bearer branch resolves the Privy account. MCP OAuth validation and the MCP resource audience live at a different boundary. The direct connection should invoke the API-owned operation as the signed-in Recoup account through a supported authentication path. Preserve the API's existing resource checks and response projection. Each token stays bound to its intended audience. Ordinary connection setup does not require a new company identity or operator-provisioned credential. [REST authentication](../../lib/auth/validateAuthContext.ts) · [Resource-bound access](../../lib/oauth/resolveOAuthAccess.ts) +- **Native Recoup app.** The canonical `POST /api/chat` starts a durable workflow. Each step builds the native nine-to-eleven-tool sandbox set, with optional skill and interactive question tools. Keeping this surface operational is a regression gate. Its startup prompt savings must be measured separately. [Chat route](../../app/api/chat/route.ts) · [Workflow turn](../../app/lib/workflows/runAgentStep.ts) · [Native tools](../../lib/agent/buildAgentTools.ts) +- **Other first-party agents.** Slack, evaluation and inbound-email paths reach the general agent. Its tool setup fetches the MCP catalog, merges independent Composio actions, then filters excluded names. Some multi-step routines force specific legacy tool names or models. Preserve equivalent operation restrictions inside the broker and test these callers when moving them off the legacy endpoint. Keep Composio's separate entitlements and precedence. Historical conversation tool calls and saved skills must remain interpretable. [General agent](../../lib/agents/generalAgent/getGeneralAgent.ts) · [Tool aggregation](../../lib/chat/setupToolsForRequest.ts) · [Named chains](../../lib/chat/toolChains/toolChains.ts) · [Slack](../../lib/slack/chat/handlers/handleSlackChatMessage.ts) · [Email](../../lib/emails/inbound/generateEmailResponse.ts) · [Evals](../../lib/evals/callChatFunctionsWithResult.ts) +- **UI, files and skills.** The MCP Apps resource `ui://recoup/explore.html` has a thread launcher and a separate app-only sidebar launcher. Both take an empty input. Their identities distinguish an active-chat handoff from starting a new chat. Host-supplied file parameters exist today on music analysis and release-pack asset upload. The modern server serves skills and resources, and older clients use `recoup_skills`. The main connection can project authorized staff skills. The dedicated staff route has its own access test and rejects selected-context grants. Count app-only launchers separately. Test uploaded-file binding, legacy hosts, staff audience and thread placement independently. Compare the legacy `recoup_skills` listing and file reads with the proposed direct `search` guide browsing and exact file retrieval under equivalent access. For native acceptance capture the host’s automatic, paginated `skills/list` discovery, the names and descriptions available before the first prompt, and the first file read after skill selection. Probe each installed host’s presentation separately. Retain the existing selected-context exclusions. [Gallery metadata](../../lib/mcp/extension/registerRecoupExtension.ts) · [Host bridge](../../ui/recoup/createHostBridge.ts) · [Music attachment](../../lib/mcp/tools/flamingo/registerAnalyzeMusicTool.ts) · [Skills fallback](../../lib/mcp/skills/registerRecoupSkillsTool.ts) · [Staff route](../../app/mcp/staff/route.ts) + +## Mapping business capabilities + +For each job a signed-in person performs, map the actual API operation, supported authentication, downstream provider and observable result. Record gaps in API coverage or OAuth projection before claiming parity. The proposed Recoup Records trial uses ordinary sign-in, runs a private correction-case write with the account's existing authorization, and reads it back independently. Use REST as the control on equivalent fixture data. [Label operating example](mcp-code-mode-autonomy.md) + +Generate searchable descriptors from stable OpenAPI operation IDs and reviewed domain adapters. Give each meaningful operation a stable ID that resolves to the API's existing authorization and domain handler, including Context actions that share a method and path. Document every former tool's input transformation, authorization, result projection, effects, migration status and owner before switching its cohort. A published REST operation is a candidate for review. The source-pinned Docs inventory also includes internal callbacks, preflight methods, pending and legacy operations. [Docs contract inventory](https://github.com/recoupable/docs/blob/873a1c93cf6ae0060702e38eba1b2715bb269f42/content/docs/contracts/operation-inventory.json) · [API qualification record](../mcp-oauth-tool-qualification.md) + +| Existing capability | API operation or adapter | Parity acceptance | +| --- | --- | --- | +| Roster, artist profile, saved posts and socials | `getArtists`, `postArtists`, `getArtistsByIdSocials`, `getArtistsByIdPosts` | Preserve personal-only versus accessible workspaces, account-bound creation and public result fields. Full OAuth artist creation omits conversation copying. [OAuth registration](../../lib/mcp/oauth/registerFullOAuthTools.ts) | +| Catalog song matching | Domain adapter over `analyzeFullCatalog`. REST `getCatalogsSongs` returns paged catalog rows. | Check authorized catalog access and the brief before AI matching. Preserve the disclosed provider fields, no Recoup credit deduction, at most 1,000 analyzed tracks and continuation via `nextPage`. Keep row retrieval as a separately reviewed operation. [MCP matching](../../lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts) · [REST catalog endpoint](../../app/api/catalogs/songs/route.ts) | +| Selected Context and records | REST `contextOperation` multiplexes actions. Delegated adapters split schemas and policy | Bind action server-side, keep the consent allowlist frozen, revalidate organization membership and omit standard-only retained evidence. Scope/identity denial must happen before storage or provider effects. [Context catalog](../../lib/mcp/oauth/contextToolOperations.ts) · [Consent actions](../../lib/oauth/selectedContextActions.ts) | +| Private catalog correction cases | **Observed legacy transport.** The existing `/api/context` route exports `POST`. Its request-body `action` selects case save, read or list. Standard named MCP reaches the same scoped processor. Current delegated MCP excludes all three. [HTTP route](../../app/api/context/route.ts) · [Action union](../../lib/context/catalogCaseOperationSchemas.ts) · [Current Context contract](../../lib/context/README.md#catalog-case-artifacts-catd-29) | **Proposed direct connection.** Provide separate catalog-case read, list and save operations as the signed-in Recoup account. Let the API enforce its existing ownership and revision rules. Qualify evidence, revision checks, idempotency and independent readback in [API #1316](https://github.com/recoupable/api/issues/1316). Bind these direct operations to the scoped domain processor in-process. Direct read/list therefore need no HTTP POST. New dedicated REST retrieval endpoints must use GET, and a new creation endpoint must use POST. Existing clients retain the observed legacy transport. [Case processor](../../lib/context/processCatalogCaseOperation.ts) · [OAuth qualification](../mcp-oauth-tool-qualification.md) | +| Social refresh and polling | `postArtistSocialsScrape` shares the business layer. The MCP wrapper adds an account-bound quote and limited result projection. | Quote → explicit maximum → one-time claim → read account-owned artist refresh batch. Preserve origin, batch and account checks plus returned public links and aggregates. Raw provider data, dataset IDs and REST deployment alone do not satisfy this path. [Quote handler](../../lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts) · [Result projection](../../lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts) | +| Release-pack lifecycle | `prepareReleasePack`, `getReleasePack`, `estimateReleasePack`, `generateReleasePack`, `retryReleasePack`, `exportReleasePack`, `uploadReleasePackAsset` | A GET of an expired running pack can settle work and refund held credits. Export updates state. Quote, spend, retry, private upload/finalize and export require individual effect classifications. Preserve host files, projected errors and existing-entitlement commerce behavior. [Pack manifest](../../lib/mcp/tools/packs/index.ts) · [Database-backed effects](../mcp-oauth-annotations.md) | +| Jobs, agents and notifications | `getTasks`, `postTasks`, `patchTasks`, `deleteTasks`, `getTasksRuns` and legacy daily email adapters | Creation/update can cause later spend and sends. A run lookup exposes only an owned, reduced projection. Test cancellation, replay and downstream effects, as well as immediate database changes. [OAuth policy](../../lib/mcp/oauth/fullOAuthToolPolicy.ts) · [Owned run adapter](../../lib/mcp/oauth/executeFullOAuthTool.ts) | +| Fan experiences and Sites | `getPlayers`, `postPlayers`, `patchPlayersById`, `getPlayersByIdFans`. Sites use `processSiteOperation` | Distinguish drafts, charged generation, public publication, plan-gated functionality, authorized private fan data, deletion and fan consent. Preserve revision/generation-token checks. [Players](../../lib/mcp/tools/players/index.ts) · [Site operations](../../lib/mcp/tools/sites/index.ts) | +| Messaging, files and media | `postEmails` plus MCP recipient/room checks, support messaging, public text/image generation, audio analysis, account-bound Sora video | Separate immediate delivery, paid analysis, public file creation and private artifacts. Preserve recipient restrictions, room ownership, host attachment projection and signed video locators. Control text returned to the model and sensitive fields crossing into provider requests. [Delegated preparation](../../lib/mcp/oauth/prepareFullOAuthTool.ts) · [Audio file schema](../../lib/mcp/tools/flamingo/analyzeMusicToolSchema.ts) · [Video locators](../../lib/mcp/oauth/executeFullOAuthTool.ts) | +| Credentials, billing, administration, integrations | Public OpenAPI includes routes such as `getAccountsByIdPaymentMethod`. The standard MCP also has credential-related behavior. | The delegated catalog deliberately excludes credential export, checkout and sandboxes. Default-deny unpublished, integration, staff, admin, secrets, callbacks and development-only operations. Record explicit entitlement decisions separately. [OAuth exclusions](../../lib/mcp/oauth/registerFullOAuthTools.ts) · [Commerce audit](../mcp-oauth-annotations.md) | + +## Review and release evidence + +Recoup's own OpenAI scan previously flagged a single empty-schema Context dispatcher that hid 27 operations. The repair exposed concrete schemas, corrected names and removed an unexpected conversation-copy input. Subsequent review work added social-refresh quotes, account-scoped results, bounded catalog matching and explicit annotations for deferred outbound effects. The November 26 review record describes an **unsubmitted publisher draft** and conditional missed-report commerce questions. Verify the publisher dashboard and deployed build before reporting the review state. [Context review repair](https://github.com/recoupable/api/pull/980) · [Social and catalog review repair](https://github.com/recoupable/api/pull/1297) · [Outbound effects and submission record](https://github.com/recoupable/api/pull/1299) + +The host matrix records earlier authenticated reads and writes in particular clients and grant configurations. Repeat actual installation, delegated execution, independent readback, cleanup, expiry, revocation and reconnect for the code-mode candidate and named host version. Verify an ordinary signed-in account can complete an already permitted private change without an additional prompt. For a separate operation with an existing API approval or quote, verify the same requirement and outcome through both interfaces. The cutover needs fresh evidence for the review account and the proposed tool shape. No code-mode business call, production change, submission or model billing measurement was made in this audit. [Cross-host acceptance](https://github.com/recoupable/mono/issues/215) diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md new file mode 100644 index 000000000..d99ec4117 --- /dev/null +++ b/docs/plans/mcp-code-mode-protocol.md @@ -0,0 +1,109 @@ +# Recoup MCP protocol compatibility and OpenAI review + +**Decision record for the proposed cutover, updated November 29, 2026.** Both direct profiles advertise exactly `search` and `execute`. The signed-in account uses `search` to discover authorized operations and guides and open the selected contract, guide or supporting file. `execute` runs permitted operations, observes status and explicitly resumes saved work. OpenAI's current Directory rules require each model-callable operation to appear independently for review. Submit a separate Directory endpoint generated from the same authorized operation definitions. Its proposed first release offers two music catalog operations. Expose each profile at a distinct, stable URL. Bind the public endpoint to its allowlist on every request, including resources, skills and UI calls. Keep the existing `/mcp` contract available through migration. [OpenAI Plugin Guidelines §6.2](https://developers.openai.com/plugins/plugin-guidelines#62-tool-independence-and-exposure) · [OpenAI tool design](https://developers.openai.com/plugins/plan/tools) + +## Wire contract + +The current revision is **2026-07-28**. At the inspected API source revision, Recoup already selects an SDK v2 handler for modern requests and an initialization-based handler for older clients. The API pins `@modelcontextprotocol/server` 2.4.0 and `@modelcontextprotocol/sdk` 1.26.0. Its lockfile resolves `mcp-handler` 1.1.0 against the latter. The upstream October 23 release is v2.4.0, alongside a separately maintained v1.32.2 release. The official v2 release also includes `server-legacy` 2.4.0 and the Node adapter 2.1.2. The code-mode change can reuse Recoup's existing transport split. Qualify a replacement transport in a separate change if one is needed. [Recoup route](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/app/mcp/route.ts) · [Recoup lockfile](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/pnpm-lock.yaml) · [SDK releases](https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/v2.4.0) · [v1.32.2](https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/1.32.2) · [MCP versioning](https://modelcontextprotocol.io/docs/2026-07-28/learn/versioning) + +| Area | Implementation and release evidence | +| --- | --- | +| Discovery and versioning | Implement modern `server/discover`. Test a direct `tools/list` as the first request, client discovery followed by a call, and an unsupported version returning `-32022` with supported revisions. Modern requests carry protocol version and client capabilities in `_meta`. Check the matching version header, method header and applicable name header. Return `resultType` on modern responses. Test `initialize` → `notifications/initialized` → list/call under each supported legacy revision. Record which revisions clients actually negotiate. [Version negotiation](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning) · [Streamable HTTP](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http) | +| Stable discovery cost | Keep `tools/list` deterministic for the same credentials and catalog revision. Return `ttlMs` and `cacheScope` on modern cacheable results. Mark grant-sensitive discovery, skill lists and resource reads private. Partition any application cache by authorization and revision. Respect revocation at execution even while a descriptor remains cached. Test two principals, differing scopes, changed grants, catalog drift, and extension-off discovery. Record serialized descriptor bytes and provider tokenizer counts separately from real host prompt usage. [Tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) · [Caching](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching) | +| Execution, effects and errors | Generate `execute` per authenticated profile. The read profile exposes only `recoup.read`. The account action profile also exposes `recoup.act`. The owning API can execute, deny, or require approval for an action. Record an API pause against the exact step. An authorized approver records the decision through the owning API. Where the API permits agent-assisted decisions, the approver signs in separately and invokes that domain operation through `execute`. If the API requires a human, use its trusted review interface. Explicit resume can finish the exact API-approved step. Compute all three hints from the union of reachable effects for each profile. A host may consequently prompt on a pure read sent through a write-capable descriptor. Keep `search` read-only in both profiles. Topic search returns typed operation and guide previews. Apply current API access and skill audience checks before ranking and pagination so hidden matches cannot affect counts or continuation. The same reader used by native and legacy clients checks current access again when opening a guide or one of its files. Route every nested business call through the API’s existing account and operation checks. Validate declared output schemas. Provide concise text and a compatible structured object for clients that need legacy shapes. Keep JSON-RPC errors distinct from domain/tool failures. [Tool results](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) · [OpenAI annotations and output schemas](https://developers.openai.com/plugins/reference) | +| Retries, cancellation and state | Use account-bound opaque application handles for continuation, approvals, jobs and receipts. The modern transport has no protocol sessions or SSE event replay. A dropped HTTP response stream cancels that request. Test cancellation before dispatch, cancellation after a downstream commit, and retry with a new request ID. Allocate the action-run receipt before guest execution. Each effect has a separately claimed step key. On reconnect look up the receipt using the caller-known run request key. Authorize any explicit resume against the durable checkpoint, completed-step ledger and the account's current API authority. Provider uncertainty enters reconciliation before further dispatch. [MCP release changes](https://modelcontextprotocol.io/specification/2026-07-28/changelog) · [Cancellation](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/cancellation) | +| Host interactions | Modern elicitation is multi-round-trip. A server can return `input_required` and request a form or URL interaction when supported. Clients retry with responses, opaque state and a new JSON-RPC ID. Responses may be declined or canceled. For an ordinary API-permitted action, return its result directly. For an API-required decision, surface the owning API's authenticated approval flow, with a Recoup URL fallback for text-only clients. An MCP input response by itself cannot satisfy an API requirement for independently recorded approval. Host confirmation policies still apply. Advertise subscriptions/progress only when implemented. [Multi round-trip requests](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr) · [Elicitation](https://modelcontextprotocol.io/specification/2026-07-28/client/elicitation) | +| OAuth | Verify issuer, expected resource/audience, expiry, grant, ownership, scope and current membership. Publish RFC 9728 protected-resource metadata and accurate issuer discovery. Use authorization code with PKCE S256, least privilege, the correct `WWW-Authenticate` challenge, and the exact callback from each host. Bind challenge metadata and token audience deliberately for each new URL. Qualify explicit aliasing or reauthorization for existing grants before moving traffic. Favor CIMD where supported. Maintain needed pre-registered clients and legacy DCR through measured migration. [Authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) · [ChatGPT auth](https://developers.openai.com/plugins/build/auth) | + +We checked the official full-text snapshot against the index on November 27. It contained all 31 indexed pages under the current specification, all ten indexed extension pages and all 27 indexed guides for the current revision. The snapshot also contains historical and draft material. Pin normative implementation tests to the dated revision. [Full documentation export](https://modelcontextprotocol.io/llms-full.txt) · [Documentation index](https://modelcontextprotocol.io/llms.txt) + +Use the official revision index for the base protocol, transports, authorization, resources, prompts, tools, patterns, utilities and schema. Prompts and resources can carry optional workflow help and artifacts. Direct hosts can use `search` and `execute` without preloading guides or resource bodies and without negotiating a resource extension. Use `execute` for observing and resuming runs. A separately named `resume` tool is outside the standard direct profile. Roots, sampling, logging, legacy HTTP+SSE and dynamic client registration are deprecated in the current revision. The newer draft adjusts CIMD references and input-request metadata. Track changes against released revisions and separately pinned compatibility tests. [Specification index](https://modelcontextprotocol.io/llms.txt) · [Released changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog) · [Draft changelog](https://modelcontextprotocol.io/specification/draft/changelog) + +## Direct action and recovery contracts + +Sign in to Recoup once through the existing account connection. A direct client uses the account's API authority subject to its connection scope. Resolve the authenticated account from verified server context and pass its identity through the API's existing authorization path. Keep credentials outside guest code. New catalog entries become discoverable under their applicable API and connection permissions after qualification. The owning API checks membership, resource access and any operation-specific constraints when receiving each read, action, continuation or delayed dispatch. If delayed work cannot run under current account authority, report the API's reconnect or denial outcome. The MCP adapter can bound code or results and journal retries. Business permission decisions and approval evidence belong to the owning API. The same account can use a personal or organization workspace without an additional agent enrollment. [Recoup account resolution](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/lib/mcp/resolveAccountId.ts) · [Recoup API authentication](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/lib/auth/validateAuthContext.ts) · [Existing paid-operation contract](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/lib/content/packs/buildReleasePackQuote.ts) + +| Call | Observable behavior | +| --- | --- | +| `search({query})`, `search({id})` or `search({cursor})` | A topic or cursor returns up to eight authorized previews in a shared page. An operation preview has `id`, `summary`, `effect` (`read` or `write`) and optional contract `detail`. A guide preview has `skill` and `summary`. Pass its exact name to `search({skill})` to open it. An exact ID can match both a guide and an operation. Only the operation can carry contract detail. A scoped cursor continues the original page. | +| `search({})` | Browse accessible guide previews, with an opaque continuation cursor when another page exists. Search discovery returns `revision`, `items` and optional `nextCursor`. Guide and resource bodies load only on an explicit read. | +| `search({skill})` or `search({skill, file})` | Read the named `SKILL.md` or one packaged supporting file. Use the same audience check, verified manifest and reader as legacy `recoup_skills` and optional native skills. Return structured `{revision,guide:{skill,file}}` with the content once as bounded MCP text or an embedded binary resource. Recheck access at retrieval. Reading a guide produces zero business effects. | +| Read-only `execute({source, revision, params})` | The sandbox exposes `recoup.read(id, args)`. It can combine and project results. A guessed write ID or `recoup.act(id, args, {requestKey})` call has no effect. Read-only run status uses `execute({runId})` when a corresponding read receipt exists. | +| Account action `execute({source, revision, requestKey, params})` | The client chooses and retains a stable run request key **before** starting the program. The supervisor persists the receipt and binds the key to the signed-in account, its connection grant, the profile and digest of source, parameters and revision. A repeat returns that run or a conflict. Reusing the key never starts a second program. | +| Guest `await recoup.act(id, args, {requestKey})` | Each action has a stable step key distinct in purpose from the run key. Claim the step under its run and bind it to the exact operation and canonical arguments. Same key and same work returns the first receipt. Different work with a claimed key conflicts. Route the step through the owning API with the current account context. Honor its permission checks, refusal and approval requirement. The owning API must atomically reserve the applicable shared budget before admitting a paid effect, including concurrent steps in separate runs. Dispatch an allowed action immediately. Mirror any API pause before the action takes effect. | +| `execute({requestKey})` or `execute({runId})` | Return current authorized state without dispatch. A client that lost its very first response can use its original run request key. Preserve successful prior effects and identify uncertain effects even if the guest later failed. An uncertain provider result blocks a dependent effect until reconciled. | +| `execute({runId, resume:true})` on an action-capable profile | Load the persisted checkpoint and exact parked step. Recheck the account’s access, decision, expiry and current business terms at the owning API. If it approved the step and completion is outstanding, atomically claim that single step and call the API with its recorded inputs and original effect key. If the API already applied the effect, use its receipt and skip dispatch. Pending or denied approval, revoked access or an unknown outcome cannot trigger dispatch. Return the outstanding requirement or reconciliation status. Continue a versioned workflow or restart-safe program only from its recorded step IDs and results. Accept only the run ID and resume flag. A short-lived JavaScript isolate without a recoverable checkpoint returns its recorded status. | + +**Receipts after guest exit.** Once an action run is admitted, every output includes its server-issued `runId`, including a completed computation, partial response or guest failure. Before admission, return an MCP tool error with `isError: true` and a single text content block containing a bounded JSON object with `code`, `retry` and `traceId` (up to 1 KiB encoded). Omit `structuredContent` because there is no admitted run. Transport authentication and malformed JSON-RPC keep their protocol error paths. Every structured result of action-capable `execute` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The owning API retains the exact paused action and its decision. The client uses the run ID for status and explicit resume. Program execution can return the guest's bounded result in `value`. On an authorized status lookup by run ID or original request key, `value` is reserved for a broker-owned projection of the durable step ledger. Build it independently of guest output. Return `{"steps":[...]}` in stable step order, with at most 16 entries for that short run. Each entry has a server-issued opaque `stepId`, step `state` and opaque `receiptRef`. Include an opaque `readbackRef` when evidence is available. A reference is a locator for an authenticated Recoup read. Recheck access on every lookup and dereference. Exclude raw provider bodies, credentials and signed delivery URLs. If access to a step is withdrawn, deny or redact the affected read according to its current policy. Long-running workflows own the list of bounded child runs and their evidence. + +For the recovery test, seed two permitted internal actions. Save the first, queue the second, then throw from the guest and drop the response before the agent learns the run ID. In a new session, recover with the original run key. Verify the same durable run ID, the recorded state of each step and independently reopened evidence for the first. If the provider outcome of the second is unknown, preserve that status and prohibit redispatch pending reconciliation. Repeat the lookup after the worker records the outcome. Assert that neither status query launches another program, duplicates either business effect or trusts the guest's claimed result. The local fixture checks the projected payload against two independently supplied ledger entries. The integration gate exercises actual dispatch, dropped transport and readback. + +Sign in with an existing test Recoup account. In a disposable workspace, run an ordinary permitted action through the direct interface, then independently read back its effect. Compare an API denial and an API-required approval through MCP and the owning API's normal entry point. Race two permitted steps whose combined cost exceeds the remaining budget. Verify the API admits only work covered by its atomic reservation, and inspect the recorded spend and effect count independently. Check one effect when the first response is dropped. Repeat with two identical retries, a conflicting step payload, two concurrent resumes and the account's access revoked between steps. On the standard profile, verify `execute({runId})` dispatches zero effects before and after the API receives a decision. Resume fixtures where the API applied the approved change itself and where it requires exact completion. Verify the first adds zero dispatches and the second adds one, even when a retry and another explicit resume race. Pending, denied, revoked, expired, altered and unknown outcomes must never dispatch the parked effect. Independently verify both the change and the durable continuation. Capture actual host prompts separately from API decisions. These cases verify behavior beyond the JSON Schema examples. [Descriptor examples](mcp-code-mode-tools.json) · [Local verifier](verify-mcp-code-mode.py) + +## Extension adoption + +Negotiate each optional extension using the peer's advertised capabilities. Test mixed discovery, guide browsing and exact file retrieval and the full core read journey with all optional features absent. The protocol's community client matrix is a starting point for test selection. A release receipt records the actual host build, capability declaration, protocol revision, account/grant, deployed SHA and outcome. [Extension stages](https://modelcontextprotocol.io/extensions/overview) · [Client matrix](https://modelcontextprotocol.io/extensions/client-matrix) + +| Feature and upstream stage | Recoup disposition and acceptance | +| --- | --- | +| MCP Apps, stable | Provide a plain-text result when a client cannot display the component. Where an actual workflow benefits from UI, link a versioned registered resource using `_meta.ui.resourceUri` and `text/html;profile=mcp-app`, restrict component CSP, and return only view-specific metadata to the component. Exercise thread and app-only entrypoints separately. Keep the first Directory release to the two named catalog reads. Qualify the existing gallery separately against the workflows its entrypoints advertise. [MCP Apps](https://modelcontextprotocol.io/extensions/apps/overview) · [OpenAI reference](https://developers.openai.com/plugins/reference) | +| OAuth client credentials and enterprise-managed authorization, stable | The cutover uses the existing account connection. Interactive OAuth uses authorization code with PKCE. Machine credentials and enterprise management are independent optional extension capabilities. Test the actual login, refresh, revocation, and reconnect path. [MCP auth extensions](https://modelcontextprotocol.io/extensions/auth/overview) · [OpenAI authentication](https://developers.openai.com/plugins/build/auth) | +| Skills over MCP, beta | On an eligible connection, a qualified native host automatically prepares the model-facing skill inventory described below. Direct `search` also lets hosts browse or open a guide or selected packaged file. Use the same audience and verified manifest across both paths. Retain the selected-context exclusion. Test revocation between discovery and retrieval. Directory’s two public tools remain the named catalog reads. Qualify any skills included in the reviewed package separately. [Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup native handler](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/lib/mcp/skills/createModernRecoupHandler.ts) | +| Tasks, beta, intended for core | Adapt durable Recoup job receipts to the current Tasks extension on supporting hosts. Test `tasks/get`, terminal success/failure, expiration, authorization, and supported mid-flight input via `tasks/update`. Keep a bounded domain status read for other clients. The 2025-11-25 experimental task wire contract differs from this extension. [Tasks](https://modelcontextprotocol.io/extensions/tasks/overview) · [Protocol changes](https://modelcontextprotocol.io/specification/2026-07-28/changelog) | +| Server Cards and Events, beta | Cards can publish public server identity and connection metadata. Keep grant-scoped inventories behind authentication. Treat subscription to upstream events as a separately authorized feature with explicit destination, lifecycle and delivery requirements. ChatGPT documents a webhook-specific events implementation. A stable launch can rely on ordinary reads and status receipts. [Server Cards](https://github.com/modelcontextprotocol/ext-server-card) · [Events](https://modelcontextprotocol.io/extensions/events/overview) · [OpenAI MCP events](https://developers.openai.com/plugins/build/mcp-events) | +| Interceptors, variants, tool annotations, file uploads, filesystems, experimental | Track prototypes and pin isolated experiments to upstream commits. Keep reviewed profiles, permission checks, effect controls and attachment access in Recoup's implementation. General-purpose extensions do not make a hidden operation eligible for public distribution. [Experimental extension registry](https://modelcontextprotocol.io/extensions/overview) | + +### Native Skills before the first task + +On a fresh authenticated connection, a host qualified for **upfront native Skills** checks the server’s `io.modelcontextprotocol/skills` and `resources` capabilities and follows every `skills/list` cursor automatically. Recoup must enumerate the complete inventory for that account and audience. Upstream allows a partial or empty listing and requires loading by a known URI. Each listed entry carries frontmatter and a file manifest with URIs, sizes and digests, or a dynamic-resource marker. For Recoup’s static bundle the host can hold the complete manifest privately. Before accepting the first task, it makes each authorized skill’s **name and description** available to the model. The first model invocation can select a relevant skill without calling `search`. No full instructions or supporting-file bytes enter discovery or model input at startup. Activation reads the selected `SKILL.md` through `resources/read`; read each supporting file only when needed, recheck authorization and verify its manifest entry. The host owns presentation, consent and instruction activation. [MCP Skills transport and pagination](https://github.com/modelcontextprotocol/ext-skills/blob/main/specification/beta/skills.mdx#listing-skills) · [Agent Skills progressive disclosure](https://agentskills.io/specification#progressive-disclosure) + +Pair a time-ordered native request trace with a sanitized capture of the actual model-facing registry and first input. Check an authorized guide from the last page, a staff-only exclusion, zero startup resource reads, and zero model search before selection. Then request one guide and one specific supporting file, verify their bytes and check that unrelated files stayed unread. Repeat after changing account, revoking access or changing the catalog revision. A wire trace proves delivery to the client. A menu screenshot records what the person could see. For hosts that hide model inputs, use a fresh synthetic catalog with randomized canaries on each page and a prompt containing none of their names. Demonstrate pre-search recall and selection of the last-page canary, compare negative controls, and label the evidence behavioral. Keep any host without enough evidence for the claimed audience on the direct-search fallback. [Existing native server tests](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/app/mcp/__tests__/oauthRoute.test.ts) · [Offline trace cases](mcp_code_mode_startup_cases.py) + +**Measured November 29 on the pinned Recoup Skills bundle.** The local API SDK 2.4.0 served `skills/list` over in-memory Fetch with the packaged audience rules and 100-entry pages. List bytes below sum compact JSON `result` objects. The model-facing projection is compact JSON containing only `name` and `description` per skill, in SDK order. These are reproducible reference costs. The installed host chooses its own framing. The direct tool descriptors cost a separate 937 read-only or 1,110 action-capable tokens. Report the host’s actual first-turn input, including server instructions and any deferred tools, for each qualified configuration. [API bundle pin](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/scripts/mcp-skills/build.mjs) · [Audience and pagination](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/lib/mcp/skills/getRecoupSkills.ts) · [Descriptor measurements](mcp-code-mode-baseline.md) + +| Authorized catalog | Skills | Pages | List result bytes | Projected UTF-8 bytes | Projected `o200k_base` tokens | +| --- | ---: | ---: | ---: | ---: | ---: | +| Customer | 47 | 1 | 130,001 | 23,796 | 4,966 | +| Staff-only connection | 85 | 1 | 285,047 | 46,503 | 10,105 | +| Staff-entitled combined connection | 132 | 2 | 415,158 | 70,298 | 15,069 | + +To reproduce, check out API `906b60faab8662fe5955d43fefe2b7568dea6f19`, install its lockfile and run `pnpm build:mcp-skills` for Skills `fd3325e0a75518be2f647ab81585c0bd48b9514c`. For each audience (`public`, `staff`, `all`), attach `await getRecoupSkills(audience)` to a local SDK `McpServer` inside `createMcpHandler`. Use the API test’s modern Fetch request with method `skills/list`, revision `2026-07-28`, and each returned `nextCursor` as the next `cursor`. Sum `Buffer.byteLength(JSON.stringify(result))` across pages. Flatten all returned `skills` in order and serialize `entries.map(({frontmatter: {name, description}}) => ({name, description}))` with `JSON.stringify` and no trailing newline. Count the UTF-8 bytes and `tiktoken==0.14.0` `o200k_base.encode_ordinary` tokens. The separate offline verifier uses two synthetic skills to exercise the startup trace. [Pinned source catalog](https://github.com/recoupable/skills/tree/fd3325e0a75518be2f647ab81585c0bd48b9514c/skills) · [Local Fetch request](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/app/mcp/__tests__/oauthRoute.test.ts#L135-L166) · [Verifier](verify-mcp-code-mode.py) + +Claude Code documents a 100-skill per-server display limit and support that depends on version, plan, session and settings. The current Recoup build checks customer and staff-only counts separately. Its combined catalog has 32 entries beyond that documented limit. Qualify each connection and audience independently, including what the model can see, with direct `search` available for missing previews. The server’s ability to serve page two does not prove a client consumed or exposed it. [Claude Code availability and limits](https://code.claude.com/docs/en/mcp#mcp-skill-limitations) · [Recoup build guard](https://github.com/recoupable/api/blob/906b60faab8662fe5955d43fefe2b7568dea6f19/scripts/mcp-skills/build.mjs) + +## Host acceptance + +| Surface | Evidence required before claiming support | +| --- | --- | +| Protocol fixtures and Inspector | Run pinned upstream conformance and project-specific tests against both wire eras, both profiles and the retained legacy URL. With extensions disabled, verify that both read-only and action-capable profiles advertise exactly `search` and `execute`. A text-only client must complete topic discovery, exact guide retrieval and an API read. Record raw sanitized discovery, tool list, schemas, auth challenge, effect results, and unsupported-version response. Exercise cancellation, concurrent grants and result bounds. [Official conformance suite](https://github.com/modelcontextprotocol/conformance) · [Inspector](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector) | +| ChatGPT custom connection and public Directory | Connect the direct and named-operation profiles separately during testing. Open a fresh conversation after a custom-server refresh. Verify installed public tools and actual list/call/readback on ChatGPT web, and on desktop for advertised UI entrypoints. Reauthorize, revoke and reconnect a synthetic account. Test catalog workflows in the packaged Directory build, including negative selection and component-free results. [Connect and test](https://developers.openai.com/plugins/deploy/connect-chatgpt) | +| Codex, Claude Code, Claude Desktop and Cursor | Exercise real client builds for the surfaces Recoup claims. Record mixed topic search, operation lookup, authorized reads and multi-operation composition. Open a guide using its preview in `search({skill})` and test guide browsing with `search({})`. On a host with native skills support, compare the accessible guidance through both interfaces. On an account action profile, exercise an ordinary API-permitted write after existing account login, a denial, and an API-required pause. Compare the results with the same operations through the API. Record actual host prompts, the result of a lost-response status lookup and independent readback. Verify exact host boundaries and token limits on each client. Account for different UI, consent, proxy headers, model capability and retry semantics. [Compatibility rules](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning) · [Recoup existing host acceptance](https://github.com/recoupable/mono/issues/215) | +| Recoup-controlled model clients | Benchmark named tools eagerly loaded, named tools with host deferred loading, and direct code mode on identical workloads. In supported OpenAI Responses API models, enable `tool_search` plus `defer_loading: true` on the MCP connection. Capture actual provider token usage, task success, wall time and tool calls by model version. Report a descriptor-size proxy separately where a host withholds prompt telemetry. [OpenAI tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) · [MCP host best practices](https://modelcontextprotocol.io/docs/2026-07-28/develop/clients/client-best-practices) | + +## Directory review and release + +The review candidate offers `select_catalogs` and `select_catalog_songs` as two independently named read operations. Give each an accurate title, purpose, schema, error contract and explicit `readOnlyHint: true`, `destructiveHint: false`, `openWorldHint: false` for the bounded catalog workflow. Derive identity from the grant. Song selection currently sends the brief, track titles, artist names and ISRCs to an AI provider. It analyzes up to 1,000 tracks per call and can return a continuation. Its description states there is no Recoup credit deduction. Provider processing and repeat costs still need verification for the production review build. Explain provider processing in the consent flow and privacy policy before the first search. Bound the search and verify that the result makes no claim of licensing clearance. Qualify a narrow catalog-read OAuth scope for the Directory connection through normal account sign-in. The existing `mcp:read` scope excludes these two operations. Enforce the same catalog ownership and resource access checks as the API. Preserve semantic matching separately from the tabular REST catalog-song read. [Current song tool](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts) · [Tool qualification](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-oauth-tool-qualification.md) · [OpenAI guidelines](https://developers.openai.com/plugins/plugin-guidelines) + +### Proposed reviewer fixtures + +Seed one reviewer-owned catalog named **Northstar Demo**, one empty catalog and a second isolated tenant. Seed synthetic tracks, including well-characterized instrumental and vocal fixtures, and enough records for a real continuation when claiming pagination. Use original or cleared fixture data. Supply actual seeded IDs in reviewer instructions. Execute every case with the exact package and account, then replace candidate expectations below with recorded outcomes. [OpenAI review information](https://developers.openai.com/plugins/deploy/submission#complete-review-information) + +| Case | Reviewer prompt | Expected behavior | +| --- | --- | --- | +| Positive 1 | “Which Recoup catalogs can I search?” | `select_catalogs` lists the two account-authorized fixtures and returns their names and IDs. | +| Positive 2 | “Find an instrumental in Northstar Demo matching this brief.” | Resolve the named catalog with `select_catalogs`, then `select_catalog_songs` yields real fixture IDs from that catalog. | +| Positive 3 | “Using this Northstar Demo catalog ID, find tracks with vocals.” | `select_catalog_songs` operates independently with the supplied fixture ID. Verify every returned ID belongs to the requested catalog. | +| Positive 4 | “Check the next set of tracks for the same brief.” | Use the continuation from the preceding seeded large-catalog call. Verify the next search window, result membership and final completion. | +| Positive 5 | “Find a matching track in my empty demo catalog.” | Return the empty result accurately. No unrelated catalog, fabricated track or rights claim. | +| Negative 1 | “Read tracks from this other workspace's catalog ID.” | A scoped rejection protects the other catalog and its rows. | +| Negative 2 | “Publish this shortlist and email it to the label.” | Explain the read-only listing boundary. No write, generated program, public URL or external send. | +| Negative 3 | “Run code through Recoup to purchase credits for me.” | No executor or checkout surface. No purchase, outbound call, or escalation of the grant. | + +### Submission sequence + +1. Inspect the owning organization's current Recoup plugin, package version, connected endpoint, pending review and permissions. Keep the published scheme, host and port when changing the Directory endpoint path on an existing listing. A change of origin requires a new plugin. If an existing version is published, keep it available during replacement review. Verify the actual status of the previous draft in the publisher portal. Verify the publisher identity. The operator needs `api.apps.write` to submit and `api.apps.read` to inspect status. Keep a release manifest containing package version, commit, endpoint, OAuth resource and schema hashes. [Submission](https://developers.openai.com/plugins/deploy/submission) · [Review permissions](https://developers.openai.com/plugins/deploy/app-review) +2. Package the reviewed plugin ZIP, including its manifest, Directory connection in `mcp.json`, approved assets and optional bundled skills. The portal supports one connected server per plugin. Verify company/support and privacy URLs, listing text, logo, locales/availability and disclosures of data categories, processing recipients, retention and controls. Check that the submitted features comply with current restrictions on digital products, subscriptions and credit sales. [Plugin packaging](https://developers.openai.com/plugins/build/plugins) · [Submission requirements](https://developers.openai.com/plugins/deploy/submission) · [Privacy and commerce policies](https://developers.openai.com/plugins/plugin-guidelines) +3. Deploy a single production HTTPS Directory endpoint. Configure OAuth discovery and the exact portal callback, serve its domain challenge, upload the draft, connect, authenticate and scan. Compare the scan to the reviewed profile manifest, including any app-only tools. Resolve findings, reconnect and rescan the changed build. Keep connection secrets and reviewer credentials outside source control and the ZIP. [Portal setup](https://developers.openai.com/plugins/deploy/submission#connect-and-scan-your-mcp-server) · [OAuth](https://developers.openai.com/plugins/build/auth) +4. Enter the dedicated sample account and sign-in instructions in the portal's private review details. It must work without inaccessible MFA, email links, or private-network access. Supply all five positive and three negative recorded cases, release notes and an accessible video walkthrough. If using UI, verify approved resource URIs, constrained CSP, actual host rendering and any iframe justification. Confirm policy attestations with release authority. [Review information](https://developers.openai.com/plugins/deploy/submission#complete-review-information) +5. Submit the selected package. Capture the portal receipt, release version and submitted status. Track reviewer feedback, fixes and rescans separately. Approval enables an explicit publish action. Verify discoverability and installed behavior with a clean account after publication. Each outcome needs its own evidence. [Review process](https://developers.openai.com/plugins/deploy/app-review) · [Publish an approved plugin](https://developers.openai.com/plugins/deploy/submission#4-publish-your-approved-plugin) +6. Maintain the previous public implementation and argument schemas while continuous review processes updates. OpenAI calls the live endpoint using its stored definitions. Removed tools disappear upon detection, added tools appear after their checks pass, and a held change leaves the old definition in service. Use independent addition and deprecation windows. Changes to bundled skills or listing metadata require a new ZIP review. Capture the actual public definition and an installed-client smoke test after each release. [Continuous review](https://developers.openai.com/plugins/deploy/app-review#continuous-review-and-tool-updates) diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md new file mode 100644 index 000000000..dda6ea233 --- /dev/null +++ b/docs/plans/mcp-code-mode-research.md @@ -0,0 +1,71 @@ +# Code Mode research for the Recoup MCP cutover + +Reviewed November 27–28, 2026. Vendor measurements describe their workloads. The rollout needs matched Recoup measurements before assigning savings or retiring a capability. + +## Where the context goes + +A connection can incur three different costs. The client downloads `tools/list` over the wire, the host decides which descriptions and schemas enter the model prompt, and later tool calls add inputs, intermediate results and final output. A smaller manifest guarantees fewer advertised tools. Native Skills adds a separate startup exchange. A qualified host can receive the complete authorized file manifests while projecting only each skill’s name and description into the agent’s initial context. Record those metadata tokens separately from the 937/1,110 read-only/action tool descriptor measurements. The tokenizer, client deferral, discovery depth and workflow determine the actual savings. A search result that returns an entire OpenAPI document can consume the tokens saved at startup. + +Cloudflare's original experiment converted MCP definitions to TypeScript signatures, supplied them together, and ran model-authored programs in network-isolated workers with host callbacks. A dependent read could pass its result directly to the next call. Its subsequent public API server moved discovery behind `search` and used `execute` with an authenticated HTTP client. Cloudflare reports roughly 1,000 tokens for the interface over an API with more than 2,500 endpoints. Recoup can use the same discovery principle with a broker that resolves reviewed operation IDs. The broker can dispatch each call into its owning API operation, where current account permissions, effect checks and response rules already belong. [Original Cloudflare experiment](https://blog.cloudflare.com/code-mode/) · [Cloudflare API MCP server](https://blog.cloudflare.com/code-mode-mcp/) + +Anthropic describes a client-side alternative in which the agent browses generated tool modules, composes calls in code, and returns a projection. Its illustrated reduction from 150,000 to 2,000 tokens depends on that catalog and task. Its separate developer-platform work offers deferred search, programmatic tool calling and worked examples. Claude Code already defers most MCP definitions in supported configurations, initially loading tool names and server instructions. A fair baseline therefore exercises ordinary named Recoup tools with the host's usual deferral, including any existing single-call aggregate that solves the task. [MCP code execution](https://www.anthropic.com/research/code-execution-with-mcp) · [Advanced tool use](https://www.anthropic.com/research/advanced-tool-use) · [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) · [Claude Code tool discovery](https://code.claude.com/docs/en/mcp#scale-with-mcp-tool-search) + +## What Executor actually implements + +The source study compared `40be470` (CLI `2.0.0-beta.73`) with `95c6b6b` (CLI `2.0.0-beta.80`), the November 28 upstream `v2` head, 44 commits later. GitHub’s latest stable release was `v1.6.11`. The published npm beta we ran was `2.0.0-beta.79`, tagged at `b240a3e`. Its macOS arm64 runtime archive matched the SHA-256 in the npm launcher manifest. [Compared source revisions](https://github.com/UsefulSoftwareCo/executor/compare/40be47066a0c2803211acd618662901e77de9f25...95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf) · [Beta.80 source version](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/apps/cli/package.json) · [Stable release](https://github.com/UsefulSoftwareCo/executor/releases/tag/v1.6.11) · [Published beta.79 runtime](https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.0.0-beta.79) + +On November 28 the isolated beta.79 server negotiated MCP `2025-11-25` over Streamable HTTP. Native mode returned the five top-level tools `skills`, `search`, `describe`, `call` and `execute`. Default mode added `resume`. Compact `{"tools":[…]}` responses measured 8,015 bytes / 1,848 reference tokens in native mode and 9,671 bytes / 2,239 tokens in default mode. Both returned 2,200 UTF-8 bytes / 529 tokens of server instructions, measured separately using `o200k_base`. We deployed a synthetic app with a SQLite table and two operations. Top-level search found both. Three separate `execute` requests read an empty table, inserted one marker and read back that exact marker. The default top-level tool descriptors were identical before and after deployment. These measurements cover the local release and its disposable app. Recoup interoperability and actual host prompt cost need their own tests. [Release toolkit definitions](https://github.com/UsefulSoftwareCo/executor/blob/b240a3ef0444c4fe46be3fa9b8616308b9c00d30/packages/mcp/src/contracts/tools.ts#L21-L45) · [App-owned SQLite contract](https://github.com/UsefulSoftwareCo/executor/blob/b240a3ef0444c4fe46be3fa9b8616308b9c00d30/packages/app-templates/executor/skills/app-authoring/storage.md#L1-L46) + +Inside `execute`, a program can call `tools.search({query, namespace})`, page with `tools.search(next)`, and pass up to 20 exact paths to `tools.search.describe({paths})` for the full signatures. It invokes the returned app paths directly and can keep intermediate results inside the program. This discovery API adds no entries to MCP `tools/list`. The 20-path limit applies to a description request. A top-level `call` can also submit independent invocations in a batch and enforces a separate configurable limit, 100 by default in beta.79. [Program discovery and description limit](https://github.com/UsefulSoftwareCo/executor/blob/b240a3ef0444c4fe46be3fa9b8616308b9c00d30/packages/app-templates/executor/skills/code-mode/SKILL.md#L24-L60) · [Default call limit](https://github.com/UsefulSoftwareCo/executor/blob/b240a3ef0444c4fe46be3fa9b8616308b9c00d30/packages/mcp/src/contracts/execute.ts#L369-L378) · [Batch enforcement](https://github.com/UsefulSoftwareCo/executor/blob/b240a3ef0444c4fe46be3fa9b8616308b9c00d30/packages/mcp/src/implementation/execute.ts#L1584-L1594) + +| Source mechanism | Design implication for Recoup | +| --- | --- | +| V1 plugins compile OpenAPI into two representations. Tool definitions describe inputs and outputs. HTTP bindings retain method, path, parameters and serialization. A host invoker handles the sandbox's `{path,args}` requests. [Compiler and bindings](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/plugins/openapi/src/sdk/backing.ts#L196-L250) · [QuickJS bridge](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/kernel/runtime-quickjs/src/index.ts#L304-L331) | Generate discoverable declarations and server-only dispatch bindings from the same admitted artifact. Compare each generated request with its route contract, including nested parameter references, escaping, arrays and pagination. Check the actual response at runtime. | +| V1 resolves credentials after argument and policy checks. V2 groups tools by app/version and supports per-user account selection. Its OpenAPI builder filters for account availability and validates input, and its code-mode broker sends an account-bound call with a query/mutation classification. [V1 dispatch](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/core/sdk/src/executor.ts#L6788-L6865) · [V2 OpenAPI](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/apps/src/implementation/openapi.ts#L161-L208) · [V2 dispatch](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/mcp/src/implementation/execute.ts#L783-L814) | Bind the signed-in Recoup account and its selected organization outside guest code. The API checks current permissions for the selected operation and resource just as it does for a direct caller. | +| V2's native toolkit contains five tools. The default and browser toolkits contain six, adding an explicit resume path. In addition to skills and execution, they expose search, exact description and direct invocation. [Implemented toolkits](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/mcp/src/contracts/tools.ts#L21-L45) | Recoup proposes two direct tools. `search` returns operation and guide previews, exact contract details or a selected guide or packaged file. `execute` composes authorized API calls, observes status and explicitly resumes a saved checkpoint. Qualifying native clients automatically expose authorized guide names and descriptions before the first prompt and retrieve selected files on demand. Direct search supplies guide discovery and reading for other clients. | +| Executor patches its guest interpreter's lazy catalog and host search. Its source notes a profile in which preparing 1,000 tools cost 69% of an execution call. It counts rendered signatures and tests that dispatching a known operation renders zero. [Lazy catalog](https://github.com/UsefulSoftwareCo/executor/blob/40be47066a0c2803211acd618662901e77de9f25/patches/codemode-lazy-catalog.md) · [Host search](https://github.com/UsefulSoftwareCo/executor/blob/40be47066a0c2803211acd618662901e77de9f25/patches/codemode-host-search.md) | Precompile versioned indexes. Load detail and types for selected operations. Include a synthetic 10× catalog growth test and record signature render count, host CPU, prompt tokens and cold/warm time. A constant-size wire menu can still conceal O(N) work on every request. | +| Executor distinguishes timeout during discovery from timeout after guest code starts. The latter can follow completed external calls. [Timeout reporting](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/mcp/src/implementation/execute.ts#L1346-L1349) | Return the last durable dispatch state and an owned status handle. Record a separate state for an uncertain external outcome. Automatic retries require a safe method or provider-supported idempotency and reconciliation. | + +Another implementation, Kody, registers search, execute and a direct one-operation API call. It returns an original in-progress or retained run for a matching execution key. Use the same account, API checks and fixture state to qualify single reads and batches in Recoup. A future proposal for a named shortcut should show a measurable benefit in a supported host. In the proposed release, clients use `execute` for single and composed operations. The owning API decides whether each action can proceed or requires approval. [Kody registration](https://github.com/kody-hq/kody/blob/9d96cfb916552b889ee8989027618b35ecd554ba/packages/worker/src/mcp/register-tools.ts#L1-L12) · [Kody execution keys](https://github.com/kody-hq/kody/blob/9d96cfb916552b889ee8989027618b35ecd554ba/packages/worker/src/mcp/tools/execute.ts#L694-L755) + +## November 29 decision on the four proposed tool names + +Recoup's direct interface advertises `search` and `execute`. Approving a purchase, completing a saved effect, continuing a job and reading guidance each have a distinct outcome. They can share two model-facing entry points while retaining different permissions and API behavior. The failure modes below are design predictions to test with installed clients. + +| Extra name | Failure if omitted | Failure if added | Release test | +| --- | --- | --- | --- | +| `approve` | Finance may never discover a request or see its exact artist, destination, amount and expiry. A host with rules keyed by tool name may see only a generic execution request. | The requester may appear able to approve its own work. A host prompt could be mistaken for a business decision. Two approval stores can disagree. | A separately signed-in eligible approver can find and decide the exact request. The API rejects a wrong approver or changed amount. Human-only decisions open a trusted Recoup screen. | +| `resume` | An agent returning to a new chat might start over or sit waiting after approval. Without the run ID, the agent needs an authorized way to find stalled work. | A second continuation path can bypass rechecks, race the first or repeat a completed step. The name can imply any arbitrary JavaScript restarts where it stopped. | Close the chat and drop the response. Find the original run, observe without dispatch, then explicitly resume twice. Only the recorded next step may run. | +| `commit` | “Finish this approved purchase and stop” differs from “continue the rest of this campaign.” A failure to model that boundary can leave approved work stranded or start a later step the operator did not request. | The agent may call commit after approval already applied the purchase, or race a resume. A user may mistake “commit” for approval. | Exercise both API behaviors: apply-on-approval and complete-after-approval. Check one receipt and at most one purchase. Scope assignments to the authorized remaining work. A distinct one-step control needs a demonstrated client use case. | +| `skills` | A mixed search might hide the relevant guide below many actions. A host that auto-discovers guides through the native Skills extension may never use a custom search convention. | Two public discovery paths can rank differently, leak staff-only guide titles, or load the same guide twice. They can cause a model to guess which tool to try first. | On a native host, let the agent select a guide from its initial name and description without a search hint. On a fallback host, return the guide and operation for one release-review query. Open just the selected file. Exercise same-name matches, missing files and public/staff/selected scopes against the same reader. | + +**Current implementations.** The refreshed Executor v2 checkout is `ae95dcc` on November 29, six commits past the November 28 study. It exposes `skills`, `search`, `describe`, `call` and `execute`. Model, automatic and browser modes also expose `resume`. Native mode can continue in the client's interaction. Browser approval records a person's decision before resume collects it. Automatic mode can accept an app's requested confirmation subject to explicit denials and the client's permissions. Executor's separate `call` handles independent calls as JSON, while `execute` composes dependent operations and filters results. The registered interface reflects its delivery modes and many connected apps. No source comparison establishes the best number of tools for Recoup. [November 29 toolkit](https://github.com/UsefulSoftwareCo/executor/blob/ae95dcc1378a49ce41df3a3756a5fd3447a21083/packages/mcp/src/contracts/tools.ts#L21-L45) · [Executor call guide](https://executor.sh/docs/mcp/code-mode) · [Approval modes](https://executor.sh/docs/mcp/approval-modes) + +**Current protocol guidance.** MCP's client guidance describes on-demand discovery when catalog size warrants it and isolated programmatic calling for workflows with intermediate data. Each nested call gets the same applicable checks as a direct call. The standard leaves tool names and user interactions to the product and recommends giving people the ability to deny calls. A host may prompt on a broad `execute`. Record such prompts separately from API approval. The working group's proposed discovery groups and asynchronous approval proposal were still open on November 29. [MCP client guidance](https://modelcontextprotocol.io/docs/2026-07-28/develop/clients/client-best-practices) · [Core tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) · [Discovery draft](https://github.com/modelcontextprotocol/progressive-disclosure-wg/pull/19) · [Approval proposal](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2848) + +**Client and server evidence.** Cloudflare's November 25 code registers search and execute for API access, plus docs, identity and feedback tools. Its consuming runtime can pause before a selected action and resume after approval. Anthropic's experimental Claude Code mode runs on the client. Its automatic classifier checks the program before execution and cannot inspect every value computed during the run. A host-level confirmation alone cannot verify the artist, destination or amount a Recoup program later derives. The owning API must check those values at dispatch. [Cloudflare registrations](https://github.com/cloudflare/mcp/blob/66b361ed7c94153bb37a5d0c94874c860a86cb0c/src/server.ts#L78-L103) · [Cloudflare runtime](https://developers.cloudflare.com/agents/tools/codemode/mcp/) · [Claude Code permissions](https://code.claude.com/docs/en/code-mode#permission-checks) + +**Interoperability.** The current core revision is `2026-07-28`. Skills and Tasks are optional Beta extensions. Once the server advertises Skills, `skills/list` returns entries with frontmatter and a complete file manifest or a dynamic-resource marker. Recoup’s target for participating hosts is to page through that listing automatically, show the agent only permitted names and descriptions before its first prompt, then read a selected `SKILL.md` and any individually needed files through the host’s skill-loading path. The extension leaves timing, model presentation and activation to each client. Confirm these behaviors by installed host, version and configuration. Direct `search` provides guide browsing and opening where native Skills is unavailable. Native Tasks can inspect an accepted job, supply requested input and request cooperative cancellation. Tasks has no account-wide listing method. Keep the API's authorized job lookup, decision inbox, effects ledger and readback. MCP Apps is Stable for in-host review interfaces. Events and Server Cards are Beta for upstream notifications and public connection metadata. File transfer is still experimental. Stable machine-to-machine and enterprise authorization extensions serve other sign-in environments. Only qualify those capabilities when relevant to an actual client or workflow. On November 24 Anthropic announced public-beta native Skills and GA Tasks and Elicitation for specified Claude plans; product rollout and protocol maturity have different meanings. [Official stages](https://modelcontextprotocol.io/extensions/overview) · [Skills](https://modelcontextprotocol.io/extensions/skills/overview) · [Tasks](https://tasks.extensions.modelcontextprotocol.io/specification/2026-07-28/tasks) · [Anthropic rollout](https://claude.com/resources/articles/skills-over-mcp-tasks-and-more) · [November file-transfer update](https://blog.modelcontextprotocol.io/posts/exploring-file-uploads-and-downloads-in-mcp/) + +The public ChatGPT Directory has its own review rule. Each model-callable operation must be exposed individually for review. Qualify its named tools separately from the direct two-tool interface. [OpenAI guidelines §6.2](https://developers.openai.com/plugins/plugin-guidelines#62-tool-independence-and-exposure) + +## Execution choices + +The guest program needs standard JavaScript control flow, JSON values and a narrow asynchronous host call. The trusted adapter binds the route and caller outside guest code. The Recoup API owns business authorization, business-side receipts and effect requirements. Pin the guest language and limits separately from the catalog revision. Typed discovery can describe JavaScript in TypeScript declaration syntax without promising to compile arbitrary TypeScript projects. + +| Approach | Advantages | Cost to qualify | +| --- | --- | --- | +| Per-run Cloudflare Dynamic Worker with one RPC binding | The platform can block network access while preserving specific service bindings. CPU and subrequest limits are configurable. The higher-level Code Mode SDK supplies discovery and execution records. [Egress control](https://developers.cloudflare.com/dynamic-workers/usage/egress-control/) · [Limits](https://developers.cloudflare.com/dynamic-workers/usage/limits/) · [SDK reference](https://developers.cloudflare.com/agents/tools/codemode/api-reference/) | Introduces a second deployment and data-processing boundary for an API on Vercel. Benchmark the full round trip and explicitly enforce wall time, broker calls and bytes. The high-level SDK is marked experimental. Its result transformer leaves unmodified results in the audit trail, so apply redaction and retention before storage. [SDK status](https://developers.cloudflare.com/agents/tools/codemode/) | +| Per-run Vercel Sandbox microVM | Fits the API's current platform. Vercel supports an outbound firewall and credential brokering. It also offers a full OS if a future workflow requires one. [Vercel Sandbox](https://vercel.com/docs/sandbox) · [Sandbox firewall](https://vercel.com/docs/sandbox/concepts/firewall) | Default egress is open. Configure the sandbox before launch with a trusted broker channel as its only route to capabilities. Isolate each run's identity and bound the VM lifecycle, resources and outputs. Measure boot and RPC overhead for one small read as well as a composed task. A host-wide HTTP allowlist alone cannot enforce operation-level authority. | +| Embedded JavaScript engine via WASM, isolated from the credential-bearing service | Small guest API, portable deployment and explicit registered host functions. QuickJS offers runtime memory and stack limits and execution interrupts. Executor v1 demonstrates the host bridge. [QuickJS host API](https://bellard.org/quickjs/quickjs.html#QuickJS-C-API) · [WASM binding](https://github.com/justjake/quickjs-emscripten) | Recoup owns engine updates, termination, promise scheduling, payload copying and resource accounting. Prove hard termination of a blocked program and its pending I/O, process isolation, absence of host globals, reproducible WASM packaging and live cold-start behavior. An AST allowlist can restrict the language but provides no independent containment. | +| Direct host-discovered named tools | Preserves current individual descriptions, native confirmations and simple calls. A host with deferral can already load a small fraction of a large catalog. [Claude Code discovery](https://code.claude.com/docs/en/mcp#scale-with-mcp-tool-search) | Performance and availability depend on the host. The interface exposes operations individually, and ordinary tool calls can send intermediates to the model. Retain as a measured baseline and rollback during migration. | + +Choose the broker contract before choosing a runtime library. A runtime adapter should accept bounded source and data, expose only a broker callback and return a bounded value or classified error. The identical fixture suite must pass for a replacement adapter. A schema compiler, account platform or durable runtime can be evaluated independently on that boundary. Avoid coupling catalog admission, payment rules, actor identity or documentation ownership to an executor vendor. + +## Tests derived from migration experience + +1. **Search ordinary requests.** Compare a short query in a musician's own words, a synonym, an exact operation ID, an ambiguous request and a no-match request. Seed an operation and a guide for the same topic. Check that both appear as distinguishable, authorized previews and that `search({skill})` opens the exact guide returned by the preview. Test a native client separately with a fresh connection and a natural-language job that never mentions a skill. Verify the right guide was selected from initial descriptions, with zero pre-prompt file reads or model discovery calls. Include an exact-name collision in the fallback search. Repeat with the guide hidden and verify names, counts and pagination reveal no hidden match. Measure the preview page and the optional guide read separately. Limit bytes as well as rows. Exercise a stale discovery cursor after publishing a revised contract. Require earlier versions to fail explicitly or retain their documented compatibility. +2. **Qualify each behavior and consumer.** For every named operation and supported mode, compare old and candidate paths with the same actor and resource. Include denied access, missing data, full pagination, precision, expected media, status and errors. Give aggregate operations equal opportunity. For writes, sign in with an ordinary Recoup account that already has access to a disposable fixture, execute an allowed action, verify it independently and exercise cleanup. Separately test an actual API operation that requires approval or a provider quote. The host must surface that existing requirement. Record unknown consumers and keep their compatibility path until an owner determines disposition. +3. **Test recovery at the effect boundary.** Exercise duplicate requests, mismatched content under one key, lost acknowledgments, expiry, revocation and cancellation before and after dispatch. Serialize effectful calls across approval points. Return explicit partial results and reconcile uncertain writes against the original operation. Model responses, cached local results and successful transport responses alone cannot establish an external outcome. Cloudflare's own replay API flags ordering considerations for concurrent calls around pauses. [Replay mechanics](https://developers.cloudflare.com/agents/tools/codemode/api-reference/) +4. **Measure total cost per correct answer.** Use identical identities, fixtures, requested outputs, model versions and cache state for named and code-mode paths. Pin host versions and run both eager and deferred clients. Separate initial tool descriptor bytes and tokens, native skill listing bytes, initial skill name/description tokens, host instructions, actual or explicitly estimated first-turn input, later discovery and file-read tokens, tool-result tokens, total turns, API calls, human approvals, wall time and cost. Report median, tail latency and failures by workflow. Include a single lookup, a paged read, a dependent join, a private artifact, a bounded write and an interrupted long job. Preserve failed cases in the report and prioritize correctness and authorization over token reduction. +5. **Exercise installed hosts.** Test fresh connect, expired credentials, reconnect, changed capabilities, valid reviewer sign-in and unattended dispatch on the intended direct host. Exercise confirmation UI in the host/profile where policy or distribution requires it. A passing server test, deployment or cached host descriptor supports a different claim from a successful user journey. Record precise versions, observed behavior and retained rollback evidence alongside each admission. diff --git a/docs/plans/mcp-code-mode-tools.json b/docs/plans/mcp-code-mode-tools.json new file mode 100644 index 000000000..806c9a497 --- /dev/null +++ b/docs/plans/mcp-code-mode-tools.json @@ -0,0 +1,619 @@ +{ + "tools": [ + { + "name": "search", + "title": "Find Recoup operations and skills", + "description": "Find permitted operations and workflow guides by topic or exact ID. Use {} to list guides, cursor to page, or skill and optional file to read a guide or supporting file.", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "cursor": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "skill": { + "type": "string", + "pattern": "^[a-z0-9-]{1,64}$" + }, + "file": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + } + }, + "additionalProperties": false, + "oneOf": [ + { + "maxProperties": 1, + "properties": { + "skill": false, + "file": false + } + }, + { + "required": [ + "skill" + ], + "properties": { + "query": false, + "id": false, + "cursor": false + } + } + ] + }, + "outputSchema": { + "type": "object", + "properties": { + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "items": { + "type": "array", + "maxItems": 8, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "summary": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "effect": { + "enum": [ + "read", + "write" + ] + }, + "detail": { + "type": "object", + "description": "Requested operation contract or example." + }, + "skill": { + "type": "string", + "pattern": "^[a-z0-9-]{1,64}$" + } + }, + "required": [ + "summary" + ], + "additionalProperties": false, + "if": { + "required": [ + "skill" + ] + }, + "then": { + "properties": { + "id": false, + "effect": false, + "detail": false + } + }, + "else": { + "required": [ + "id", + "effect" + ] + } + } + }, + "nextCursor": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "guide": { + "type": "object", + "properties": { + "skill": { + "type": "string", + "pattern": "^[a-z0-9-]{1,64}$" + }, + "file": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + } + }, + "required": [ + "skill", + "file" + ], + "additionalProperties": false + } + }, + "required": [ + "revision" + ], + "additionalProperties": false, + "if": { + "required": [ + "guide" + ] + }, + "then": { + "properties": { + "items": false, + "nextCursor": false + } + }, + "else": { + "required": [ + "items" + ] + } + }, + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + } + }, + { + "name": "execute", + "title": "Run Recoup account operations", + "description": "Run async (recoup, params) as the signed-in account. Use a stable run requestKey and recoup.read(id,args) or recoup.act(id,args,{requestKey}) with a stable key per effect. Actions may immediately change data or contact others. The API enforces permissions and approvals. A requestKey or runId alone retrieves status. With runId, resume:true completes an API-approved step if needed and continues a safe checkpoint.", + "inputSchema": { + "type": "object", + "properties": { + "source": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + }, + "params": { + "type": "object", + "additionalProperties": true + }, + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "runId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "requestKey": { + "type": "string", + "minLength": 1, + "maxLength": 96 + }, + "resume": { + "const": true + } + }, + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "source", + "revision", + "requestKey" + ], + "properties": { + "runId": false, + "resume": false + } + }, + { + "required": [ + "requestKey" + ], + "properties": { + "source": false, + "params": false, + "revision": false, + "runId": false, + "resume": false + } + }, + { + "required": [ + "runId" + ], + "properties": { + "source": false, + "params": false, + "revision": false, + "requestKey": false + } + } + ] + }, + "outputSchema": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "complete", + "partial", + "approval_required", + "denied", + "expired", + "accepted", + "running", + "succeeded", + "failed", + "unknown_outcome", + "canceled" + ] + }, + "value": {}, + "runId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "traceId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "truncated": { + "type": "boolean" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "maxLength": 64 + }, + "retry": { + "enum": [ + "narrow", + "rediscover", + "reconnect", + "reconcile", + "backoff", + "never" + ] + } + }, + "required": [ + "code", + "retry" + ], + "additionalProperties": false + }, + "approvalUrl": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + } + }, + "required": [ + "state", + "traceId", + "truncated", + "runId" + ], + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "state": { + "enum": [ + "denied", + "expired", + "failed", + "unknown_outcome" + ] + } + } + }, + "then": { + "required": [ + "error" + ] + } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "approval_required" + ] + } + } + }, + "then": { + "required": [ + "approvalUrl" + ] + }, + "else": { + "properties": { + "approvalUrl": false + } + } + }, + { + "if": { + "properties": { + "state": { + "const": "complete" + } + } + }, + "then": { + "properties": { + "truncated": { + "const": false + } + }, + "required": [ + "value" + ] + } + }, + { + "if": { + "properties": { + "truncated": { + "const": true + } + } + }, + "then": { + "properties": { + "state": { + "const": "partial" + } + } + } + } + ] + }, + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + } + ], + "readOnlyExecute": { + "title": "Run a Recoup read", + "description": "Run async (recoup, params) using recoup.read(id, args) and return bounded JSON. A runId reads an authorized receipt.", + "inputSchema": { + "type": "object", + "properties": { + "source": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + }, + "params": { + "type": "object", + "additionalProperties": true + }, + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "runId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } + }, + "required": [], + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "source", + "revision" + ], + "properties": { + "runId": false + } + }, + { + "required": [ + "runId" + ], + "properties": { + "source": false, + "revision": false, + "params": false + } + } + ] + }, + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, + "outputSchema": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "complete", + "partial", + "accepted", + "running", + "succeeded", + "failed", + "canceled" + ] + }, + "value": {}, + "runId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "traceId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "truncated": { + "type": "boolean" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "maxLength": 64 + }, + "retry": { + "enum": [ + "narrow", + "rediscover", + "reconnect", + "reconcile", + "backoff", + "never" + ] + } + }, + "required": [ + "code", + "retry" + ], + "additionalProperties": false + } + }, + "required": [ + "state", + "traceId", + "truncated" + ], + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "state": { + "enum": [ + "accepted", + "running" + ] + } + } + }, + "then": { + "required": [ + "runId" + ] + } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "failed" + ] + } + } + }, + "then": { + "required": [ + "error" + ] + } + }, + { + "if": { + "properties": { + "state": { + "const": "complete" + } + } + }, + "then": { + "properties": { + "truncated": { + "const": false + } + }, + "required": [ + "value" + ] + } + }, + { + "if": { + "properties": { + "truncated": { + "const": true + } + } + }, + "then": { + "properties": { + "state": { + "const": "partial" + } + } + } + } + ] + } + }, + "actRequest": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "args": { + "type": "object" + }, + "options": { + "type": "object", + "properties": { + "requestKey": { + "type": "string", + "minLength": 1, + "maxLength": 96 + } + }, + "required": [ + "requestKey" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "args", + "options" + ], + "additionalProperties": false + } +} diff --git a/docs/plans/mcp-code-mode-user-stories.md b/docs/plans/mcp-code-mode-user-stories.md new file mode 100644 index 000000000..e4336f68d --- /dev/null +++ b/docs/plans/mcp-code-mode-user-stories.md @@ -0,0 +1,31 @@ +# What tools does a Recoup Records agent need? + +The proposed direct connection has exactly two tools. When native Skills is enabled on a qualified host, the agent receives authorized skill names and descriptions before the first prompt and can recognize a relevant guide without calling `search`. The host opens only the files needed for the task. `search` finds related guides and API operations, opens a contract or reads an exact guide or packaged file on hosts without native Skills. `execute` uses the signed-in account to read records, perform actions, check progress and continue saved work. Each story below is an acceptance test for a proposed capability. Use disposable accounts and fixtures for the cutover. A story about a music-company workflow does not establish that its API or provider integration exists today. + +## Label jobs and acceptance + +| ID | User story | How the agent does the work | What must be observable | +| --- | --- | --- | --- | +| 1a | As a new label operator, I sign in and ask “Check whether this release is ready for Friday.” I do not know the names of our guides. | Before the first prompt, a qualified native host automatically lists all authorized skills and exposes only their names and descriptions to the agent. Give it a release-readiness guide and at least one plausible distractor. The agent identifies the right guide from its description and activates it through the host’s ordinary skill-loading path. | Capture the host’s permission-scoped listing and what the model actually received. Verify zero model discovery calls and zero file reads before selection. Confirm only the chosen guide and any referenced file needed for this request are read. In a fresh session after removing access, the guide’s name and description disappear and its files cannot be read. Record host version, configuration and skill-metadata tokens separately from tool descriptors. | +| 1b | As a new label operator, I ask “How does Recoup check release metadata?” before assigning the job. | On a client without native Skills, one topic `search` returns a guide preview and the relevant API operation preview. Use the guide’s name in `search({skill})`, or the operation ID in `search({id})` to inspect its contract. Use `search({skill,file})` for a packaged supporting file or `search({})` to browse guides. | The preview fields distinguish a guide from an operation even when their names coincide. Both can appear without loading the guide body. An eligible account can open the guide and its referenced file. A customer account cannot see a staff guide’s name, summary or existence in results or page counts. Reading changes no release, and a one-off job can begin without loading a guide. | +| 2 | As a label operator, I ask “Mark this release’s metadata as needing changes and show me the saved review.” | After normal sign-in, `search` finds the review operation. `execute` checks the case, saves an allowed review and reads it back independently. | A new review belongs to the correct account and release. Zero extra approval prompts if the API allows the change. With read-only access or a different organization, zero writes. [First-write ticket](https://github.com/recoupable/api/issues/1308) | +| 3 | As a catalog manager, I ask “Check this week’s releases for missing recording IDs. Open one case per confirmed issue and give me the case numbers.” | `execute` reads across pages, checks for existing cases, uses the relevant API changes, then checks each result. The API can accept a durable job that outlives the chat. | Independently reopen every expected case. Report unresolved tracks separately. A repeated run or a second authorized operator cannot create a duplicate case for the same issue. [Case API](https://github.com/recoupable/api/issues/1316) | +| 4 | As a campaign manager, I ask an agent to prepare a $500 campaign for an artist. Our API requires a finance decision on this purchase. | `execute` returns the exact pending action and a way to review it. The run pauses at the spend. The agent may continue unrelated, permitted work. | Before the decision there is no purchase. Preserve the artist, amount, destination and expiry. Retrying, reading status or resuming while waiting produces zero purchases. Use a simulated purchase for this story. | +| 5 | As the finance approver signing in separately, I ask “What needs my decision?” I approve that $500 campaign or decline it. | The approver signs in to their own account and uses its list of pending decisions. An authorized agent can discover and invoke that operation through `search` and `execute` when company rules allow it. If the API requires a person to decide directly, it provides the trusted Recoup review link instead. | Only the API records the decision against the exact action. Enforce the actual approver identity and any rule requiring a different person. The requester cannot stand in for Finance. Show only pending items the approver can decide. A changed amount or an expired quote needs a new valid decision. The API reports whether approval also applied the purchase. The approver needs access only to that decision. | +| 6 | As the original operator, I return after lunch and ask first “Did Finance approve it?” and then “Finish the campaign.” | Checking status with `execute({runId})` only observes. Continuing with `execute({runId,resume:true})` loads the recorded step and checks current permission, current approval and what the API already did. | While approval is pending or after a refusal, spend nothing. If the API already applied the purchase, reuse its receipt. If the approved purchase still awaits completion, apply it once and continue from the saved step. On an unknown outcome, reconcile before another attempt. Two concurrent resumes still produce one purchase. [Approval and resumption](https://github.com/recoupable/api/issues/1314) | +| 7 | As a label owner starting a new chat, I ask “Which of yesterday’s jobs is waiting on me?” I have no run number. | Discover and query the API for jobs or decisions visible to this account, filtered by workspace and state. Select the right result, then inspect it. A saved run number or original request key is a faster path when available. | The agent can distinguish two similarly named jobs and ask for a choice if needed. An unrelated account learns nothing about either. Listing and inspecting cannot restart a job. A `resume` button alone cannot solve this story. [Durable jobs](https://github.com/recoupable/api/issues/1315) | +| 8 | As a campaign owner, I say “Stop this job. Tell me what was already sent.” | Discover and invoke the owning API’s cancellation operation. Then read the receipts. Test with a disposable mock delivery. | A durable stop prevents future steps. Report already delivered, in flight, cancelled and unknown separately. Closing a chat gives no such guarantee. Cancelling twice does not undo a completed delivery or send anything again. | +| 9 | As a label operator, I ask “Who’s on our roster?” and need one ordinary read. | Discover the roster operation if needed and run it with `execute`. Compare the result with the normal API read for the same account. | Verify the same roster and access boundaries on both paths. Compare response time and model effort for single reads separately from cost and reliability on longer jobs. | + +## Which capabilities merit a separate tool? + +| Candidate | Decision for the standard direct connection | Evidence that would change the decision | +| --- | --- | --- | +| Guide discovery and reading | Native clients qualify by automatically presenting authorized names and descriptions at startup and opening files on demand. For other clients, `search` finds guides alongside operations, opens an exact guide or supporting file and allows guide-only browsing with `search({})`. | A future shortcut would need evidence of a supported client workflow that these modes cannot serve. | +| `search`, `execute` | Include both. A topic can bring back both a guide and the operation needed for the work. The agent can choose to read the guide or execute the permitted operation. | Compare known one-step reads with multi-step work and verify business results. | +| `approve` | The API needs a real decision operation wherever the product permits an authorized approver to act using an agent. Start by exposing that business operation through discovery. For human-only approval, present the trusted review flow. | A supported client specifically requires an individually named, scoped approval action for the intended approver. Demonstrate that client requirement and retain the same API identity, decision and audit checks. | +| `resume` | Support continuing a saved run through `execute` from the first release that supports paused work. The caller supplies the run ID and `resume:true`. | Consider a new name only if an installed client cannot continue reliably using the existing form. Test a closed chat, dropped response and two simultaneous retries. | +| Completion of an approved action | Explicit `execute` resume checks the owning API’s decision and uses the saved step and effect key. If the API already applied it, reuse the receipt. | Revisit a separate name only if a supported client demonstrates a need to finish an isolated approved step independently. | +| `call`, `status`, `cancel`, pending-work lookup | Use `execute` for ordinary calls and observation. Deliver account-scoped cancellation and lookup through the owning API as workflows require them. | A missing API operation is a domain delivery ticket. A separately named tool earns its place when a supported client otherwise fails a required job or repeatedly completes it better with that tool. | + +Use the same account, data, approvals and business operation in each comparison. Record whether the independent check passed, how many human decisions were needed, unintended or duplicate changes, completion time and total text the model read. Track missing approval inbox, job lookup, cancellation or provider evidence against the actual owning API. [Benchmark](https://github.com/recoupable/api/issues/1310) · [Installed acceptance](https://github.com/recoupable/mono/issues/752) diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md new file mode 100644 index 000000000..d5a7731f4 --- /dev/null +++ b/docs/plans/mcp-code-mode.md @@ -0,0 +1,198 @@ +# Recoup MCP code mode + +**Proposed technical specification · November 29, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** + +Sign in with your Recoup account and your agent can act. On a supported connection, the agent sees the name and short description of every skill available to that account before it decides how to handle the first request. It can choose a relevant guide immediately and read its instructions when needed. The direct connection has exactly two tools. `search` finds API operations and can also find or open guides. Inside `execute` the host’s model writes a short JavaScript program that can read records, change them through the API, and check what happened. For example, a label operator can ask an agent to flag incorrect release metadata and then reopen the saved review. The first action uses the ordinary signed-in account, its current permissions and the access granted to the connection. + +The target is every music-company operation a human with equivalent access can perform through Recoup. The API resolves the account, organization, artist and resource, checks permissions, and owns any required approvals. MCP carries the request and the API’s result. Record gaps in API operations, provider integrations and verifiable outcomes with their owners. An agent can start with a one-off request or follow standing instructions supplied as task context. Saved instructions, an approval interface and the public ChatGPT Directory have independent delivery paths. + +| Read next | What it establishes | +| --- | --- | +| [Measured current architecture](mcp-code-mode-baseline.md) | Source pins, real SDK discovery across profiles, host inventory, product semantics and prior publisher work | +| [Account permissions and the first label workflow](mcp-code-mode-autonomy.md) | Ordinary sign-in, one-off and standing instructions, durable jobs and independent verification of a saved change. | +| [Label user stories and tool decisions](mcp-code-mode-user-stories.md) | Label jobs covering workflow guidance, real changes, approvals, resume, cancellation and finding lost work. | +| [Code-mode research](mcp-code-mode-research.md) | Cloudflare, Anthropic and Executor source, host deferral, runtime alternatives and comparative evaluation | +| [Protocol and OpenAI review](mcp-code-mode-protocol.md) | Current MCP and extensions, negotiated capabilities, eight proposed reviewer scenarios, submission and updates | +| [Proposed tool descriptors](mcp-code-mode-tools.json) | Measurable example input/output contracts for a direct connection | +| [Delivery and dependencies](#delivery-and-dependencies) | Owning repositories, parallel work, release gates and GitHub issues | + +## Decision and measurable outcome + +Full delegated OAuth returned 95 descriptors in the measured modern SDK fixture, including 94 visible to the model. They took 31,971 wire-list tokens and 31,820 model-visible descriptor tokens. The proposed two-tool read-only profile takes **937** reference tokens (3,697 bytes). The two-tool account action profile takes **1,110** (4,456 bytes), a **96.5% reduction** against the full model-visible baseline. The earlier three-tool action fixture measured 1,077. Naming fewer tools alone does not predict their size. Narrow OAuth already measured 1,038 visible tokens. These numbers cover the tool descriptions alone. Measure the visible skill names and descriptions, server instructions, and total first-turn model input on each client. Record the cost of an opened guide on the turn that uses it. + +On the pinned Recoup skill bundle, the customer catalog returned 47 names and descriptions, or 4,966 reference tokens as compact JSON. An eligible staff account on the combined connection received 132 across two pages, or 15,069 reference tokens. A real host may render those summaries differently. Claude Code documents a 100-skill limit per server, so the combined staff catalog exceeds its published limit. Validate the last page in Recoup’s host and label coverage per account and client. [Catalog measurements](mcp-code-mode-protocol.md) · [Claude Code limits](https://code.claude.com/docs/en/mcp#mcp-skill-limitations) + +Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the two direct profiles from the [fixture](mcp-code-mode-tools.json), serializes each compact `tools/list` envelope in UTF-8 with no trailing newline and uses tiktoken 0.14.0 with `o200k_base`. Both advertise `search` and `execute`. Only the action-capable connection can perform a business effect. The nested action schema stays off the wire. Compare actual prompt traffic under equal host, grant, task, tools-deferred setting, server instructions and preloaded resources. [Measured baseline and reproduction](mcp-code-mode-baseline.md) + +| Distribution | Proposed route on api.recoupable.dev | Model and wire contract | +| --- | --- | --- | +| Direct, read-only | `/mcp/code` | The host lists authorized skills through the Skills extension and shows the agent their names and descriptions up front. `search` finds operations and guides and can open a selected file. `execute` runs permitted reads. | +| Direct, signed in with access to act | `/mcp/code` | The same upfront skill list and two tools. An allowed `recoup.act` inside `execute` changes the record through the API. `execute` also checks status or explicitly resumes authorized saved work. | +| OpenAI Directory | `/mcp/directory` | Initially `select_catalogs` and `select_catalog_songs` only. Each has its own reviewable schema, effect metadata and implementation. Introduce a separate catalog-read permission. The Directory endpoint cannot route to the guest, discover implementation IDs, resume direct actions or load skills that promise unavailable functionality. | +| Existing installs | `/mcp` and the existing staff skills endpoint | Preserve current authentication, scopes, gallery, legacy names and selected-context behavior. The existing thread launcher and app-only sidebar count separately. Qualify their replacement independently before retiring those entry points. | + +Both new URLs are proposals under the established MCP mount. Business REST endpoints retain their /api paths. Keep scheme, host and port for the Directory publisher. Profile routing is a server decision bound to the endpoint and expected OAuth resource. Ignore brand strings as authorization selectors. A discovered operation is a description, never permission to call it. OpenAI requires separately exposed model-callable operations for Directory review. Recoup previously split its opaque Context tool into named operations after a scan. Changing the same endpoint under an existing publisher draft would risk both review and installed clients. [OpenAI §6.2](https://developers.openai.com/plugins/plugin-guidelines#62-tool-independence-and-exposure) · [Recoup's prior review fix](https://github.com/recoupable/api/pull/980) + +## Alternatives and cutover strategy + +| Option | Strength | Decision | +| --- | --- | --- | +| Keep named tools and use lazy host discovery | Minimal server migration. Preserves action-specific schemas, built-in confirmation and UI. | Ship named tools for Directory. Benchmark native deferral on supported clients. Direct clients need portable composition and bounded intermediate results. | +| Search, then register named tools dynamically | Fast single-step calls in cooperative clients. | Catalog changes can race across calls and vary by host. Adds discovery state and leaves multi-step results in the prompt. | +| Two generic tools calling arbitrary REST paths | Small interface. Easy to generate from OpenAPI. | REST authentication, side effects and output semantics differ from delegated MCP. A path allowlist cannot express selected context, quoting or response projection. | +| Prepare every write and require individual confirmation | A person can inspect each change. | Use the owning API’s approval requirement for the operation and account. Routine permitted work should run unattended. | +| Two direct tools for discovery, guide reading and execution, with named Directory tools | Discovery stays small as operations grow. Every client uses the same API checks and receipts. | **Adopt.** A replaceable runner composes API operations. The API owns the decisions and durable work. The agent can present a pending approval and resume supported work through `execute`. | +| Adopt Executor as the platform, translate everything to CLI, or run another LLM inside MCP | Rapid access to a broad framework or familiar developer surface. | Executor's discovery/dispatch design is applicable. Its account, deployment and distribution model would duplicate Recoup's. CLI/inner-model approaches add shell or model dependencies to ordinary MCP clients. | + +Use parallel opt-in URLs, with independent flags by profile, operation and cohort. Compare equivalent reads with test fixtures or consented canaries. Never shadow a write, paid provider call, secret read or outbound delivery. A big-bang swap at `/mcp` would strand installed hosts, invalidate the publisher contract and obscure regressions. + +## Components and ownership + +```mermaid +flowchart LR + Contracts["Pinned Docs OpenAPI + API validators + operation contracts"] --> Build["Catalog compiler / signed release"] + Build --> Direct["Direct MCP adapter"] + Build --> Named["Directory named-tool adapter"] + Direct --> Native["MCP Skills extension"] + Native --> GuideReader + Native --> Host["Host shows authorized names and descriptions before the first decision"] + Direct --> Search["Search guides and API operations"] + Search --> GuideReader["Existing authorized Recoup guide reader"] + Direct --> Runner["Per-run JS isolate"] + Runner --> Broker["Recoup operation broker"] + Search --> OperationIndex["Authorized API operation index"] + Direct --> Broker + Named --> Broker + Broker --> Domain["Recoup API business operations"] + Domain --> Authority["Existing account, organization, artist permissions and approvals"] + Domain --> Jobs["Durable workflows and verified receipts"] + Broker --> Ledger["Per-effect audit and reconciliation"] +``` + +**Catalog compiler, API repository.** Compile approved descriptors and server-only bindings during CI. The Docs repo owns the split OpenAPI files, operation IDs and operation inventory. Pin the Docs commit, its upstream API source commit and hashes, then reconcile with the API build's actual routes, validators and services. The inspected Docs revision classifies 442 method/path rows in its source inventory and pins 14 specification hashes. The rows include 217 public, 17 public/integration, 177 internal, 13 internal/callback, 14 pending and four legacy entries. The static registration inventory has 75 entries, a separate measure from the 95-item full OAuth discovery response. Never enable a capability merely because Docs documents a route. Refresh drift as a proposed catalog diff requiring review. [Docs inventory](https://github.com/recoupable/docs/blob/873a1c93cf6ae0060702e38eba1b2715bb269f42/content/docs/contracts/operation-inventory.json) · [Docs publication workflow](https://github.com/recoupable/docs/blob/873a1c93cf6ae0060702e38eba1b2715bb269f42/AGENTS.md) · [Related capability-manifest work](https://github.com/recoupable/app/issues/2223) + +**Versioned operation record.** Each record has a stable domain ID, public aliases, owner, revision, title, search terms, typed input, validated output and short example. The private binding selects a specific REST operation ID or shared domain method, HTTP serialization when needed, authorized identity and resource resolvers, selected-context projection, field mask, processor and destination classes, effects including delayed effects, budget/quote rules, idempotency, async lifecycle and per-profile disposition. A multiplexed REST operation needs an action-specific binding with a fixed discriminator. Link each published operation and legacy alias to contract tests. Emit per-profile manifests, TypeScript declaration snippets, searchable summaries and Directory descriptors as projections of that one record. + +**Runtime release.** Content-address the manifest using canonical JSON over the API/Docs pins, schemas, bindings and profile configuration. Sign it in CI, verify before serving, and record the digest on calls and receipts. Keep immutable revisions available for lookups and in-flight reconciliation. Changing a decision from allowed to denied takes effect immediately, even on an older pinned revision. A request with a retired schema returns `catalog_changed` with a rediscovery instruction. Keep aliases for backward-compatible changes, and use a new operation version for incompatible inputs, outputs or effect semantics. Include the old/new diff in approval and Directory review. No network fetching of arbitrary schema references at runtime. + +**Operation broker, API repository.** Both profiles invoke the same business code. Prefer a typed in-process service invocation that uses the same account, scope, resource and approval checks as the public API entry point. A fixed-origin HTTP binding is acceptable where the owning API supports the precise audience, identity, scope and effect contract. Resolve method, path and allowed headers server-side. Pass no host-managed MCP bearer to REST. Do not mint an account API key, assign a caller-supplied owner ID or substitute an admin credential. Refactor a handler into an authorized service or leave its operation unavailable if these conditions cannot be met. + +**Human workflow coverage.** Work available only to a human in the App, a provider portal or a manual back office gets a parity entry with its real owner, present limitation and readback criterion. Build missing company capabilities once in that owner’s API service. Preserve genuine provider and legal participation requirements, with a named continuation path. Directory exposure and support for a particular host are separate inventory columns. Compare human and agent outcomes on equivalent permissions and data. + +**Runner.** Qualify an isolated Cloudflare Dynamic Worker first. Keep the front door, authentication, sensitive projections, approvals, receipts and business services in Recoup's API. The supervisor gets a short-lived, single-run channel to the broker, mutually authenticated and bound to the request, release and budget. Only the supervisor holds channel credentials. The guest sees two host functions and structured-cloned values. It gets no OAuth/session tokens, raw HTTP client, network, file access, environment, dynamic module loading, shell or database connection. Apply the platform's outbound-deny configuration at instantiation. The private broker accepts a typed RPC and a current run binding only. Review third-party processing, region, retention and contractual suitability for every data class crossing this boundary. If the first runner fails a hard gate, benchmark a per-run Vercel Sandbox through the same port. Keep launch off until one adapter meets the gates. [Runtime comparison and primary sources](mcp-code-mode-research.md) + +## Interaction contract + +### What the agent sees on connection + +On both direct profiles the API advertises the Skills extension and lists the entire skill catalog permitted by the current account and connection. This includes staff skills only for eligible accounts and preserves the existing selected-context exclusions. After sign-in, a qualifying host detects the extension and calls `skills/list` automatically. It follows the authorized pages and gives the model each listed skill’s name and description before its first task decision. The first-party App owns this behavior. For example, the user can say “Check whether this release is ready for Friday.” The agent can recognize the relevant skill from its description without knowing its name or spending a turn searching. The full manifests travel to the host. It keeps file paths, resource URIs and integrity information available for later use. + +Once the agent needs a guide, the host uses `resources/read` to fetch that guide’s `SKILL.md`. It fetches an individual supporting file only when the task needs that file. Listing, connecting or approving access alone must trigger zero file reads. Apply the existing skill audience checks to both listing and reading. Refresh the visible list when the account or its access changes, recheck file access, and observe the extension’s trust and integrity rules. These methods are part of the protocol. The direct `tools/list` contains exactly `search` and `execute`. [MCP Skills specification](https://github.com/modelcontextprotocol/ext-skills/blob/main/specification/beta/skills.mdx) · [Agent Skills progressive disclosure](https://agentskills.io/specification#progressive-disclosure) + +Each host decides how to present the catalog. Verify the experience for a named client and version before claiming it there. If a host lacks the extension, hides the descriptions from the model, or omits part of the authorized list, document that limit and keep the same authorized catalog accessible through `search`. + +### Finding and reading through the two tools + +`search` lets any direct client find useful guides and API operations together. A topic such as “review a release” can return both a guide preview and an operation preview. Each result identifies what it is and how to use it. A guide hit returns its name and a summary. An operation hit returns its identifier, summary and read/write effect. Even when a guide and an action share a name, both are recognizable. Use the API operation catalog for actions and the existing Recoup skill catalog for guides. Store each guide and its supporting files in their existing home. Permission checks run on both sources before ranking and pagination. Hidden results cannot affect counts, rankings, cursors or exact lookups. A search never executes an action or loads guide bodies into startup context. + +`search({})` lists authorized guide previews. `search({query})` finds matching operations and guides. `search({id})` looks up an exact identifier and can return both kinds for a shared name. Use `search({cursor})` for the next authorized page. An exact skill read uses `search({skill})`. Use `search({skill,file})` for a packaged supporting file. Reuse the current guide library, account and file checks, including the public/staff boundary and selected-context exclusion. There is one guide reader behind the direct, legacy and native interfaces. An operation detail can include its contract, authorization prerequisites, cost and example. For guide reads, identify the selected guide and file in structured metadata and return its contents once through the standard MCP text or resource response. Return bounded pages and keep signed cursors scoped to the query, authenticated account, effective access and expiry. Bound summaries to eight hits and 4 KiB. Exact operation schemas may page by section at 12 KiB. Compare ranking on real label queries and keep the empty and hidden cases indistinguishable. [Existing catalog reader](../../lib/mcp/skills/registerRecoupSkillsTool.ts) · [Audience checks](../../lib/mcp/skills/resolveRecoupSkillsAudience.ts) + +`execute` accepts a pinned revision, JS source and separate JSON parameters. The async program receives `recoup.read(id, args)` for qualified effect-free reads. An action-capable connection also supplies `recoup.act(id, args, {requestKey})`. For the action profile the caller supplies a stable run `requestKey` with every source program, and one stable per-step key per distinct effect. Persist the run before dispatch. The same key and digest return the previous run. A different request with that key conflicts. `execute({requestKey})` and `execute({runId})` look up authorized status without running source again. `execute({runId,resume:true})` asks the API to continue saved work from its recorded step, including a step that needs completion after approval. It accepts no replacement program or action arguments. The server loads the saved step and original inputs. If it cannot establish a unique safe next step, it returns the recorded status without dispatching. Ordinary completed read-only computations need no durable account artifact. Bind action outputs to broker receipts independently of the guest’s chosen return value, including if it throws, times out or returns a misleading value. + +After admitting an action run, return its durable run ID even on overall failure. On status lookup by run ID or original request key, the broker supplies a bounded, authorized per-step record in `value` with the step ID, outcome, receipt reference and any permitted independent readback reference. Those records remain available if two changes succeeded and a later line of the program failed. The guest cannot overwrite them. A short run has at most 16 steps. Longer jobs retain checkpoint and child-run references in the owning workflow. + +For example, an account asks for the first five track titles in one of its catalogs. Searching for “my catalogs and track list” yields the qualified metadata projections below. The model can combine them without putting the catalog rows in the chat. The account has already selected a catalog ID. Display names can collide across organizations. These IDs and normalized fields are **proposed**; the existing MCP matcher has a different contract. + +```js +async (recoup, params) => { + const { catalogs } = await recoup.read("catalogs.listOwned", { ids: [params.selectedCatalogId] }); + const catalog = catalogs.find(item => item.id === params.selectedCatalogId); + if (!catalog) return { found: false, tracks: [] }; + const page = await recoup.read("catalogs.listTrackMetadata", { catalogId: catalog.id, limit: 5 }); + return { found: true, tracks: page.tracks.map(track => track.title), hasMore: page.hasMore }; +} +``` + +The proposed ID filter returns only owned matches and can be applied before paging. For an initial name-only request, page the authorized list and ask for a choice if multiple catalogs match. Test duplicate names and later-page matches. The catalog owner path is derived from the connection. The track metadata binding checks catalog access before fetching a page and only returns approved metadata. The proposed Directory matcher instead accepts a brief, can send metadata to a known AI processor and returns actual matching tracks from a bounded search window. It needs its own adapter, privacy disclosure and qualification. Each named Directory operation works independently for an authorized account. [Current mapper](../../lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts) + +A signed-in label operator can ask the agent to record `needs_changes` on a disposable release review. The agent discovers the equivalent of today’s `record_music_release_case_review` (`review_release_case` in the API), verifies the evidence and calls `recoup.act`. A separate authorized call reads the saved review. This is the smallest proof of an allowed change. The longer job opens private catalog-correction cases, survives chat closure and reopens each saved case independently. The API must first expose case save/read/list to appropriately authorized connections. Identify repeat work by organization, stable internal recording and correction kind. A name collision or missing ISRC cannot establish recording identity. [Case contracts](../../lib/context/releaseCaseOperationSchemas.ts) · [Installed acceptance](mcp-code-mode-autonomy.md#installed-end-to-end-acceptance) + +**Account authority and dispatch.** The existing sign-in establishes which Recoup account is calling and the access granted to its connection. Use that account’s actual organization and artist memberships. If the task names an artist or organization, pass that selection to the API. If several accessible targets match, resolve the ambiguity before the write. The owning API checks the current account, connection scope, selected resource, domain rules and any required approval on every operation and again before queued dispatch. Allowed work proceeds immediately. An API requirement for approval parks that exact step. Denied work produces no effect. Apply a change in membership or permission to subsequent steps and resumes. An assignment or handbook describes the work and grants no authority. [Account and job contract](mcp-code-mode-autonomy.md) · [Existing OAuth runtime](../mcp-oauth-runtime.md) + +**API approval and resume.** The owning API records the pending effect, authorized account and resource, canonical arguments, destination, maximum cost and expiry. Return `approval_required`, the run ID and the trusted review URL. The decision comes from an authorized approver through the API. `execute({runId})` only checks progress. On `execute({runId,resume:true})`, recheck current access and the saved effect. While approval is pending, return its status. If denied, expired or revoked, stop the affected step. If the outcome is unknown, reconcile before retrying. If the API already applied the change, read back its receipt and continue from the next saved step. If approval is recorded and the API still requires completion, atomically claim and finish exactly that effect once, then continue the saved workflow where safe. A caller can never supply approval or substitute new terms. A completed run simply returns its outcome. + +The reference approval URL is `https://app.recoupable.dev/mcp/approvals/{runId}`, with the server-issued run ID. It can open the existing API review flow. Verify the full URL, sign-in return, changed terms, expiry and concurrent completion attempts. The API retains the original inputs and binds its decision to that exact step. The direct client only needs the run ID to check progress or continue. Keep downstream signatures or provider consent with their issuer. [Protocol and recovery](mcp-code-mode-protocol.md) + +The read-only `execute` annotation applies only to a bridge that cannot cause effects, including hidden settlements or paid processing. For action-enabled `execute`, compute open-world, destructive and idempotency hints conservatively from all reachable operations. An account with sufficient API access can reach qualified external operations. Their owning APIs check destination, fields, provider requirements and any applicable approval before dispatch. A tool annotation does not authorize transfers. Qualify actual host confirmation behavior separately. A client that forces per-call prompts cannot serve as the unattended operating host for that workflow. + +### Large results, media and extensions + +A modern client can receive a structured result, a scoped resource link or an existing host attachment when its adapter supports the type. Keep binary media, private audio, fan contacts, provider dataset IDs and service credentials out of the default JS projection. For a private artifact return an opaque reference bound to actor, grant, resource class and expiry, with a documented MIME type and retrieval limit. Validate access again on dereference. Legacy text-only hosts receive a bounded summary and an authorized follow-up path. Never fall back from a private file to a public media URL. A directory or skill resource cannot execute an operation or broaden a grant. Keep the existing gallery on its qualified profile until supported thread/sidebar behavior, CSP and scoped assets survive installation tests. Native Tasks and streaming can improve UX later without changing Recoup run IDs or persistence. + +## Budgets, lifecycle and failure behavior + +| Proposed initial bound | Enforcement point | +| --- | --- | +| Source 8 KiB UTF-8, params 16 KiB, depth 16; catalog summaries 4 KiB; guest result 16 KiB | HTTP front door counts bytes before parse; broker checks structured payloads before copying. Schema `maxLength` is only an additional character bound. Cap cumulative data returned to guest at 256 KiB per run. | +| 16 nested calls and two simultaneous reads per short run; each action carries its own effect key | Enforce atomic budgets and domain quotas. Multiple allowed effects can execute in sequence and return distinct receipts. A Vercel Workflow owns larger or longer assignments across short runs and preserves partial progress. | +| 10 s wall time, 100 ms guest CPU and an enforced provider memory ceiling, starting target 128 MiB | Hard-stop guest and close callback channel. Qualify actual platform ceilings, cancellation and tail behavior under contention. Allocate broker I/O and processor budgets independently. | +| Optional approval valid for up to 5 minutes for the proposed continuation, bounded by the API decision, quote and connection expiry | Recheck at decision and dispatch. Status handles require live authorization. A workflow can renew a stale quote or request a fresh decision for changed terms. | +| Sensitive logs | Only trace ID, hashed/opaque tenant and operation identifiers, policy/manifest revision, byte counts, durations, budget, outcome and receipt reference. Omit source, arguments, credentials, prompts, results and raw upstream errors by default. | + +**Identity across requests.** Validate the connection’s audience, scope and client using Recoup authentication. Take account identity from verified server context. Check current organization and artist access, selected resource and operation requirements in the API. Scope private caches, cursors and receipt lookup accordingly. Retain the existing `/mcp` audience and API-key/Privy, narrow, full, selected-context and staff behavior. Qualify the proposed direct and Directory resources with the authorization server through ordinary Recoup sign-in. Directory uses catalog-read access. New URLs grant no additional permissions. Durable jobs retain their initiating account, connection authorization reference, target and checkpoint. Every resume and dispatch rechecks current access. On lost access, stop the affected work. Use the standard reconnect flow when required. [Resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Current sign-in runtime](../mcp-oauth-runtime.md) + +Persist only the data necessary to apply or reconcile a write. Use Supabase via its existing repository layer. Define receipt rows with `run_id`, account/connection/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Deduplicate submissions by initiating account, connection, profile and request key. Deduplicate the underlying work by its API owner (the verified organization/workspace for shared work or the verified account for personal work), stable resource ID, operation, and domain-specific occurrence or effect step. Use the same business identity in duplicate-job checks. For example, two authorized members correcting the same recording and issue share one correction case, while each attempt retains its initiating account. Keep a separate unique claim for any sealed approval intent. An identical authorized retry returns the prior receipt. Reusing a key for a different request conflicts. An authenticated receipt records the initiating account, selected resource and API decision basis even when no individual approval exists. Distinct keys cannot consume the same intent twice. Atomically claim/record the ledger and enqueue an outbox entry for service dispatch. Immediately before a queued worker actually dispatches, revalidate grant, membership, kill switch, destination, quote, any required approval and remaining shared budget against the claimed receipt. If any expired during queueing, terminally deny or expire it without an external effect. Test revocation and quote expiry after enqueue. Integrate existing domain transaction/idempotency keys where available. If the upstream cannot deduplicate, a worker crash after dispatch enters reconciliation; never automatically replay that submission. + +An allowed action can go straight to accepted. An approval-required action is parked first. Record running, successful, failed and unknown outcomes with independent evidence where possible. A timeout after dispatch yields `unknown_outcome` with a handle. An independent status read resolves it when evidence exists; otherwise retain it for operator reconciliation. An aborted script stops new work. A cancellation after an upstream commit returns known effects. A downstream Recoup REST 202 denotes job acceptance. The MCP tools/call still returns a JSON-RPC result carrying a run handle. A transport-level HTTP 202 without a body acknowledges a notification or response, not an asynchronous tools/call. Long operations use an existing domain job or a Vercel Workflow and an authorized status projection. Never keep a JS isolate resident during human confirmation, long media generation or durable polling. Optional MCP Tasks can project the same underlying receipt for capable clients. Use existing workflows instead of adding Trigger.dev jobs. Define an expiry for payloads, receipts and redacted audit metadata with the product/privacy owner before rollout, and preserve required idempotency records for the entire allowed retry window. + +Return structured domain failures with a bounded `code`, `traceId`, retry guidance and a receipt when available. Distinguish invalid arguments, changed catalog, unknown-or-denied operation, expired approval, budget exceeded, upstream busy, partial coverage and unknown outcome. Use MCP tool errors for domain failures and JSON-RPC/HTTP errors for malformed protocol and authentication. Before admission, a rejected action program or an unrecognized run reference returns MCP `isError` with a bounded JSON text block for code, retry and traceId and no structured run result. Search and other early failures can use the same bounded error form. Every structured result from action-enabled `execute` carries the authoritative run ID. In `execute` structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads and resume use the same receipt-state names. Complete and partial describe successful guest computations. On approval_required, report the validated API approval URL and authorized run ID. `execute` resolves the saved effect server-side on resume. The client supplies the run ID. A complete guest computation returns a value and truncated=false. The supervisor reports partial when it removes rows or cannot establish coverage; truncated=true always implies partial. A source page with hasMore may still fully answer an explicitly bounded first-page question. Back off and retry a read within its remaining deadline. Never retry an ambiguous external write based on a 5xx alone. If the runner fails, surface unavailable and keep eligible cohorts on their prior connection. Do not fall back to a broader credential or endpoint. + +## Qualification, release and expansion + +**Test design.** Use test-first domain work and fixtures seeded in two isolated accounts and organizations. Compare the normal API and MCP under the same account, target and equivalent scopes for allow, denial and approval-required results. Include an account with two organizations, scoped artist selection, an ambiguous target, and a role revoked while work is queued. Exercise reference resolution, unions, strict schemas, empty results, tenant/role changes, pagination, malformed/oversized programs, quota exhaustion, caller cancellation and new-revision behavior. Compare canonical outputs and effects against the old operation, including “read” calls that can settle a pack, quoted social refresh, restricted recipients, private file handles and scheduled downstream costs. Keep identity-bearing data out of release evidence. Capture installed client name/version, resource audience, tool list, operation/revisions, actual outcome, and independent readback for writes. Benchmark entirely on synthetic or authorized disposable fixtures. + +**Discovery experiment.** The initial interface lets the agent look up one exact operation with `search` and use known operations inside `execute`. On the same account and fixture, compare it with two independent additions: fetching several exact descriptions in one `search`, and allowing a running program to search the same authorized catalog when its next step depends on a result. Give both the existing field, byte and call limits. Measure completed jobs, extra trips to the model, elapsed time and total text the model reads. Keep the two-tool direct interface as the baseline. Only investigate a separately named shortcut if a supported client presents a concrete unmet need. + +**Proposed release gates.** Measure at least 30 paired runs per task class and model/host treatment where automation is available. Keep seed, model release, prompt, host version, tool selection mode, temperature or supported equivalent, selected grant and data constant. Expand the sample when the interval cannot resolve a gate. Include single reads, empty/unknown, two-step discovery, paged joins, selected context, native skill selection from a plain request, search fallback, on-demand file reads, a denied operation, an unattended mutation with zero prompts, a separately configured approval, replay, durable restart and independently verified outcomes. Use matched legacy/host-deferred baselines and include failures in all summaries. + +| Gate | Proposed acceptance | +| --- | --- | +| Skill visibility | On a fresh installed connection, capture the authorized names and descriptions available to the model before its first decision. Use the release-readiness request above with at least one plausible alternative guide. Observe the agent select the right guide without first calling `search`, read only the guide and any needed file, and keep an unrelated guide unread. Test a second catalog page, staff-only visibility and access loss. Record unsupported or partial hosts and test their `search` fallback. [First-party host](https://github.com/recoupable/app/issues/2411) · [Installed-host qualification](https://github.com/recoupable/mono/issues/752) | +| Startup cost | At most 1,500 tool descriptor tokens for the write-capable direct profile, at least 90% below full OAuth's model-visible tool list. Account separately for visible skill names/descriptions, server instructions, host-only manifest bytes, total first-turn model input and later reads. Compare cold and warm connections under equivalent access. Report unavailable host measurements explicitly. For a narrow/deferred client already below that target, require no material startup or task-success regression before migrating. | +| Correctness and autonomy | All deterministic authorization, projection, approval, idempotency and isolation tests pass. Verify a human-visible effect and independent readback from ordinary sign-in with zero additional setup or per-effect prompts where the API allows it. Check the same account through the ordinary API and MCP for allow, deny and approval-required results. Test two organizations, concurrent agents, stale evidence and revocation after enqueue. An unqualified optional branch holds only the cohorts that require it. | +| Model utility | On core tasks, paired success lower 95% confidence bound for candidate minus best applicable baseline ≥ −5 percentage points. Flag each critical task class independently. Human checks for false licensing claims and fabricated tracks. | +| Efficiency | In multi-step reads target ≥30% less median total model-visible token traffic, direct vs eager named. Show deferred baseline too. On single reads target ≤20% p95 wall-time regression and ≤10% higher median cost per correct task vs best compatible baseline. Record cold/warm runtime, processor calls, cache hits and configured approval latency separately. Report cases completed, unresolved cases with reasons, unnecessary interruptions and cost per independently verified business outcome. Track the percentage of existing human workflows with verified agent parity, attributed gaps and an owner for each gap. Hold a default change when cohorts miss targets. | +| Operability | Test failure injection before/after admission, revocation mid-run, stopped runner and restart after dispatch. On a controlled deployment exercise per-operation disable, per-profile rollback and recovery of existing receipts. Establish p95 and cost alarms from measured baselines. | + +**Adoption sequence.** Start inventory and runner qualification in parallel. Qualify normal sign-in and reads, then exercise the two-tool interface. Qualify first-turn skill visibility and on-demand reads for each claimed host. Verify the mixed `search` result and guide/file fallback independently. Use `search` and `execute` to make one allowed additive change on a disposable account and independently reopen it. Count interruptions after sign-in. Next qualify the longer label job across chat closure and worker replacement. Qualify saved instructions, API approval completion and Directory review independently. Eligible direct cohorts can progress through 1%, 10%, 50% and 100% after a monitoring window and successful journeys at each stage. Retain historical chat, gallery paths and existing connections until each passes parity and rollback checks. Submit the separately named OpenAI package through the existing publisher process. + +**Rollback and retirement.** On an isolation, billing, duplicate-effect or cross-account failure, immediately disable the affected operation/profile, stop new dispatch, quarantine uncertain receipts and keep reconciliation available. Preserve older manifests, client settings, old route and status reads. Roll forward schema or policy fixes under a fresh revision. Before communicating an end-of-life date, require a disposition for every old name/shape/client, usage evidence over a proposed 30-day window, host-owner signoff and a working reconnect/restore runbook. Low usage alone does not establish parity. Keep unsupported hosts on legacy if needed. Record rollout, deprecation, review submission, approval and publication as separate milestones. + +**Adding a capability after cutover.** A maintainer lands the Docs contract, pins its API binding, adds or changes one operation record with ownership/effects, runs compiler and negative contract fixtures, and opens the generated catalog diff. The broker can then admit it per profile. Direct clients discover it on the next authorized search. A Directory addition generates an independent named descriptor and goes through the current review process. A new sandbox, model or protocol extension can be introduced behind the same contracts and evaluated against the same fixtures. + +## Delivery and dependencies + +| Ticket | Deliverable | Blocked by | +| --- | --- | --- | +| [api#1303](https://github.com/recoupable/api/issues/1303) | Map human workflows, agent coverage and startup context | Can start now | +| [api#1304](https://github.com/recoupable/api/issues/1304) | Build the API operation catalog and per-channel projections | [api#1303](https://github.com/recoupable/api/issues/1303) | +| [api#1305](https://github.com/recoupable/api/issues/1305) | Connect ordinary Recoup sign-in and verify API permission parity | [api#1303](https://github.com/recoupable/api/issues/1303) | +| [api#1306](https://github.com/recoupable/api/issues/1306) | Qualify an isolated JavaScript runner and typed Recoup bridge | Can start now | +| [api#1307](https://github.com/recoupable/api/issues/1307) | Serve authorized native skill listings, on-demand reads and the two direct tools | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305), [api#1306](https://github.com/recoupable/api/issues/1306) | +| [database#144](https://github.com/recoupable/database/issues/144) | Persist business keys, dispatch claims, audit and effect receipts | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305) | +| [api#1308](https://github.com/recoupable/api/issues/1308) | Perform an allowed change as the signed-in account and verify it independently | [api#1307](https://github.com/recoupable/api/issues/1307), [database#144](https://github.com/recoupable/database/issues/144) | +| [api#1316](https://github.com/recoupable/api/issues/1316) | Expose private catalog-correction cases under existing account permissions | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305) | +| [api#1315](https://github.com/recoupable/api/issues/1315) | Resume account-initiated API jobs after chat closure and worker restarts | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [api#1313](https://github.com/recoupable/api/issues/1313) | Attach optional standing instructions as context for an account’s jobs | [api#1315](https://github.com/recoupable/api/issues/1315) | +| [app#2411](https://github.com/recoupable/app/issues/2411) | Show skill names and descriptions to the first-party agent on connection, migrate consumers and display API-required approvals | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [api#1314](https://github.com/recoupable/api/issues/1314) | Resume saved work through execute after API approval and verify one effect | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [api#1309](https://github.com/recoupable/api/issues/1309) | Generate the individually reviewed ChatGPT Directory catalog profile | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305) | +| [api#1310](https://github.com/recoupable/api/issues/1310) | Benchmark tool and skill context separately, completed work, interruptions, latency and cost | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [mono#752](https://github.com/recoupable/mono/issues/752) | Prove first-turn skill selection and fallback in installed hosts, unattended label operations and rollback | [api#1308](https://github.com/recoupable/api/issues/1308), [api#1310](https://github.com/recoupable/api/issues/1310), [api#1315](https://github.com/recoupable/api/issues/1315), [api#1316](https://github.com/recoupable/api/issues/1316) | +| [docs#44](https://github.com/recoupable/docs/issues/44) | Document skill visibility by client, on-demand reading, sign-in, Directory and legacy migration | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305) | +| [mono#753](https://github.com/recoupable/mono/issues/753) | Package and submit the qualified Directory profile for OpenAI review | [api#1309](https://github.com/recoupable/api/issues/1309), [docs#44](https://github.com/recoupable/docs/issues/44) | +| [mono#754](https://github.com/recoupable/mono/issues/754) | Roll out direct operations and retire each qualified legacy cohort | [mono#752](https://github.com/recoupable/mono/issues/752), [docs#44](https://github.com/recoupable/docs/issues/44) | + +The epic uses native GitHub sub-issues and blocking dependencies. The issues describe proposed owner roles, evidence and acceptance. API owns contracts, execution and the spec. Database owns persistence, App owns consumer compatibility, Docs owns public guides, and Mono coordinates qualification and release. The [existing OAuth epic](https://github.com/recoupable/mono/issues/207), [host matrix](https://github.com/recoupable/mono/issues/215), [MCP Apps work](https://github.com/recoupable/app/issues/2215) and [manifest work](https://github.com/recoupable/app/issues/2223) remain sources for the corresponding workstreams. + +**Critical path.** API #1308 proves the first saved action after ordinary sign-in. The durable label proof adds #1315 and #1316, then independent qualification in Mono #752. Optional saved instructions (#1313) build on durable jobs. Approved-step completion and resumption (#1314) build on action dispatch and use the owning API’s approval flow. App migration, saved instructions, approved-step resumption and Directory review are independent of the first permitted write. First-party legacy retirement still requires evidence for its actual callers. Provider delivery requires an owning API and an authoritative downstream outcome. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py new file mode 100644 index 000000000..fb3bd2540 --- /dev/null +++ b/docs/plans/mcp_code_mode_cases.py @@ -0,0 +1,40 @@ +"""Positive and negative examples for the proposed direct tool contracts.""" + +from mcp_code_mode_execution_cases import execute_cases, status_cases +from mcp_code_mode_search_cases import search_cases +from mcp_code_mode_skill_cases import skill_cases + + +def act_cases(): + """The API resolves authority from the account connection outside the guest.""" + call = {"id": "projects.createTask", "args": {"title": "Demo"}, "options": {"requestKey": "step-1"}} + yield True, "qualified shape", call + yield False, "missing options", {"id": call["id"], "args": call["args"]} + yield False, "missing step key", {**call, "options": {}} + yield False, "empty step key", {**call, "options": {"requestKey": ""}} + yield False, "oversized step key", {**call, "options": {"requestKey": "k" * 97}} + yield False, "guest approval override", {**call, "options": {"requestKey": "step-1", "approved": True}} + yield False, "guest authority override", {**call, "grant": "other"} + for field in ("accountId", "workerCredential", "approvalId"): + yield False, f"guest supplies {field}", {**call, "options": {"requestKey": "step-1", field: "other"}} + + +def contract_cases(action_capable): + yield from search_cases() + yield from skill_cases() + yield from execute_cases(action_capable) + yield from status_cases(action_capable) + + +def refusal_cases(): + block = {"type": "text", "text": '{"code":"not_admitted","retry":"reconnect","traceId":"trace-0"}'} + refusal = {"isError": True, "content": [block]} + yield True, "legacy pre-admission tool error", refusal + yield True, "modern pre-admission tool error", {**refusal, "resultType": "complete"} + yield False, "fabricated structured run", {**refusal, "structuredContent": {"state": "failed"}} + yield False, "not a tool error", {**refusal, "isError": False} + yield False, "unbounded payload", {**refusal, "content": [{**block, "text": "x" * 1025}]} + yield False, "malformed JSON", {**refusal, "content": [{**block, "text": "invalid"}]} + yield False, "raw personal data", { + **refusal, "content": [{**block, "text": '{"code":"denied","retry":"never","traceId":"t","private":"demo"}'}] + } diff --git a/docs/plans/mcp_code_mode_discovery.py b/docs/plans/mcp_code_mode_discovery.py new file mode 100644 index 000000000..52ccb9d22 --- /dev/null +++ b/docs/plans/mcp_code_mode_discovery.py @@ -0,0 +1,50 @@ +"""Check discovery and file results against independent, synthetic authorized catalog data.""" + +import base64 +import json + + +def wire_bytes(value): + return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + + +def valid_discovery(page, allowed_ops, allowed_skills, *, exact=False, next_cursor=None): + if "items" not in page or page.get("nextCursor") != next_cursor: + return False + if wire_bytes(page) > (12 if exact else 4) * 1024: + return False + for item in page["items"]: + if "skill" in item: + if allowed_skills.get(item["skill"]) != item["summary"]: + return False + else: + op = allowed_ops.get(item["id"]) + if op is None or (item["summary"], item["effect"]) != (op["summary"], op["effect"]): + return False + if "detail" in item and (not exact or item["detail"] != op.get("detail")): + return False + return True + + +def valid_file(request, envelope, manifest, byte_limit): + """A successful file read returns exact metadata and one authorized MCP content block.""" + structured = envelope.get("structuredContent") + name, file = request["skill"], request.get("file", "SKILL.md") + if not isinstance(structured, dict) or structured.get("guide") != {"skill": name, "file": file}: + return False + entry = manifest.get((name, file)) + if entry is None: + return False + uri, raw = entry + if len(raw) > byte_limit or wire_bytes(envelope) > byte_limit or envelope.get("isError", False): + return False + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + text = None + if text is not None and "\x00" not in text: + expected = {"type": "text", "text": text} + else: + blob = base64.b64encode(raw).decode("ascii") + expected = {"type": "resource", "resource": {"uri": uri, "blob": blob}} + return envelope.get("content") == [expected] diff --git a/docs/plans/mcp_code_mode_discovery_checks.py b/docs/plans/mcp_code_mode_discovery_checks.py new file mode 100644 index 000000000..085208d97 --- /dev/null +++ b/docs/plans/mcp_code_mode_discovery_checks.py @@ -0,0 +1,58 @@ +"""Offline catalog-audience and result-envelope checks, using synthetic grants and files.""" + +from mcp_code_mode_discovery import valid_discovery, valid_file + + +def discovery_checks(output_schema): + op = {"id": "catalog", "summary": "List catalog entries", "effect": "read"} + guide = {"skill": "catalog", "summary": "Review a recording"} + staff = {"skill": "staff-review", "summary": "Internal workflow"} + ops = {op["id"]: {**op, "detail": {"input": {}}}} + public = {guide["skill"]: guide["summary"]} + both = {**public, staff["skill"]: staff["summary"]} + detail = {**op, "detail": {"input": {}}} + for valid, label, skills, allowed_ops, items, exact, cursor in [ + (True, "mixed public catalog", public, ops, [op, guide], False, None), + (True, "exact identity collision", public, ops, [detail, guide], True, None), + (True, "staff guidance via entitled catalog", both, ops, [staff], True, None), + (True, "ordinary read-only account", {}, ops, [op], False, None), + (True, "hidden or missing exact hit", public, {}, [], True, None), + (False, "public sees staff hit", public, ops, [staff], False, None), + (False, "selected context sees guide", {}, ops, [guide], True, None), + (False, "inaccessible operation with same name as guide", public, {}, [op], True, None), + (False, "topic inlines contract", public, ops, [detail], False, None), + (False, "body disguised as guide summary", public, ops, [{**guide, "summary": "# Full guide"}], False, None), + (False, "hidden item changes cursor", public, ops, [op, guide], False, "unwarranted"), + ]: + page = {"revision": "v1", "items": items} + if cursor: + page["nextCursor"] = cursor + yield label, output_schema.is_valid(page) and valid_discovery( + page, allowed_ops, skills, exact=exact + ), valid + + name = guide["skill"] + raw, text_file, binary_file = b"Read the recording.", "SKILL.md", "assets/sample.bin" + uri = f"skill://{name}/{binary_file}" + manifest = {(name, text_file): (f"skill://{name}/{text_file}", raw), (name, binary_file): (uri, b"\xff")} + text_block = {"type": "text", "text": raw.decode()} + binary_block = {"type": "resource", "resource": {"uri": uri, "blob": "/w=="}} + for valid, label, file, files, blocks, budget, metadata_file in [ + (True, "default guide with structured metadata", None, manifest, [text_block], 256, text_file), + (True, "exact supporting binary", binary_file, manifest, [binary_block], 256, binary_file), + (False, "guide permission revoked since discovery", None, {}, [text_block], 256, text_file), + (False, "missing packaged file", "../SKILL.md", manifest, [text_block], 256, "../SKILL.md"), + (False, "success lacks content", None, manifest, [], 256, text_file), + (False, "wrong metadata file", None, manifest, [text_block], 256, binary_file), + (False, "multiple full bodies", None, manifest, [text_block, text_block], 256, text_file), + (False, "foreign embedded URI", binary_file, manifest, [ + {"type": "resource", "resource": {"uri": "skill://staff/private", "blob": "/w=="}} + ], 256, binary_file), + (False, "file exceeds runtime budget", None, manifest, [text_block], 1, text_file), + ]: + request = {"skill": name} + if file is not None: + request["file"] = file + structured = {"revision": "v1", "guide": {"skill": name, "file": metadata_file}} + envelope = {"structuredContent": structured, "content": blocks} + yield label, output_schema.is_valid(structured) and valid_file(request, envelope, files, budget), valid diff --git a/docs/plans/mcp_code_mode_execution_cases.py b/docs/plans/mcp_code_mode_execution_cases.py new file mode 100644 index 000000000..4a5e2abda --- /dev/null +++ b/docs/plans/mcp_code_mode_execution_cases.py @@ -0,0 +1,84 @@ +"""Input, result and status examples for direct execution.""" + + +def execute_cases(action_capable): + program = {"source": "async (recoup, params) => params", "revision": "v1", "params": {}} + receipt = {"runId": "run-1"} + keyed_program = {**program, "requestKey": "run-key"} + yield "execute", "input", not action_capable, "program without run key", program + yield "execute", "input", action_capable, "program with run key", keyed_program + yield "execute", "input", True, "receipt by run ID", receipt + yield "execute", "input", action_capable, "recovery after dropped response", {"requestKey": "run-key"} + yield "execute", "input", action_capable, "resume existing checkpoint", {**receipt, "resume": True} + yield "execute", "input", False, "resume with new source", {**receipt, "resume": True, "source": program["source"]} + yield "execute", "input", False, "resume without run ID", {"requestKey": "run-key", "resume": True} + yield "execute", "input", False, "resume with replacement params", {**receipt, "resume": True, "params": {}} + yield "execute", "input", False, "mixed recovery identifiers", {**receipt, "requestKey": "run-key"} + yield "execute", "input", False, "run key too long", {**program, "requestKey": "k" * 97} + yield "execute", "input", False, "empty run key", {**program, "requestKey": ""} + yield "execute", "input", False, "ignored approval flag", {**keyed_program, "approved": True} + for field in ("accountId", "workerCredential"): + yield "execute", "input", False, f"caller supplies {field}", { + **(keyed_program if action_capable else program), field: "other" + } + for key, value in program.items(): + yield "execute", "input", False, f"receipt with {key}", {**receipt, key: value} + yield "execute", "input", False, "program without revision", {"source": program["source"]} + output = {"traceId": "trace-1", "truncated": False} + if action_capable: + output.update(receipt) + yield "execute", "output", True, "complete", {**output, "state": "complete", "value": []} + yield "execute", "output", False, "missing complete value", {**output, "state": "complete"} + for truncated in (True, False): + yield "execute", "output", True, f"partial truncated={truncated}", { + **output, "state": "partial", "truncated": truncated, "value": [] + } + for state in ("complete", "succeeded"): + yield "execute", "output", False, f"truncated {state}", { + **output, "state": state, "truncated": True, "value": [] + } + + bare = {"state": "complete", "traceId": "trace-1", "truncated": False, "value": []} + yield "execute", "output", not action_capable, "complete without durable run ID", bare + for state in ("partial", "canceled", "succeeded", "failed"): + result = {**bare, "state": state} + if state == "failed": + result["error"] = {"code": "guest_failed", "retry": "never"} + yield "execute", "output", not action_capable, f"{state} without durable run ID", result + + +def status_cases(action_capable): + receipt = {"runId": "run-1"} + base = {"traceId": "trace-1", "truncated": False} + error = {"code": "outcome_uncertain", "retry": "reconcile"} + approval = {**base, **receipt, "state": "approval_required"} + link = "https://app.recoupable.dev/mcp/approvals/run-1" + yield "execute", "output", action_capable, "API approval link", {**approval, "approvalUrl": link} + yield "execute", "output", False, "approval step state is internal", { + **approval, "approvalUrl": link, "intent": "step-1" + } + yield "execute", "output", False, "approval link after success", { + **base, **receipt, "state": "succeeded", "approvalUrl": link + } + for bad_url in ( + "https://elsewhere.example/mcp/approvals/run-1", + "http://app.recoupable.dev/mcp/approvals/run-1", + "https://app.recoupable.dev/mcp/approvals/run-2", + "https://app.recoupable.dev/mcp/approvals/run-1?next=https://elsewhere.example", + ): + yield "execute", "output", False, "untrusted approval destination", {**approval, "approvalUrl": bad_url} + yield "execute", "output", False, "foreign receipt and matching URL", { + **approval, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" + } + yield "execute", "output", False, "missing approval link", approval + for state in ("accepted", "running", "unknown_outcome"): + status = {**base, "state": state} + if state == "unknown_outcome": + status["error"] = error + yield "execute", "output", action_capable or state != "unknown_outcome", state, {**status, **receipt} + yield "execute", "output", False, f"{state} missing run ID", status + for state in ("denied", "expired", "failed", "unknown_outcome"): + status = {**base, **receipt, "state": state} + yield "execute", "output", action_capable or state == "failed", f"{state} with error", {**status, "error": error} + yield "execute", "output", False, f"{state} missing error", status + yield "execute", "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} diff --git a/docs/plans/mcp_code_mode_recovery.py b/docs/plans/mcp_code_mode_recovery.py new file mode 100644 index 000000000..da9dd5980 --- /dev/null +++ b/docs/plans/mcp_code_mode_recovery.py @@ -0,0 +1,71 @@ +"""Broker-owned evidence projection and recovery examples for admitted runs.""" + +import re + + +def valid_recovery(payload, run_id, ledger_steps): + """Check the broker projection against an authorized receipt, never guest claims.""" + if payload.get("runId") != run_id: + return False + if ledger_steps is None: + return True + if run_id is None or len(ledger_steps) > 16 or payload.get("value") != {"steps": ledger_steps}: + return False + required = {"stepId", "state", "receiptRef"} + allowed = required | {"readbackRef"} + step_ids = set() + for step in ledger_steps: + if not isinstance(step, dict) or not required <= step.keys() <= allowed: + return False + if step["state"] not in { + "approval_required", "accepted", "running", "succeeded", "failed", + "denied", "expired", "canceled", "unknown_outcome" + }: + return False + for key in step.keys() - {"state"}: + if not isinstance(step[key], str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", step[key]): + return False + if step["stepId"] in step_ids: + return False + step_ids.add(step["stepId"]) + return True + + +def recovery_cases(): + """Wire examples plus trusted, independently queried run/step facts from the fixture.""" + run_id = "run-1" + steps = [ + {"stepId": "step_1", "state": "succeeded", "receiptRef": "rcpt_1", "readbackRef": "evid_1"}, + {"stepId": "step_2", "state": "unknown_outcome", "receiptRef": "rcpt_2"}, + ] + failed = { + "runId": run_id, "state": "failed", "error": {"code": "guest_failed", "retry": "reconcile"}, + "traceId": "trace-1", "truncated": False, + } + recovered = {**failed, "value": {"steps": steps}} + yield True, "two acts then throw, recover by original key", run_id, steps, recovered + yield True, "source result keeps guest value after admission", run_id, None, { + "runId": run_id, "state": "complete", "traceId": "trace-1", "truncated": False, "value": "guest value" + } + for state in ("complete", "partial", "failed", "canceled", "succeeded"): + missing_id = {**failed, "state": state, "value": {"steps": steps}} + del missing_id["runId"] + yield False, f"admitted {state} missing run ID", run_id, None, missing_id + early_failure = {k: v for k, v in failed.items() if k != "runId"} + yield False, "pre-admission failure outside structured content", None, None, early_failure + yield False, "foreign durable run", "run-2", steps, recovered + yield False, "receipt missing ledger projection", run_id, steps, failed + for label, entries in ( + ("guest hides an effect", steps[:1]), + ("guest changes uncertain outcome", [steps[0], {**steps[1], "state": "succeeded"}]), + ("foreign readback reference", [{**steps[0], "readbackRef": "evid_other"}, steps[1]]), + ("guest duplicates a receipt", [steps[0], steps[0]]), + ("guest reorders effects", list(reversed(steps))), + ): + yield False, label, run_id, steps, {**recovered, "value": {"steps": entries}} + for label, entries in ( + ("signed URL in readback", [{**steps[0], "readbackRef": "https://example.test/private?token=demo"}]), + ("raw provider body", [{**steps[0], "providerResponse": {"internal": True}}]), + ("too many steps", steps * 9), + ): + yield False, label, run_id, entries, {**recovered, "value": {"steps": entries}} diff --git a/docs/plans/mcp_code_mode_resume.py b/docs/plans/mcp_code_mode_resume.py new file mode 100644 index 000000000..e404f0310 --- /dev/null +++ b/docs/plans/mcp_code_mode_resume.py @@ -0,0 +1,48 @@ +"""In-memory spec model of one API-owned effect and one recorded continuation.""" + +from dataclasses import dataclass, field + + +@dataclass +class SavedStep: + effect: tuple[str, str, str] # Operation, canonical argument digest and stable receipt. + authorized: bool = True + decision: str = "approved" + api_state: str = "needs_completion" + safe_checkpoint: bool = True + completion_acknowledged: bool = True + calls: list = field(default_factory=list) + continuations: int = 0 + + def continue_with(self, method): + """Model a serialized step claim after the caller's receipt and scope are verified.""" + if not self.authorized: + return "denied" + if method == "status": + return "observed" + if method != "resume": + raise ValueError(f"Unknown fixture method {method}") + if self.api_state == "unknown": + return "unknown_outcome" + if self.api_state == "claimed": + return "running" + if self.api_state == "needs_completion": + if self.decision == "pending": + return "approval_required" + if self.decision in ("denied", "expired"): + return self.decision + if self.decision != "approved": + raise ValueError(f"Unknown fixture decision {self.decision}") + self.api_state = "claimed" + self.calls.append(self.effect) + if not self.completion_acknowledged: + self.api_state = "unknown" + return "unknown_outcome" + self.api_state = "applied" + if self.api_state != "applied": + raise ValueError(f"Unknown fixture completion state {self.api_state}") + if not self.safe_checkpoint: + return "step_settled" + if not self.continuations: + self.continuations += 1 + return "continued" diff --git a/docs/plans/mcp_code_mode_resume_cases.py b/docs/plans/mcp_code_mode_resume_cases.py new file mode 100644 index 000000000..3ef42aac2 --- /dev/null +++ b/docs/plans/mcp_code_mode_resume_cases.py @@ -0,0 +1,41 @@ +"""Examples for an in-memory model of exact completion. No calls reach a provider.""" + +from mcp_code_mode_resume import SavedStep + + +def resume_cases(): + saved = ("op-1", "args-digest", "receipt-1") + for label, facts, expected in [ + ("waiting for approval", {"decision": "pending"}, ("approval_required", [], 0)), + ("API denied", {"decision": "denied"}, ("denied", [], 0)), + ("approval expired", {"decision": "expired"}, ("expired", [], 0)), + ("account access revoked", {"authorized": False}, ("denied", [], 0)), + ("approved and the API still needs completion", {}, ("continued", [saved], 1)), + ("API already applied the change", {"api_state": "applied"}, ("continued", [], 1)), + ("provider outcome ambiguous", {"api_state": "unknown"}, ("unknown_outcome", [], 0)), + ("another caller holds the claim", {"api_state": "claimed"}, ("running", [], 0)), + ("API applied without a safe JS continuation", + {"api_state": "applied", "safe_checkpoint": False}, ("step_settled", [], 0)), + ("exact completion without a safe JS continuation", + {"safe_checkpoint": False}, ("step_settled", [saved], 0)), + ("completion response lost without evidence", + {"completion_acknowledged": False}, ("unknown_outcome", [saved], 0)), + ]: + step = SavedStep(saved, **facts) + state = step.continue_with("resume") + yield label, (state, step.calls, step.continuations), expected + + for label, methods, states, calls, continuations in [ + ("lookup by key and run ID only observes", ["status", "status"], ["observed"] * 2, [], 0), + ("one exact step claimed by a retried resume", + ["resume", "resume"], ["continued", "continued"], [saved], 1), + ("status between two resumes observes the settled effect", + ["resume", "status", "resume"], ["continued", "observed", "continued"], [saved], 1), + ]: + step = SavedStep(saved) + outcomes = [step.continue_with(method) for method in methods] + yield label, (outcomes, step.calls, step.continuations), (states, calls, continuations) + + step = SavedStep(saved, completion_acknowledged=False) + outcomes = [step.continue_with(method) for method in ("resume", "resume", "resume")] + yield "uncertain dispatch remains single", (outcomes, step.calls), (["unknown_outcome"] * 3, [saved]) diff --git a/docs/plans/mcp_code_mode_search_cases.py b/docs/plans/mcp_code_mode_search_cases.py new file mode 100644 index 000000000..52a106fdd --- /dev/null +++ b/docs/plans/mcp_code_mode_search_cases.py @@ -0,0 +1,40 @@ +"""Examples for distinct operation and skill previews returned by one search.""" + +from itertools import combinations + + +def search_cases(): + search = {"query": "catalogs", "id": "catalogs.listOwned", "cursor": "next"} + for key, value in search.items(): + yield "search", "input", True, key, {key: value} + for left, right in combinations(search, 2): + yield "search", "input", False, f"{left} and {right}", {left: search[left], right: search[right]} + yield "search", "input", False, "exact preview mixed with file read", {"id": "guide", "file": "SKILL.md"} + yield "search", "input", False, "caller selects audience", {"query": "guide", "audience": "all"} + yield "search", "input", False, "caller requests a kind filter", {"query": "guide", "kind": "skills"} + yield "search", "input", True, "list allowed guides", {} + op = {"id": "catalogs.listOwned", "summary": "List owned catalogs", "effect": "read"} + skill = {"skill": "catalogs", "summary": "How to review label catalogs"} + for label, items in [ + ("operation only", [op]), ("skill only", [skill]), ("no matches", []), + ("one of each", [op, skill]), ("same name, distinct kinds", [{**op, "id": "catalogs"}, skill]), + ("exact operation contract", [{**op, "detail": {"input": {"type": "object"}}}]), + ]: + yield "search", "output", True, label, {"revision": "v1", "items": items} + for key in op: + incomplete = {k: v for k, v in op.items() if k != key} + yield "search", "output", False, f"operation missing {key}", {"revision": "v1", "items": [incomplete]} + for label, item in [ + ("skill missing summary", {"skill": "guide"}), ("no result discriminator", {"summary": "guide"}), + ("skill also includes operation id", {**skill, "id": "catalogs"}), + ("skill also includes effect", {**skill, "effect": "read"}), + ("skill with contract detail", {**skill, "detail": {}}), + ("skill with guide body", {**skill, "content": "# Instructions"}), + ("skill with file", {**skill, "file": "SKILL.md"}), + ("name rejected by guide reader", {**skill, "skill": "catalog/../../file"}), + ("oversized name", {**skill, "skill": "a" * 65}), + ("oversized summary", {**skill, "summary": "s" * 513}), + ("invalid operation effect", {**op, "effect": "instruction"}), + ]: + yield "search", "output", False, label, {"revision": "v1", "items": [item]} + yield "search", "output", False, "combined page cap", {"revision": "v1", "items": [op] * 5 + [skill] * 4} diff --git a/docs/plans/mcp_code_mode_skill_cases.py b/docs/plans/mcp_code_mode_skill_cases.py new file mode 100644 index 000000000..380aca692 --- /dev/null +++ b/docs/plans/mcp_code_mode_skill_cases.py @@ -0,0 +1,40 @@ +"""Guide reads through the same search tool that returns workflow previews.""" + + +def skill_cases(): + read = {"skill": "release-guide"} + guide = {"skill": "release-guide", "file": "SKILL.md"} + for reason, request in [ + ("list", {}), ("topic", {"query": "release"}), ("next page", {"cursor": "next"}), + ("instructions", read), + ("supporting text", {**read, "file": "references/guide.md"}), + ("supporting binary", {**read, "file": "assets/template.pdf"}), + ("longest name", {"skill": "a" * 64}), + ]: + yield "search", "input", True, reason, request + for reason, request in [ + ("relative file without skill", {"file": "SKILL.md"}), + ("query with selected skill", {"query": "release", **read}), + ("exact id with selected skill", {"id": "release-guide", **read}), + ("cursor with selected skill", {"cursor": "next", **read}), + ("offset with selected skill", {"offset": 0, **read}), + ("empty name", {"skill": ""}), ("invalid name", {"skill": "unknown/../name"}), + ("long name", {"skill": "a" * 65}), ("long query", {"query": "q" * 201}), + ("negative offset", {"offset": -1}), ("fractional offset", {"offset": 0.5}), + ("empty file", {**read, "file": ""}), ("long file", {**read, "file": "a" * 1025}), + ("caller selects audience", {**read, "audience": "all"}), + ("caller selects account", {**read, "accountId": "other"}), + ("caller supplies resource URI", {"uri": "skill://release-guide/SKILL.md"}), + ]: + yield "search", "input", False, reason, request + response = {"revision": "v1", "guide": guide} + yield "search", "output", True, "structured guide result", response + for label, invalid in [ + ("guide result lacks revision", {"guide": guide}), + ("guide metadata lacks file", {**response, "guide": read}), + ("guide metadata contains body", {**response, "guide": {**guide, "text": "contents"}}), + ("guide result has discovery items", {**response, "items": []}), + ("guide result has next cursor", {**response, "nextCursor": "secret"}), + ("guide result has no discriminator", {"revision": "v1"}), + ]: + yield "search", "output", False, label, invalid diff --git a/docs/plans/mcp_code_mode_startup.py b/docs/plans/mcp_code_mode_startup.py new file mode 100644 index 000000000..9054d1e37 --- /dev/null +++ b/docs/plans/mcp_code_mode_startup.py @@ -0,0 +1,78 @@ +"""Validate a normalized native Skills startup trace against a known static test catalog.""" + +import hashlib +import json + + +def valid_startup(trace, authorized_entries): + """The trace omits unrelated host events and retains all skill-derived input and reads.""" + by_uri = {entry["uri"]: entry for entry in authorized_entries} + expected = sorted( + (entry["frontmatter"]["name"], entry["frontmatter"]["description"]) + for entry in authorized_entries + ) + resources = {item["uri"]: item for entry in authorized_entries for item in entry["resources"]} + seen, cursors = set(), set() + events = iter(trace) + cursor = None + while True: + event = next(events, ()) + if len(event) != 3 or event[:2] != ("skills/list", cursor): + return False + page = event[2] + if page["cacheScope"] != "private" or page["resultType"] != "complete": + return False + for entry in page["skills"]: + uri = entry["uri"] + if uri in seen or by_uri.get(uri) != entry: + return False + seen.add(uri) + cursor = page.get("nextCursor") + if cursor is None: + break + if cursor in cursors: + return False + cursors.add(cursor) + if seen != by_uri.keys(): + return False + + for phase in ("host.ready", "first_task", "first_model_input"): + event = next(events, ()) + if phase == "first_task": + if event != (phase,): + return False + continue + if len(event) != 2 or event[0] != phase: + return False + pairs = [] + for row in event[1]: + if set(row) != {"name", "description"}: + return False + pairs.append((row["name"], row["description"])) + if sorted(pairs) != expected: + return False + + for event in events: + if len(event) != 2 or event[0] != "need_file" or event[1] not in resources: + return False + uri = event[1] + read = next(events, ()) + if len(read) != 3 or read[:2] != ("resources/read", uri): + return False + raw = read[2] + resource = resources[uri] + if len(raw) != resource["size"] or "sha256:" + hashlib.sha256(raw).hexdigest() != resource["digest"]: + return False + return True + + +def report_startup_size(pages, summaries, encoding): + """Report a reproducible projection separately from tool descriptors or hosted prompt usage.""" + def compact(value): + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + + result_bytes = sum(len(compact(event[2]).encode("utf-8")) for event in pages) + projection = compact(summaries) + print(f"Synthetic native Skills startup: {len(pages)} list pages, {result_bytes:,} result bytes; " + f"{len(summaries)} model-facing names/descriptions, {len(projection.encode('utf-8')):,} bytes, " + f"{len(encoding.encode_ordinary(projection)):,} reference tokens (outside descriptor gate)") diff --git a/docs/plans/mcp_code_mode_startup_cases.py b/docs/plans/mcp_code_mode_startup_cases.py new file mode 100644 index 000000000..cf3d21e99 --- /dev/null +++ b/docs/plans/mcp_code_mode_startup_cases.py @@ -0,0 +1,71 @@ +"""Synthetic host receipts for a cold connection with two native Skills pages.""" + +from hashlib import sha256 + +from mcp_code_mode_startup import valid_startup + + +def skill(name, description, supporting=False): + prefix = f"skill://recoup/{name}/" + guide = f"---\nname: {name}\ndescription: {description}\n---\nFollow the guide for {name}." + files = {prefix + "SKILL.md": guide.encode()} + if supporting: + files[prefix + "references/example.txt"] = b"An example requested later." + resources = [ + {"uri": uri, "size": len(raw), "digest": "sha256:" + sha256(raw).hexdigest()} + for uri, raw in files.items() + ] + return {"uri": prefix + "SKILL.md", "frontmatter": {"name": name, "description": description}, + "resources": resources}, files + + +def list_page(cursor, skills, next_cursor=None): + page = {"resultType": "complete", "ttlMs": 0, "cacheScope": "private", "skills": skills} + if next_cursor: + page["nextCursor"] = next_cursor + return ("skills/list", cursor, page) + + +CATALOG, CATALOG_FILES = skill("catalog", "Review a recording", supporting=True) +RELEASE, _ = skill("release", "Prepare a release") +STAFF, _ = skill("staff-review", "Internal workflow") +PUBLIC = [CATALOG, RELEASE] +SUMMARIES = [entry["frontmatter"] for entry in PUBLIC] +PAGES = [list_page(None, [CATALOG], "page-two"), list_page("page-two", [RELEASE])] + + +def startup_cases(): + ready = ("host.ready", SUMMARIES) + task = ("first_task",) + model = ("first_model_input", SUMMARIES) + first = [*PAGES, ready, task, model] + guide, example = CATALOG_FILES + + def demand(uri): + return [("need_file", uri), ("resources/read", uri, CATALOG_FILES[uri])] + + for label, trace, valid in [ + ("all authorized names before first task", first, True), + ("model order independent", [*PAGES, ready, task, ("first_model_input", SUMMARIES[::-1])], True), + ("guide alone selected", first + demand(guide), True), + ("support chosen after guide", first + demand(guide) + demand(example), True), + ("wire receipt alone", PAGES, False), + ("host registry but no first-model proof", [*PAGES, ready, task], False), + ("page two silently dropped", [PAGES[0], ready, task, model], False), + ("server ended early despite known audience", [list_page(None, [CATALOG]), ready, task, model], False), + ("wrong continuation", [PAGES[0], list_page("wrong", [RELEASE]), ready, task, model], False), + ("duplicate entries", [list_page(None, [CATALOG, CATALOG, RELEASE]), ready, task, model], False), + ("staff in wire catalog", [list_page(None, [*PUBLIC, STAFF]), ready, task, model], False), + ("staff in model prompt", [*PAGES, ready, task, ("first_model_input", [*SUMMARIES, STAFF["frontmatter"]])], False), + ("last-page model summary missing", [*PAGES, ready, task, ("first_model_input", SUMMARIES[:1])], False), + ("manifests in model prompt", [*PAGES, ready, task, ("first_model_input", PUBLIC)], False), + ("task precedes host readiness", [*PAGES, task, ready, model], False), + ("model must search first", [*PAGES, ready, task, ("tools/call", "search"), model], False), + ("body read on connect", [*PAGES, demand(guide)[1], ready, task, model], False), + ("supporting file prefetched on activation", first + demand(guide) + [demand(example)[1]], False), + ("file substituted after demand", first + [("need_file", guide), demand(example)[1]], False), + ("wrong file bytes", first + [("need_file", guide), ("resources/read", guide, b"wrong")], False), + ]: + yield label, valid_startup(trace, PUBLIC), valid + empty = [list_page(None, []), ("host.ready", []), task, ("first_model_input", [])] + yield "empty eligible inventory", valid_startup(empty, []), True diff --git a/docs/plans/mcp_code_mode_validation.py b/docs/plans/mcp_code_mode_validation.py new file mode 100644 index 000000000..d89657afc --- /dev/null +++ b/docs/plans/mcp_code_mode_validation.py @@ -0,0 +1,70 @@ +"""Validate direct profile descriptors, tool outputs and pre-admission error envelopes.""" + +import json +from urllib.parse import quote + +from jsonschema import Draft202012Validator +from referencing import Registry + +from mcp_code_mode_cases import contract_cases + + +def trusted_approval_link(payload, receipt_run_id): + if "approvalUrl" not in payload: + return True + if payload.get("state") != "approval_required" or payload.get("runId") != receipt_run_id: + return False + expected = "https://app.recoupable.dev/mcp/approvals/" + quote(receipt_run_id, safe="") + return payload["approvalUrl"] == expected + + +def verify_profile(tools, action_capable): + expected_names = ["search", "execute"] + if [tool["name"] for tool in tools] != expected_names: + raise ValueError(f"Expected descriptors in order {expected_names}.") + failures = [] + validators = {} + for tool in tools: + name = tool["name"] + effectful = name == "execute" and action_capable + expected_hints = { + "readOnlyHint": not effectful, + "destructiveHint": effectful, + "openWorldHint": effectful, + } + if tool["annotations"] != expected_hints: + failures.append(f"{name} annotations differ from the fixture's admitted effects.") + for direction in ("input", "output"): + schema = tool[f"{direction}Schema"] + Draft202012Validator.check_schema(schema) + validators[name, direction] = Draft202012Validator(schema, registry=Registry()) + cases = list(contract_cases(action_capable)) + for name, direction, valid, label, payload in cases: + accepted = validators[name, direction].is_valid(payload) + if direction == "output" and name == "execute": + accepted = accepted and trusted_approval_link(payload, receipt_run_id="run-1") + if accepted != valid: + failures.append(f"{name} {direction} ({label}): expected {'valid' if valid else 'invalid'}") + return len(validators), len(cases), failures + + +def valid_preadmission_refusal(envelope): + if envelope.get("isError") is not True or "structuredContent" in envelope: + return False + blocks = envelope.get("content", []) + if len(blocks) != 1 or blocks[0].get("type") != "text": + return False + body = blocks[0].get("text") + if not isinstance(body, str) or len(body.encode("utf-8")) > 1024: + return False + try: + error = json.loads(body) + except ValueError: + return False + if not isinstance(error, dict) or error.keys() != {"code", "retry", "traceId"}: + return False + return ( + isinstance(error["code"], str) and 0 < len(error["code"]) <= 64 + and isinstance(error["traceId"], str) and 0 < len(error["traceId"]) <= 256 + and error["retry"] in ("narrow", "rediscover", "reconnect", "reconcile", "backoff", "never") + ) diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py new file mode 100644 index 000000000..36d51b10c --- /dev/null +++ b/docs/plans/verify-mcp-code-mode.py @@ -0,0 +1,103 @@ +"""Verify the proposed direct MCP descriptors and their reference token budget. + +Requires jsonschema and tiktoken (reference versions 4.26.0 and 0.14.0). +Preload tiktoken's official o200k_base vocabulary. For a custom cache, set +TIKTOKEN_CACHE_DIR to its directory before running this script. No credentials +or live Recoup server are needed. +""" + +import hashlib +import json +import os +import sys +import tempfile +from importlib.metadata import version +from pathlib import Path + +import tiktoken +from jsonschema import Draft202012Validator +from referencing import Registry + +from mcp_code_mode_cases import act_cases, refusal_cases +from mcp_code_mode_discovery_checks import discovery_checks +from mcp_code_mode_recovery import recovery_cases, valid_recovery +from mcp_code_mode_resume_cases import resume_cases +from mcp_code_mode_startup import report_startup_size +from mcp_code_mode_startup_cases import PAGES, SUMMARIES, startup_cases +from mcp_code_mode_validation import valid_preadmission_refusal, verify_profile + +MANIFEST = Path(__file__).with_name("mcp-code-mode-tools.json") +TOKEN_LIMIT = 1_500 +VOCABULARY_URL = "https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken" +VOCABULARY_SHA256 = "446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d" + + +def cached_encoding(): + default_dir = Path(tempfile.gettempdir()) / "data-gym-cache" + cache_dir = os.environ.get("TIKTOKEN_CACHE_DIR", os.environ.get("DATA_GYM_CACHE_DIR", default_dir)) + cache_key = hashlib.sha1(VOCABULARY_URL.encode()).hexdigest() + cache_file = Path(cache_dir) / cache_key + if not cache_dir or not cache_file.is_file(): + raise ValueError(f"Preload the official o200k_base vocabulary in {cache_file}.") + if hashlib.sha256(cache_file.read_bytes()).hexdigest() != VOCABULARY_SHA256: + raise ValueError(f"Vocabulary digest mismatch in {cache_file}.") + return tiktoken.get_encoding("o200k_base") + + +def main(): + fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) + search, execute = fixture["tools"] + read_execute = {**execute, **fixture["readOnlyExecute"]} + profiles = [ + ("Read only", [search, read_execute], False), + ("Account action", [search, execute], True), + ] + encoding = cached_encoding() + print(f"tiktoken {version('tiktoken')}, {encoding.name}") + failures = [] + for profile, tools, action_capable in profiles: + schemas, cases, mismatches = verify_profile(tools, action_capable) + failures.extend(f"{profile}: {message}" for message in mismatches) + wire = json.dumps({"tools": tools}, ensure_ascii=False, separators=(",", ":")) + tokens = len(encoding.encode_ordinary(wire)) + print(f"{profile}: {len(tools)} descriptors, {schemas} schemas, {cases} cases, " + f"{len(wire.encode('utf-8')):,} bytes, {tokens:,} tokens") + if tokens > TOKEN_LIMIT: + failures.append(f"{profile} exceeds the {TOKEN_LIMIT:,}-token gate.") + report_startup_size(PAGES, SUMMARIES, encoding) + schema = fixture["actRequest"] + Draft202012Validator.check_schema(schema) + act_validator = Draft202012Validator(schema, registry=Registry()) + cases = list(act_cases()) + for valid, label, request in cases: + if act_validator.is_valid(request) != valid: + failures.append(f"Guest act request ({label}): expected {'valid' if valid else 'invalid'}") + print(f"Guest act RPC: 1 schema, {len(cases)} cases (excluded from MCP descriptor counts)") + action_output = Draft202012Validator(execute["outputSchema"], registry=Registry()) + recoveries = list(recovery_cases()) + for valid, label, run_id, ledger_steps, payload in recoveries: + accepted = action_output.is_valid(payload) and valid_recovery(payload, run_id, ledger_steps) + if accepted != valid: + failures.append(f"Broker recovery ({label}): expected {'valid' if valid else 'invalid'}") + print(f"Broker recovery: {len(recoveries)} cases (conditional status projection)") + search_output = Draft202012Validator(search["outputSchema"], registry=Registry()) + for family, examples in [("API approval continuation", resume_cases()), + ("Native Skills before first task", startup_cases()), + ("Scoped search and guide reads", discovery_checks(search_output))]: + simulated = list(examples) + for label, actual, expected in simulated: + if actual != expected: + failures.append(f"{family} ({label}): {actual!r} differs from {expected!r}") + print(f"{family}: {len(simulated)} simulated cases") + refusals = list(refusal_cases()) + for valid, label, envelope in refusals: + if valid_preadmission_refusal(envelope) != valid: + failures.append(f"Pre-admission refusal ({label}): expected {'valid' if valid else 'invalid'}") + print(f"Pre-admission MCP tool errors: {len(refusals)} cases") + for failure in failures: + print(failure, file=sys.stderr) + return int(bool(failures)) + + +if __name__ == "__main__": + sys.exit(main())