From f2c06d0e37aabeb186dd858d7ec34828127f9df2 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:43:16 -0500 Subject: [PATCH 01/13] Specify a governed code-mode migration for Recoup MCP --- docs/plans/mcp-code-mode-baseline.md | 55 ++++ docs/plans/mcp-code-mode-protocol.md | 70 +++++ docs/plans/mcp-code-mode-research.md | 46 +++ docs/plans/mcp-code-mode-tools.json | 440 +++++++++++++++++++++++++++ docs/plans/mcp-code-mode.md | 159 ++++++++++ 5 files changed, 770 insertions(+) create mode 100644 docs/plans/mcp-code-mode-baseline.md create mode 100644 docs/plans/mcp-code-mode-protocol.md create mode 100644 docs/plans/mcp-code-mode-research.md create mode 100644 docs/plans/mcp-code-mode-tools.json create mode 100644 docs/plans/mcp-code-mode.md diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md new file mode 100644 index 000000000..6f9f956eb --- /dev/null +++ b/docs/plans/mcp-code-mode-baseline.md @@ -0,0 +1,55 @@ +# 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 measure discovery. 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 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 broker should enter an API-owned operation using a verified principal and that operation's delegated projection. Provisioning a broad key for a code program would change the granted authority. [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, skill fallback, staff audience and thread placement independently. [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 + +Generate searchable descriptors from stable OpenAPI operation IDs and reviewed domain adapters. Keep one policy identifier per meaningful operation, including Context actions that share a REST 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) | +| 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, approval, execution, independent readback, cleanup, expiry, revocation and reconnect for the code-mode candidate and named host version. 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..4762530c7 --- /dev/null +++ b/docs/plans/mcp-code-mode-protocol.md @@ -0,0 +1,70 @@ +# Recoup MCP protocol compatibility and OpenAI review + +**Decision record for the proposed cutover, November 27, 2026.** Recoup can deliver a two-tool code-mode server to direct MCP clients. 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 | Keep `search` read-only. Enforce the advertised bounds of `execute` across all reachable operations. Preparing an effect qualifies as a read-only preview only if the operation does not persist artifacts, enqueue jobs, reserve budget or alter external state. A materialized proposal must carry accurate effects metadata. The optional `commit` requires trusted, transaction-specific approval and fresh authority. An annotation, a model-authored field or a tool retry does not authorize a write. 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. Reconcile durable side effects through application receipts. Server-side idempotency and truthful partial outcomes matter even when a host retries transparently. [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. Require independently verifiable authorization for commits. Supply a Recoup-owned authenticated confirmation flow where the host lacks the necessary interaction. Keep ordinary reads usable with a text-only client. 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. Keep the essential search and execution contracts callable without preloading either. 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) + +## Extension adoption + +Negotiate each optional extension using the peer's advertised capabilities. Test 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 | Evaluate enterprise machine access and centrally managed grants as separate products when required. ChatGPT's delegated account connection uses interactive authorization code with PKCE. 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 | Preserve entitled resources, manifest verification, `skills/list`, `skills/get` and supporting file reads for native clients. Direct clients lacking native support can use bounded skill discovery/read within `search`. A skill cannot expand API permissions. OpenAI's release package includes only reviewed audience-appropriate skills. Verify packaged and native behaviors independently. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | +| 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) | + +## 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. A text-only client with no optional capabilities must complete the read flow. 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 direct discovery, authorized read, multi-operation composition, skill fallback, denied write and confirmation handling. Record receipt readback when a controlled confirmed write is supported. 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. Introduce a dedicated delegated catalog-read grant. The existing narrow MCP grant does not include these operations. 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..d97564a8a --- /dev/null +++ b/docs/plans/mcp-code-mode-research.md @@ -0,0 +1,46 @@ +# Code Mode research for the Recoup MCP cutover + +Reviewed November 27, 2026. This evidence informs the proposed architecture. Vendor measurements describe their workloads. The rollout needs its own 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. 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. That lets the broker enforce account, resource, effect and response rules on every call. [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 locally studied v2 source is `40be470` (CLI `2.0.0-beta.73`). On the review date the upstream default branch was `v2` at `95c6b6b` (CLI `2.0.0-beta.80`), 44 commits ahead of that snapshot. We compared the trees and checked current MCP registrations. The latest GitHub *release* endpoint identified `v1.6.11`. Keep tagged releases, beta source and the consuming application's verified dependency distinct. The review covered source contracts and implementation. Runtime compatibility with Recoup still requires fixtures and deployed qualification. [Pinned upstream tree](https://github.com/UsefulSoftwareCo/executor/tree/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf) · [CLI version](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/apps/cli/package.json) · [Compared revisions](https://github.com/UsefulSoftwareCo/executor/compare/40be47066a0c2803211acd618662901e77de9f25...95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf) · [v1.6.11 release](https://github.com/UsefulSoftwareCo/executor/releases/tag/v1.6.11) + +| 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 principal and selected organization outside the guest program. Discoverability, a generated type and a previous successful call each supply information only. The current request's resource authorization and effect policy govern dispatch. | +| 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. Evaluate an effect-specific third tool for independent host confirmation. | +| 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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. For Recoup, the stronger reason to spend a third tool is a distinct user-visible effect boundary when required by the host. [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) + +## Execution choices + +The guest program needs standard JavaScript control flow, JSON values and a narrow asynchronous host call. The trusted side owns the route, credentials, principal, method, resource checks and call ledger. 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. Return ranked summaries before details. 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, prepare a seeded disposable object, obtain real confirmation, read back the effect independently and exercise cleanup. 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 wire bytes, actual or explicitly estimated prompt tokens, discovery 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 the actual confirmation UI in each release target. 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..b46faded7 --- /dev/null +++ b/docs/plans/mcp-code-mode-tools.json @@ -0,0 +1,440 @@ +{ + "tools": [ + { + "name": "search", + "title": "Find Recoup operations and skills", + "description": "Discover operations available to this connection. Request details by exact ID or read an authorized skill file. A cursor continues the same query.", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "kind": { + "type": "string", + "enum": [ + "operations", + "skills" + ] + }, + "file": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "cursor": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } + }, + "required": [], + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "query" + ] + }, + { + "required": [ + "id" + ] + }, + { + "required": [ + "cursor" + ] + } + ], + "allOf": [ + { + "if": { + "required": [ + "file" + ] + }, + "then": { + "required": [ + "id", + "kind" + ], + "properties": { + "kind": { + "const": "skills" + } + } + } + } + ] + }, + "outputSchema": { + "type": "object", + "properties": { + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "items": { + "type": "array", + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": true + } + }, + "nextCursor": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } + }, + "required": [ + "revision", + "items" + ], + "additionalProperties": false + }, + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + } + }, + { + "name": "execute", + "title": "Run a Recoup read or preview", + "description": "Run one async JavaScript function (recoup, params) against authorized Recoup operations. Use recoup.read(id, args) or recoup.prepare(id, args), then return a bounded JSON result. A runId reads an existing 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" + ], + "not": { + "required": [ + "runId" + ] + } + }, + { + "required": [ + "runId" + ], + "not": { + "anyOf": [ + { + "required": [ + "source" + ] + }, + { + "required": [ + "revision" + ] + }, + { + "required": [ + "params" + ] + } + ] + } + } + ] + }, + "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 + } + }, + "required": [ + "state", + "traceId", + "truncated" + ], + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "state": { + "enum": [ + "approval_required", + "accepted", + "running", + "unknown_outcome" + ] + } + } + }, + "then": { + "required": [ + "runId" + ] + } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "denied", + "expired", + "failed", + "unknown_outcome" + ] + } + } + }, + "then": { + "required": [ + "error" + ] + } + } + ] + }, + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + } + }, + { + "name": "commit", + "title": "Apply an approved Recoup change", + "description": "Apply one exact prepared change after Recoup records approval. Reuse the same requestKey to recover its receipt after interruption.", + "inputSchema": { + "type": "object", + "properties": { + "intent": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + }, + "requestKey": { + "type": "string", + "minLength": 1, + "maxLength": 96 + } + }, + "required": [ + "intent", + "requestKey" + ], + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "approval_required", + "denied", + "expired", + "accepted", + "running", + "succeeded", + "failed", + "unknown_outcome", + "canceled" + ] + }, + "runId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "approvalUrl": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "traceId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "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" + ], + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "state": { + "enum": [ + "approval_required", + "accepted", + "running", + "unknown_outcome" + ] + } + } + }, + "then": { + "required": [ + "runId" + ] + } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "denied", + "expired", + "failed", + "unknown_outcome" + ] + } + } + }, + "then": { + "required": [ + "error" + ] + } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "approval_required" + ] + } + } + }, + "then": { + "required": [ + "approvalUrl" + ] + } + } + ] + }, + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + } + ] +} diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md new file mode 100644 index 000000000..225b1a765 --- /dev/null +++ b/docs/plans/mcp-code-mode.md @@ -0,0 +1,159 @@ +# Recoup MCP code mode + +**Proposed technical specification · November 27, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** + +Give direct MCP clients two tools to discover and compose Recoup reads. Advertise a third tool when a connection can commit a qualified change. The host model writes ordinary JavaScript at request time. Recoup executes the program in an isolated service, validates each operation against the authenticated account and returns just the requested result. Recoup does not need a second model to translate a program into API calls. + +Use one API-owned operation catalog to generate both this interface and the individually named tools that OpenAI reviews. Launch the proposed Directory profile with two useful catalog tools. Keep current connections on their existing URL until each supported workflow has a verified migration or an explicitly accepted disposition. This proposal covers the build, evidence required for a production cutover and submission for review. + +| 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 | +| [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 currently returns 95 descriptors, including one app-only entry. On the current protocol the compact list is 111,082 bytes or 31,971 reference tokens, of which 31,820 represent model-visible descriptors. The proposed read-only descriptors together occupy **2,998 bytes / 732 tokens**. Including the write descriptor gives **4,527 bytes / 1,097 tokens**, about **96.6% less descriptor text** than that full model-visible baseline. The 732/1,097 figures measure the checked-in design fixture, before serialization by the production SDK. They establish a size budget, not host prompt savings or task parity. Existing narrow OAuth already measures only 1,038 model-visible modern tokens. Evaluate it separately. + +To reproduce the candidate measurement, load the JSON fixture and compactly serialize `{"tools": tools[:n]}` in stored order with UTF-8, no trailing newline, for `n=2,3`. Count using tiktoken 0.14.0, `o200k_base`. The current implementation used the same envelope and tokenizer. Include server instructions, preloaded resources/skills and host-added wrappers in the later actual startup measurement. Use the same host configuration, account, task and granted behaviors in paired tests. [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` | Exactly `search` and `execute`. Native skills/resources use negotiated protocol methods. Text-only hosts can find permitted skills through search. | +| Direct, write-entitled | Same route | Exactly `search`, `execute`, `commit`. Only register commit when the caller can use at least one admitted mutation. No hidden fourth launcher. | +| 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, call commit 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. 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. | +| One broad execute tool for reads and writes | Smallest list, single program per workflow. | Host prompts cannot distinguish a catalog read from a send. Exact consent, failure recovery and keeping reads usable justify an optional third tool. | +| Direct mode with typed code, separate exact commit and a named Directory projection | Fixed-size bootstrap with independent auth, guest, business operations and publication. | **Adopt.** Costs include operating an isolate service, maintaining contract mappings and qualifying each client. A generated catalog and release gates bound that cost. | +| 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 + reviewed policy"] --> Build["Catalog compiler / signed release"] + Build --> Direct["Direct MCP adapter"] + Build --> Named["Directory named-tool adapter"] + Direct --> Search["Authorized catalog index"] + Direct --> Runner["Per-run JS isolate"] + Runner --> Broker["Recoup operation broker"] + Direct --> Commit["Exact approval and commit"] + Commit --> Broker + Named --> Broker + Broker --> Domain["Existing Recoup API domain services"] + Broker --> Ledger["Scoped receipts 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 policy. 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 after the route's and profile's authorization/ownership checks have been composed. 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. + +**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 + +`search` accepts a natural-language query, exact ID or page cursor. Operation summaries provide stable ID, short purpose and principal-specific effect. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, principal, policy and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. + +`execute` accepts a pinned revision, JS source and separately encoded JSON parameters. The source is an async function with the signature `(recoup, params) => Promise`. It may compose reads, branch, map, group and return a projection. The guest API exposes `read(id, args)` and `prepare(id, args)`. Neither can cause a business write. Running with only a `runId` reads the caller's authorized durable receipt. The host adds trace, truncation and outcome metadata outside the guest. Ordinary completed reads require no persisted user artifact. Modern/legacy adapters validate output schemas and supply a small text fallback. Oversized outputs fail with a narrowing instruction or explicitly indicate partial coverage. Never silently claim complete coverage of partial pages. + +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. A user can use either named Directory operation independently. [Current mapper](../../lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts) + +`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. Limit canonical effect arguments to 4 KiB, the sealed base64url intent to 8 KiB and the complete returned result to 16 KiB. Check all three after encoding before issuance. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. + +For the write-capable descriptor fixture the generic commit has conservative destructive/open-world hints for a profile that includes those admitted effects. Generate the actual flags from the union of reachable effects per profile, including narrowing them for an additive-only pilot. Keep `execute` closed-world during the first release. A new outbound data path requires a separately reviewed disclosure and information-flow rule. Code that reads private files cannot forward them through a public search, URL-bearing argument, provider prompt or external recipient in the same run. The pilot enforces this by omitting such destinations from the read bridge and denying disallowed fields at input and projection time. Qualify additional data routes and their new descriptor annotations before enabling them. + +### 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, two simultaneous reads, one effect per commit | Atomic supervisor counters on every call, including rejected attempts and paginated reads. Derive per-account/provider quotas from existing limits. | +| 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. | +| 5 min preview validity, earlier of domain quote or grant expiry | Enforce on prepare, human approval and commit. Scope status handles to actor and grant; a handle never grants access. | +| 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. | + +Model authentication and human approval as distinct authorities. Check grant, client, resource, current membership, feature flags, document ownership and profile on **every** broker call, readback and commit. Share only immutable public artifacts in global caches. Key private query/cursor caches by profile, principal/grant, selected workspace and policy revision. Keep selected-context and narrow OAuth restrictions even on guessed IDs. The existing protected resource uses the exact `/mcp` audience. New routes need their own resource metadata, explicit approved scopes, issuance and agreement on callback paths. Require deliberate reauthorization. The first direct and Directory pilots accept only explicitly consented, audience-specific OAuth. Propose a catalog-read scope for the initial reads. The Directory grant cannot call /mcp/code. Write-enabled direct pilot accounts need a separately consented, admitted write scope. Legacy API-key/Privy, broad or narrow /mcp grants, selected-context and staff credentials stay on their current routes. Future standard-credential opt-in requires a documented audience/profile entitlement and isolated tests. A new scope for a Directory reader never upgrades an existing narrow grant. [Current resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Full delegated checks](../../lib/mcp/oauth/registerFullOAuthTools.ts) + +Persist only the data necessary to apply or reconcile a write. Use Supabase via its existing repository layer. Define receipt rows with `run_id`, actor/grant/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Use a unique key for the intent claim as well as the actor/profile/request-key binding. Same key+digest returns the prior receipt; same key+different content conflicts. 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, approval and remaining 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. + +Status advances from approval to accepted, running and succeeded/failed. 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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. The Recoup-owned approval URL is required in a legacy approval_required commit result. 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. 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. + +**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, skill reads, a denied operation, one confirmed mutation, replay and long-job status. Use matched legacy/host-deferred baselines and include failures in all summaries. + +| Gate | Proposed acceptance | +| --- | --- | +| Startup | At most 1,500 descriptor tokens for the write-capable direct profile, at least 90% below full OAuth's model-visible reference list. Verify actual first-turn token delta on controlled hosts and report measured vs unavailable separately. For a narrow/deferred client already below that target, require no material startup or task-success regression before migrating. | +| Correctness | All deterministic authorization, projection, approval, idempotency and cross-tenant tests pass. Zero unauthorized effects, duplicate writes or credentials in output. Every admitted workflow passes normal-entry E2E with independent outcome evidence. A failed boundary test disables the operation. | +| 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 approval latency separately. 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.** Deploy dormant catalog, broker and additive storage. Verify descriptors on a preview. Enable read-only direct for internal disposable accounts; then canary qualified cohorts at 1%, 10%, 50%, 100%, with enough successful journeys and a full monitoring window at each stage. Introduce one disposable additive write after the ledger, confirmation and readback tests pass. Expand operation families according to measured use and risk, retaining named support for gaps. Keep first-party native chat and existing transcripts working on their established paths. An OpenAI reviewer receives the separately staged named profile. Recoup's direct launch can proceed independently of the publisher's review decision. + +**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) | Baseline startup context and map every existing MCP operation to its consumers | Can start now | +| [api#1304](https://github.com/recoupable/api/issues/1304) | Compile a versioned operation catalog from Recoup contracts and admission policy | [api#1303](https://github.com/recoupable/api/issues/1303) | +| [api#1305](https://github.com/recoupable/api/issues/1305) | Bind MCP profiles and per-operation execution to the authenticated grant | [api#1303](https://github.com/recoupable/api/issues/1303) | +| [api#1306](https://github.com/recoupable/api/issues/1306) | Qualify an isolated JavaScript runner with a Recoup-only operation bridge | Can start now | +| [api#1307](https://github.com/recoupable/api/issues/1307) | Ship search and execute for a read-only direct MCP pilot | [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 actor-bound approval decisions and effect receipts atomically | [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) | Add exact write previews, trusted approval, commit and reconciliation | [api#1307](https://github.com/recoupable/api/issues/1307), [database#144](https://github.com/recoupable/database/issues/144) | +| [app#2411](https://github.com/recoupable/app/issues/2411) | Migrate first-party chat, stored transcripts, Skills and gallery consumers | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [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 model success, context, latency and cost across MCP designs | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify real MCP hosts, business behavior and the rollback drill | [api#1308](https://github.com/recoupable/api/issues/1308), [app#2411](https://github.com/recoupable/app/issues/2411), [api#1310](https://github.com/recoupable/api/issues/1310) | +| [docs#44](https://github.com/recoupable/docs/issues/44) | Publish versioned code-mode, named-tool and legacy migration guides | [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 Recoup 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 code mode and retire legacy cohorts with measured parity | [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. + +**First implementation slice.** Begin the baseline/parity inventory and runtime qualification in parallel. The first product demonstration is a real read-only host connection that finds two authorized catalog operations, runs the five-title example, and reports measured setup cost, permissions and output. The first write demonstration is separate and requires a recorded human approval and independent readback. The Directory milestone is an actual submission receipt for a qualified named-tool package. From 706b3a7ee3e167e0c94335bf2f6fe43073829b6e Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:50:08 -0500 Subject: [PATCH 02/13] Validate code-mode discovery, receipts and partial results --- docs/plans/mcp-code-mode-tools.json | 86 +++++++++++++++++- docs/plans/mcp-code-mode.md | 16 ++-- docs/plans/verify-mcp-code-mode.py | 135 ++++++++++++++++++++++++++++ 3 files changed, 228 insertions(+), 9 deletions(-) create mode 100644 docs/plans/verify-mcp-code-mode.py diff --git a/docs/plans/mcp-code-mode-tools.json b/docs/plans/mcp-code-mode-tools.json index b46faded7..f4be73b6e 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -88,7 +88,35 @@ "maxItems": 8, "items": { "type": "object", - "additionalProperties": true + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "summary": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "effect": { + "enum": [ + "read", + "write", + "instruction" + ] + }, + "detail": { + "type": "object", + "description": "Authorized contract, example, or requested skill content. Section-specific schemas and byte caps are validated by the catalog broker." + } + }, + "required": [ + "id", + "summary", + "effect" + ], + "additionalProperties": false } }, "nextCursor": { @@ -232,6 +260,11 @@ "retry" ], "additionalProperties": false + }, + "approvalUrl": { + "type": "string", + "minLength": 1, + "maxLength": 1024 } }, "required": [ @@ -278,6 +311,57 @@ "error" ] } + }, + { + "if": { + "properties": { + "state": { + "enum": [ + "approval_required" + ] + } + } + }, + "then": { + "required": [ + "approvalUrl" + ] + } + }, + { + "if": { + "properties": { + "state": { + "const": "complete" + } + } + }, + "then": { + "properties": { + "truncated": { + "const": false + } + }, + "required": [ + "value" + ] + } + }, + { + "if": { + "properties": { + "truncated": { + "const": true + } + } + }, + "then": { + "properties": { + "state": { + "const": "partial" + } + } + } } ] }, diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index 225b1a765..041366dec 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -16,9 +16,9 @@ Use one API-owned operation catalog to generate both this interface and the indi ## Decision and measurable outcome -Full delegated OAuth currently returns 95 descriptors, including one app-only entry. On the current protocol the compact list is 111,082 bytes or 31,971 reference tokens, of which 31,820 represent model-visible descriptors. The proposed read-only descriptors together occupy **2,998 bytes / 732 tokens**. Including the write descriptor gives **4,527 bytes / 1,097 tokens**, about **96.6% less descriptor text** than that full model-visible baseline. The 732/1,097 figures measure the checked-in design fixture, before serialization by the production SDK. They establish a size budget, not host prompt savings or task parity. Existing narrow OAuth already measures only 1,038 model-visible modern tokens. Evaluate it separately. +Full delegated OAuth currently returns 95 descriptors, including one app-only entry. On the current protocol the compact list is 111,082 bytes or 31,971 reference tokens, of which 31,820 represent model-visible descriptors. The proposed read-only descriptors together occupy **3,779 bytes / 912 tokens**. Including the write descriptor gives **5,308 bytes / 1,277 tokens**, about **96.0% less descriptor text** than that full model-visible baseline. The 912/1,277 figures measure the checked-in design fixture, before serialization by the production SDK. They establish a size budget, not host prompt savings or task parity. Existing narrow OAuth already measures only 1,038 model-visible modern tokens. Evaluate it separately. -To reproduce the candidate measurement, load the JSON fixture and compactly serialize `{"tools": tools[:n]}` in stored order with UTF-8, no trailing newline, for `n=2,3`. Count using tiktoken 0.14.0, `o200k_base`. The current implementation used the same envelope and tokenizer. Include server instructions, preloaded resources/skills and host-added wrappers in the later actual startup measurement. Use the same host configuration, account, task and granted behaviors in paired tests. [Measured baseline and reproduction](mcp-code-mode-baseline.md) +To reproduce the candidate measurement, load the JSON fixture and compactly serialize `{"tools": tools[:n]}` in stored order with UTF-8, no trailing newline, for `n=2,3`. Count using tiktoken 0.14.0, `o200k_base`. The current implementation used the same envelope and tokenizer. Include server instructions, preloaded resources/skills and host-added wrappers in the later actual startup measurement. Use the same host configuration, account, task and granted behaviors in paired tests. The [schema and size verifier](verify-mcp-code-mode.py) runs the contract cases and reproduces the proposed footprint. Keep the JSON as a single wire example so the measured object can be serialized directly. [Measured baseline and reproduction](mcp-code-mode-baseline.md) | Distribution | Proposed route on api.recoupable.dev | Model and wire contract | | --- | --- | --- | @@ -27,7 +27,7 @@ To reproduce the candidate measurement, load the JSON fixture and compactly seri | 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, call commit 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. 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) +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 @@ -71,9 +71,9 @@ flowchart LR ## Interaction contract -`search` accepts a natural-language query, exact ID or page cursor. Operation summaries provide stable ID, short purpose and principal-specific effect. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, principal, policy and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. +`search` accepts a natural-language query, exact ID or page cursor. Each result has an id, summary and effect. Operations carry read or write, while skill material carries instruction. Requested contract sections and skill files use the optional bounded detail object. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, principal, policy and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. -`execute` accepts a pinned revision, JS source and separately encoded JSON parameters. The source is an async function with the signature `(recoup, params) => Promise`. It may compose reads, branch, map, group and return a projection. The guest API exposes `read(id, args)` and `prepare(id, args)`. Neither can cause a business write. Running with only a `runId` reads the caller's authorized durable receipt. The host adds trace, truncation and outcome metadata outside the guest. Ordinary completed reads require no persisted user artifact. Modern/legacy adapters validate output schemas and supply a small text fallback. Oversized outputs fail with a narrowing instruction or explicitly indicate partial coverage. Never silently claim complete coverage of partial pages. +`execute` accepts a pinned revision, JS source and separately encoded JSON parameters. The source is an async function with the signature `(recoup, params) => Promise`. It may compose reads, branch, map, group and return a projection. The guest API exposes `read(id, args)` and `prepare(id, args)`. Neither can cause a business write. Running with only a `runId` reads the caller's authorized durable receipt. The host adds trace, truncation and outcome metadata outside the guest. Ordinary completed reads require no persisted account artifact. Modern/legacy adapters validate output schemas and supply a small text fallback. Oversized outputs fail with a narrowing instruction or explicitly indicate partial coverage. Never silently claim complete coverage of partial pages. 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. @@ -87,9 +87,9 @@ async (recoup, params) => { } ``` -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. A user can use either named Directory operation independently. [Current mapper](../../lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts) +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) -`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. Limit canonical effect arguments to 4 KiB, the sealed base64url intent to 8 KiB and the complete returned result to 16 KiB. Check all three after encoding before issuance. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. +`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. For the write-capable descriptor fixture the generic commit has conservative destructive/open-world hints for a profile that includes those admitted effects. Generate the actual flags from the union of reachable effects per profile, including narrowing them for an additive-only pilot. Keep `execute` closed-world during the first release. A new outbound data path requires a separately reviewed disclosure and information-flow rule. Code that reads private files cannot forward them through a public search, URL-bearing argument, provider prompt or external recipient in the same run. The pilot enforces this by omitting such destinations from the read bridge and denying disallowed fields at input and projection time. Qualify additional data routes and their new descriptor annotations before enabling them. @@ -113,7 +113,7 @@ Persist only the data necessary to apply or reconcile a write. Use Supabase via Status advances from approval to accepted, running and succeeded/failed. 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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. The Recoup-owned approval URL is required in a legacy approval_required commit result. 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. +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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. Include the Recoup-owned approval URL in approval_required fallback results from both commit and receipt reads. 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 diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py new file mode 100644 index 000000000..f4c193fe6 --- /dev/null +++ b/docs/plans/verify-mcp-code-mode.py @@ -0,0 +1,135 @@ +"""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 Recoup server are needed. +""" + +import hashlib +import json +import os +import sys +import tempfile +from importlib.metadata import version +from itertools import combinations +from pathlib import Path + +import tiktoken +from jsonschema import Draft202012Validator +from referencing import Registry + + +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 contract_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]} + skill = {"id": "catalog-guide", "kind": "skills", "file": "SKILL.md"} + yield "search", "input", True, "skill file", skill + yield "search", "input", False, "file without skill", {**skill, "kind": "operations"} + yield "search", "input", False, "no selection", {} + item = {"id": "catalogs.listOwned", "summary": "List catalogs", "effect": "read"} + results = {"revision": "v1", "items": [item]} + yield "search", "output", True, "summary", results + for key in item: + incomplete = {k: v for k, v in item.items() if k != key} + yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} + yield "search", "output", False, "nine summaries", {**results, "items": [item] * 9} + + program = {"source": "async (recoup, params) => params", "revision": "v1", "params": {}} + receipt = {"runId": "run-1"} + yield "execute", "input", True, "program", program + yield "execute", "input", True, "receipt", receipt + 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} + 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": [] + } + + error = {"code": "outcome_uncertain", "retry": "reconcile"} + for tool in ("execute", "commit"): + base = output if tool == "execute" else {"traceId": "trace-1"} + approval = {**base, **receipt, "state": "approval_required"} + yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://recoup.example/approve"} + yield tool, "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 tool, "output", True, state, {**status, **receipt} + yield tool, "output", False, f"{state} missing run ID", status + for state in ("denied", "expired", "failed", "unknown_outcome"): + status = {**base, **receipt, "state": state} + yield tool, "output", True, f"{state} with error", {**status, "error": error} + yield tool, "output", False, f"{state} missing error", status + yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} + + commit = {"intent": "a" * 8192, "requestKey": "request-1"} + yield "commit", "input", True, "maximum sealed intent", commit + for length in (0, 8193): + yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} + yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} + yield "commit", "input", False, "new source", {**commit, "source": program["source"]} + + +def main(): + tools = json.loads(MANIFEST.read_text(encoding="utf-8"))["tools"] + if [tool["name"] for tool in tools] != ["search", "execute", "commit"]: + raise ValueError("The descriptor fixture must contain search, execute and commit in release order.") + validators = {} + for tool in tools: + for direction in ("input", "output"): + schema = tool[f"{direction}Schema"] + Draft202012Validator.check_schema(schema) + validators[tool["name"], direction] = Draft202012Validator(schema, registry=Registry()) + + failures = [] + cases = list(contract_cases()) + for name, direction, valid, label, payload in cases: + if validators[name, direction].is_valid(payload) != valid: + failures.append(f"{name} {direction} ({label}): expected {'valid' if valid else 'invalid'}") + print(f"{len(validators)} schemas, {len(cases)} contract cases, {len(failures)} case failures") + encoding = cached_encoding() + print(f"tiktoken {version('tiktoken')}, {encoding.name}") + for count in (2, 3): + wire = json.dumps({"tools": tools[:count]}, ensure_ascii=False, separators=(",", ":")) + tokens = len(encoding.encode_ordinary(wire)) + print(f"{count} descriptors: {len(wire.encode('utf-8')):,} bytes, {tokens:,} tokens") + if tokens > TOKEN_LIMIT: + failures.append(f"{count} descriptors exceed the {TOKEN_LIMIT:,}-token gate.") + for failure in failures: + print(failure, file=sys.stderr) + return int(bool(failures)) + + +if __name__ == "__main__": + sys.exit(main()) From c93af0e4d624b17c06364a686d340e04790e6555 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:55:57 -0500 Subject: [PATCH 03/13] Bind approval links to the authenticated receipt --- docs/plans/mcp-code-mode.md | 2 +- docs/plans/mcp_code_mode_cases.py | 76 +++++++++++++++++++++++++++++ docs/plans/verify-mcp-code-mode.py | 77 ++++++------------------------ 3 files changed, 91 insertions(+), 64 deletions(-) create mode 100644 docs/plans/mcp_code_mode_cases.py diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index 041366dec..fb2c27d38 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -89,7 +89,7 @@ async (recoup, params) => { 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) -`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. +`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. The broker constructs the confirmation URL from a release-pinned HTTPS Recoup origin, a fixed approval path and the encoded server-issued run ID. For production the proposed form is `https://chat.recoupable.dev/mcp/approvals/{runId}`. Before emitting any approval URL in either tool, verify exact equality with the server-built URL for the authenticated receipt. The confirmation route disallows redirects, arbitrary destinations and return URLs. The portable descriptor describes a string; the broker validates this deployment-specific URL contract. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. For the write-capable descriptor fixture the generic commit has conservative destructive/open-world hints for a profile that includes those admitted effects. Generate the actual flags from the union of reachable effects per profile, including narrowing them for an additive-only pilot. Keep `execute` closed-world during the first release. A new outbound data path requires a separately reviewed disclosure and information-flow rule. Code that reads private files cannot forward them through a public search, URL-bearing argument, provider prompt or external recipient in the same run. The pilot enforces this by omitting such destinations from the read bridge and denying disallowed fields at input and projection time. Qualify additional data routes and their new descriptor annotations before enabling them. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py new file mode 100644 index 000000000..c8bd8ba3e --- /dev/null +++ b/docs/plans/mcp_code_mode_cases.py @@ -0,0 +1,76 @@ +"""Positive and negative examples for the proposed direct tool contracts.""" + +from itertools import combinations + + +def contract_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]} + skill = {"id": "catalog-guide", "kind": "skills", "file": "SKILL.md"} + yield "search", "input", True, "skill file", skill + yield "search", "input", False, "file without skill", {**skill, "kind": "operations"} + yield "search", "input", False, "no selection", {} + item = {"id": "catalogs.listOwned", "summary": "List catalogs", "effect": "read"} + results = {"revision": "v1", "items": [item]} + yield "search", "output", True, "summary", results + for key in item: + incomplete = {k: v for k, v in item.items() if k != key} + yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} + yield "search", "output", False, "nine summaries", {**results, "items": [item] * 9} + + program = {"source": "async (recoup, params) => params", "revision": "v1", "params": {}} + receipt = {"runId": "run-1"} + yield "execute", "input", True, "program", program + yield "execute", "input", True, "receipt", receipt + 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} + 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": [] + } + + error = {"code": "outcome_uncertain", "retry": "reconcile"} + for tool in ("execute", "commit"): + base = output if tool == "execute" else {"traceId": "trace-1"} + approval = {**base, **receipt, "state": "approval_required"} + yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://chat.recoupable.dev/mcp/approvals/run-1"} + for bad_url in ( + "https://elsewhere.example/mcp/approvals/run-1", + "http://chat.recoupable.dev/mcp/approvals/run-1", + "https://chat.recoupable.dev/mcp/approvals/run-2", + "https://chat.recoupable.dev/mcp/approvals/run-1?next=https://elsewhere.example", + ): + yield tool, "output", False, "untrusted approval destination", {**approval, "approvalUrl": bad_url} + yield tool, "output", False, "foreign receipt and matching URL", { + **approval, "runId": "run-2", "approvalUrl": "https://chat.recoupable.dev/mcp/approvals/run-2" + } + yield tool, "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 tool, "output", True, state, {**status, **receipt} + yield tool, "output", False, f"{state} missing run ID", status + for state in ("denied", "expired", "failed", "unknown_outcome"): + status = {**base, **receipt, "state": state} + yield tool, "output", True, f"{state} with error", {**status, "error": error} + yield tool, "output", False, f"{state} missing error", status + yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} + + commit = {"intent": "a" * 8192, "requestKey": "request-1"} + yield "commit", "input", True, "maximum sealed intent", commit + for length in (0, 8193): + yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} + yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} + yield "commit", "input", False, "new source", {**commit, "source": program["source"]} diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index f4c193fe6..fe05cc966 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -12,13 +12,15 @@ import sys import tempfile from importlib.metadata import version -from itertools import combinations from pathlib import Path +from urllib.parse import quote import tiktoken from jsonschema import Draft202012Validator from referencing import Registry +from mcp_code_mode_cases import contract_cases + MANIFEST = Path(__file__).with_name("mcp-code-mode-tools.json") TOKEN_LIMIT = 1_500 @@ -38,67 +40,13 @@ def cached_encoding(): return tiktoken.get_encoding("o200k_base") -def contract_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]} - skill = {"id": "catalog-guide", "kind": "skills", "file": "SKILL.md"} - yield "search", "input", True, "skill file", skill - yield "search", "input", False, "file without skill", {**skill, "kind": "operations"} - yield "search", "input", False, "no selection", {} - item = {"id": "catalogs.listOwned", "summary": "List catalogs", "effect": "read"} - results = {"revision": "v1", "items": [item]} - yield "search", "output", True, "summary", results - for key in item: - incomplete = {k: v for k, v in item.items() if k != key} - yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} - yield "search", "output", False, "nine summaries", {**results, "items": [item] * 9} - - program = {"source": "async (recoup, params) => params", "revision": "v1", "params": {}} - receipt = {"runId": "run-1"} - yield "execute", "input", True, "program", program - yield "execute", "input", True, "receipt", receipt - 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} - 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": [] - } - - error = {"code": "outcome_uncertain", "retry": "reconcile"} - for tool in ("execute", "commit"): - base = output if tool == "execute" else {"traceId": "trace-1"} - approval = {**base, **receipt, "state": "approval_required"} - yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://recoup.example/approve"} - yield tool, "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 tool, "output", True, state, {**status, **receipt} - yield tool, "output", False, f"{state} missing run ID", status - for state in ("denied", "expired", "failed", "unknown_outcome"): - status = {**base, **receipt, "state": state} - yield tool, "output", True, f"{state} with error", {**status, "error": error} - yield tool, "output", False, f"{state} missing error", status - yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} - - commit = {"intent": "a" * 8192, "requestKey": "request-1"} - yield "commit", "input", True, "maximum sealed intent", commit - for length in (0, 8193): - yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} - yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} - yield "commit", "input", False, "new source", {**commit, "source": program["source"]} +def trusted_approval_link(payload, receipt_run_id): + if "approvalUrl" not in payload: + return True + if payload.get("runId") != receipt_run_id: + return False + expected = "https://chat.recoupable.dev/mcp/approvals/" + quote(receipt_run_id, safe="") + return payload["approvalUrl"] == expected def main(): @@ -115,7 +63,10 @@ def main(): failures = [] cases = list(contract_cases()) for name, direction, valid, label, payload in cases: - if validators[name, direction].is_valid(payload) != valid: + accepted = validators[name, direction].is_valid(payload) + if direction == "output" and name in {"execute", "commit"}: + 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'}") print(f"{len(validators)} schemas, {len(cases)} contract cases, {len(failures)} case failures") encoding = cached_encoding() From f295911ace787007ed719985c55cbb6f126fabcd Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:01:18 -0500 Subject: [PATCH 04/13] Use the canonical Recoup App origin for approvals --- docs/plans/mcp-code-mode.md | 2 +- docs/plans/mcp_code_mode_cases.py | 10 +++++----- docs/plans/verify-mcp-code-mode.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index fb2c27d38..84163cfe1 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -89,7 +89,7 @@ async (recoup, params) => { 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) -`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. The broker constructs the confirmation URL from a release-pinned HTTPS Recoup origin, a fixed approval path and the encoded server-issued run ID. For production the proposed form is `https://chat.recoupable.dev/mcp/approvals/{runId}`. Before emitting any approval URL in either tool, verify exact equality with the server-built URL for the authenticated receipt. The confirmation route disallows redirects, arbitrary destinations and return URLs. The portable descriptor describes a string; the broker validates this deployment-specific URL contract. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. +`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. The broker constructs the confirmation URL from a release-pinned HTTPS Recoup origin, a fixed approval path and the encoded server-issued run ID. App owns a new authenticated route at `app/mcp/approvals/[runId]/page.tsx` in the App repository. The production URL to qualify is `https://app.recoupable.dev/mcp/approvals/{runId}`. The chat hostname redirects to the App origin. Verify a direct, signed-in visit and the login-return journey on the canonical origin before enabling commit. [Existing production consent origin](../mcp-oauth-runtime.md) Before emitting any approval URL in either tool, verify exact equality with the server-built URL for the authenticated receipt. The confirmation route disallows redirects, arbitrary destinations and return URLs. The portable descriptor describes a string; the broker validates this deployment-specific URL contract. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. For the write-capable descriptor fixture the generic commit has conservative destructive/open-world hints for a profile that includes those admitted effects. Generate the actual flags from the union of reachable effects per profile, including narrowing them for an additive-only pilot. Keep `execute` closed-world during the first release. A new outbound data path requires a separately reviewed disclosure and information-flow rule. Code that reads private files cannot forward them through a public search, URL-bearing argument, provider prompt or external recipient in the same run. The pilot enforces this by omitting such destinations from the read bridge and denying disallowed fields at input and projection time. Qualify additional data routes and their new descriptor annotations before enabling them. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index c8bd8ba3e..9efa48f67 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -44,16 +44,16 @@ def contract_cases(): for tool in ("execute", "commit"): base = output if tool == "execute" else {"traceId": "trace-1"} approval = {**base, **receipt, "state": "approval_required"} - yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://chat.recoupable.dev/mcp/approvals/run-1"} + yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-1"} for bad_url in ( "https://elsewhere.example/mcp/approvals/run-1", - "http://chat.recoupable.dev/mcp/approvals/run-1", - "https://chat.recoupable.dev/mcp/approvals/run-2", - "https://chat.recoupable.dev/mcp/approvals/run-1?next=https://elsewhere.example", + "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 tool, "output", False, "untrusted approval destination", {**approval, "approvalUrl": bad_url} yield tool, "output", False, "foreign receipt and matching URL", { - **approval, "runId": "run-2", "approvalUrl": "https://chat.recoupable.dev/mcp/approvals/run-2" + **approval, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" } yield tool, "output", False, "missing approval link", approval for state in ("accepted", "running", "unknown_outcome"): diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index fe05cc966..b805878e8 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -45,7 +45,7 @@ def trusted_approval_link(payload, receipt_run_id): return True if payload.get("runId") != receipt_run_id: return False - expected = "https://chat.recoupable.dev/mcp/approvals/" + quote(receipt_run_id, safe="") + expected = "https://app.recoupable.dev/mcp/approvals/" + quote(receipt_run_id, safe="") return payload["approvalUrl"] == expected From 7a1c0722c9ada595d85a06077b9343bbcceb4a3e Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:19:34 -0500 Subject: [PATCH 05/13] Design two-tool company-agent operation with optional approvals --- docs/plans/mcp-code-mode-autonomy.md | 33 +++ docs/plans/mcp-code-mode-baseline.md | 7 +- docs/plans/mcp-code-mode-protocol.md | 25 ++- docs/plans/mcp-code-mode-research.md | 8 +- docs/plans/mcp-code-mode-tools.json | 297 ++++++++++++++++++++++++--- docs/plans/mcp-code-mode.md | 87 ++++---- docs/plans/mcp_code_mode_cases.py | 56 ++++- docs/plans/verify-mcp-code-mode.py | 65 ++++-- 8 files changed, 474 insertions(+), 104 deletions(-) create mode 100644 docs/plans/mcp-code-mode-autonomy.md diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md new file mode 100644 index 000000000..dd916a138 --- /dev/null +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -0,0 +1,33 @@ +# Operating a label through Recoup + +**Proposed first-release contract.** A company can appoint an agent to perform work that its authorized staff can perform. The first action slice must persist a real change without per-action confirmation. The unattended label release must complete a job after the initiating chat closes, even when the optional standing-instruction and approval modules are absent. Track product capability parity by business outcome, including the source of authority, supported entry points, downstream requirements and evidence of completion for each operation. + +## Who decides and who acts + +| Component | Responsibility | +| --- | --- | +| Company identity and delegation | An authorized company administrator appoints a separately identifiable agent, selects its company and delegates either the full company operating role or specified operations and resources. The owner can attach destination, spending or time limits when desired. A background worker authenticates as that agent with a renewable, audience-bound credential. Renewal respects the original grant's expiry and revocation. Existing personal registration issues one hour of personal `mcp:read` access and has no refresh token. Company appointment and worker credential renewal are new implementation work. [Current personal registration](../agent-registration.md) | +| Agent and optional standing instructions | An authorized caller can assign a goal directly. A company may also save a recurring instruction describing the trigger, selection criteria and desired outcome. The agent chooses the operations, checks the results and decides how to proceed within its delegation. Instruction text, tool input and stored case assertions cannot mint credentials or enlarge the company's grant. | +| API authorization | The API resolves the actual principal, delegation and current resource permissions. For a concrete action it returns **allow**, **deny**, or **requires interaction** with a reason and, where available, a supported next action. A valid company delegation that covers the action is sufficient for unattended dispatch. An organization may configure additional approvals for particular work. A qualifying individual approval can satisfy that condition within the approver's own authority. Enforce genuine host or provider requirements at the boundary that owns them. | +| Operation owner and workflow | The operation owner checks business preconditions, reserves shared budget atomically when applicable and issues an idempotent request. A durable Recoup workflow records the goal, actor, business key, source versions, checkpoints and completion criteria. It rechecks live authority before each effect and before exposing saved results. It resumes across worker replacement and reconciles an uncertain dispatch against its original receipt. | + +The direct MCP exposes `search` and `execute`. A program inside `execute` reads with `recoup.read(id, args)` and requests an effect with `recoup.act(id, args, {requestKey})`. The outer program and each effect have separate stable request keys. For **allow**, the broker dispatches the effect immediately inside `execute` and records the receipt or job handle. For **deny**, it stops before dispatch. When policy requires approval, it parks the exact intent and returns `approval_required`. The optional third MCP tool, `commit({intent, requestKey})`, applies only the parked effect after the approval is independently recorded and current authority passes again. The rest of the run can then continue from its checkpoint with `execute({runId, resume:true})`. Status lookup by `runId` or the outer `requestKey` has no business effect. A provider-owned signature or approval step can remain pending in the underlying job even after dispatch. + +The principal or authorized policy owner controls delegation. A guest program cannot select its authority, claim that a person approved, or raise its budget. A run whose authorization expires while queued must be denied before the effect. + +For example, an owner can say “check the release catalog today and open cases for confirmed missing identifiers.” The same owner can save “do this every Monday and reopen a case only when the evidence changes.” A scheduler submits the same job under the same company agent. If the owner later chooses “ask me before sending a correction outside the label,” that exact send pauses when a qualified sending operation exists. The agent can keep handling unrelated private cases. Removing the recurring assignment stops its future triggers and leaves the underlying grant under the owner’s control. + +REST, standard named MCP tools, direct code mode and the first-party app call the same operation and authorization logic. Verify equivalent outcomes for equivalent principals, capabilities and resources. Different audiences may have different entitlements. Preserve legacy grants without upgrading them. The Directory exposes only its individually reviewed actions. A Directory consent dialog or downstream requirement for a person's signature applies to that channel or transaction. An unattended job needing that step records the dependency, waits or routes an exception, then resumes using the original intent. Keep a capability ledger for human-supported jobs that still lack a delegated API action, provider access, readback or distribution path. + +## First job and its implementation gap + +For a disposable label, assign an agent to open one private metadata correction case per recording with current evidence of a missing recording identifier (ISRC). Appoint the agent with full operating authority over the disposable label and give it this one-off task with no stored instruction or action-specific approval. Only the private case change is needed. Repeat under a narrower delegation limited to catalog reads and case edits, with zero spend and external messaging disabled. These are two configurations of the same interface. A company can later schedule the assignment as a standing instruction. + +Existing code distinguishes an observed missing ISRC from a failed lookup, partial coverage and stale source versions. `POST /api/context` and standard MCP already save and reopen workspace-scoped catalog cases with revision checks and idempotency keys. Saved cases are private workpapers. A stored assertion about authorization confers no provider authority. The existing delegated MCP profile excludes case save, read and list. Add the case operations to the full company role and make the same operations individually selectable for a restricted role. Verify the workspace and evidence boundaries before offering the job in direct code mode. Reuse the existing case processor, validate evidence against the selected recording and workspace, and keep withdrawal/redaction behavior on subsequent reads. [Release observations](../../lib/context/planning/readReleaseTrackObservations.ts) · [Case contract and retention](../../lib/context/README.md#catalog-case-artifacts-catd-29) · [Current OAuth exclusions](../mcp-oauth-tool-qualification.md) + +## Installed end-to-end acceptance + +1. Seed two isolated organizations. Give the pilot label multiple pages of releases, known missing ISRCs, a failed lookup, a conflict, an already-handled recording and a partial source. Define the expected outcomes independently of the agent. Have an authorized administrator create the grant once. Run the same business operation through REST and the direct MCP host using equivalent isolated fixtures. On the direct path the agent uses `recoup.act` in `execute`, and the receipt must identify an immediate delegated dispatch with zero `commit` calls. Use standard named MCP as an additional control where its existing credential is eligible. +2. Start the agent's job and end its initiating session. Restart a worker, run a second worker against the same business key and change a source version during execution. Persist a stable key derived from organization, recording and correction kind across sessions. Use the existing case ID for retries, check the expected revision and keep source versions on the case so later evidence can update it. Record an unresolved finding when the evidence cannot support a confirmed gap. +3. Using an independent authorized read path, reopen each saved case and verify its ID, workspace, recording, revision, evidence references and source freshness against the seed. Confirm zero wrong or duplicate cases and no cross-company case access, messages, spending or rights changes. Revoke the delegation while a second job is queued and verify zero subsequent writes. For the optional approvals release, configure a separate trial to require one approval. Verify that the exact effect stays parked, the optional `commit` applies it once after approval, and resuming the checkpoint preserves earlier completed effects. +4. Publish a redacted receipt with expected versus observed cases, reason for every unresolved recording, number of human interruptions **after appointment**, recovery behavior and cost per verified case. An accepted job or an in-memory preview is insufficient. The release gate is a persisted business change with independent readback and unattended completion under the original company delegation. diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md index 6f9f956eb..1ed47978c 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -1,6 +1,6 @@ # 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 measure discovery. 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 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. The amended direct interface has its own fixture, including immediate delegated actions within `execute` and optional `commit` for previously parked effects. Reproduce current candidate counts with the [wire fixture verifier](verify-mcp-code-mode.py). 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 @@ -34,6 +34,8 @@ The connected Codex Recoup connector independently exposed 94 tool names in this ## Mapping business capabilities +For every human-supported job, map the existing route, credential and restrictions to the proposed company principal and operation. Track gaps in delegated authorization, domain implementation, provider execution and independent readback. Current personal and selected-context limits are compatibility baselines. A company can separately authorize its agent for specified work. The first release exercises an unattended correction-case write through the direct endpoint and the same API operation through REST. [Company delegation and pilot](mcp-code-mode-autonomy.md) + Generate searchable descriptors from stable OpenAPI operation IDs and reviewed domain adapters. Keep one policy identifier per meaningful operation, including Context actions that share a REST 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 | @@ -41,6 +43,7 @@ Generate searchable descriptors from stable OpenAPI operation IDs and reviewed d | 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 | `POST /api/context` and standard MCP use `save_catalog_case`, `read_catalog_case` and `list_catalog_cases`. Existing delegated MCP excludes these operations. | Qualify a company-scoped correction case with source evidence, revision checking, a stable idempotency key and independent readback. A saved workpaper records the gap. Provider registration and rights changes require their own operations. [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) | @@ -52,4 +55,4 @@ Generate searchable descriptors from stable OpenAPI operation IDs and reviewed d 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, approval, execution, independent readback, cleanup, expiry, revocation and reconnect for the code-mode candidate and named host version. 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) +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. Exercise a zero-interruption delegated change and, independently, an effect parked by policy that is approved and applied once. 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 index 4762530c7..390e1d397 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -1,6 +1,6 @@ # Recoup MCP protocol compatibility and OpenAI review -**Decision record for the proposed cutover, November 27, 2026.** Recoup can deliver a two-tool code-mode server to direct MCP clients. 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) +**Decision record for the proposed cutover, November 27, 2026.** Direct clients discover and run authorized Recoup operations with two tools. A company can delegate specific business actions to its agent within agreed limits. A third tool is available on profiles configured to complete individual actions paused for approval. 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 @@ -10,15 +10,30 @@ The current revision is **2026-07-28**. At the inspected API source revision, Re | --- | --- | | 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 | Keep `search` read-only. Enforce the advertised bounds of `execute` across all reachable operations. Preparing an effect qualifies as a read-only preview only if the operation does not persist artifacts, enqueue jobs, reserve budget or alter external state. A materialized proposal must carry accurate effects metadata. The optional `commit` requires trusted, transaction-specific approval and fresh authority. An annotation, a model-authored field or a tool retry does not authorize a write. 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. Reconcile durable side effects through application receipts. Server-side idempotency and truthful partial outcomes matter even when a host retries transparently. [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. Require independently verifiable authorization for commits. Supply a Recoup-owned authenticated confirmation flow where the host lacks the necessary interaction. Keep ordinary reads usable with a text-only client. 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) | +| Execution, effects and errors | Generate `execute` per authenticated profile. The read profile exposes only `recoup.read`. An action profile also exposes `recoup.act` for current company delegations. An authorized operation can run immediately. When policy requires approval, persist the exact paused step. The optional `commit` releases only that step after the independently recorded decision. 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 and enforce grants inside the broker on every nested call. 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 current delegation. 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. Allow a valid standing delegation to authorize ordinary actions without a fresh human reply. If a particular step requires a new approval, offer a Recoup-owned authenticated decision flow on hosts lacking the necessary interaction. Keep delegated work and ordinary reads usable with a text-only client. 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. Keep the essential search and execution contracts callable without preloading either. 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 + +The account delegates through Recoup's control plane. Bind the delegation to the company/workspace, agent/client, the full operating role or selected operations, and the grant lifecycle. Apply company-selected resource, destination or spending limits where configured. Enforce each operation’s current API and provider requirements. A full-role grant may expressly include newly qualified operations within the same authority boundary. At every read, action, resumed step and actual delayed dispatch, intersect that delegation with the authenticated grant, current company membership, operation policy and remaining authority. An ordinary OAuth scope establishes the client's potential access. A matching company delegation establishes which business actions the agent can take. An instruction in guest code supplies neither. [MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) + +| Call | Observable behavior | +| --- | --- | +| Read-only `execute({source, revision, params})` | The sandbox exposes `read`. It can combine and project results. A guessed write ID or `act` call has no effect. Read-only run status uses `execute({runId})` when a corresponding read receipt exists. | +| Delegated `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 principal/profile, authenticated grant 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. Atomically recheck authority and reserve any budget under concurrency. Dispatch allowed steps. Deny excluded steps. Pause before dispatch only where a configured decision is needed. | +| `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})` | Resume from a durable, versioned checkpoint under fresh authority. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | +| `commit({intent, requestKey})`, where offered | Consume the exact server-sealed paused step after a recorded decision. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | + +Qualify an allowed internal business action under an existing synthetic company delegation in one direct call against a disposable workspace and verify its result through an independent read. Then drop the first response after dispatch, reconnect with only the original key and check for one observed effect. Repeat with two identical retries, a conflicting step payload, two concurrent resumes, and delegation revocation between two steps. A separate fixture triggers a policy-specific approval and verifies that a stale or altered decision cannot release another step. Capture actual host prompts separately from Recoup's authorization 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 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) @@ -38,7 +53,7 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | --- | --- | | Protocol fixtures and Inspector | Run pinned upstream conformance and project-specific tests against both wire eras, both profiles and the retained legacy URL. A text-only client with no optional capabilities must complete the read flow. 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 direct discovery, authorized read, multi-operation composition, skill fallback, denied write and confirmation handling. Record receipt readback when a controlled confirmed write is supported. 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) | +| Codex, Claude Code, Claude Desktop and Cursor | Exercise real client builds for the surfaces Recoup claims. Record direct discovery, authorized reads, multi-operation composition and skill fallback. On a delegated profile, exercise one allowed write with zero additional Recoup approval prompts, one denied action and one explicitly paused action. 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 diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md index d97564a8a..0e33bd0e7 100644 --- a/docs/plans/mcp-code-mode-research.md +++ b/docs/plans/mcp-code-mode-research.md @@ -18,11 +18,11 @@ The locally studied v2 source is `40be470` (CLI `2.0.0-beta.73`). On the review | --- | --- | | 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 principal and selected organization outside the guest program. Discoverability, a generated type and a previous successful call each supply information only. The current request's resource authorization and effect policy govern dispatch. | -| 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. Evaluate an effect-specific third tool for independent host confirmation. | +| 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. The two-tool direct path carries ordinary delegated work, including writes. Reserve an optional third tool for applying an already parked and approved effect. | | 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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. For Recoup, the stronger reason to spend a third tool is a distinct user-visible effect boundary when required by the host. [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) +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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. Recoup's chosen direct path runs `recoup.act(id, args, {requestKey})` within `execute` and immediately dispatches a permitted effect. Its optional `commit` applies only an effect previously parked for approval under the applicable policy. [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) ## Execution choices @@ -40,7 +40,7 @@ Choose the broker contract before choosing a runtime library. A runtime adapter ## 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. Return ranked summaries before details. 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, prepare a seeded disposable object, obtain real confirmation, read back the effect independently and exercise cleanup. Record unknown consumers and keep their compatibility path until an owner determines disposition. +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, grant the company agent a bounded disposable fixture, execute an unattended action, verify the result independently and exercise cleanup. A separate trial enables an approval policy and verifies that the effect occurs only after approval. 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 wire bytes, actual or explicitly estimated prompt tokens, discovery 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 the actual confirmation UI in each release target. 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. +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 index f4be73b6e..8fcf53612 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -139,8 +139,8 @@ }, { "name": "execute", - "title": "Run a Recoup read or preview", - "description": "Run one async JavaScript function (recoup, params) against authorized Recoup operations. Use recoup.read(id, args) or recoup.prepare(id, args), then return a bounded JSON result. A runId reads an existing receipt.", + "title": "Run delegated Recoup operations", + "description": "Run async (recoup, params) with a stable run requestKey. Use recoup.read(id,args) or recoup.act(id,args,{requestKey}) with a stable key per effect. Delegated actions may immediately change data or contact external parties. A requestKey or runId alone retrieves status. Use runId with resume:true for a checkpointed continuation.", "inputSchema": { "type": "object", "properties": { @@ -162,44 +162,50 @@ "type": "string", "minLength": 1, "maxLength": 256 + }, + "requestKey": { + "type": "string", + "minLength": 1, + "maxLength": 96 + }, + "resume": { + "const": true } }, - "required": [], "additionalProperties": false, "oneOf": [ { "required": [ "source", - "revision" + "revision", + "requestKey" ], - "not": { - "required": [ - "runId" - ] + "properties": { + "runId": false, + "resume": false + } + }, + { + "required": [ + "requestKey" + ], + "properties": { + "source": false, + "params": false, + "revision": false, + "runId": false, + "resume": false } }, { "required": [ "runId" ], - "not": { - "anyOf": [ - { - "required": [ - "source" - ] - }, - { - "required": [ - "revision" - ] - }, - { - "required": [ - "params" - ] - } - ] + "properties": { + "source": false, + "params": false, + "revision": false, + "requestKey": false } } ] @@ -265,6 +271,12 @@ "type": "string", "minLength": 1, "maxLength": 1024 + }, + "intent": { + "type": "string", + "minLength": 1, + "maxLength": 8192, + "pattern": "^[A-Za-z0-9_-]+$" } }, "required": [ @@ -366,22 +378,23 @@ ] }, "annotations": { - "readOnlyHint": true, - "destructiveHint": false, - "openWorldHint": false + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true } }, { "name": "commit", "title": "Apply an approved Recoup change", - "description": "Apply one exact prepared change after Recoup records approval. Reuse the same requestKey to recover its receipt after interruption.", + "description": "Apply one exact policy-paused effect after recorded approval. Reuse requestKey on retry. Look up the run with execute.", "inputSchema": { "type": "object", "properties": { "intent": { "type": "string", "minLength": 1, - "maxLength": 8192 + "maxLength": 8192, + "pattern": "^[A-Za-z0-9_-]+$" }, "requestKey": { "type": "string", @@ -520,5 +533,225 @@ "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.md b/docs/plans/mcp-code-mode.md index 84163cfe1..f6ff44dfa 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -2,13 +2,14 @@ **Proposed technical specification · November 27, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** -Give direct MCP clients two tools to discover and compose Recoup reads. Advertise a third tool when a connection can commit a qualified change. The host model writes ordinary JavaScript at request time. Recoup executes the program in an isolated service, validates each operation against the authenticated account and returns just the requested result. Recoup does not need a second model to translate a program into API calls. +Under this design a Recoup Records owner can appoint an agent to run the label. The agent can take a one-off assignment or follow standing company instructions. With full delegated authority it can act immediately, through two direct MCP tools. `search` finds the relevant Recoup operations. In `execute`, the host’s model writes a short JavaScript program, reads the records it needs, calls the Recoup API to make changes, and obtains evidence of what happened. The API owns the business rules for every client. -Use one API-owned operation catalog to generate both this interface and the individually named tools that OpenAI reviews. Launch the proposed Directory profile with two useful catalog tools. Keep current connections on their existing URL until each supported workflow has a verified migration or an explicitly accepted disposition. This proposal covers the build, evidence required for a production cutover and submission for review. +The product target is every music-company operation a human with equivalent authority can perform. Each missing API action, provider integration or independently verifiable outcome has an owner in the coverage inventory. A company can delegate the full operating role once, narrow it, or require individual approval for specified actions. New personal connections retain their own expressly granted access. The optional instruction and approval features, first-party App migration and public ChatGPT Directory submission 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 | +| [Company delegation and the first label workflow](mcp-code-mode-autonomy.md) | One-off and standing assignments, company authority, policy decisions, a verified catalog-case change and restart after disconnect | | [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 | @@ -16,14 +17,14 @@ Use one API-owned operation catalog to generate both this interface and the indi ## Decision and measurable outcome -Full delegated OAuth currently returns 95 descriptors, including one app-only entry. On the current protocol the compact list is 111,082 bytes or 31,971 reference tokens, of which 31,820 represent model-visible descriptors. The proposed read-only descriptors together occupy **3,779 bytes / 912 tokens**. Including the write descriptor gives **5,308 bytes / 1,277 tokens**, about **96.0% less descriptor text** than that full model-visible baseline. The 912/1,277 figures measure the checked-in design fixture, before serialization by the production SDK. They establish a size budget, not host prompt savings or task parity. Existing narrow OAuth already measures only 1,038 model-visible modern tokens. Evaluate it separately. +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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **1,017** (4,189 bytes), a **96.8% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,397** (5,734 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. -To reproduce the candidate measurement, load the JSON fixture and compactly serialize `{"tools": tools[:n]}` in stored order with UTF-8, no trailing newline, for `n=2,3`. Count using tiktoken 0.14.0, `o200k_base`. The current implementation used the same envelope and tokenizer. Include server instructions, preloaded resources/skills and host-added wrappers in the later actual startup measurement. Use the same host configuration, account, task and granted behaviors in paired tests. The [schema and size verifier](verify-mcp-code-mode.py) runs the contract cases and reproduces the proposed footprint. Keep the JSON as a single wire example so the measured object can be serialized directly. [Measured baseline and reproduction](mcp-code-mode-baseline.md) +Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. Its internal `actRequest` 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` | Exactly `search` and `execute`. Native skills/resources use negotiated protocol methods. Text-only hosts can find permitted skills through search. | -| Direct, write-entitled | Same route | Exactly `search`, `execute`, `commit`. Only register commit when the caller can use at least one admitted mutation. No hidden fourth launcher. | +| Direct, company-authorized | `/mcp/code` | Exactly `search` and `execute` for an agent that can act unattended. An allowed `recoup.act` inside `execute` applies the requested change. An approval-enabled profile may also expose `commit` to finish one exact parked effect. Truthful annotations describe the effects reachable on each profile. | | 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, call commit 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. | @@ -36,8 +37,8 @@ Both new URLs are proposals under the established MCP mount. Business REST endpo | 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. | -| One broad execute tool for reads and writes | Smallest list, single program per workflow. | Host prompts cannot distinguish a catalog read from a send. Exact consent, failure recovery and keeping reads usable justify an optional third tool. | -| Direct mode with typed code, separate exact commit and a named Directory projection | Fixed-size bootstrap with independent auth, guest, business operations and publication. | **Adopt.** Costs include operating an isolate service, maintaining contract mappings and qualifying each client. A generated catalog and release gates bound that cost. | +| Prepare every write and require individual confirmation | Gives a person an opportunity to inspect each change. | Offer exact review where the company chooses it or the transaction requires it. Requiring this for routine delegated work would prevent an agent from running the label unattended. | +| Two direct tools, an API-owned authorization decision, an optional approval continuation and named Directory tools | Stable discovery cost as operations grow. The same API checks and receipts cover autonomous and individually approved work. | **Adopt.** The API owns behavior. An interchangeable runner composes its operations. Optional modules provide standing assignments, approval journeys and durable scheduling. | | 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. @@ -52,11 +53,13 @@ flowchart LR Direct --> Search["Authorized catalog index"] Direct --> Runner["Per-run JS isolate"] Runner --> Broker["Recoup operation broker"] - Direct --> Commit["Exact approval and commit"] + Direct --> Commit["Optional exact approval continuation"] Commit --> Broker Named --> Broker - Broker --> Domain["Existing Recoup API domain services"] - Broker --> Ledger["Scoped receipts and reconciliation"] + Broker --> Authority["Company delegation and optional policy"] + Broker --> Domain["Recoup API business operations"] + 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) @@ -67,13 +70,15 @@ flowchart LR **Operation broker, API repository.** Both profiles invoke the same business code. Prefer a typed in-process service invocation after the route's and profile's authorization/ownership checks have been composed. 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 `search` accepts a natural-language query, exact ID or page cursor. Each result has an id, summary and effect. Operations carry read or write, while skill material carries instruction. Requested contract sections and skill files use the optional bounded detail object. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, principal, policy and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. -`execute` accepts a pinned revision, JS source and separately encoded JSON parameters. The source is an async function with the signature `(recoup, params) => Promise`. It may compose reads, branch, map, group and return a projection. The guest API exposes `read(id, args)` and `prepare(id, args)`. Neither can cause a business write. Running with only a `runId` reads the caller's authorized durable receipt. The host adds trace, truncation and outcome metadata outside the guest. Ordinary completed reads require no persisted account artifact. Modern/legacy adapters validate output schemas and supply a small text fallback. Oversized outputs fail with a narrowing instruction or explicitly indicate partial coverage. Never silently claim complete coverage of partial pages. +`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. A guarded `execute({runId,resume:true})` continues only a recorded checkpoint. 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. 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. @@ -89,9 +94,13 @@ async (recoup, params) => { 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) -`commit` takes one opaque intent plus a request key, never code or replacement arguments. A pure preview canonicalizes a single operation and its complete arguments into an encrypted, authenticated, expiring intent. When preparing an intent, measure the canonical arguments (4 KiB maximum) and the sealed base64url intent (8 KiB maximum) before issuing it. After the guest returns, the supervisor verifies that the entire projected result fits the separate 16 KiB cap before sending it to the host. Reject an oversized preview response without starting a change. Return intent_too_large with narrowing guidance if any bound fails. Test incompressible near-limit arguments and confirm each issued intent round-trips unchanged. It binds actor, client/grant, selected resource, audience, operation and schema/policy revisions, destination, quote or spending ceiling and input hash. Return a separately derived human-readable summary. A quote that reserves credits, writes state or contacts a provider needs its own classified operation; it cannot masquerade as a pure preview. With no trusted consent, record a minimal pending receipt and return an authenticated confirmation URL with `approval_required`. With modern elicitation negotiated the adapter may instead return the protocol-level `resultType: input_required` carrying bound request state. On resumption verify the independently recorded approval and payload. The app shows the exact target, before/after change, recipients, data sent, amount and expiration. Bind approval in Recoup after account sign-in. The broker constructs the confirmation URL from a release-pinned HTTPS Recoup origin, a fixed approval path and the encoded server-issued run ID. App owns a new authenticated route at `app/mcp/approvals/[runId]/page.tsx` in the App repository. The production URL to qualify is `https://app.recoupable.dev/mcp/approvals/{runId}`. The chat hostname redirects to the App origin. Verify a direct, signed-in visit and the login-return journey on the canonical origin before enabling commit. [Existing production consent origin](../mcp-oauth-runtime.md) Before emitting any approval URL in either tool, verify exact equality with the server-built URL for the authenticated receipt. The confirmation route disallows redirects, arbitrary destinations and return URLs. The portable descriptor describes a string; the broker validates this deployment-specific URL contract. Possession of a URL or model-generated approval text is insufficient. On a subsequent commit, atomically claim the approved intent, recheck authority and quote, and dispatch **only that recorded operation**. The original program never resumes with permission to perform a different write. +For a direct assignment, an appointed agent can find the current metadata observation and private case operations, read the evidence, create or update a case with `recoup.act` and reopen it independently. The authenticated company and selected catalog come from the connection. Stable internal recording identity, correction kind and company identify the same business work across chats and retries. A name collision, missing ISRC or partial source cannot establish identity. This proposed case grant needs API work. A smaller first dispatch can use the existing additive `review_context_release_case` operation with `needs_changes` on qualified evidence, then independently read the immutable review. The catalog-correction workflow demonstrates continued operation after chat closure. [Case contracts](../../lib/context/releaseCaseOperationSchemas.ts) · [Installed acceptance](mcp-code-mode-autonomy.md#installed-end-to-end-acceptance) + +**Authority and dispatch.** The owner appoints a named, revocable company agent with full or selected operating authority. A grant can cover qualified future actions in an authorized role and domain if the owner explicitly selects that behavior. Show material scope/effect changes and require a fresh grant for an expanded audience, role, data boundary or ungranted capability. Company membership, a saved instruction, program source or provider account access alone cannot appoint the agent. With no optional policy the API uses the explicit grant and the operation’s own requirements. With a configured policy, evaluate active company rules as well. `allow` dispatches immediately. `requires interaction` parks the exact effect with an actionable reason. `deny` dispatches nothing. Denial takes precedence, then required approval, then allow. If a configured policy is unavailable, hold affected effects. An absent optional module never delays a properly granted action. Recheck authority on every operation, checkpoint and dispatch. [Full contract](mcp-code-mode-autonomy.md) + +**Optional exact approval.** When the company requests individual confirmation, the broker seals a canonical one-effect intent bound to actor, grant, company, selected resource, operation and policy revisions, destination, quote or ceiling, expiration and input digest. For a company approval return `approval_required` with the run ID, parked intent and a broker-derived URL for the exact receipt. Build it from the fixed HTTPS Recoup App origin, path and server-issued ID. The signed-in App at `https://app.recoupable.dev/mcp/approvals/{runId}` presents the target, change, destination, charge and expiry to an authorized approver. Validate exact URL equality before every response and test login and sign-in return at the canonical origin. Accept a trusted, bound decision before `commit({intent,requestKey})` dispatches that effect once. It cannot substitute arguments or approve another step. Recovery via `execute` reads the same receipt and, where supported, resumes a saved checkpoint after the effect is settled. Limit canonical arguments to 4 KiB and sealed intent to 8 KiB for this optional interface. Refuse oversized pending approval inputs before dispatch and supply narrowing guidance. Quotes that reserve credits or send data have their own effect contracts. An external signature or provider consent needs proof from its issuer. [Existing production consent origin](../mcp-oauth-runtime.md) -For the write-capable descriptor fixture the generic commit has conservative destructive/open-world hints for a profile that includes those admitted effects. Generate the actual flags from the union of reachable effects per profile, including narrowing them for an additive-only pilot. Keep `execute` closed-world during the first release. A new outbound data path requires a separately reviewed disclosure and information-flow rule. Code that reads private files cannot forward them through a public search, URL-bearing argument, provider prompt or external recipient in the same run. The pilot enforces this by omitting such destinations from the read bridge and denying disallowed fields at input and projection time. Qualify additional data routes and their new descriptor annotations before enabling them. +The read-only `execute` annotation applies only to a bridge that cannot cause effects, including hidden settlements or paid processing. For action-enabled `execute` and optional `commit`, compute open-world, destructive and idempotency hints conservatively from all reachable operations. A full direct role can reach external effects once its API operations are qualified. Authorize the destination and fields against the company grant, provider contract and configured policy. 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 @@ -102,34 +111,34 @@ A modern client can receive a structured result, a scoped resource link or an ex | 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, two simultaneous reads, one effect per commit | Atomic supervisor counters on every call, including rejected attempts and paginated reads. Derive per-account/provider quotas from existing limits. | +| 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. | -| 5 min preview validity, earlier of domain quote or grant expiry | Enforce on prepare, human approval and commit. Scope status handles to actor and grant; a handle never grants access. | +| Optional approval valid for up to 5 minutes or earlier quote/grant 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. | -Model authentication and human approval as distinct authorities. Check grant, client, resource, current membership, feature flags, document ownership and profile on **every** broker call, readback and commit. Share only immutable public artifacts in global caches. Key private query/cursor caches by profile, principal/grant, selected workspace and policy revision. Keep selected-context and narrow OAuth restrictions even on guessed IDs. The existing protected resource uses the exact `/mcp` audience. New routes need their own resource metadata, explicit approved scopes, issuance and agreement on callback paths. Require deliberate reauthorization. The first direct and Directory pilots accept only explicitly consented, audience-specific OAuth. Propose a catalog-read scope for the initial reads. The Directory grant cannot call /mcp/code. Write-enabled direct pilot accounts need a separately consented, admitted write scope. Legacy API-key/Privy, broad or narrow /mcp grants, selected-context and staff credentials stay on their current routes. Future standard-credential opt-in requires a documented audience/profile entitlement and isolated tests. A new scope for a Directory reader never upgrades an existing narrow grant. [Current resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Full delegated checks](../../lib/mcp/oauth/registerFullOAuthTools.ts) +Validate audience-specific credentials, client, operating role, current company/artist access, asset ownership, policy and emergency disable on each call. Private caches and signed cursors are scoped to those boundaries. The present `/mcp` audience and legacy API-key/Privy, narrow, full, selected-context and staff connections retain their present access. Add an explicitly appointed company principal and renewable, revocable credential for the new direct audience. Owners can authorize full operating authority during appointment. Personal one-hour read-only agent registration and mere organization membership cannot serve as this grant. Use a separate catalog-read grant for Directory. Activation of equivalent domain services for the new identity requires normal-entry tests. Qualification for one channel cannot change another channel’s credentials. [Current resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Current agent registration](../agent-registration.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`, actor/grant/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Use a unique key for the intent claim as well as the actor/profile/request-key binding. Same key+digest returns the prior receipt; same key+different content conflicts. 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, approval and remaining 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. +Persist only the data necessary to apply or reconcile a write. Use Supabase via its existing repository layer. Define receipt rows with `run_id`, actor/grant/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Use a unique key for company business key + effect step as well as the actor/profile/request-key binding and any optional sealed intent claim. An identical authorized retry returns the prior receipt. Reusing a key for a different request conflicts. An authenticated receipt records the company delegation and 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. -Status advances from approval to accepted, running and succeeded/failed. 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. +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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. Include the Recoup-owned approval URL in approval_required fallback results from both commit and receipt reads. 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. +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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the broker-derived URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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. 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. -**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, skill reads, a denied operation, one confirmed mutation, replay and long-job status. Use matched legacy/host-deferred baselines and include failures in all summaries. +**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, skill 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 | | --- | --- | | Startup | At most 1,500 descriptor tokens for the write-capable direct profile, at least 90% below full OAuth's model-visible reference list. Verify actual first-turn token delta on controlled hosts and report measured vs unavailable separately. For a narrow/deferred client already below that target, require no material startup or task-success regression before migrating. | -| Correctness | All deterministic authorization, projection, approval, idempotency and cross-tenant tests pass. Zero unauthorized effects, duplicate writes or credentials in output. Every admitted workflow passes normal-entry E2E with independent outcome evidence. A failed boundary test disables the operation. | +| Correctness and autonomy | All deterministic authorization, projection, optional approval, idempotency and isolation tests pass. Zero unauthorized or duplicate changes. Verify a real human-visible effect with zero per-effect approvals under full delegation and no stored instructions; separately demonstrate the exact number of interactions a configured exception requires. Test two companies, concurrent agents, stale evidence and revocation after enqueue. An unqualified optional branch holds only the cohort or operations depending on 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 approval latency separately. Hold a default change when cohorts miss targets. | +| 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.** Deploy dormant catalog, broker and additive storage. Verify descriptors on a preview. Enable read-only direct for internal disposable accounts; then canary qualified cohorts at 1%, 10%, 50%, 100%, with enough successful journeys and a full monitoring window at each stage. Introduce one disposable additive write after the ledger, confirmation and readback tests pass. Expand operation families according to measured use and risk, retaining named support for gaps. Keep first-party native chat and existing transcripts working on their established paths. An OpenAI reviewer receives the separately staged named profile. Recoup's direct launch can proceed independently of the publisher's review decision. +**Adoption sequence.** Start the inventory and runner qualification in parallel. Test reads to validate connectivity, then dispatch one real additive action for a disposable company through two tools and independently reopen the result, with zero confirmations after appointment. Launch this slice without saved instructions, an approval UI or Directory review. Next qualify an end-to-end label assignment across chat closure and worker replacement, and test optional standing instructions and human review on their own tracks. Eligible direct cohorts can progress through 1%, 10%, 50% and 100% after a monitoring window and successful journeys at each stage. Keep existing installs, historical chat and gallery paths until their own parity and rollback gates pass. Publish the independently named OpenAI package through its 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. @@ -139,21 +148,25 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | Ticket | Deliverable | Blocked by | | --- | --- | --- | -| [api#1303](https://github.com/recoupable/api/issues/1303) | Baseline startup context and map every existing MCP operation to its consumers | Can start now | -| [api#1304](https://github.com/recoupable/api/issues/1304) | Compile a versioned operation catalog from Recoup contracts and admission policy | [api#1303](https://github.com/recoupable/api/issues/1303) | -| [api#1305](https://github.com/recoupable/api/issues/1305) | Bind MCP profiles and per-operation execution to the authenticated grant | [api#1303](https://github.com/recoupable/api/issues/1303) | -| [api#1306](https://github.com/recoupable/api/issues/1306) | Qualify an isolated JavaScript runner with a Recoup-only operation bridge | Can start now | -| [api#1307](https://github.com/recoupable/api/issues/1307) | Ship search and execute for a read-only direct MCP pilot | [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 actor-bound approval decisions and effect receipts atomically | [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) | Add exact write previews, trusted approval, commit and reconciliation | [api#1307](https://github.com/recoupable/api/issues/1307), [database#144](https://github.com/recoupable/database/issues/144) | -| [app#2411](https://github.com/recoupable/app/issues/2411) | Migrate first-party chat, stored transcripts, Skills and gallery consumers | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [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) | Appoint, authenticate, renew and revoke company agents | [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) | Ship search and execute with separate read and action profiles | [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) | Dispatch allowed company actions from execute with zero confirmations | [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 to company agents | [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) | Continue jobs across chat closure, worker restarts and events | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [api#1313](https://github.com/recoupable/api/issues/1313) | Add optional standing instructions and policy overrides | [api#1305](https://github.com/recoupable/api/issues/1305), [api#1308](https://github.com/recoupable/api/issues/1308) | +| [app#2411](https://github.com/recoupable/app/issues/2411) | Migrate first-party consumers and build the optional approval screen | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [api#1314](https://github.com/recoupable/api/issues/1314) | Resume an exact action after a required approval | [api#1308](https://github.com/recoupable/api/issues/1308), [app#2411](https://github.com/recoupable/app/issues/2411) | | [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 model success, context, latency and cost across MCP designs | [api#1307](https://github.com/recoupable/api/issues/1307) | -| [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify real MCP hosts, business behavior and the rollback drill | [api#1308](https://github.com/recoupable/api/issues/1308), [app#2411](https://github.com/recoupable/app/issues/2411), [api#1310](https://github.com/recoupable/api/issues/1310) | -| [docs#44](https://github.com/recoupable/docs/issues/44) | Publish versioned code-mode, named-tool and legacy migration guides | [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 Recoup 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 code mode and retire legacy cohorts with measured parity | [mono#752](https://github.com/recoupable/mono/issues/752), [docs#44](https://github.com/recoupable/docs/issues/44) | +| [api#1310](https://github.com/recoupable/api/issues/1310) | Benchmark startup context, completed work, interruptions, latency and cost | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify unattended label operations, real hosts 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) | Publish versioned direct, company-agent, Directory and legacy guides | [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. -**First implementation slice.** Begin the baseline/parity inventory and runtime qualification in parallel. The first product demonstration is a real read-only host connection that finds two authorized catalog operations, runs the five-title example, and reports measured setup cost, permissions and output. The first write demonstration is separate and requires a recorded human approval and independent readback. The Directory milestone is an actual submission receipt for a qualified named-tool package. +**Critical path.** The first persisted autonomous action is API #1308. A durable label proof adds #1315 and #1316, then independent qualification in Mono #752. Standing instructions (#1313), optional approval continuation (#1314), its App screen (#2411) and Directory review (#753) can ship independently. First-party legacy retirement still requires evidence for its actual callers. Provider delivery remains a product capability gap until an owning API and an authoritative downstream outcome are available. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index 9efa48f67..3ab5e3241 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -3,7 +3,7 @@ from itertools import combinations -def contract_cases(): +def contract_cases(action_capable, has_commit): search = {"query": "catalogs", "id": "catalogs.listOwned", "cursor": "next"} for key, value in search.items(): yield "search", "input", True, key, {key: value} @@ -23,8 +23,19 @@ def contract_cases(): program = {"source": "async (recoup, params) => params", "revision": "v1", "params": {}} receipt = {"runId": "run-1"} - yield "execute", "input", True, "program", program - yield "execute", "input", True, "receipt", receipt + 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 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"]} @@ -41,36 +52,63 @@ def contract_cases(): } error = {"code": "outcome_uncertain", "retry": "reconcile"} - for tool in ("execute", "commit"): + for tool in (("execute", "commit") if has_commit else ("execute",)): base = output if tool == "execute" else {"traceId": "trace-1"} approval = {**base, **receipt, "state": "approval_required"} - yield tool, "output", True, "approval link", {**approval, "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-1"} + exact_intent = {"intent": "sealed_intent"} if tool == "execute" and has_commit else {} + link = "https://app.recoupable.dev/mcp/approvals/run-1" + yield tool, "output", action_capable, "approval link", {**approval, "approvalUrl": link, **exact_intent} + yield tool, "output", False, "approval link after success", { + **base, **receipt, "state": "succeeded", "approvalUrl": link + } + if tool == "execute": + yield tool, "output", action_capable and not has_commit, "approval without sealed intent", { + **approval, "approvalUrl": link + } + yield tool, "output", has_commit, "optional approved-effect completion", { + **approval, "approvalUrl": link, "intent": "sealed_intent" + } 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 tool, "output", False, "untrusted approval destination", {**approval, "approvalUrl": bad_url} + yield tool, "output", False, "untrusted approval destination", {**approval, **exact_intent, "approvalUrl": bad_url} yield tool, "output", False, "foreign receipt and matching URL", { - **approval, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" + **approval, **exact_intent, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" } yield tool, "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 tool, "output", True, state, {**status, **receipt} + yield tool, "output", action_capable or state != "unknown_outcome", state, {**status, **receipt} yield tool, "output", False, f"{state} missing run ID", status for state in ("denied", "expired", "failed", "unknown_outcome"): status = {**base, **receipt, "state": state} - yield tool, "output", True, f"{state} with error", {**status, "error": error} + yield tool, "output", action_capable or state == "failed", f"{state} with error", {**status, "error": error} yield tool, "output", False, f"{state} missing error", status yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} + if not has_commit: + return commit = {"intent": "a" * 8192, "requestKey": "request-1"} yield "commit", "input", True, "maximum sealed intent", commit for length in (0, 8193): yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} + yield "commit", "input", False, "malformed intent", {**commit, "intent": "wrong value!"} yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} yield "commit", "input", False, "new source", {**commit, "source": program["source"]} + + +def act_cases(): + """The guest calls act(id, args, {requestKey}); the supervisor supplies authority.""" + 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"} diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index b805878e8..4998bfa3b 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -19,7 +19,7 @@ from jsonschema import Draft202012Validator from referencing import Registry -from mcp_code_mode_cases import contract_cases +from mcp_code_mode_cases import act_cases, contract_cases MANIFEST = Path(__file__).with_name("mcp-code-mode-tools.json") @@ -43,40 +43,75 @@ def cached_encoding(): def trusted_approval_link(payload, receipt_run_id): if "approvalUrl" not in payload: return True - if payload.get("runId") != receipt_run_id: + 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 main(): - tools = json.loads(MANIFEST.read_text(encoding="utf-8"))["tools"] - if [tool["name"] for tool in tools] != ["search", "execute", "commit"]: - raise ValueError("The descriptor fixture must contain search, execute and commit in release order.") +def verify_profile(tools, action_capable, has_commit): + expected_names = ["search", "execute"] + (["commit"] if has_commit else []) + 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 == "commit" or (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[tool["name"], direction] = Draft202012Validator(schema, registry=Registry()) - - failures = [] - cases = list(contract_cases()) + validators[name, direction] = Draft202012Validator(schema, registry=Registry()) + cases = list(contract_cases(action_capable, has_commit)) for name, direction, valid, label, payload in cases: accepted = validators[name, direction].is_valid(payload) if direction == "output" and name in {"execute", "commit"}: accepted = accepted and trusted_approval_link(payload, receipt_run_id="run-1") + if name == "execute" and "intent" in payload: + accepted = accepted and has_commit and payload.get("state") == "approval_required" + if name == "execute" and has_commit and payload.get("state") == "approval_required": + accepted = accepted and "intent" in payload if accepted != valid: failures.append(f"{name} {direction} ({label}): expected {'valid' if valid else 'invalid'}") - print(f"{len(validators)} schemas, {len(cases)} contract cases, {len(failures)} case failures") + return len(validators), len(cases), failures + + +def main(): + fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) + search, execute, commit = fixture["tools"] + read_execute = {**execute, **fixture["readOnlyExecute"]} + profiles = [ + ("Read only", [search, read_execute], False, False), + ("Delegated action", [search, execute], True, False), + ("Delegated action with approval completion", [search, execute, commit], True, True), + ] encoding = cached_encoding() print(f"tiktoken {version('tiktoken')}, {encoding.name}") - for count in (2, 3): - wire = json.dumps({"tools": tools[:count]}, ensure_ascii=False, separators=(",", ":")) + failures = [] + for profile, tools, action_capable, has_commit in profiles: + schemas, cases, mismatches = verify_profile(tools, action_capable, has_commit) + 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"{count} descriptors: {len(wire.encode('utf-8')):,} bytes, {tokens:,} tokens") + 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"{count} descriptors exceed the {TOKEN_LIMIT:,}-token gate.") + failures.append(f"{profile} exceeds the {TOKEN_LIMIT:,}-token gate.") + 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)") for failure in failures: print(failure, file=sys.stderr) return int(bool(failures)) From 749dd452201fd8bcf1710fcb4e8388c3958e238c Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:21:03 -0500 Subject: [PATCH 06/13] Specify independent recovery of effects after guest failure --- docs/plans/mcp-code-mode-protocol.md | 4 +++ docs/plans/mcp-code-mode.md | 4 ++- docs/plans/mcp_code_mode_cases.py | 40 ++++++++++++++++++++++++++++ docs/plans/verify-mcp-code-mode.py | 38 +++++++++++++++++++++++++- 4 files changed, 84 insertions(+), 2 deletions(-) diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index 390e1d397..a3f2ed830 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -32,6 +32,10 @@ The account delegates through Recoup's control plane. Bind the delegation to the | `execute({runId, resume:true})` | Resume from a durable, versioned checkpoint under fresh authority. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | | `commit({intent, requestKey})`, where offered | Consume the exact server-sealed paused step after a recorded decision. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | +**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. A rejection before allocation may omit the handle. 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. + Qualify an allowed internal business action under an existing synthetic company delegation in one direct call against a disposable workspace and verify its result through an independent read. Then drop the first response after dispatch, reconnect with only the original key and check for one observed effect. Repeat with two identical retries, a conflicting step payload, two concurrent resumes, and delegation revocation between two steps. A separate fixture triggers a policy-specific approval and verifies that a stale or altered decision cannot release another step. Capture actual host prompts separately from Recoup's authorization 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 diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index f6ff44dfa..f851309c4 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -80,6 +80,8 @@ flowchart LR `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. A guarded `execute({runId,resume:true})` continues only a recorded checkpoint. 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 @@ -98,7 +100,7 @@ For a direct assignment, an appointed agent can find the current metadata observ **Authority and dispatch.** The owner appoints a named, revocable company agent with full or selected operating authority. A grant can cover qualified future actions in an authorized role and domain if the owner explicitly selects that behavior. Show material scope/effect changes and require a fresh grant for an expanded audience, role, data boundary or ungranted capability. Company membership, a saved instruction, program source or provider account access alone cannot appoint the agent. With no optional policy the API uses the explicit grant and the operation’s own requirements. With a configured policy, evaluate active company rules as well. `allow` dispatches immediately. `requires interaction` parks the exact effect with an actionable reason. `deny` dispatches nothing. Denial takes precedence, then required approval, then allow. If a configured policy is unavailable, hold affected effects. An absent optional module never delays a properly granted action. Recheck authority on every operation, checkpoint and dispatch. [Full contract](mcp-code-mode-autonomy.md) -**Optional exact approval.** When the company requests individual confirmation, the broker seals a canonical one-effect intent bound to actor, grant, company, selected resource, operation and policy revisions, destination, quote or ceiling, expiration and input digest. For a company approval return `approval_required` with the run ID, parked intent and a broker-derived URL for the exact receipt. Build it from the fixed HTTPS Recoup App origin, path and server-issued ID. The signed-in App at `https://app.recoupable.dev/mcp/approvals/{runId}` presents the target, change, destination, charge and expiry to an authorized approver. Validate exact URL equality before every response and test login and sign-in return at the canonical origin. Accept a trusted, bound decision before `commit({intent,requestKey})` dispatches that effect once. It cannot substitute arguments or approve another step. Recovery via `execute` reads the same receipt and, where supported, resumes a saved checkpoint after the effect is settled. Limit canonical arguments to 4 KiB and sealed intent to 8 KiB for this optional interface. Refuse oversized pending approval inputs before dispatch and supply narrowing guidance. Quotes that reserve credits or send data have their own effect contracts. An external signature or provider consent needs proof from its issuer. [Existing production consent origin](../mcp-oauth-runtime.md) +**Optional exact approval.** When the company requests individual confirmation, the broker seals a canonical one-effect intent bound to actor, grant, company, selected resource, operation and policy revisions, destination, quote or ceiling, expiration and input digest. For a company approval return `approval_required` with the run ID and a broker-derived URL for the exact receipt. Include the sealed intent for the caller only on a profile that exposes `commit`. Build it from the fixed HTTPS Recoup App origin, path and server-issued ID. The signed-in App at `https://app.recoupable.dev/mcp/approvals/{runId}` presents the target, change, destination, charge and expiry to an authorized approver. Validate exact URL equality before every response and test login and sign-in return at the canonical origin. Accept a trusted, bound decision before `commit({intent,requestKey})` dispatches that effect once. It cannot substitute arguments or approve another step. Recovery via `execute` reads the same receipt and, where supported, resumes a saved checkpoint after the effect is settled. Limit canonical arguments to 4 KiB and sealed intent to 8 KiB for this optional interface. Refuse oversized pending approval inputs before dispatch and supply narrowing guidance. Quotes that reserve credits or send data have their own effect contracts. An external signature or provider consent needs proof from its issuer. [Existing production consent origin](../mcp-oauth-runtime.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` and optional `commit`, compute open-world, destructive and idempotency hints conservatively from all reachable operations. A full direct role can reach external effects once its API operations are qualified. Authorize the destination and fields against the company grant, provider contract and configured policy. 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. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index 3ab5e3241..c731bbb20 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -112,3 +112,43 @@ def act_cases(): 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"} + + +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 True, "pre-admission rejection", 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/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index 4998bfa3b..cdb08c11a 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -9,6 +9,7 @@ import hashlib import json import os +import re import sys import tempfile from importlib.metadata import version @@ -19,7 +20,7 @@ from jsonschema import Draft202012Validator from referencing import Registry -from mcp_code_mode_cases import act_cases, contract_cases +from mcp_code_mode_cases import act_cases, contract_cases, recovery_cases MANIFEST = Path(__file__).with_name("mcp-code-mode-tools.json") @@ -49,6 +50,34 @@ def trusted_approval_link(payload, receipt_run_id): return payload["approvalUrl"] == expected +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 verify_profile(tools, action_capable, has_commit): expected_names = ["search", "execute"] + (["commit"] if has_commit else []) if [tool["name"] for tool in tools] != expected_names: @@ -112,6 +141,13 @@ def main(): 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)") for failure in failures: print(failure, file=sys.stderr) return int(bool(failures)) From 1b686e864c40a1d5d0434bf461511a76da437852 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:30:03 -0500 Subject: [PATCH 07/13] Enforce the delegated action and approval contracts on the wire --- docs/plans/mcp-code-mode-autonomy.md | 2 + docs/plans/mcp-code-mode-baseline.md | 2 +- docs/plans/mcp-code-mode-protocol.md | 4 +- docs/plans/mcp-code-mode-tools.json | 203 ++++++++++++++++---- docs/plans/mcp-code-mode.md | 10 +- docs/plans/mcp_code_mode_cases.py | 135 +++---------- docs/plans/mcp_code_mode_execution_cases.py | 94 +++++++++ docs/plans/mcp_code_mode_recovery.py | 71 +++++++ docs/plans/mcp_code_mode_validation.py | 72 +++++++ docs/plans/verify-mcp-code-mode.py | 85 +------- 10 files changed, 444 insertions(+), 234 deletions(-) create mode 100644 docs/plans/mcp_code_mode_execution_cases.py create mode 100644 docs/plans/mcp_code_mode_recovery.py create mode 100644 docs/plans/mcp_code_mode_validation.py diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index dd916a138..2aa1b7bfa 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -15,6 +15,8 @@ The direct MCP exposes `search` and `execute`. A program inside `execute` reads The principal or authorized policy owner controls delegation. A guest program cannot select its authority, claim that a person approved, or raise its budget. A run whose authorization expires while queued must be denied before the effect. +A label can already keep standing instructions in its company workspace. An authorized owner or host can supply the approved handbook or an accessible versioned reference with a one-off job. The agent uses it to choose the work under its existing company grant. Record the instruction’s source, version and assignment with the job. Recoup can execute allowed work before it has a built-in instruction editor, recurring-assignment store or scheduler. An administrator uses trusted company settings to change a grant or enforce a new approval rule. Treat retrieved artist or provider documents as task data. + For example, an owner can say “check the release catalog today and open cases for confirmed missing identifiers.” The same owner can save “do this every Monday and reopen a case only when the evidence changes.” A scheduler submits the same job under the same company agent. If the owner later chooses “ask me before sending a correction outside the label,” that exact send pauses when a qualified sending operation exists. The agent can keep handling unrelated private cases. Removing the recurring assignment stops its future triggers and leaves the underlying grant under the owner’s control. REST, standard named MCP tools, direct code mode and the first-party app call the same operation and authorization logic. Verify equivalent outcomes for equivalent principals, capabilities and resources. Different audiences may have different entitlements. Preserve legacy grants without upgrading them. The Directory exposes only its individually reviewed actions. A Directory consent dialog or downstream requirement for a person's signature applies to that channel or transaction. An unattended job needing that step records the dependency, waits or routes an exception, then resumes using the original intent. Keep a capability ledger for human-supported jobs that still lack a delegated API action, provider access, readback or distribution path. diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md index 1ed47978c..27ab34610 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -43,7 +43,7 @@ Generate searchable descriptors from stable OpenAPI operation IDs and reviewed d | 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 | `POST /api/context` and standard MCP use `save_catalog_case`, `read_catalog_case` and `list_catalog_cases`. Existing delegated MCP excludes these operations. | Qualify a company-scoped correction case with source evidence, revision checking, a stable idempotency key and independent readback. A saved workpaper records the gap. Provider registration and rights changes require their own operations. [Case processor](../../lib/context/processCatalogCaseOperation.ts) · [OAuth qualification](../mcp-oauth-tool-qualification.md) | +| 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 delegated operations.** Admit separate read/list projections through `recoup.read` and a correction-case mutation through `recoup.act`. Qualify evidence, revision checks, idempotency and independent readback in [API #1316](https://github.com/recoupable/api/issues/1316). Preserve the existing multiplexed contract for its callers. If a dedicated resource-oriented REST projection is added, use GET for retrieval and POST for creation. [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) | diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index a3f2ed830..36082f9fe 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -25,14 +25,14 @@ The account delegates through Recoup's control plane. Bind the delegation to the | Call | Observable behavior | | --- | --- | -| Read-only `execute({source, revision, params})` | The sandbox exposes `read`. It can combine and project results. A guessed write ID or `act` call has no effect. Read-only run status uses `execute({runId})` when a corresponding read receipt exists. | +| 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. | | Delegated `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 principal/profile, authenticated grant 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. Atomically recheck authority and reserve any budget under concurrency. Dispatch allowed steps. Deny excluded steps. Pause before dispatch only where a configured decision is needed. | | `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})` | Resume from a durable, versioned checkpoint under fresh authority. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | | `commit({intent, requestKey})`, where offered | Consume the exact server-sealed paused step after a recorded decision. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | -**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. A rejection before allocation may omit the handle. 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. +**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The two-tool delegated output schema excludes `intent`. The three-tool profile requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. diff --git a/docs/plans/mcp-code-mode-tools.json b/docs/plans/mcp-code-mode-tools.json index 8fcf53612..75028d2c0 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -282,29 +282,11 @@ "required": [ "state", "traceId", - "truncated" + "truncated", + "runId" ], "additionalProperties": false, "allOf": [ - { - "if": { - "properties": { - "state": { - "enum": [ - "approval_required", - "accepted", - "running", - "unknown_outcome" - ] - } - } - }, - "then": { - "required": [ - "runId" - ] - } - }, { "if": { "properties": { @@ -336,8 +318,15 @@ }, "then": { "required": [ - "approvalUrl" + "approvalUrl", + "intent" ] + }, + "else": { + "properties": { + "intent": false, + "approvalUrl": false + } } }, { @@ -467,29 +456,11 @@ }, "required": [ "state", - "traceId" + "traceId", + "runId" ], "additionalProperties": false, "allOf": [ - { - "if": { - "properties": { - "state": { - "enum": [ - "approval_required", - "accepted", - "running", - "unknown_outcome" - ] - } - } - }, - "then": { - "required": [ - "runId" - ] - } - }, { "if": { "properties": { @@ -753,5 +724,155 @@ "options" ], "additionalProperties": false + }, + "delegatedExecute": { + "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" + } + } + } + } + ] + } } } diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index f851309c4..a7393e0b6 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -2,7 +2,7 @@ **Proposed technical specification · November 27, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** -Under this design a Recoup Records owner can appoint an agent to run the label. The agent can take a one-off assignment or follow standing company instructions. With full delegated authority it can act immediately, through two direct MCP tools. `search` finds the relevant Recoup operations. In `execute`, the host’s model writes a short JavaScript program, reads the records it needs, calls the Recoup API to make changes, and obtains evidence of what happened. The API owns the business rules for every client. +Under this design a Recoup Records owner can appoint an agent to run the label. The agent can take a one-off assignment or follow standing company instructions supplied from its approved operating handbook. A versioned reference or an owner-provided assignment works before Recoup has its own instruction editor or scheduler. With full delegated authority it can act immediately, through two direct MCP tools. `search` finds the relevant Recoup operations. In `execute`, the host’s model writes a short JavaScript program, reads the records it needs, calls the Recoup API to make changes, and obtains evidence of what happened. The API owns the business rules for every client. The product target is every music-company operation a human with equivalent authority can perform. Each missing API action, provider integration or independently verifiable outcome has an owner in the coverage inventory. A company can delegate the full operating role once, narrow it, or require individual approval for specified actions. New personal connections retain their own expressly granted access. The optional instruction and approval features, first-party App migration and public ChatGPT Directory submission have independent delivery paths. @@ -17,9 +17,9 @@ The product target is every music-company operation a human with equivalent auth ## 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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **1,017** (4,189 bytes), a **96.8% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,397** (5,734 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. +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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **969** (4,022 bytes), a **97.0% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,358** (5,554 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. -Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. Its internal `actRequest` 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) +Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each two-tool profile it applies the matching `readOnlyExecute` or `delegatedExecute` override. Its internal `actRequest` 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 | | --- | --- | --- | @@ -124,7 +124,7 @@ Persist only the data necessary to apply or reconcile a write. Use Supabase via 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. For search and failures before a valid result envelope exists, return isError with one bounded JSON text block containing code, retry and traceId. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the broker-derived URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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. +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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the broker-derived URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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 @@ -171,4 +171,4 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan 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.** The first persisted autonomous action is API #1308. A durable label proof adds #1315 and #1316, then independent qualification in Mono #752. Standing instructions (#1313), optional approval continuation (#1314), its App screen (#2411) and Directory review (#753) can ship independently. First-party legacy retirement still requires evidence for its actual callers. Provider delivery remains a product capability gap until an owning API and an authoritative downstream outcome are available. +**Critical path.** The first persisted autonomous action is API #1308. A durable label proof adds #1315 and #1316, then independent qualification in Mono #752. Standing instructions (#1313), the individual-approval track and Directory review (#753) are outside the direct rollout’s critical path. Within the individual-approval track, API #1314 depends on the App confirmation screen in #2411. First-party legacy retirement still requires evidence for its actual callers. Provider delivery remains a product capability gap until an owning API and an authoritative downstream outcome are available. diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index c731bbb20..c93b63ba5 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -2,8 +2,10 @@ from itertools import combinations +from mcp_code_mode_execution_cases import execute_cases, status_cases -def contract_cases(action_capable, has_commit): + +def search_cases(): search = {"query": "catalogs", "id": "catalogs.listOwned", "cursor": "next"} for key, value in search.items(): yield "search", "input", True, key, {key: value} @@ -21,89 +23,20 @@ def contract_cases(action_capable, has_commit): yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} yield "search", "output", False, "nine summaries", {**results, "items": [item] * 9} - 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 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} - 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": [] - } - error = {"code": "outcome_uncertain", "retry": "reconcile"} - for tool in (("execute", "commit") if has_commit else ("execute",)): - base = output if tool == "execute" else {"traceId": "trace-1"} - approval = {**base, **receipt, "state": "approval_required"} - exact_intent = {"intent": "sealed_intent"} if tool == "execute" and has_commit else {} - link = "https://app.recoupable.dev/mcp/approvals/run-1" - yield tool, "output", action_capable, "approval link", {**approval, "approvalUrl": link, **exact_intent} - yield tool, "output", False, "approval link after success", { - **base, **receipt, "state": "succeeded", "approvalUrl": link - } - if tool == "execute": - yield tool, "output", action_capable and not has_commit, "approval without sealed intent", { - **approval, "approvalUrl": link - } - yield tool, "output", has_commit, "optional approved-effect completion", { - **approval, "approvalUrl": link, "intent": "sealed_intent" - } - 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 tool, "output", False, "untrusted approval destination", {**approval, **exact_intent, "approvalUrl": bad_url} - yield tool, "output", False, "foreign receipt and matching URL", { - **approval, **exact_intent, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" - } - yield tool, "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 tool, "output", action_capable or state != "unknown_outcome", state, {**status, **receipt} - yield tool, "output", False, f"{state} missing run ID", status - for state in ("denied", "expired", "failed", "unknown_outcome"): - status = {**base, **receipt, "state": state} - yield tool, "output", action_capable or state == "failed", f"{state} with error", {**status, "error": error} - yield tool, "output", False, f"{state} missing error", status - yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} - if not has_commit: - return +def commit_cases(): commit = {"intent": "a" * 8192, "requestKey": "request-1"} yield "commit", "input", True, "maximum sealed intent", commit for length in (0, 8193): yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} yield "commit", "input", False, "malformed intent", {**commit, "intent": "wrong value!"} yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} - yield "commit", "input", False, "new source", {**commit, "source": program["source"]} + yield "commit", "input", False, "new source", {**commit, "source": "async (recoup, params) => params"} def act_cases(): - """The guest calls act(id, args, {requestKey}); the supervisor supplies authority.""" + """The guest calls recoup.act(id, args, {requestKey}); the supervisor supplies authority.""" 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"]} @@ -114,41 +47,23 @@ def act_cases(): yield False, "guest authority override", {**call, "grant": "other"} -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" +def contract_cases(action_capable, has_commit): + yield from search_cases() + yield from execute_cases(action_capable) + yield from status_cases(action_capable, has_commit) + if has_commit: + yield from commit_cases() + + +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"}'}] } - 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 True, "pre-admission rejection", 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_execution_cases.py b/docs/plans/mcp_code_mode_execution_cases.py new file mode 100644 index 000000000..4dd0402c5 --- /dev/null +++ b/docs/plans/mcp_code_mode_execution_cases.py @@ -0,0 +1,94 @@ +"""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 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, has_commit): + receipt = {"runId": "run-1"} + output = {"traceId": "trace-1", "truncated": False} + error = {"code": "outcome_uncertain", "retry": "reconcile"} + for tool in (("execute", "commit") if has_commit else ("execute",)): + base = output if tool == "execute" else {"traceId": "trace-1"} + approval = {**base, **receipt, "state": "approval_required"} + exact_intent = {"intent": "sealed_intent"} if tool == "execute" and has_commit else {} + link = "https://app.recoupable.dev/mcp/approvals/run-1" + yield tool, "output", action_capable, "approval link", {**approval, "approvalUrl": link, **exact_intent} + yield tool, "output", False, "approval link after success", { + **base, **receipt, "state": "succeeded", "approvalUrl": link + } + if tool == "execute": + yield tool, "output", action_capable and not has_commit, "approval without sealed intent", { + **approval, "approvalUrl": link + } + yield tool, "output", has_commit, "optional approved-effect completion", { + **approval, "approvalUrl": link, "intent": "sealed_intent" + } + if tool == "execute": + yield tool, "output", False, "sealed intent on unpaused run", { + **base, **receipt, "state": "running", "intent": "sealed_intent" + } + yield tool, "output", False, "invalid sealed token on pause", { + **approval, "approvalUrl": link, "intent": "malformed token!" + } + 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 tool, "output", False, "untrusted approval destination", {**approval, **exact_intent, "approvalUrl": bad_url} + yield tool, "output", False, "foreign receipt and matching URL", { + **approval, **exact_intent, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" + } + yield tool, "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 tool, "output", action_capable or state != "unknown_outcome", state, {**status, **receipt} + yield tool, "output", False, f"{state} missing run ID", status + for state in ("denied", "expired", "failed", "unknown_outcome"): + status = {**base, **receipt, "state": state} + yield tool, "output", action_capable or state == "failed", f"{state} with error", {**status, "error": error} + yield tool, "output", False, f"{state} missing error", status + yield tool, "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_validation.py b/docs/plans/mcp_code_mode_validation.py new file mode 100644 index 000000000..a7ca62706 --- /dev/null +++ b/docs/plans/mcp_code_mode_validation.py @@ -0,0 +1,72 @@ +"""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, has_commit): + expected_names = ["search", "execute"] + (["commit"] if has_commit else []) + 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 == "commit" or (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.") + if name == "execute" and ("intent" in tool["outputSchema"]["properties"]) != has_commit: + failures.append("Only the approval-completion profile may advertise a sealed intent.") + 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, has_commit)) + for name, direction, valid, label, payload in cases: + accepted = validators[name, direction].is_valid(payload) + if direction == "output" and name in {"execute", "commit"}: + 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 index cdb08c11a..91b273ae5 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -9,18 +9,18 @@ import hashlib import json import os -import re import sys import tempfile from importlib.metadata import version from pathlib import Path -from urllib.parse import quote import tiktoken from jsonschema import Draft202012Validator from referencing import Registry -from mcp_code_mode_cases import act_cases, contract_cases, recovery_cases +from mcp_code_mode_cases import act_cases, refusal_cases +from mcp_code_mode_recovery import recovery_cases, valid_recovery +from mcp_code_mode_validation import valid_preadmission_refusal, verify_profile MANIFEST = Path(__file__).with_name("mcp-code-mode-tools.json") @@ -41,84 +41,14 @@ def cached_encoding(): return tiktoken.get_encoding("o200k_base") -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 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 verify_profile(tools, action_capable, has_commit): - expected_names = ["search", "execute"] + (["commit"] if has_commit else []) - 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 == "commit" or (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, has_commit)) - for name, direction, valid, label, payload in cases: - accepted = validators[name, direction].is_valid(payload) - if direction == "output" and name in {"execute", "commit"}: - accepted = accepted and trusted_approval_link(payload, receipt_run_id="run-1") - if name == "execute" and "intent" in payload: - accepted = accepted and has_commit and payload.get("state") == "approval_required" - if name == "execute" and has_commit and payload.get("state") == "approval_required": - accepted = accepted and "intent" in payload - if accepted != valid: - failures.append(f"{name} {direction} ({label}): expected {'valid' if valid else 'invalid'}") - return len(validators), len(cases), failures - - def main(): fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) search, execute, commit = fixture["tools"] read_execute = {**execute, **fixture["readOnlyExecute"]} + delegated_execute = {**execute, **fixture["delegatedExecute"]} profiles = [ ("Read only", [search, read_execute], False, False), - ("Delegated action", [search, execute], True, False), + ("Delegated action", [search, delegated_execute], True, False), ("Delegated action with approval completion", [search, execute, commit], True, True), ] encoding = cached_encoding() @@ -148,6 +78,11 @@ def main(): 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)") + 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)) From 9bdd1a5bd420ce6ef0081a197234d15842cf1f41 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:38:19 -0500 Subject: [PATCH 08/13] Bind company handbook assignments to their authorized versions --- docs/plans/mcp-code-mode-autonomy.md | 2 +- docs/plans/mcp-code-mode-baseline.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index 2aa1b7bfa..df300891a 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -15,7 +15,7 @@ The direct MCP exposes `search` and `execute`. A program inside `execute` reads The principal or authorized policy owner controls delegation. A guest program cannot select its authority, claim that a person approved, or raise its budget. A run whose authorization expires while queued must be denied before the effect. -A label can already keep standing instructions in its company workspace. An authorized owner or host can supply the approved handbook or an accessible versioned reference with a one-off job. The agent uses it to choose the work under its existing company grant. Record the instruction’s source, version and assignment with the job. Recoup can execute allowed work before it has a built-in instruction editor, recurring-assignment store or scheduler. An administrator uses trusted company settings to change a grant or enforce a new approval rule. Treat retrieved artist or provider documents as task data. +An owner can use the label’s existing handbook from day one. At assignment time, accept inline instructions from the authenticated owner or resolve an owner-designated document from a company-authorized source. A host may relay a document reference. The API verifies the assigning principal’s authority and the document’s company, identity and version before using it as an instruction. Bind the exact content digest and an immutable snapshot or retrievable immutable version to the job, together with the company, assigning actor, agent grant and assignment ID. On restart use that same version and recheck live authority. If it was withdrawn, cannot be verified or no longer matches its digest, hold the affected work. A new version can steer future work when the authorized owner revises the assignment. Test a changed document and a substituted cross-company reference before and after a worker restart. This works through ordinary job assignment before a native instruction editor or scheduler exists. Retrieved artist or provider documents remain task data. The owner can also issue a direct assignment without any document. For example, an owner can say “check the release catalog today and open cases for confirmed missing identifiers.” The same owner can save “do this every Monday and reopen a case only when the evidence changes.” A scheduler submits the same job under the same company agent. If the owner later chooses “ask me before sending a correction outside the label,” that exact send pauses when a qualified sending operation exists. The agent can keep handling unrelated private cases. Removing the recurring assignment stops its future triggers and leaves the underlying grant under the owner’s control. diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md index 27ab34610..7cf11e132 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -43,7 +43,7 @@ Generate searchable descriptors from stable OpenAPI operation IDs and reviewed d | 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 delegated operations.** Admit separate read/list projections through `recoup.read` and a correction-case mutation through `recoup.act`. Qualify evidence, revision checks, idempotency and independent readback in [API #1316](https://github.com/recoupable/api/issues/1316). Preserve the existing multiplexed contract for its callers. If a dedicated resource-oriented REST projection is added, use GET for retrieval and POST for creation. [Case processor](../../lib/context/processCatalogCaseOperation.ts) · [OAuth qualification](../mcp-oauth-tool-qualification.md) | +| 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 delegated operations.** Admit separate read/list projections through `recoup.read` and a correction-case mutation through `recoup.act`. 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) | From f94a50c4663860b9ff90b653b44b02890c41b055 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:01:03 -0500 Subject: [PATCH 09/13] Use ordinary Recoup sign-in and API-owned permissions in the code mode cutover --- docs/plans/mcp-code-mode-autonomy.md | 39 +++++------- docs/plans/mcp-code-mode-baseline.md | 12 ++-- docs/plans/mcp-code-mode-protocol.md | 28 ++++----- docs/plans/mcp-code-mode-research.md | 20 +++--- docs/plans/mcp-code-mode-tools.json | 8 +-- docs/plans/mcp-code-mode.md | 70 +++++++++++---------- docs/plans/mcp_code_mode_cases.py | 6 +- docs/plans/mcp_code_mode_execution_cases.py | 4 ++ docs/plans/verify-mcp-code-mode.py | 6 +- 9 files changed, 101 insertions(+), 92 deletions(-) diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index df300891a..d65a791c5 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -1,35 +1,30 @@ -# Operating a label through Recoup +# Operating Recoup Records through the API -**Proposed first-release contract.** A company can appoint an agent to perform work that its authorized staff can perform. The first action slice must persist a real change without per-action confirmation. The unattended label release must complete a job after the initiating chat closes, even when the optional standing-instruction and approval modules are absent. Track product capability parity by business outcome, including the source of authority, supported entry points, downstream requirements and evidence of completion for each operation. +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) -## Who decides and who acts +## Authority and instructions | Component | Responsibility | | --- | --- | -| Company identity and delegation | An authorized company administrator appoints a separately identifiable agent, selects its company and delegates either the full company operating role or specified operations and resources. The owner can attach destination, spending or time limits when desired. A background worker authenticates as that agent with a renewable, audience-bound credential. Renewal respects the original grant's expiry and revocation. Existing personal registration issues one hour of personal `mcp:read` access and has no refresh token. Company appointment and worker credential renewal are new implementation work. [Current personal registration](../agent-registration.md) | -| Agent and optional standing instructions | An authorized caller can assign a goal directly. A company may also save a recurring instruction describing the trigger, selection criteria and desired outcome. The agent chooses the operations, checks the results and decides how to proceed within its delegation. Instruction text, tool input and stored case assertions cannot mint credentials or enlarge the company's grant. | -| API authorization | The API resolves the actual principal, delegation and current resource permissions. For a concrete action it returns **allow**, **deny**, or **requires interaction** with a reason and, where available, a supported next action. A valid company delegation that covers the action is sufficient for unattended dispatch. An organization may configure additional approvals for particular work. A qualifying individual approval can satisfy that condition within the approver's own authority. Enforce genuine host or provider requirements at the boundary that owns them. | -| Operation owner and workflow | The operation owner checks business preconditions, reserves shared budget atomically when applicable and issues an idempotent request. A durable Recoup workflow records the goal, actor, business key, source versions, checkpoints and completion criteria. It rechecks live authority before each effect and before exposing saved results. It resumes across worker replacement and reconciles an uncertain dispatch against its original receipt. | +| 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 API validates a supported bearer or API key and resolves the account and organization. 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 | Discover the relevant operations and use `execute` to compose calls, pass intermediate results and return a compact answer. The host supplies authenticated context outside the generated program. The agent can start useful work immediately. 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. | -The direct MCP exposes `search` and `execute`. A program inside `execute` reads with `recoup.read(id, args)` and requests an effect with `recoup.act(id, args, {requestKey})`. The outer program and each effect have separate stable request keys. For **allow**, the broker dispatches the effect immediately inside `execute` and records the receipt or job handle. For **deny**, it stops before dispatch. When policy requires approval, it parks the exact intent and returns `approval_required`. The optional third MCP tool, `commit({intent, requestKey})`, applies only the parked effect after the approval is independently recorded and current authority passes again. The rest of the run can then continue from its checkpoint with `execute({runId, resume:true})`. Status lookup by `runId` or the outer `requestKey` has no business effect. A provider-owned signature or approval step can remain pending in the underlying job even after dispatch. +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 principal or authorized policy owner controls delegation. A guest program cannot select its authority, claim that a person approved, or raise its budget. A run whose authorization expires while queued must be denied before the effect. +## The durable catalog job -An owner can use the label’s existing handbook from day one. At assignment time, accept inline instructions from the authenticated owner or resolve an owner-designated document from a company-authorized source. A host may relay a document reference. The API verifies the assigning principal’s authority and the document’s company, identity and version before using it as an instruction. Bind the exact content digest and an immutable snapshot or retrievable immutable version to the job, together with the company, assigning actor, agent grant and assignment ID. On restart use that same version and recheck live authority. If it was withdrawn, cannot be verified or no longer matches its digest, hold the affected work. A new version can steer future work when the authorized owner revises the assignment. Test a changed document and a substituted cross-company reference before and after a worker restart. This works through ordinary job assignment before a native instruction editor or scheduler exists. Retrieved artist or provider documents remain task data. The owner can also issue a direct assignment without any document. +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. -For example, an owner can say “check the release catalog today and open cases for confirmed missing identifiers.” The same owner can save “do this every Monday and reopen a case only when the evidence changes.” A scheduler submits the same job under the same company agent. If the owner later chooses “ask me before sending a correction outside the label,” that exact send pauses when a qualified sending operation exists. The agent can keep handling unrelated private cases. Removing the recurring assignment stops its future triggers and leaves the underlying grant under the owner’s control. +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) -REST, standard named MCP tools, direct code mode and the first-party app call the same operation and authorization logic. Verify equivalent outcomes for equivalent principals, capabilities and resources. Different audiences may have different entitlements. Preserve legacy grants without upgrading them. The Directory exposes only its individually reviewed actions. A Directory consent dialog or downstream requirement for a person's signature applies to that channel or transaction. An unattended job needing that step records the dependency, waits or routes an exception, then resumes using the original intent. Keep a capability ledger for human-supported jobs that still lack a delegated API action, provider access, readback or distribution path. - -## First job and its implementation gap - -For a disposable label, assign an agent to open one private metadata correction case per recording with current evidence of a missing recording identifier (ISRC). Appoint the agent with full operating authority over the disposable label and give it this one-off task with no stored instruction or action-specific approval. Only the private case change is needed. Repeat under a narrower delegation limited to catalog reads and case edits, with zero spend and external messaging disabled. These are two configurations of the same interface. A company can later schedule the assignment as a standing instruction. - -Existing code distinguishes an observed missing ISRC from a failed lookup, partial coverage and stale source versions. `POST /api/context` and standard MCP already save and reopen workspace-scoped catalog cases with revision checks and idempotency keys. Saved cases are private workpapers. A stored assertion about authorization confers no provider authority. The existing delegated MCP profile excludes case save, read and list. Add the case operations to the full company role and make the same operations individually selectable for a restricted role. Verify the workspace and evidence boundaries before offering the job in direct code mode. Reuse the existing case processor, validate evidence against the selected recording and workspace, and keep withdrawal/redaction behavior on subsequent reads. [Release observations](../../lib/context/planning/readReleaseTrackObservations.ts) · [Case contract and retention](../../lib/context/README.md#catalog-case-artifacts-catd-29) · [Current 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. Give the pilot label multiple pages of releases, known missing ISRCs, a failed lookup, a conflict, an already-handled recording and a partial source. Define the expected outcomes independently of the agent. Have an authorized administrator create the grant once. Run the same business operation through REST and the direct MCP host using equivalent isolated fixtures. On the direct path the agent uses `recoup.act` in `execute`, and the receipt must identify an immediate delegated dispatch with zero `commit` calls. Use standard named MCP as an additional control where its existing credential is eligible. -2. Start the agent's job and end its initiating session. Restart a worker, run a second worker against the same business key and change a source version during execution. Persist a stable key derived from organization, recording and correction kind across sessions. Use the existing case ID for retries, check the expected revision and keep source versions on the case so later evidence can update it. Record an unresolved finding when the evidence cannot support a confirmed gap. -3. Using an independent authorized read path, reopen each saved case and verify its ID, workspace, recording, revision, evidence references and source freshness against the seed. Confirm zero wrong or duplicate cases and no cross-company case access, messages, spending or rights changes. Revoke the delegation while a second job is queued and verify zero subsequent writes. For the optional approvals release, configure a separate trial to require one approval. Verify that the exact effect stays parked, the optional `commit` applies it once after approval, and resuming the checkpoint preserves earlier completed effects. -4. Publish a redacted receipt with expected versus observed cases, reason for every unresolved recording, number of human interruptions **after appointment**, recovery behavior and cost per verified case. An accepted job or an in-memory preview is insufficient. The release gate is a persisted business change with independent readback and unattended completion under the original company delegation. +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. +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. 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 index 7cf11e132..913d34a3e 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -1,6 +1,6 @@ # 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. The amended direct interface has its own fixture, including immediate delegated actions within `execute` and optional `commit` for previously parked effects. Reproduce current candidate counts with the [wire fixture verifier](verify-mcp-code-mode.py). 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 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. The direct interface has its own design fixture. Its authenticated calls use the signed-in account's existing API operations, permissions and approval requirements. Reproduce current candidate counts with the [wire fixture verifier](verify-mcp-code-mode.py). 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 @@ -27,23 +27,23 @@ The connected Codex Recoup connector independently exposed 94 tool names in this - **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 broker should enter an API-owned operation using a verified principal and that operation's delegated projection. Provisioning a broad key for a code program would change the granted authority. [REST authentication](../../lib/auth/validateAuthContext.ts) · [Resource-bound access](../../lib/oauth/resolveOAuthAccess.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, skill fallback, staff audience and thread placement independently. [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 every human-supported job, map the existing route, credential and restrictions to the proposed company principal and operation. Track gaps in delegated authorization, domain implementation, provider execution and independent readback. Current personal and selected-context limits are compatibility baselines. A company can separately authorize its agent for specified work. The first release exercises an unattended correction-case write through the direct endpoint and the same API operation through REST. [Company delegation and pilot](mcp-code-mode-autonomy.md) +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. Keep one policy identifier per meaningful operation, including Context actions that share a REST 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) +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 delegated operations.** Admit separate read/list projections through `recoup.read` and a correction-case mutation through `recoup.act`. 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) | +| 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) | @@ -55,4 +55,4 @@ Generate searchable descriptors from stable OpenAPI operation IDs and reviewed d 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. Exercise a zero-interruption delegated change and, independently, an effect parked by policy that is approved and applied once. 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) +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 index 36082f9fe..48f6390cd 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -1,6 +1,6 @@ # Recoup MCP protocol compatibility and OpenAI review -**Decision record for the proposed cutover, November 27, 2026.** Direct clients discover and run authorized Recoup operations with two tools. A company can delegate specific business actions to its agent within agreed limits. A third tool is available on profiles configured to complete individual actions paused for approval. 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) +**Decision record for the proposed cutover, updated November 28, 2026.** Direct clients discover and run authorized Recoup operations with two tools. The account signs in through the existing Recoup connection, and its agent can take the actions the Recoup API permits. An optional third tool forwards completion of an action paused for API approval. 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 @@ -10,9 +10,9 @@ The current revision is **2026-07-28**. At the inspected API source revision, Re | --- | --- | | 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`. An action profile also exposes `recoup.act` for current company delegations. An authorized operation can run immediately. When policy requires approval, persist the exact paused step. The optional `commit` releases only that step after the independently recorded decision. 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 and enforce grants inside the broker on every nested call. 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 current delegation. 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. Allow a valid standing delegation to authorize ordinary actions without a fresh human reply. If a particular step requires a new approval, offer a Recoup-owned authenticated decision flow on hosts lacking the necessary interaction. Keep delegated work and ordinary reads usable with a text-only client. 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) | +| 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. The optional `commit` forwards completion to that API operation after the API records the decision. 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 and route every nested 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) @@ -21,22 +21,22 @@ Use the official revision index for the base protocol, transports, authorization ## Direct action and recovery contracts -The account delegates through Recoup's control plane. Bind the delegation to the company/workspace, agent/client, the full operating role or selected operations, and the grant lifecycle. Apply company-selected resource, destination or spending limits where configured. Enforce each operation’s current API and provider requirements. A full-role grant may expressly include newly qualified operations within the same authority boundary. At every read, action, resumed step and actual delayed dispatch, intersect that delegation with the authenticated grant, current company membership, operation policy and remaining authority. An ordinary OAuth scope establishes the client's potential access. A matching company delegation establishes which business actions the agent can take. An instruction in guest code supplies neither. [MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) +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 | | --- | --- | | 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. | -| Delegated `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 principal/profile, authenticated grant 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. Atomically recheck authority and reserve any budget under concurrency. Dispatch allowed steps. Deny excluded steps. Pause before dispatch only where a configured decision is needed. | +| 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 and budget checks, its refusal, and its approval requirement. 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})` | Resume from a durable, versioned checkpoint under fresh authority. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | -| `commit({intent, requestKey})`, where offered | Consume the exact server-sealed paused step after a recorded decision. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | +| `execute({runId, resume:true})` | Resume from a durable, versioned checkpoint after rechecking the account's current API access. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | +| `commit({intent, requestKey})`, where offered | Forward the exact sealed step to the owning API's completion path after that API records approval. Offer this tool only where the API supports exact, independently verifiable approval completion. On the two-tool profile, the approver uses the same API flow and the agent checks `execute` for its result. An agent-supplied decision is rejected. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | -**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The two-tool delegated output schema excludes `intent`. The three-tool profile requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. +**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The two-tool account action output schema excludes `intent`. The three-tool profile requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. -Qualify an allowed internal business action under an existing synthetic company delegation in one direct call against a disposable workspace and verify its result through an independent read. Then drop the first response after dispatch, reconnect with only the original key and check for one observed effect. Repeat with two identical retries, a conflicting step payload, two concurrent resumes, and delegation revocation between two steps. A separate fixture triggers a policy-specific approval and verifies that a stale or altered decision cannot release another step. Capture actual host prompts separately from Recoup's authorization decisions. These cases verify behavior beyond the JSON Schema examples. [Descriptor examples](mcp-code-mode-tools.json) · [Local verifier](verify-mcp-code-mode.py) +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. 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. Verify that an altered or stale approval cannot release another step and that delayed work respects revoked credentials. 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 @@ -45,7 +45,7 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | 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 | Evaluate enterprise machine access and centrally managed grants as separate products when required. ChatGPT's delegated account connection uses interactive authorization code with PKCE. 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) | +| 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 | Preserve entitled resources, manifest verification, `skills/list`, `skills/get` and supporting file reads for native clients. Direct clients lacking native support can use bounded skill discovery/read within `search`. A skill cannot expand API permissions. OpenAI's release package includes only reviewed audience-appropriate skills. Verify packaged and native behaviors independently. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | | 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) | @@ -57,12 +57,12 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | --- | --- | | Protocol fixtures and Inspector | Run pinned upstream conformance and project-specific tests against both wire eras, both profiles and the retained legacy URL. A text-only client with no optional capabilities must complete the read flow. 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 direct discovery, authorized reads, multi-operation composition and skill fallback. On a delegated profile, exercise one allowed write with zero additional Recoup approval prompts, one denied action and one explicitly paused action. 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) | +| Codex, Claude Code, Claude Desktop and Cursor | Exercise real client builds for the surfaces Recoup claims. Record direct discovery, authorized reads, multi-operation composition and skill fallback. 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. Introduce a dedicated delegated catalog-read grant. The existing narrow MCP grant does not include these operations. 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) +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 diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md index 0e33bd0e7..b86fbf3dc 100644 --- a/docs/plans/mcp-code-mode-research.md +++ b/docs/plans/mcp-code-mode-research.md @@ -1,32 +1,36 @@ # Code Mode research for the Recoup MCP cutover -Reviewed November 27, 2026. This evidence informs the proposed architecture. Vendor measurements describe their workloads. The rollout needs its own matched Recoup measurements before assigning savings or retiring a capability. +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. 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. That lets the broker enforce account, resource, effect and response rules on every call. [Original Cloudflare experiment](https://blog.cloudflare.com/code-mode/) · [Cloudflare API MCP server](https://blog.cloudflare.com/code-mode-mcp/) +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 locally studied v2 source is `40be470` (CLI `2.0.0-beta.73`). On the review date the upstream default branch was `v2` at `95c6b6b` (CLI `2.0.0-beta.80`), 44 commits ahead of that snapshot. We compared the trees and checked current MCP registrations. The latest GitHub *release* endpoint identified `v1.6.11`. Keep tagged releases, beta source and the consuming application's verified dependency distinct. The review covered source contracts and implementation. Runtime compatibility with Recoup still requires fixtures and deployed qualification. [Pinned upstream tree](https://github.com/UsefulSoftwareCo/executor/tree/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf) · [CLI version](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/apps/cli/package.json) · [Compared revisions](https://github.com/UsefulSoftwareCo/executor/compare/40be47066a0c2803211acd618662901e77de9f25...95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf) · [v1.6.11 release](https://github.com/UsefulSoftwareCo/executor/releases/tag/v1.6.11) +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 principal and selected organization outside the guest program. Discoverability, a generated type and a previous successful call each supply information only. The current request's resource authorization and effect policy govern dispatch. | -| 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. The two-tool direct path carries ordinary delegated work, including writes. Reserve an optional third tool for applying an already parked and approved effect. | +| 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. The two-tool direct path can carry an ordinary signed-in account's reads and writes. Delegate any required quote, consent or approval to the API that owns that operation. | | 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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. Recoup's chosen direct path runs `recoup.act(id, args, {requestKey})` within `execute` and immediately dispatches a permitted effect. Its optional `commit` applies only an effect previously parked for approval under the applicable policy. [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) +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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. Recoup's direct path uses `execute` to invoke API operations as the signed-in account. The API decides whether an authenticated action can proceed immediately or requires an existing approval. Single-operation latency is a benchmark question for the Recoup fixtures. [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) ## Execution choices -The guest program needs standard JavaScript control flow, JSON values and a narrow asynchronous host call. The trusted side owns the route, credentials, principal, method, resource checks and call ledger. 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. +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 | | --- | --- | --- | @@ -40,7 +44,7 @@ Choose the broker contract before choosing a runtime library. A runtime adapter ## 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. Return ranked summaries before details. 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, grant the company agent a bounded disposable fixture, execute an unattended action, verify the result independently and exercise cleanup. A separate trial enables an approval policy and verifies that the effect occurs only after approval. Record unknown consumers and keep their compatibility path until an owner determines disposition. +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 wire bytes, actual or explicitly estimated prompt tokens, discovery 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 index 75028d2c0..0cfc1d111 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -139,8 +139,8 @@ }, { "name": "execute", - "title": "Run delegated Recoup operations", - "description": "Run async (recoup, params) with a stable run requestKey. Use recoup.read(id,args) or recoup.act(id,args,{requestKey}) with a stable key per effect. Delegated actions may immediately change data or contact external parties. A requestKey or runId alone retrieves status. Use runId with resume:true for a checkpointed continuation.", + "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. Use runId with resume:true to continue a checkpoint.", "inputSchema": { "type": "object", "properties": { @@ -375,7 +375,7 @@ { "name": "commit", "title": "Apply an approved Recoup change", - "description": "Apply one exact policy-paused effect after recorded approval. Reuse requestKey on retry. Look up the run with execute.", + "description": "Forward completion of one exact paused action to the Recoup API after it records approval. Reuse requestKey on retry. Look up the run with execute.", "inputSchema": { "type": "object", "properties": { @@ -725,7 +725,7 @@ ], "additionalProperties": false }, - "delegatedExecute": { + "accountExecute": { "outputSchema": { "type": "object", "properties": { diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index a7393e0b6..583ea85c2 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -1,15 +1,15 @@ # Recoup MCP code mode -**Proposed technical specification · November 27, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** +**Proposed technical specification · November 28, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** -Under this design a Recoup Records owner can appoint an agent to run the label. The agent can take a one-off assignment or follow standing company instructions supplied from its approved operating handbook. A versioned reference or an owner-provided assignment works before Recoup has its own instruction editor or scheduler. With full delegated authority it can act immediately, through two direct MCP tools. `search` finds the relevant Recoup operations. In `execute`, the host’s model writes a short JavaScript program, reads the records it needs, calls the Recoup API to make changes, and obtains evidence of what happened. The API owns the business rules for every client. +Sign in with your Recoup account and your agent can act. With `search` it finds the Recoup API operations that apply to the task. 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 product target is every music-company operation a human with equivalent authority can perform. Each missing API action, provider integration or independently verifiable outcome has an owner in the coverage inventory. A company can delegate the full operating role once, narrow it, or require individual approval for specified actions. New personal connections retain their own expressly granted access. The optional instruction and approval features, first-party App migration and public ChatGPT Directory submission have independent delivery paths. +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 | -| [Company delegation and the first label workflow](mcp-code-mode-autonomy.md) | One-off and standing assignments, company authority, policy decisions, a verified catalog-case change and restart after disconnect | +| [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. | | [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 | @@ -17,14 +17,14 @@ The product target is every music-company operation a human with equivalent auth ## 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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **969** (4,022 bytes), a **97.0% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,358** (5,554 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. +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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **978** (4,061 bytes), a **96.9% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,373** (5,622 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. -Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each two-tool profile it applies the matching `readOnlyExecute` or `delegatedExecute` override. Its internal `actRequest` 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) +Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each two-tool profile it applies the matching `readOnlyExecute` or `accountExecute` override. Its internal `actRequest` 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` | Exactly `search` and `execute`. Native skills/resources use negotiated protocol methods. Text-only hosts can find permitted skills through search. | -| Direct, company-authorized | `/mcp/code` | Exactly `search` and `execute` for an agent that can act unattended. An allowed `recoup.act` inside `execute` applies the requested change. An approval-enabled profile may also expose `commit` to finish one exact parked effect. Truthful annotations describe the effects reachable on each profile. | +| Direct, signed in with access to act | `/mcp/code` | Exactly `search` and `execute`. A permitted `recoup.act` inside `execute` applies the requested change through the API. If an operation supports completion of a previously approved effect, the profile may also expose `commit`. Tool annotations describe the effects reachable on each profile. | | 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, call commit 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. | @@ -37,8 +37,8 @@ Both new URLs are proposals under the established MCP mount. Business REST endpo | 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 | Gives a person an opportunity to inspect each change. | Offer exact review where the company chooses it or the transaction requires it. Requiring this for routine delegated work would prevent an agent from running the label unattended. | -| Two direct tools, an API-owned authorization decision, an optional approval continuation and named Directory tools | Stable discovery cost as operations grow. The same API checks and receipts cover autonomous and individually approved work. | **Adopt.** The API owns behavior. An interchangeable runner composes its operations. Optional modules provide standing assignments, approval journeys and durable scheduling. | +| 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 sharing the API’s permissions, optional approval continuation and 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. Optional clients can present a pending approval or resume a supported action. | | 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. @@ -47,7 +47,7 @@ Use parallel opt-in URLs, with independent flags by profile, operation and cohor ```mermaid flowchart LR - Contracts["Pinned Docs OpenAPI + API validators + reviewed policy"] --> Build["Catalog compiler / signed release"] + 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 --> Search["Authorized catalog index"] @@ -56,8 +56,8 @@ flowchart LR Direct --> Commit["Optional exact approval continuation"] Commit --> Broker Named --> Broker - Broker --> Authority["Company delegation and optional policy"] 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"] ``` @@ -66,9 +66,9 @@ flowchart LR **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 policy. 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. +**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 after the route's and profile's authorization/ownership checks have been composed. 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. +**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. @@ -76,7 +76,7 @@ flowchart LR ## Interaction contract -`search` accepts a natural-language query, exact ID or page cursor. Each result has an id, summary and effect. Operations carry read or write, while skill material carries instruction. Requested contract sections and skill files use the optional bounded detail object. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, principal, policy and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. +`search` accepts a natural-language query, exact ID or page cursor. Each result has an id, summary and effect. Operations carry read or write, while skill material carries instruction. Requested contract sections and skill files use the optional bounded detail object. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, signed-in account, effective access and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. `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. A guarded `execute({runId,resume:true})` continues only a recorded checkpoint. 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. @@ -96,13 +96,13 @@ async (recoup, params) => { 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) -For a direct assignment, an appointed agent can find the current metadata observation and private case operations, read the evidence, create or update a case with `recoup.act` and reopen it independently. The authenticated company and selected catalog come from the connection. Stable internal recording identity, correction kind and company identify the same business work across chats and retries. A name collision, missing ISRC or partial source cannot establish identity. This proposed case grant needs API work. A smaller first dispatch can use the existing additive `review_context_release_case` operation with `needs_changes` on qualified evidence, then independently read the immutable review. The catalog-correction workflow demonstrates continued operation after chat closure. [Case contracts](../../lib/context/releaseCaseOperationSchemas.ts) · [Installed acceptance](mcp-code-mode-autonomy.md#installed-end-to-end-acceptance) +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) -**Authority and dispatch.** The owner appoints a named, revocable company agent with full or selected operating authority. A grant can cover qualified future actions in an authorized role and domain if the owner explicitly selects that behavior. Show material scope/effect changes and require a fresh grant for an expanded audience, role, data boundary or ungranted capability. Company membership, a saved instruction, program source or provider account access alone cannot appoint the agent. With no optional policy the API uses the explicit grant and the operation’s own requirements. With a configured policy, evaluate active company rules as well. `allow` dispatches immediately. `requires interaction` parks the exact effect with an actionable reason. `deny` dispatches nothing. Denial takes precedence, then required approval, then allow. If a configured policy is unavailable, hold affected effects. An absent optional module never delays a properly granted action. Recheck authority on every operation, checkpoint and dispatch. [Full contract](mcp-code-mode-autonomy.md) +**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) -**Optional exact approval.** When the company requests individual confirmation, the broker seals a canonical one-effect intent bound to actor, grant, company, selected resource, operation and policy revisions, destination, quote or ceiling, expiration and input digest. For a company approval return `approval_required` with the run ID and a broker-derived URL for the exact receipt. Include the sealed intent for the caller only on a profile that exposes `commit`. Build it from the fixed HTTPS Recoup App origin, path and server-issued ID. The signed-in App at `https://app.recoupable.dev/mcp/approvals/{runId}` presents the target, change, destination, charge and expiry to an authorized approver. Validate exact URL equality before every response and test login and sign-in return at the canonical origin. Accept a trusted, bound decision before `commit({intent,requestKey})` dispatches that effect once. It cannot substitute arguments or approve another step. Recovery via `execute` reads the same receipt and, where supported, resumes a saved checkpoint after the effect is settled. Limit canonical arguments to 4 KiB and sealed intent to 8 KiB for this optional interface. Refuse oversized pending approval inputs before dispatch and supply narrowing guidance. Quotes that reserve credits or send data have their own effect contracts. An external signature or provider consent needs proof from its issuer. [Existing production consent origin](../mcp-oauth-runtime.md) +**API-owned approvals.** When an operation requires approval, its API records the pending effect, the authorized account and resource, canonical arguments, destination, allowed cost and expiry. MCP returns `approval_required`, the account-scoped run ID and a trusted Recoup link to the corresponding decision. Only the owning API can accept a decision from an authorized approver, bind it to the recorded inputs, and apply or release it once. The two-tool client can look up status with `execute`. If the operation provides an exact completion endpoint, an optional `commit({intent,requestKey})` forwards its opaque reference to that endpoint. It cannot approve an action. Verify the canonical HTTPS origin and exact reference, login return, changed terms, expiry and duplicate attempts. A client may present the existing Recoup flow. A new MCP approval screen or store is unnecessary. The fixture budgets 4 KiB for canonical inputs and 8 KiB for a sealed intent. 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` and optional `commit`, compute open-world, destructive and idempotency hints conservatively from all reachable operations. A full direct role can reach external effects once its API operations are qualified. Authorize the destination and fields against the company grant, provider contract and configured policy. 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. +The read-only `execute` annotation applies only to a bridge that cannot cause effects, including hidden settlements or paid processing. For action-enabled `execute` and optional `commit`, 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 @@ -115,32 +115,34 @@ A modern client can receive a structured result, a scoped resource link or an ex | 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 or earlier quote/grant 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. | +| 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. | -Validate audience-specific credentials, client, operating role, current company/artist access, asset ownership, policy and emergency disable on each call. Private caches and signed cursors are scoped to those boundaries. The present `/mcp` audience and legacy API-key/Privy, narrow, full, selected-context and staff connections retain their present access. Add an explicitly appointed company principal and renewable, revocable credential for the new direct audience. Owners can authorize full operating authority during appointment. Personal one-hour read-only agent registration and mere organization membership cannot serve as this grant. Use a separate catalog-read grant for Directory. Activation of equivalent domain services for the new identity requires normal-entry tests. Qualification for one channel cannot change another channel’s credentials. [Current resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Current agent registration](../agent-registration.md) +**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`, actor/grant/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Use a unique key for company business key + effect step as well as the actor/profile/request-key binding and any optional sealed intent claim. An identical authorized retry returns the prior receipt. Reusing a key for a different request conflicts. An authenticated receipt records the company delegation and 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. +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. Use a unique key for company business key + effect step as well as the account/connection/profile/request-key binding and any optional sealed intent claim. 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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the broker-derived URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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. +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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the validated API approval URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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. 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. +**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 top-level tools in every variant. **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, skill 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 | | --- | --- | | Startup | At most 1,500 descriptor tokens for the write-capable direct profile, at least 90% below full OAuth's model-visible reference list. Verify actual first-turn token delta on controlled hosts and report measured vs unavailable separately. 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, optional approval, idempotency and isolation tests pass. Zero unauthorized or duplicate changes. Verify a real human-visible effect with zero per-effect approvals under full delegation and no stored instructions; separately demonstrate the exact number of interactions a configured exception requires. Test two companies, concurrent agents, stale evidence and revocation after enqueue. An unqualified optional branch holds only the cohort or operations depending on it. | +| 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 the inventory and runner qualification in parallel. Test reads to validate connectivity, then dispatch one real additive action for a disposable company through two tools and independently reopen the result, with zero confirmations after appointment. Launch this slice without saved instructions, an approval UI or Directory review. Next qualify an end-to-end label assignment across chat closure and worker replacement, and test optional standing instructions and human review on their own tracks. Eligible direct cohorts can progress through 1%, 10%, 50% and 100% after a monitoring window and successful journeys at each stage. Keep existing installs, historical chat and gallery paths until their own parity and rollback gates pass. Publish the independently named OpenAI package through its existing publisher process. +**Adoption sequence.** Start inventory and runner qualification in parallel. Qualify normal sign-in and reads, then use two tools to perform 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. @@ -152,23 +154,23 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | --- | --- | --- | | [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) | Appoint, authenticate, renew and revoke company agents | [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) | Ship search and execute with separate read and action profiles | [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) | Dispatch allowed company actions from execute with zero confirmations | [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 to company agents | [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) | Continue jobs across chat closure, worker restarts and events | [api#1308](https://github.com/recoupable/api/issues/1308) | -| [api#1313](https://github.com/recoupable/api/issues/1313) | Add optional standing instructions and policy overrides | [api#1305](https://github.com/recoupable/api/issues/1305), [api#1308](https://github.com/recoupable/api/issues/1308) | -| [app#2411](https://github.com/recoupable/app/issues/2411) | Migrate first-party consumers and build the optional approval screen | [api#1307](https://github.com/recoupable/api/issues/1307) | -| [api#1314](https://github.com/recoupable/api/issues/1314) | Resume an exact action after a required approval | [api#1308](https://github.com/recoupable/api/issues/1308), [app#2411](https://github.com/recoupable/app/issues/2411) | +| [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) | Migrate first-party consumers and display API-required approvals | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [api#1314](https://github.com/recoupable/api/issues/1314) | Relay completion of an exact API-approved action where supported | [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 startup context, completed work, interruptions, latency and cost | [api#1308](https://github.com/recoupable/api/issues/1308) | | [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify unattended label operations, real hosts 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) | Publish versioned direct, company-agent, Directory and legacy guides | [api#1304](https://github.com/recoupable/api/issues/1304), [api#1305](https://github.com/recoupable/api/issues/1305) | +| [docs#44](https://github.com/recoupable/docs/issues/44) | Publish versioned account sign-in, Directory and legacy migration guides | [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.** The first persisted autonomous action is API #1308. A durable label proof adds #1315 and #1316, then independent qualification in Mono #752. Standing instructions (#1313), the individual-approval track and Directory review (#753) are outside the direct rollout’s critical path. Within the individual-approval track, API #1314 depends on the App confirmation screen in #2411. First-party legacy retirement still requires evidence for its actual callers. Provider delivery remains a product capability gap until an owning API and an authoritative downstream outcome are available. +**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. The optional approval relay (#1314) builds on action dispatch and uses the owning API’s approval flow. App migration, saved instructions, the relay 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. \ No newline at end of file diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index c93b63ba5..3dbf7524e 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -33,10 +33,12 @@ def commit_cases(): yield "commit", "input", False, "malformed intent", {**commit, "intent": "wrong value!"} yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} yield "commit", "input", False, "new source", {**commit, "source": "async (recoup, params) => params"} + yield "commit", "input", False, "caller supplies an approval decision", {**commit, "approved": True} + yield "commit", "input", False, "caller selects the approving account", {**commit, "accountId": "other"} def act_cases(): - """The guest calls recoup.act(id, args, {requestKey}); the supervisor supplies authority.""" + """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"]} @@ -45,6 +47,8 @@ def act_cases(): 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, has_commit): diff --git a/docs/plans/mcp_code_mode_execution_cases.py b/docs/plans/mcp_code_mode_execution_cases.py index 4dd0402c5..7e7f60dc0 100644 --- a/docs/plans/mcp_code_mode_execution_cases.py +++ b/docs/plans/mcp_code_mode_execution_cases.py @@ -17,6 +17,10 @@ def execute_cases(action_capable): 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"]} diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index 91b273ae5..0d1f2c577 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -45,11 +45,11 @@ def main(): fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) search, execute, commit = fixture["tools"] read_execute = {**execute, **fixture["readOnlyExecute"]} - delegated_execute = {**execute, **fixture["delegatedExecute"]} + account_execute = {**execute, **fixture["accountExecute"]} profiles = [ ("Read only", [search, read_execute], False, False), - ("Delegated action", [search, delegated_execute], True, False), - ("Delegated action with approval completion", [search, execute, commit], True, True), + ("Account action", [search, account_execute], True, False), + ("Account action with API approval completion", [search, execute, commit], True, True), ] encoding = cached_encoding() print(f"tiktoken {version('tiktoken')}, {encoding.name}") From 9c2f39f449236efe30f2dd93462bef5dc973feb6 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:07:13 -0500 Subject: [PATCH 10/13] Clarify API checks for shared work, spending and approval links --- docs/plans/mcp-code-mode-autonomy.md | 2 +- docs/plans/mcp-code-mode-protocol.md | 4 ++-- docs/plans/mcp-code-mode.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index d65a791c5..f2b484649 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -6,7 +6,7 @@ A Recoup Records operator signs in with an ordinary Recoup account, selects a la | 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 API validates a supported bearer or API key and resolves the account and organization. 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) | +| 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 | Discover the relevant operations and use `execute` to compose calls, pass intermediate results and return a compact answer. The host supplies authenticated context outside the generated program. The agent can start useful work immediately. 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. | diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index 48f6390cd..29cbd2000 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -27,7 +27,7 @@ Sign in to Recoup once through the existing account connection. A direct client | --- | --- | | 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 and budget checks, its refusal, and its approval requirement. Dispatch an allowed action immediately. Mirror any API pause before the action takes effect. | +| 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})` | Resume from a durable, versioned checkpoint after rechecking the account's current API access. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | | `commit({intent, requestKey})`, where offered | Forward the exact sealed step to the owning API's completion path after that API records approval. Offer this tool only where the API supports exact, independently verifiable approval completion. On the two-tool profile, the approver uses the same API flow and the agent checks `execute` for its result. An agent-supplied decision is rejected. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | @@ -36,7 +36,7 @@ Sign in to Recoup once through the existing account connection. A direct client 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. 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. Verify that an altered or stale approval cannot release another step and that delayed work respects revoked credentials. 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) +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. Verify that an altered or stale approval cannot release another step and that delayed work respects revoked credentials. 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 diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index 583ea85c2..50c45b376 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -100,7 +100,7 @@ A signed-in label operator can ask the agent to record `needs_changes` on a disp **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-owned approvals.** When an operation requires approval, its API records the pending effect, the authorized account and resource, canonical arguments, destination, allowed cost and expiry. MCP returns `approval_required`, the account-scoped run ID and a trusted Recoup link to the corresponding decision. Only the owning API can accept a decision from an authorized approver, bind it to the recorded inputs, and apply or release it once. The two-tool client can look up status with `execute`. If the operation provides an exact completion endpoint, an optional `commit({intent,requestKey})` forwards its opaque reference to that endpoint. It cannot approve an action. Verify the canonical HTTPS origin and exact reference, login return, changed terms, expiry and duplicate attempts. A client may present the existing Recoup flow. A new MCP approval screen or store is unnecessary. The fixture budgets 4 KiB for canonical inputs and 8 KiB for a sealed intent. Keep downstream signatures or provider consent with their issuer. [Protocol and recovery](mcp-code-mode-protocol.md) +**API-owned approvals.** When an operation requires approval, its API records the pending effect, the authorized account and resource, canonical arguments, destination, allowed cost and expiry. MCP returns `approval_required`, the account-scoped run ID and a trusted Recoup link to the corresponding decision. Only the owning API can accept a decision from an authorized approver, bind it to the recorded inputs, and apply or release it once. The two-tool client can look up status with `execute`. If the operation provides an exact completion endpoint, an optional `commit({intent,requestKey})` forwards its opaque reference to that endpoint. It cannot approve an action. For the reference profile, the exact approval URL is `https://app.recoupable.dev/mcp/approvals/{runId}`, with the server-issued run ID. This link can open the owning API’s existing review flow. Verify the full URL, login return, changed terms, expiry and duplicate attempts. A client may present the existing Recoup flow. A new MCP approval screen or store is unnecessary. The fixture budgets 4 KiB for canonical inputs and 8 KiB for a sealed intent. 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` and optional `commit`, 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. @@ -120,7 +120,7 @@ A modern client can receive a structured result, a scoped resource link or an ex **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. Use a unique key for company business key + effect step as well as the account/connection/profile/request-key binding and any optional sealed intent claim. 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. +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. From 38d376f8e73d15ca95d67ecffa92d30eb53803c3 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:15:39 -0500 Subject: [PATCH 11/13] Give skills a dedicated tool and resume approved work through execute --- docs/plans/mcp-code-mode-autonomy.md | 6 +- docs/plans/mcp-code-mode-baseline.md | 6 +- docs/plans/mcp-code-mode-protocol.md | 25 ++++--- docs/plans/mcp-code-mode-research.md | 4 +- docs/plans/mcp-code-mode-tools.json | 95 ++++++++++++++---------- docs/plans/mcp-code-mode-user-stories.md | 30 ++++++++ docs/plans/mcp-code-mode.md | 40 +++++----- docs/plans/mcp_code_mode_cases.py | 8 +- docs/plans/mcp_code_mode_resume.py | 48 ++++++++++++ docs/plans/mcp_code_mode_resume_cases.py | 43 +++++++++++ docs/plans/mcp_code_mode_skill_cases.py | 27 +++++++ docs/plans/mcp_code_mode_validation.py | 4 +- docs/plans/verify-mcp-code-mode.py | 14 +++- 13 files changed, 269 insertions(+), 81 deletions(-) create mode 100644 docs/plans/mcp-code-mode-user-stories.md create mode 100644 docs/plans/mcp_code_mode_resume.py create mode 100644 docs/plans/mcp_code_mode_resume_cases.py create mode 100644 docs/plans/mcp_code_mode_skill_cases.py diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index f2b484649..85693af6b 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -7,7 +7,7 @@ A Recoup Records operator signs in with an ordinary Recoup account, selects a la | 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 | Discover the relevant operations and use `execute` to compose calls, pass intermediate results and return a compact answer. The host supplies authenticated context outside the generated program. The agent can start useful work immediately. The API alone decides business authorization, including any approval the underlying operation already requires. | +| MCP and agent | Use `search` to find permitted operations and `execute` to compose calls and return a compact answer. Use `skills` to list or read guidance permitted for the signed-in account when the job calls for it. 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. | @@ -23,8 +23,8 @@ To qualify the direct connection, expose the authorized case operations for its ## 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. +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 the direct profile, list and read a permitted guide through `skills` and verify that reading it produces 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. Record real host-imposed prompts separately from API decisions. Publish only sanitized task outcomes, receipt references, interruptions and cost per verified case. +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. Compare both with an optional `commit` client using the same API completion path. 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 index 913d34a3e..8183edfdf 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -1,6 +1,6 @@ # 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. The direct interface has its own design fixture. Its authenticated calls use the signed-in account's existing API operations, permissions and approval requirements. Reproduce current candidate counts with the [wire fixture verifier](verify-mcp-code-mode.py). 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 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 @@ -14,6 +14,8 @@ Each cell gives UTF-8 bytes / tokens. The payload is compact JSON of `{"tools":[ | 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** for `search`, `execute` and `skills` measures **3,685 bytes / 904 tokens** with read-only execution and **4,444 / 1,077** with account actions. The latter is 96.6% smaller than the historical 31,820-token full OAuth model-visible list. A client needing a separate call for exact API-approved completion can also receive `commit`, a fourth tool forwarding to the same API path as explicit `execute` resume. That fixture measures **5,987 / 1,466**. These counts cover the compact `tools/list` result. A guide’s contents arrive only when requested. [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 @@ -30,7 +32,7 @@ The connected Codex Recoup connector independently exposed 94 tool names in this - **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, skill fallback, staff audience and thread placement independently. [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) +- **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 `skills` tool under equivalent access. Exercise negotiated native skills separately and 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 diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index 29cbd2000..2a2d6872c 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -1,6 +1,6 @@ # Recoup MCP protocol compatibility and OpenAI review -**Decision record for the proposed cutover, updated November 28, 2026.** Direct clients discover and run authorized Recoup operations with two tools. The account signs in through the existing Recoup connection, and its agent can take the actions the Recoup API permits. An optional third tool forwards completion of an action paused for API approval. 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) +**Decision record for the proposed cutover, updated November 29, 2026.** Direct clients use three model tools. `search` discovers permitted operations, `execute` runs them and `skills` lists or reads permitted guidance on demand. The account signs in through the existing Recoup connection, and its agent can take the actions the Recoup API permits. The standard `execute` tool supports durable continuation. A client with a demonstrated need for a separate completion call may also receive an optional fourth tool, `commit`, for the same exact API-approved action. 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 @@ -10,14 +10,14 @@ The current revision is **2026-07-28**. At the inspected API source revision, Re | --- | --- | | 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. The optional `commit` forwards completion to that API operation after the API records the decision. 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 and route every nested 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) | +| 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 at the owning API. An explicit `execute` resume can forward exact approved completion to that API. Optional `commit` uses the same API path. 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` and `skills` read-only. The former returns operation metadata; the latter resolves only guidance the account may access. 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. Keep the essential search and execution contracts callable without preloading either. 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) +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`, `execute` and `skills` without preloading a guide or 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 @@ -25,28 +25,31 @@ Sign in to Recoup once through the existing account connection. A direct client | Call | Observable behavior | | --- | --- | +| `search` | Look up permitted API operations by query, exact ID or cursor. Return the matching contract and examples on demand. | +| `skills({})` or `skills({query, offset})` | List or filter permitted guidance. Return a bounded page of names and descriptions as JSON text, with `nextOffset` when another page exists. | +| `skills({skill})` or `skills({skill, file})` | Read the named guide’s `SKILL.md` or one supporting file from its approved manifest. Return bounded UTF-8 text or an authorized embedded binary resource. Apply the same audience and file checks as native skills, including after an access change. A read cannot dispatch a business operation or approve an action. | | 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})` | Resume from a durable, versioned checkpoint after rechecking the account's current API access. Accept no replacement code, args or run key. An ordinary short-lived JS isolate has no portable continuation. Resume a recorded workflow or a restart-safe program with deterministic, recorded step identity and results. Return a recoverable state when that guarantee is unavailable. Checkpoint ingress uses a single atomic claim across concurrent resumes. | -| `commit({intent, requestKey})`, where offered | Forward the exact sealed step to the owning API's completion path after that API records approval. Offer this tool only where the API supports exact, independently verifiable approval completion. On the two-tool profile, the approver uses the same API flow and the agent checks `execute` for its result. An agent-supplied decision is rejected. The approval result carries the canonical Recoup URL and an authorized run ID. Expose the sealed intent only when the profile provides `commit`. Bind it to the paused step and expiry. Deduplicate a racing resume and commit on the same step claim. Resume the larger workflow with `execute`. | +| `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. | +| `commit({intent, requestKey})`, where offered | Offer this fourth tool only for a demonstrated client need. It forwards one already approved step to the same API completion path available through `execute({runId,resume:true})`. Expose its sealed intent only on this profile and bind it to the exact step and expiry. A racing `commit` and `execute` resume share the same atomic step claim and effect key. Return the existing receipt if the API already applied it. Approval belongs to an authorized approver at the owning API. Resume the larger workflow with `execute`. | -**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The two-tool account action output schema excludes `intent`. The three-tool profile requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. +**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The standard three-tool account action output schema excludes `intent`. The four-tool profile with `commit` requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. Verify that an altered or stale approval cannot release another step and that delayed work respects revoked credentials. 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) +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 or optional `commit` races it. 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 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) +Negotiate each optional extension using the peer's advertised capabilities. Test operation discovery, skill list/read 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 | Preserve entitled resources, manifest verification, `skills/list`, `skills/get` and supporting file reads for native clients. Direct clients lacking native support can use bounded skill discovery/read within `search`. A skill cannot expand API permissions. OpenAI's release package includes only reviewed audience-appropriate skills. Verify packaged and native behaviors independently. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | +| Skills over MCP, beta | Direct clients list or read permitted guidance through the dedicated `skills` tool. Clients that negotiate the extension can also use `skills/list`, `skills/get` and `resources/read`. Resolve both paths against the same audience and verified manifest. Test a customer guide, an entitled staff guide, changed access and an unavailable file through both paths. Directory’s two public tools remain the named catalog reads. Validate separately any audience-appropriate skills included in the reviewed package. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | | 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) | @@ -55,9 +58,9 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | 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. A text-only client with no optional capabilities must complete the read flow. 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) | +| Protocol fixtures and Inspector | Run pinned upstream conformance and project-specific tests against both wire eras, both profiles and the retained legacy URL. A text-only client with extensions disabled must list the three standard direct tools and complete operation discovery, guide retrieval and an API read. Verify the optional action-completion profile adds exactly `commit`. 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 direct discovery, authorized reads, multi-operation composition and skill fallback. 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) | +| Codex, Claude Code, Claude Desktop and Cursor | Exercise real client builds for the surfaces Recoup claims. Record direct operation discovery, authorized reads, multi-operation composition and guide list/read through `skills`. 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 diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md index b86fbf3dc..ee38062cc 100644 --- a/docs/plans/mcp-code-mode-research.md +++ b/docs/plans/mcp-code-mode-research.md @@ -22,11 +22,11 @@ Inside `execute`, a program can call `tools.search({query, namespace})`, page wi | --- | --- | | 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) | Treat tool count as a product decision. Fold exact lookup into discovery. Preserve convenient single reads, status and recovery within the chosen contract. The two-tool direct path can carry an ordinary signed-in account's reads and writes. Delegate any required quote, consent or approval to the API that owns that operation. | +| 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 three direct tools. `search` finds operations and their exact contracts, `execute` composes API calls under the signed-in account, and `skills` lists or reads permitted guidance. Supported hosts can also negotiate native skill resources. The agent observes status or explicitly resumes a checkpoint with `execute`. A separately named `commit` is an optional fourth tool for clients needing the same exact API-approved completion path. | | 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. The third tool can help single-operation latency, but every path must share exactly the same validation and policy. Recoup's direct path uses `execute` to invoke API operations as the signed-in account. The API decides whether an authenticated action can proceed immediately or requires an existing approval. Single-operation latency is a benchmark question for the Recoup fixtures. [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) +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. For Recoup, a top-level `call` is a benchmark experiment. Compare a single read or a batch of independent reads against `execute` under the same account, API checks and fixture state. Measure latency, task success, first-turn context and total tokens. 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) ## Execution choices diff --git a/docs/plans/mcp-code-mode-tools.json b/docs/plans/mcp-code-mode-tools.json index 0cfc1d111..dd3a2ba7d 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -2,8 +2,8 @@ "tools": [ { "name": "search", - "title": "Find Recoup operations and skills", - "description": "Discover operations available to this connection. Request details by exact ID or read an authorized skill file. A cursor continues the same query.", + "title": "Find Recoup operations", + "description": "Find available operations by query, request a contract by exact ID, or continue with a cursor.", "inputSchema": { "type": "object", "properties": { @@ -17,25 +17,12 @@ "minLength": 1, "maxLength": 256 }, - "kind": { - "type": "string", - "enum": [ - "operations", - "skills" - ] - }, - "file": { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, "cursor": { "type": "string", "minLength": 1, "maxLength": 256 } }, - "required": [], "additionalProperties": false, "oneOf": [ { @@ -53,26 +40,6 @@ "cursor" ] } - ], - "allOf": [ - { - "if": { - "required": [ - "file" - ] - }, - "then": { - "required": [ - "id", - "kind" - ], - "properties": { - "kind": { - "const": "skills" - } - } - } - } ] }, "outputSchema": { @@ -102,13 +69,12 @@ "effect": { "enum": [ "read", - "write", - "instruction" + "write" ] }, "detail": { "type": "object", - "description": "Authorized contract, example, or requested skill content. Section-specific schemas and byte caps are validated by the catalog broker." + "description": "Requested contract or example, validated against its section schema and byte cap." } }, "required": [ @@ -140,7 +106,7 @@ { "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. Use runId with resume:true to continue a checkpoint.", + "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": { @@ -372,10 +338,59 @@ "openWorldHint": true } }, + { + "name": "skills", + "title": "Find and read Recoup skills", + "description": "List workflows available to this account or search by query. Pass a skill name to read SKILL.md or select its supporting file. Use nextOffset to continue a list.", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "maxLength": 200 + }, + "offset": { + "type": "integer", + "minimum": 0 + }, + "skill": { + "type": "string", + "pattern": "^[a-z0-9-]{1,64}$" + }, + "file": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + } + }, + "additionalProperties": false, + "dependentRequired": { + "file": [ + "skill" + ] + }, + "if": { + "required": [ + "skill" + ] + }, + "then": { + "properties": { + "query": false, + "offset": false + } + } + }, + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + } + }, { "name": "commit", "title": "Apply an approved Recoup change", - "description": "Forward completion of one exact paused action to the Recoup API after it records approval. Reuse requestKey on retry. Look up the run with execute.", + "description": "Optional alternative to execute resume for one exact API-approved step. Reuse requestKey on retry. Check run status with execute.", "inputSchema": { "type": "object", "properties": { 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..c15342ebe --- /dev/null +++ b/docs/plans/mcp-code-mode-user-stories.md @@ -0,0 +1,30 @@ +# What tools does a Recoup Records agent need? + +The proposed direct connection starts with three tools. `skills` finds workflow guidance, `search` finds Recoup API operations, and `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 | +| --- | --- | --- | --- | +| 1 | As a new label operator, I ask “How does Recoup check release metadata?” before assigning the job. | `skills` finds a guide by topic and opens its instructions or a referenced file. | An eligible account can open the right guide. Staff-only guidance stays within its existing audience. 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 a named `call` shortcut for this same request. | 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 | +| --- | --- | --- | +| `skills` | Include. “How do we do this?” has a distinct, read-only answer from the connected account’s guide library. | Test that an installed agent can find a guide and read a supporting file without loading the whole library on sign-in. | +| `search`, `execute` | Include both. An agent must find the right operation and be able to use it. | 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. One call with the run ID is sufficient. | Add a named `resume` if an installed client cannot continue reliably using the existing form. Test a closed chat, dropped response and two simultaneous retries. | +| `commit` | Optional compatibility example. It finishes one exact, previously approved action and stops. Both it and resume use the same API completion record. Every standard story above works without an extra `commit` call. | A client needs an explicit “finish this approved action only” control. Prove that using either entry point, in either order, applies that action once. | +| `call`, `status`, `cancel`, pending-work lookup | Benchmark a `call` shortcut. Deliver account-scoped observation, 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 index 50c45b376..c2f6d674c 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -2,7 +2,7 @@ **Proposed technical specification · November 28, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** -Sign in with your Recoup account and your agent can act. With `search` it finds the Recoup API operations that apply to the task. 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. +Sign in with your Recoup account and your agent can act. With `skills` it can look up a Recoup workflow or read its instructions when useful. With `search` it finds the Recoup API operations that apply to the task. 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. @@ -10,6 +10,7 @@ The target is every music-company operation a human with equivalent access can p | --- | --- | | [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) | Nine 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 | @@ -17,14 +18,14 @@ The target is every music-company operation a human with equivalent access can p ## 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 **813** reference tokens (3,347 bytes). The two-tool profile that lets an agent act takes **978** (4,061 bytes), a **96.9% reduction** against that full model-visible baseline. Enabling the optional approval continuation takes **1,373** (5,622 bytes) across three tools. Narrow OAuth already measured 1,038 visible tokens. Storage, model prompts, actual startup and task cost are separate measurements. +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 three-tool read-only profile takes **904** reference tokens (3,685 bytes). The three-tool account action profile takes **1,077** (4,444 bytes), a **96.6% reduction** against the full model-visible baseline. The optional four-tool compatibility profile with `commit` takes **1,466** (5,987 bytes). Narrow OAuth already measured 1,038 visible tokens. Verify actual startup text, latency and task cost per client. -Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each two-tool profile it applies the matching `readOnlyExecute` or `accountExecute` override. Its internal `actRequest` 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) +Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each profile without `commit` it applies the matching `readOnlyExecute` or `accountExecute` override. Its internal `actRequest` 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` | Exactly `search` and `execute`. Native skills/resources use negotiated protocol methods. Text-only hosts can find permitted skills through search. | -| Direct, signed in with access to act | `/mcp/code` | Exactly `search` and `execute`. A permitted `recoup.act` inside `execute` applies the requested change through the API. If an operation supports completion of a previously approved effect, the profile may also expose `commit`. Tool annotations describe the effects reachable on each profile. | +| Direct, read-only | `/mcp/code` | `skills` finds and reads permitted workflow guides, `search` finds API operations, and `execute` runs permitted reads. Clients supporting native skills/resources may use the corresponding protocol methods. | +| Direct, signed in with access to act | `/mcp/code` | `skills`, `search` and `execute`. Inside `execute`, an allowed `recoup.act` changes the record through the API. The agent can resume eligible saved work through `execute`. A separately qualified client may expose `commit` as an optional fourth shortcut to finish one exact API-approved effect. | | 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, call commit 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. | @@ -38,7 +39,7 @@ Both new URLs are proposals under the established MCP mount. Business REST endpo | 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 sharing the API’s permissions, optional approval continuation and 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. Optional clients can present a pending approval or resume a supported action. | +| Three direct tools for workflow guidance, API discovery and execution, approval and resumption through the API and 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. @@ -50,10 +51,11 @@ 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 --> Search["Authorized catalog index"] + Direct --> Skills["Read permitted Recoup skills on demand"] + Direct --> Search["Search API operations"] Direct --> Runner["Per-run JS isolate"] Runner --> Broker["Recoup operation broker"] - Direct --> Commit["Optional exact approval continuation"] + Direct --> Commit["Optional one-effect client shortcut"] Commit --> Broker Named --> Broker Broker --> Domain["Recoup API business operations"] @@ -76,9 +78,11 @@ flowchart LR ## Interaction contract -`search` accepts a natural-language query, exact ID or page cursor. Each result has an id, summary and effect. Operations carry read or write, while skill material carries instruction. Requested contract sections and skill files use the optional bounded detail object. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, signed-in account, effective access and expiry. Reject mixed modes and invalid file paths. Skill fallback resolves only accessible skill IDs/files using the existing audience resolver. Use the same denial for hidden and unknown IDs. +`skills` lists permitted workflow guides or finds them by topic. `skills({})` returns a page of names and descriptions. `skills({skill})` reads the selected guide and `skills({skill,file})` reads one of its packaged supporting files. Use the existing `recoup_skills` catalog, file lookup, account checks and public/staff boundaries. Existing selected-context connections have no skills access. Load instructions only on request. A guide can suggest API actions, but reading a guide grants no access and runs no action. The native skills methods and the direct tool use the same underlying catalog. [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. A guarded `execute({runId,resume:true})` continues only a recorded checkpoint. 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. +`search` accepts a natural-language query, exact API operation ID or page cursor. Each result has an ID, summary and read/write effect. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, signed-in account, effective access and expiry. Reject mixed modes. Return the same denial for hidden and unknown IDs. + +`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. @@ -100,7 +104,9 @@ A signed-in label operator can ask the agent to record `needs_changes` on a disp **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-owned approvals.** When an operation requires approval, its API records the pending effect, the authorized account and resource, canonical arguments, destination, allowed cost and expiry. MCP returns `approval_required`, the account-scoped run ID and a trusted Recoup link to the corresponding decision. Only the owning API can accept a decision from an authorized approver, bind it to the recorded inputs, and apply or release it once. The two-tool client can look up status with `execute`. If the operation provides an exact completion endpoint, an optional `commit({intent,requestKey})` forwards its opaque reference to that endpoint. It cannot approve an action. For the reference profile, the exact approval URL is `https://app.recoupable.dev/mcp/approvals/{runId}`, with the server-issued run ID. This link can open the owning API’s existing review flow. Verify the full URL, login return, changed terms, expiry and duplicate attempts. A client may present the existing Recoup flow. A new MCP approval screen or store is unnecessary. The fixture budgets 4 KiB for canonical inputs and 8 KiB for a sealed intent. Keep downstream signatures or provider consent with their issuer. [Protocol and recovery](mcp-code-mode-protocol.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. + +An optional fourth tool, `commit({intent,requestKey})`, can expose the same one-effect completion to a client that needs a separate button or call. It shares the completion claim with `execute` and stops after that effect. Qualify a client need before exposing this shortcut. The standard three tools can handle the full approval journey. The reference approval URL is `https://app.recoupable.dev/mcp/approvals/{runId}`, with the server-issued run ID, and can open the existing API review flow. Verify the full URL, sign-in return, changed terms, expiry and concurrent completion attempts. Budget 4 KiB for canonical inputs and 8 KiB for a sealed intent. 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` and optional `commit`, 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. @@ -124,13 +130,13 @@ Persist only the data necessary to apply or reconcile a write. Use Supabase via 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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the validated API approval URL and authorized run ID. On an approval-enabled profile, execution and receipt lookup also return the exact parked intent. The caller already supplies that intent to commit. 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. +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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the validated API approval URL and authorized run ID. Only a profile exposing the optional `commit` shortcut also returns the exact parked intent on execution and receipt lookup. Standard `execute` resumes by run ID and resolves the saved intent server-side. 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 top-level tools in every variant. +**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 `skills`, `search` and `execute` as the baseline in these comparisons. Separately benchmark a direct `call` shortcut for a known operation, using the same permissions, inputs and independently verified result. Test an explicitly named `resume` only if supported clients struggle to continue through `execute`. **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, skill 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. @@ -142,7 +148,7 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | 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 use two tools to perform 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. +**Adoption sequence.** Start inventory and runner qualification in parallel. Qualify normal sign-in and reads, then exercise the three-tool interface. Verify list and read on `skills` independently and 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. @@ -156,14 +162,14 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | [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) | Ship search and execute with separate read and action profiles | [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) | +| [api#1307](https://github.com/recoupable/api/issues/1307) | Ship dedicated skills, API search and execute with read and action profiles | [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) | Migrate first-party consumers and display API-required approvals | [api#1307](https://github.com/recoupable/api/issues/1307) | -| [api#1314](https://github.com/recoupable/api/issues/1314) | Relay completion of an exact API-approved action where supported | [api#1308](https://github.com/recoupable/api/issues/1308) | +| [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 startup context, completed work, interruptions, latency and cost | [api#1308](https://github.com/recoupable/api/issues/1308) | | [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify unattended label operations, real hosts 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) | @@ -173,4 +179,4 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan 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. The optional approval relay (#1314) builds on action dispatch and uses the owning API’s approval flow. App migration, saved instructions, the relay 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. \ No newline at end of file +**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. \ No newline at end of file diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index 3dbf7524e..c722ce1d4 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -3,6 +3,7 @@ from itertools import combinations from mcp_code_mode_execution_cases import execute_cases, status_cases +from mcp_code_mode_skill_cases import skill_cases def search_cases(): @@ -12,12 +13,16 @@ def search_cases(): for left, right in combinations(search, 2): yield "search", "input", False, f"{left} and {right}", {left: search[left], right: search[right]} skill = {"id": "catalog-guide", "kind": "skills", "file": "SKILL.md"} - yield "search", "input", True, "skill file", skill + yield "search", "input", False, "skill file belongs on skills", skill yield "search", "input", False, "file without skill", {**skill, "kind": "operations"} + yield "search", "input", False, "skill discovery belongs on skills", {"query": "catalogs", "kind": "skills"} yield "search", "input", False, "no selection", {} item = {"id": "catalogs.listOwned", "summary": "List catalogs", "effect": "read"} results = {"revision": "v1", "items": [item]} yield "search", "output", True, "summary", results + yield "search", "output", False, "skill in operation results", { + **results, "items": [{**item, "effect": "instruction"}] + } for key in item: incomplete = {k: v for k, v in item.items() if k != key} yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} @@ -53,6 +58,7 @@ def act_cases(): def contract_cases(action_capable, has_commit): yield from search_cases() + yield from skill_cases() yield from execute_cases(action_capable) yield from status_cases(action_capable, has_commit) if has_commit: diff --git a/docs/plans/mcp_code_mode_resume.py b/docs/plans/mcp_code_mode_resume.py new file mode 100644 index 000000000..9620d175f --- /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 not in ("resume", "commit"): + 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 method == "commit" or 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..b1d91e9f8 --- /dev/null +++ b/docs/plans/mcp_code_mode_resume_cases.py @@ -0,0 +1,43 @@ +"""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), + ("compatibility completion first and resume after", + ["commit", "resume"], ["step_settled", "continued"], [saved], 1), + ("resume wins the shared claim and commit follows", + ["resume", "commit"], ["continued", "step_settled"], [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", "commit", "resume")] + yield "uncertain dispatch remains single", (outcomes, step.calls), (["unknown_outcome"] * 3, [saved]) 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..8a432acff --- /dev/null +++ b/docs/plans/mcp_code_mode_skill_cases.py @@ -0,0 +1,27 @@ +"""Wire examples for the dedicated tool over Recoup's authorized skill catalog.""" + + +def skill_cases(): + read = {"skill": "release-guide"} + page = {"query": "release", "offset": 25} + for reason, request in [ + ("list", {}), ("topic", {"query": "release"}), ("next page", page), + ("offset only", {"offset": 25}), ("instructions", read), + ("supporting text", {**read, "file": "references/guide.md"}), + ("supporting binary", {**read, "file": "assets/template.pdf"}), + ("longest name", {"skill": "a" * 64}), + ]: + yield "skills", "input", True, reason, request + for reason, request in [ + ("relative file without skill", {"file": "SKILL.md"}), + ("query with selected skill", {**page, **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 "skills", "input", False, reason, request diff --git a/docs/plans/mcp_code_mode_validation.py b/docs/plans/mcp_code_mode_validation.py index a7ca62706..1bd2ce327 100644 --- a/docs/plans/mcp_code_mode_validation.py +++ b/docs/plans/mcp_code_mode_validation.py @@ -19,7 +19,7 @@ def trusted_approval_link(payload, receipt_run_id): def verify_profile(tools, action_capable, has_commit): - expected_names = ["search", "execute"] + (["commit"] if has_commit else []) + expected_names = ["search", "execute", "skills"] + (["commit"] if has_commit else []) if [tool["name"] for tool in tools] != expected_names: raise ValueError(f"Expected descriptors in order {expected_names}.") failures = [] @@ -37,6 +37,8 @@ def verify_profile(tools, action_capable, has_commit): if name == "execute" and ("intent" in tool["outputSchema"]["properties"]) != has_commit: failures.append("Only the approval-completion profile may advertise a sealed intent.") for direction in ("input", "output"): + if name == "skills" and direction == "output" and "outputSchema" not in tool: + continue # Native MCP text and resource content blocks use no structuredContent. schema = tool[f"{direction}Schema"] Draft202012Validator.check_schema(schema) validators[name, direction] = Draft202012Validator(schema, registry=Registry()) diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index 0d1f2c577..5f1ab833e 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -20,6 +20,7 @@ from mcp_code_mode_cases import act_cases, refusal_cases from mcp_code_mode_recovery import recovery_cases, valid_recovery +from mcp_code_mode_resume_cases import resume_cases from mcp_code_mode_validation import valid_preadmission_refusal, verify_profile @@ -43,13 +44,13 @@ def cached_encoding(): def main(): fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) - search, execute, commit = fixture["tools"] + search, execute, skills, commit = fixture["tools"] read_execute = {**execute, **fixture["readOnlyExecute"]} account_execute = {**execute, **fixture["accountExecute"]} profiles = [ - ("Read only", [search, read_execute], False, False), - ("Account action", [search, account_execute], True, False), - ("Account action with API approval completion", [search, execute, commit], True, True), + ("Read only", [search, read_execute, skills], False, False), + ("Account action", [search, account_execute, skills], True, False), + ("Account action with optional commit shortcut", [search, execute, skills, commit], True, True), ] encoding = cached_encoding() print(f"tiktoken {version('tiktoken')}, {encoding.name}") @@ -78,6 +79,11 @@ def main(): 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)") + continuations = list(resume_cases()) + for label, actual, expected in continuations: + if actual != expected: + failures.append(f"Simulated API continuation ({label}): {actual!r} differs from {expected!r}") + print(f"API approval continuation: {len(continuations)} simulated cases") refusals = list(refusal_cases()) for valid, label, envelope in refusals: if valid_preadmission_refusal(envelope) != valid: From 53c11425afa2748c57a94735cb482b235eaf0054 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:54:24 -0500 Subject: [PATCH 12/13] Unify guide discovery and reading under search; keep two direct MCP tools --- docs/plans/mcp-code-mode-autonomy.md | 6 +- docs/plans/mcp-code-mode-baseline.md | 4 +- docs/plans/mcp-code-mode-protocol.md | 25 +- docs/plans/mcp-code-mode-research.md | 27 +- docs/plans/mcp-code-mode-tools.json | 446 ++++--------------- docs/plans/mcp-code-mode-user-stories.md | 16 +- docs/plans/mcp-code-mode.md | 40 +- docs/plans/mcp_code_mode_cases.py | 45 +- docs/plans/mcp_code_mode_discovery.py | 50 +++ docs/plans/mcp_code_mode_discovery_checks.py | 58 +++ docs/plans/mcp_code_mode_execution_cases.py | 80 ++-- docs/plans/mcp_code_mode_resume.py | 4 +- docs/plans/mcp_code_mode_resume_cases.py | 8 +- docs/plans/mcp_code_mode_search_cases.py | 40 ++ docs/plans/mcp_code_mode_skill_cases.py | 27 +- docs/plans/mcp_code_mode_validation.py | 14 +- docs/plans/verify-mcp-code-mode.py | 29 +- 17 files changed, 384 insertions(+), 535 deletions(-) create mode 100644 docs/plans/mcp_code_mode_discovery.py create mode 100644 docs/plans/mcp_code_mode_discovery_checks.py create mode 100644 docs/plans/mcp_code_mode_search_cases.py diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index 85693af6b..501f94c6d 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -7,7 +7,7 @@ A Recoup Records operator signs in with an ordinary Recoup account, selects a la | 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 | Use `search` to find permitted operations and `execute` to compose calls and return a compact answer. Use `skills` to list or read guidance permitted for the signed-in account when the job calls for it. The host supplies authenticated context outside the generated program. The API alone decides business authorization, including any approval the underlying operation already requires. | +| MCP and agent | A topic search can surface both an authorized guide and a relevant API operation. Pass the exact guide name to `search({skill})` to read it, or browse permitted guides 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. | @@ -23,8 +23,8 @@ To qualify the direct connection, expose the authorized case operations for its ## 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 the direct profile, list and read a permitted guide through `skills` and verify that reading it produces zero business effects. +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 the direct profile, search for release metadata. Verify the fixture returns separate guide and operation previews, and that `search({skill})` opens the guide by the exact name returned. Repeat with an account outside the guide’s audience. Its search and guide listing must conceal that entry, and reading guidance 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. Compare both with an optional `commit` client using the same API completion path. Record real host-imposed prompts separately from API decisions. Publish only sanitized task outcomes, receipt references, interruptions and cost per verified case. +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 index 8183edfdf..ef54f8a3b 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -14,7 +14,7 @@ Each cell gives UTF-8 bytes / tokens. The payload is compact JSON of `{"tools":[ | 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** for `search`, `execute` and `skills` measures **3,685 bytes / 904 tokens** with read-only execution and **4,444 / 1,077** with account actions. The latter is 96.6% smaller than the historical 31,820-token full OAuth model-visible list. A client needing a separate call for exact API-approved completion can also receive `commit`, a fourth tool forwarding to the same API path as explicit `execute` resume. That fixture measures **5,987 / 1,466**. These counts cover the compact `tools/list` result. A guide’s contents arrive only when requested. [Proposed descriptors](mcp-code-mode-tools.json) · [Wire fixture verifier](verify-mcp-code-mode.py) +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. Measure mixed preview pages and exact guide reads separately. The client loads guide or resource bodies only on request. [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) @@ -32,7 +32,7 @@ The connected Codex Recoup connector independently exposed 94 tool names in this - **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 `skills` tool under equivalent access. Exercise negotiated native skills separately and 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) +- **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. Exercise negotiated native skills separately and 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 diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index 2a2d6872c..560460da2 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -1,6 +1,6 @@ # Recoup MCP protocol compatibility and OpenAI review -**Decision record for the proposed cutover, updated November 29, 2026.** Direct clients use three model tools. `search` discovers permitted operations, `execute` runs them and `skills` lists or reads permitted guidance on demand. The account signs in through the existing Recoup connection, and its agent can take the actions the Recoup API permits. The standard `execute` tool supports durable continuation. A client with a demonstrated need for a separate completion call may also receive an optional fourth tool, `commit`, for the same exact API-approved action. 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) +**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 @@ -10,14 +10,14 @@ The current revision is **2026-07-28**. At the inspected API source revision, Re | --- | --- | | 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 at the owning API. An explicit `execute` resume can forward exact approved completion to that API. Optional `commit` uses the same API path. 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` and `skills` read-only. The former returns operation metadata; the latter resolves only guidance the account may access. 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) | +| 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`, `execute` and `skills` without preloading a guide or 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) +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 @@ -25,31 +25,30 @@ Sign in to Recoup once through the existing account connection. A direct client | Call | Observable behavior | | --- | --- | -| `search` | Look up permitted API operations by query, exact ID or cursor. Return the matching contract and examples on demand. | -| `skills({})` or `skills({query, offset})` | List or filter permitted guidance. Return a bounded page of names and descriptions as JSON text, with `nextOffset` when another page exists. | -| `skills({skill})` or `skills({skill, file})` | Read the named guide’s `SKILL.md` or one supporting file from its approved manifest. Return bounded UTF-8 text or an authorized embedded binary resource. Apply the same audience and file checks as native skills, including after an access change. A read cannot dispatch a business operation or approve an action. | +| `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. | -| `commit({intent, requestKey})`, where offered | Offer this fourth tool only for a demonstrated client need. It forwards one already approved step to the same API completion path available through `execute({runId,resume:true})`. Expose its sealed intent only on this profile and bind it to the exact step and expiry. A racing `commit` and `execute` resume share the same atomic step claim and effect key. Return the existing receipt if the API already applied it. Approval belongs to an authorized approver at the owning API. Resume the larger workflow with `execute`. | -**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` or `commit` requires `runId`. A read-only `execute` can return a bounded completed computation without allocating a durable run. The standard three-tool account action output schema excludes `intent`. The four-tool profile with `commit` requires a sealed `intent` on `execute` results in the `approval_required` state and excludes it in every other state. 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. +**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 or optional `commit` races it. 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) +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 operation discovery, skill list/read 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) +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 | Direct clients list or read permitted guidance through the dedicated `skills` tool. Clients that negotiate the extension can also use `skills/list`, `skills/get` and `resources/read`. Resolve both paths against the same audience and verified manifest. Test a customer guide, an entitled staff guide, changed access and an unavailable file through both paths. Directory’s two public tools remain the named catalog reads. Validate separately any audience-appropriate skills included in the reviewed package. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | +| Skills over MCP, beta | Direct clients use `search` to browse guide previews or open a specific guide or packaged file. Clients that negotiate the extension can also use `skills/list`, `skills/get` and `resources/read`. Resolve topic-search guide previews, direct guide reads and negotiated native reads against the same audience and verified manifest. Test a customer guide, an entitled staff guide, revocation between preview and retrieval, and an unavailable file. Directory’s two public tools remain the named catalog reads. Validate separately any audience-appropriate skills included in the reviewed package. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | | 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) | @@ -58,9 +57,9 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | 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. A text-only client with extensions disabled must list the three standard direct tools and complete operation discovery, guide retrieval and an API read. Verify the optional action-completion profile adds exactly `commit`. 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) | +| 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 direct operation discovery, authorized reads, multi-operation composition and guide list/read through `skills`. 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) | +| 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 diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md index ee38062cc..7ddc923c3 100644 --- a/docs/plans/mcp-code-mode-research.md +++ b/docs/plans/mcp-code-mode-research.md @@ -22,11 +22,32 @@ Inside `execute`, a program can call `tools.search({query, namespace})`, page wi | --- | --- | | 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 three direct tools. `search` finds operations and their exact contracts, `execute` composes API calls under the signed-in account, and `skills` lists or reads permitted guidance. Supported hosts can also negotiate native skill resources. The agent observes status or explicitly resumes a checkpoint with `execute`. A separately named `commit` is an optional fourth tool for clients needing the same exact API-approved completion path. | +| 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. Native skill resources remain available to clients that negotiate the extension. | | 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. For Recoup, a top-level `call` is a benchmark experiment. Compare a single read or a batch of independent reads against `execute` under the same account, API checks and fixture state. Measure latency, task success, first-turn context and total tokens. 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) +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. | Return the guide and operation for one release-review query. Open just the selected file. Exercise same-name matches, missing files, native Skills, 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. A capable host can list skills, request a manifest and read selected resources without advertising a named model tool. 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 @@ -43,7 +64,7 @@ Choose the broker contract before choosing a runtime library. A runtime adapter ## 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. Return ranked summaries before details. 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. +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. Include an exact-name collision. 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 wire bytes, actual or explicitly estimated prompt tokens, discovery 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. diff --git a/docs/plans/mcp-code-mode-tools.json b/docs/plans/mcp-code-mode-tools.json index dd3a2ba7d..806c9a497 100644 --- a/docs/plans/mcp-code-mode-tools.json +++ b/docs/plans/mcp-code-mode-tools.json @@ -2,8 +2,8 @@ "tools": [ { "name": "search", - "title": "Find Recoup operations", - "description": "Find available operations by query, request a contract by exact ID, or continue with a cursor.", + "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": { @@ -21,24 +21,35 @@ "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": [ { - "required": [ - "query" - ] - }, - { - "required": [ - "id" - ] + "maxProperties": 1, + "properties": { + "skill": false, + "file": false + } }, { "required": [ - "cursor" - ] + "skill" + ], + "properties": { + "query": false, + "id": false, + "cursor": false + } } ] }, @@ -74,28 +85,82 @@ }, "detail": { "type": "object", - "description": "Requested contract or example, validated against its section schema and byte cap." + "description": "Requested operation contract or example." + }, + "skill": { + "type": "string", + "pattern": "^[a-z0-9-]{1,64}$" } }, "required": [ - "id", - "summary", - "effect" + "summary" ], - "additionalProperties": false + "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", - "items" + "revision" ], - "additionalProperties": false + "additionalProperties": false, + "if": { + "required": [ + "guide" + ] + }, + "then": { + "properties": { + "items": false, + "nextCursor": false + } + }, + "else": { + "required": [ + "items" + ] + } }, "annotations": { "readOnlyHint": true, @@ -237,12 +302,6 @@ "type": "string", "minLength": 1, "maxLength": 1024 - }, - "intent": { - "type": "string", - "minLength": 1, - "maxLength": 8192, - "pattern": "^[A-Za-z0-9_-]+$" } }, "required": [ @@ -284,13 +343,11 @@ }, "then": { "required": [ - "approvalUrl", - "intent" + "approvalUrl" ] }, "else": { "properties": { - "intent": false, "approvalUrl": false } } @@ -337,187 +394,6 @@ "destructiveHint": true, "openWorldHint": true } - }, - { - "name": "skills", - "title": "Find and read Recoup skills", - "description": "List workflows available to this account or search by query. Pass a skill name to read SKILL.md or select its supporting file. Use nextOffset to continue a list.", - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "maxLength": 200 - }, - "offset": { - "type": "integer", - "minimum": 0 - }, - "skill": { - "type": "string", - "pattern": "^[a-z0-9-]{1,64}$" - }, - "file": { - "type": "string", - "minLength": 1, - "maxLength": 1024 - } - }, - "additionalProperties": false, - "dependentRequired": { - "file": [ - "skill" - ] - }, - "if": { - "required": [ - "skill" - ] - }, - "then": { - "properties": { - "query": false, - "offset": false - } - } - }, - "annotations": { - "readOnlyHint": true, - "destructiveHint": false, - "openWorldHint": false - } - }, - { - "name": "commit", - "title": "Apply an approved Recoup change", - "description": "Optional alternative to execute resume for one exact API-approved step. Reuse requestKey on retry. Check run status with execute.", - "inputSchema": { - "type": "object", - "properties": { - "intent": { - "type": "string", - "minLength": 1, - "maxLength": 8192, - "pattern": "^[A-Za-z0-9_-]+$" - }, - "requestKey": { - "type": "string", - "minLength": 1, - "maxLength": 96 - } - }, - "required": [ - "intent", - "requestKey" - ], - "additionalProperties": false - }, - "outputSchema": { - "type": "object", - "properties": { - "state": { - "type": "string", - "enum": [ - "approval_required", - "denied", - "expired", - "accepted", - "running", - "succeeded", - "failed", - "unknown_outcome", - "canceled" - ] - }, - "runId": { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - "approvalUrl": { - "type": "string", - "minLength": 1, - "maxLength": 1024 - }, - "traceId": { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - "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", - "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" - ] - } - } - ] - }, - "annotations": { - "readOnlyHint": false, - "destructiveHint": true, - "openWorldHint": true - } } ], "readOnlyExecute": { @@ -739,155 +615,5 @@ "options" ], "additionalProperties": false - }, - "accountExecute": { - "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" - } - } - } - } - ] - } } } diff --git a/docs/plans/mcp-code-mode-user-stories.md b/docs/plans/mcp-code-mode-user-stories.md index c15342ebe..a3fd640bb 100644 --- a/docs/plans/mcp-code-mode-user-stories.md +++ b/docs/plans/mcp-code-mode-user-stories.md @@ -1,12 +1,12 @@ # What tools does a Recoup Records agent need? -The proposed direct connection starts with three tools. `skills` finds workflow guidance, `search` finds Recoup API operations, and `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. +The proposed direct connection has exactly two tools. `search` finds related guides and API operations, opens a contract or reads an exact guide or packaged file. `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 | | --- | --- | --- | --- | -| 1 | As a new label operator, I ask “How does Recoup check release metadata?” before assigning the job. | `skills` finds a guide by topic and opens its instructions or a referenced file. | An eligible account can open the right guide. Staff-only guidance stays within its existing audience. Reading changes no release, and a one-off job can begin without loading a guide. | +| 1 | As a new label operator, I ask “How does Recoup check release metadata?” before assigning the job. | 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. | @@ -14,17 +14,17 @@ The proposed direct connection starts with three tools. `skills` finds workflow | 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 a named `call` shortcut for this same request. | 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. | +| 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 | | --- | --- | --- | -| `skills` | Include. “How do we do this?” has a distinct, read-only answer from the connected account’s guide library. | Test that an installed agent can find a guide and read a supporting file without loading the whole library on sign-in. | -| `search`, `execute` | Include both. An agent must find the right operation and be able to use it. | Compare known one-step reads with multi-step work and verify business results. | +| Guide discovery and reading | `search` finds guides alongside operations and opens an exact guide or packaged supporting file. A guide-only browse is available through `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. One call with the run ID is sufficient. | Add a named `resume` if an installed client cannot continue reliably using the existing form. Test a closed chat, dropped response and two simultaneous retries. | -| `commit` | Optional compatibility example. It finishes one exact, previously approved action and stops. Both it and resume use the same API completion record. Every standard story above works without an extra `commit` call. | A client needs an explicit “finish this approved action only” control. Prove that using either entry point, in either order, applies that action once. | -| `call`, `status`, `cancel`, pending-work lookup | Benchmark a `call` shortcut. Deliver account-scoped observation, 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. | +| `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 index c2f6d674c..f8c06f8bc 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -1,8 +1,8 @@ # Recoup MCP code mode -**Proposed technical specification · November 28, 2026 · [Delivery epic](https://github.com/recoupable/mono/issues/751)** +**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. With `skills` it can look up a Recoup workflow or read its instructions when useful. With `search` it finds the Recoup API operations that apply to the task. 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. +Sign in with your Recoup account and your agent can act. With `search` it finds both workflow guides and API operations. It can open an exact guide or supporting file with the same tool. 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. @@ -18,15 +18,15 @@ The target is every music-company operation a human with equivalent access can p ## 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 three-tool read-only profile takes **904** reference tokens (3,685 bytes). The three-tool account action profile takes **1,077** (4,444 bytes), a **96.6% reduction** against the full model-visible baseline. The optional four-tool compatibility profile with `commit` takes **1,466** (5,987 bytes). Narrow OAuth already measured 1,038 visible tokens. Verify actual startup text, latency and task cost per client. +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. Verify actual startup text, latency and task cost per client. -Run the [schema and size verifier](verify-mcp-code-mode.py) from the API repository. It builds the three wire 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`. For each profile without `commit` it applies the matching `readOnlyExecute` or `accountExecute` override. Its internal `actRequest` 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) +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` | `skills` finds and reads permitted workflow guides, `search` finds API operations, and `execute` runs permitted reads. Clients supporting native skills/resources may use the corresponding protocol methods. | -| Direct, signed in with access to act | `/mcp/code` | `skills`, `search` and `execute`. Inside `execute`, an allowed `recoup.act` changes the record through the API. The agent can resume eligible saved work through `execute`. A separately qualified client may expose `commit` as an optional fourth shortcut to finish one exact API-approved effect. | -| 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, call commit or load skills that promise unavailable functionality. | +| Direct, read-only | `/mcp/code` | `search` finds authorized guides and API operations and opens a selected guide or supporting file. `execute` runs permitted reads. Clients that support native skills and resources may use the same guide library through those methods. | +| Direct, signed in with access to act | `/mcp/code` | `search` and `execute`. 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) @@ -39,7 +39,7 @@ Both new URLs are proposals under the established MCP mount. Business REST endpo | 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. | -| Three direct tools for workflow guidance, API discovery and execution, approval and resumption through the API and 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`. | +| 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. @@ -51,12 +51,12 @@ 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 --> Skills["Read permitted Recoup skills on demand"] - Direct --> Search["Search API operations"] + 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"] - Direct --> Commit["Optional one-effect client shortcut"] - Commit --> 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"] @@ -78,9 +78,9 @@ flowchart LR ## Interaction contract -`skills` lists permitted workflow guides or finds them by topic. `skills({})` returns a page of names and descriptions. `skills({skill})` reads the selected guide and `skills({skill,file})` reads one of its packaged supporting files. Use the existing `recoup_skills` catalog, file lookup, account checks and public/staff boundaries. Existing selected-context connections have no skills access. Load instructions only on request. A guide can suggest API actions, but reading a guide grants no access and runs no action. The native skills methods and the direct tool use the same underlying catalog. [Existing catalog reader](../../lib/mcp/skills/registerRecoupSkillsTool.ts) · [Audience checks](../../lib/mcp/skills/resolveRecoupSkillsAudience.ts) +`search` is the direct connection’s single place to find useful guides and API operations. 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` accepts a natural-language query, exact API operation ID or page cursor. Each result has an ID, summary and read/write effect. An exact lookup supplies input, output, one runnable example, authorization prerequisites, cost, pagination and revision. Rank exact IDs and aliases first, then domain terms and deterministic lexical matches. Add semantic reranking only if a measured query set improves without leaking unauthorized metadata or regressing exact matches. Limit summaries to eight and 4 KiB per response. Exact schemas may page by section at 12 KiB. A signed cursor binds selection, query, signed-in account, effective access and expiry. Reject mixed modes. Return the same denial for hidden and unknown IDs. +`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. @@ -106,9 +106,9 @@ A signed-in label operator can ask the agent to record `needs_changes` on a disp **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. -An optional fourth tool, `commit({intent,requestKey})`, can expose the same one-effect completion to a client that needs a separate button or call. It shares the completion claim with `execute` and stops after that effect. Qualify a client need before exposing this shortcut. The standard three tools can handle the full approval journey. The reference approval URL is `https://app.recoupable.dev/mcp/approvals/{runId}`, with the server-issued run ID, and can open the existing API review flow. Verify the full URL, sign-in return, changed terms, expiry and concurrent completion attempts. Budget 4 KiB for canonical inputs and 8 KiB for a sealed intent. Keep downstream signatures or provider consent with their issuer. [Protocol and recovery](mcp-code-mode-protocol.md) +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` and optional `commit`, 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. +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 @@ -130,13 +130,13 @@ Persist only the data necessary to apply or reconcile a write. Use Supabase via 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 approval continuation 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` or `commit` carries the authoritative run ID. In execute/commit structured results, put code and retry under error. Require runId for approval_required, accepted, running and unknown_outcome. Status reads return the same receipt-state names as commit; complete and partial describe successful guest computations. On approval_required, report the validated API approval URL and authorized run ID. Only a profile exposing the optional `commit` shortcut also returns the exact parked intent on execution and receipt lookup. Standard `execute` resumes by run ID and resolves the saved intent server-side. 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. +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 `skills`, `search` and `execute` as the baseline in these comparisons. Separately benchmark a direct `call` shortcut for a known operation, using the same permissions, inputs and independently verified result. Test an explicitly named `resume` only if supported clients struggle to continue through `execute`. +**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, skill 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. @@ -148,7 +148,7 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | 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 three-tool interface. Verify list and read on `skills` independently and 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. +**Adoption sequence.** Start inventory and runner qualification in parallel. Qualify normal sign-in and reads, then exercise the two-tool interface. Verify one mixed search result and an explicit guide/file read and 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. @@ -162,7 +162,7 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | [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) | Ship dedicated skills, API search and execute with read and action profiles | [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) | +| [api#1307](https://github.com/recoupable/api/issues/1307) | Ship unified guide/operation search and execute with read and action profiles | [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) | diff --git a/docs/plans/mcp_code_mode_cases.py b/docs/plans/mcp_code_mode_cases.py index c722ce1d4..fb3bd2540 100644 --- a/docs/plans/mcp_code_mode_cases.py +++ b/docs/plans/mcp_code_mode_cases.py @@ -1,47 +1,10 @@ """Positive and negative examples for the proposed direct tool contracts.""" -from itertools import combinations - 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 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]} - skill = {"id": "catalog-guide", "kind": "skills", "file": "SKILL.md"} - yield "search", "input", False, "skill file belongs on skills", skill - yield "search", "input", False, "file without skill", {**skill, "kind": "operations"} - yield "search", "input", False, "skill discovery belongs on skills", {"query": "catalogs", "kind": "skills"} - yield "search", "input", False, "no selection", {} - item = {"id": "catalogs.listOwned", "summary": "List catalogs", "effect": "read"} - results = {"revision": "v1", "items": [item]} - yield "search", "output", True, "summary", results - yield "search", "output", False, "skill in operation results", { - **results, "items": [{**item, "effect": "instruction"}] - } - for key in item: - incomplete = {k: v for k, v in item.items() if k != key} - yield "search", "output", False, f"summary missing {key}", {**results, "items": [incomplete]} - yield "search", "output", False, "nine summaries", {**results, "items": [item] * 9} - - - -def commit_cases(): - commit = {"intent": "a" * 8192, "requestKey": "request-1"} - yield "commit", "input", True, "maximum sealed intent", commit - for length in (0, 8193): - yield "commit", "input", False, f"sealed length {length}", {**commit, "intent": "a" * length} - yield "commit", "input", False, "malformed intent", {**commit, "intent": "wrong value!"} - yield "commit", "input", False, "new arguments", {**commit, "args": {"target": "other"}} - yield "commit", "input", False, "new source", {**commit, "source": "async (recoup, params) => params"} - yield "commit", "input", False, "caller supplies an approval decision", {**commit, "approved": True} - yield "commit", "input", False, "caller selects the approving account", {**commit, "accountId": "other"} - - 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"}} @@ -56,13 +19,11 @@ def act_cases(): yield False, f"guest supplies {field}", {**call, "options": {"requestKey": "step-1", field: "other"}} -def contract_cases(action_capable, has_commit): +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, has_commit) - if has_commit: - yield from commit_cases() + yield from status_cases(action_capable) def refusal_cases(): 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 index 7e7f60dc0..4a5e2abda 100644 --- a/docs/plans/mcp_code_mode_execution_cases.py +++ b/docs/plans/mcp_code_mode_execution_cases.py @@ -47,52 +47,38 @@ def execute_cases(action_capable): yield "execute", "output", not action_capable, f"{state} without durable run ID", result -def status_cases(action_capable, has_commit): +def status_cases(action_capable): receipt = {"runId": "run-1"} - output = {"traceId": "trace-1", "truncated": False} + base = {"traceId": "trace-1", "truncated": False} error = {"code": "outcome_uncertain", "retry": "reconcile"} - for tool in (("execute", "commit") if has_commit else ("execute",)): - base = output if tool == "execute" else {"traceId": "trace-1"} - approval = {**base, **receipt, "state": "approval_required"} - exact_intent = {"intent": "sealed_intent"} if tool == "execute" and has_commit else {} - link = "https://app.recoupable.dev/mcp/approvals/run-1" - yield tool, "output", action_capable, "approval link", {**approval, "approvalUrl": link, **exact_intent} - yield tool, "output", False, "approval link after success", { - **base, **receipt, "state": "succeeded", "approvalUrl": link - } - if tool == "execute": - yield tool, "output", action_capable and not has_commit, "approval without sealed intent", { - **approval, "approvalUrl": link - } - yield tool, "output", has_commit, "optional approved-effect completion", { - **approval, "approvalUrl": link, "intent": "sealed_intent" - } - if tool == "execute": - yield tool, "output", False, "sealed intent on unpaused run", { - **base, **receipt, "state": "running", "intent": "sealed_intent" - } - yield tool, "output", False, "invalid sealed token on pause", { - **approval, "approvalUrl": link, "intent": "malformed token!" - } - 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 tool, "output", False, "untrusted approval destination", {**approval, **exact_intent, "approvalUrl": bad_url} - yield tool, "output", False, "foreign receipt and matching URL", { - **approval, **exact_intent, "runId": "run-2", "approvalUrl": "https://app.recoupable.dev/mcp/approvals/run-2" - } - yield tool, "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 tool, "output", action_capable or state != "unknown_outcome", state, {**status, **receipt} - yield tool, "output", False, f"{state} missing run ID", status - for state in ("denied", "expired", "failed", "unknown_outcome"): - status = {**base, **receipt, "state": state} - yield tool, "output", action_capable or state == "failed", f"{state} with error", {**status, "error": error} - yield tool, "output", False, f"{state} missing error", status - yield tool, "output", False, f"{state} missing guidance", {**status, "error": {"code": "failed"}} + 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_resume.py b/docs/plans/mcp_code_mode_resume.py index 9620d175f..e404f0310 100644 --- a/docs/plans/mcp_code_mode_resume.py +++ b/docs/plans/mcp_code_mode_resume.py @@ -20,7 +20,7 @@ def continue_with(self, method): return "denied" if method == "status": return "observed" - if method not in ("resume", "commit"): + if method != "resume": raise ValueError(f"Unknown fixture method {method}") if self.api_state == "unknown": return "unknown_outcome" @@ -41,7 +41,7 @@ def continue_with(self, method): self.api_state = "applied" if self.api_state != "applied": raise ValueError(f"Unknown fixture completion state {self.api_state}") - if method == "commit" or not self.safe_checkpoint: + if not self.safe_checkpoint: return "step_settled" if not self.continuations: self.continuations += 1 diff --git a/docs/plans/mcp_code_mode_resume_cases.py b/docs/plans/mcp_code_mode_resume_cases.py index b1d91e9f8..3ef42aac2 100644 --- a/docs/plans/mcp_code_mode_resume_cases.py +++ b/docs/plans/mcp_code_mode_resume_cases.py @@ -29,15 +29,13 @@ def resume_cases(): ("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), - ("compatibility completion first and resume after", - ["commit", "resume"], ["step_settled", "continued"], [saved], 1), - ("resume wins the shared claim and commit follows", - ["resume", "commit"], ["continued", "step_settled"], [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", "commit", "resume")] + 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 index 8a432acff..380aca692 100644 --- a/docs/plans/mcp_code_mode_skill_cases.py +++ b/docs/plans/mcp_code_mode_skill_cases.py @@ -1,20 +1,22 @@ -"""Wire examples for the dedicated tool over Recoup's authorized skill catalog.""" +"""Guide reads through the same search tool that returns workflow previews.""" def skill_cases(): read = {"skill": "release-guide"} - page = {"query": "release", "offset": 25} + guide = {"skill": "release-guide", "file": "SKILL.md"} for reason, request in [ - ("list", {}), ("topic", {"query": "release"}), ("next page", page), - ("offset only", {"offset": 25}), ("instructions", read), + ("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 "skills", "input", True, reason, request + yield "search", "input", True, reason, request for reason, request in [ ("relative file without skill", {"file": "SKILL.md"}), - ("query with selected skill", {**page, **read}), + ("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}), @@ -24,4 +26,15 @@ def skill_cases(): ("caller selects account", {**read, "accountId": "other"}), ("caller supplies resource URI", {"uri": "skill://release-guide/SKILL.md"}), ]: - yield "skills", "input", False, reason, request + 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_validation.py b/docs/plans/mcp_code_mode_validation.py index 1bd2ce327..d89657afc 100644 --- a/docs/plans/mcp_code_mode_validation.py +++ b/docs/plans/mcp_code_mode_validation.py @@ -18,15 +18,15 @@ def trusted_approval_link(payload, receipt_run_id): return payload["approvalUrl"] == expected -def verify_profile(tools, action_capable, has_commit): - expected_names = ["search", "execute", "skills"] + (["commit"] if has_commit else []) +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 == "commit" or (name == "execute" and action_capable) + effectful = name == "execute" and action_capable expected_hints = { "readOnlyHint": not effectful, "destructiveHint": effectful, @@ -34,18 +34,14 @@ def verify_profile(tools, action_capable, has_commit): } if tool["annotations"] != expected_hints: failures.append(f"{name} annotations differ from the fixture's admitted effects.") - if name == "execute" and ("intent" in tool["outputSchema"]["properties"]) != has_commit: - failures.append("Only the approval-completion profile may advertise a sealed intent.") for direction in ("input", "output"): - if name == "skills" and direction == "output" and "outputSchema" not in tool: - continue # Native MCP text and resource content blocks use no structuredContent. schema = tool[f"{direction}Schema"] Draft202012Validator.check_schema(schema) validators[name, direction] = Draft202012Validator(schema, registry=Registry()) - cases = list(contract_cases(action_capable, has_commit)) + 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 in {"execute", "commit"}: + 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'}") diff --git a/docs/plans/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index 5f1ab833e..836134f62 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -3,7 +3,7 @@ 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 Recoup server are needed. +or live Recoup server are needed. """ import hashlib @@ -19,11 +19,11 @@ 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_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" @@ -44,19 +44,17 @@ def cached_encoding(): def main(): fixture = json.loads(MANIFEST.read_text(encoding="utf-8")) - search, execute, skills, commit = fixture["tools"] + search, execute = fixture["tools"] read_execute = {**execute, **fixture["readOnlyExecute"]} - account_execute = {**execute, **fixture["accountExecute"]} profiles = [ - ("Read only", [search, read_execute, skills], False, False), - ("Account action", [search, account_execute, skills], True, False), - ("Account action with optional commit shortcut", [search, execute, skills, commit], True, True), + ("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, has_commit in profiles: - schemas, cases, mismatches = verify_profile(tools, action_capable, has_commit) + 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)) @@ -79,11 +77,14 @@ def main(): 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)") - continuations = list(resume_cases()) - for label, actual, expected in continuations: - if actual != expected: - failures.append(f"Simulated API continuation ({label}): {actual!r} differs from {expected!r}") - print(f"API approval continuation: {len(continuations)} simulated cases") + search_output = Draft202012Validator(search["outputSchema"], registry=Registry()) + for family, examples in [("API approval continuation", resume_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: From ef92f051b6505c9c38b269d9ec1d72cbed6653b3 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:24:14 -0500 Subject: [PATCH 13/13] Show authorized skill names and descriptions before the first task --- docs/plans/mcp-code-mode-autonomy.md | 4 +- docs/plans/mcp-code-mode-baseline.md | 4 +- docs/plans/mcp-code-mode-protocol.md | 20 +++++- docs/plans/mcp-code-mode-research.md | 12 ++-- docs/plans/mcp-code-mode-user-stories.md | 7 +- docs/plans/mcp-code-mode.md | 46 ++++++++----- docs/plans/mcp_code_mode_startup.py | 78 +++++++++++++++++++++++ docs/plans/mcp_code_mode_startup_cases.py | 71 +++++++++++++++++++++ docs/plans/verify-mcp-code-mode.py | 4 ++ 9 files changed, 217 insertions(+), 29 deletions(-) create mode 100644 docs/plans/mcp_code_mode_startup.py create mode 100644 docs/plans/mcp_code_mode_startup_cases.py diff --git a/docs/plans/mcp-code-mode-autonomy.md b/docs/plans/mcp-code-mode-autonomy.md index 501f94c6d..175853ecf 100644 --- a/docs/plans/mcp-code-mode-autonomy.md +++ b/docs/plans/mcp-code-mode-autonomy.md @@ -7,7 +7,7 @@ A Recoup Records operator signs in with an ordinary Recoup account, selects a la | 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 | A topic search can surface both an authorized guide and a relevant API operation. Pass the exact guide name to `search({skill})` to read it, or browse permitted guides 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. | +| 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. | @@ -23,7 +23,7 @@ To qualify the direct connection, expose the authorized case operations for its ## 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 the direct profile, search for release metadata. Verify the fixture returns separate guide and operation previews, and that `search({skill})` opens the guide by the exact name returned. Repeat with an account outside the guide’s audience. Its search and guide listing must conceal that entry, and reading guidance must produce zero business effects. +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. diff --git a/docs/plans/mcp-code-mode-baseline.md b/docs/plans/mcp-code-mode-baseline.md index ef54f8a3b..36cccea6e 100644 --- a/docs/plans/mcp-code-mode-baseline.md +++ b/docs/plans/mcp-code-mode-baseline.md @@ -14,7 +14,7 @@ Each cell gives UTF-8 bytes / tokens. The payload is compact JSON of `{"tools":[ | 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. Measure mixed preview pages and exact guide reads separately. The client loads guide or resource bodies only on request. [Proposed descriptors](mcp-code-mode-tools.json) · [Wire fixture verifier](verify-mcp-code-mode.py) +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) @@ -32,7 +32,7 @@ The connected Codex Recoup connector independently exposed 94 tool names in this - **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. Exercise negotiated native skills separately and 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) +- **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 diff --git a/docs/plans/mcp-code-mode-protocol.md b/docs/plans/mcp-code-mode-protocol.md index 560460da2..d99ec4117 100644 --- a/docs/plans/mcp-code-mode-protocol.md +++ b/docs/plans/mcp-code-mode-protocol.md @@ -48,11 +48,29 @@ Negotiate each optional extension using the peer's advertised capabilities. Test | --- | --- | | 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 | Direct clients use `search` to browse guide previews or open a specific guide or packaged file. Clients that negotiate the extension can also use `skills/list`, `skills/get` and `resources/read`. Resolve topic-search guide previews, direct guide reads and negotiated native reads against the same audience and verified manifest. Test a customer guide, an entitled staff guide, revocation between preview and retrieval, and an unavailable file. Directory’s two public tools remain the named catalog reads. Validate separately any audience-appropriate skills included in the reviewed package. [Skills specification](https://modelcontextprotocol.io/extensions/skills/overview) · [Recoup Skills implementation](https://github.com/recoupable/api/blob/ff33a113d3fcb40813b41b61007ebc724b199e51/docs/mcp-skills.md) | +| 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 | diff --git a/docs/plans/mcp-code-mode-research.md b/docs/plans/mcp-code-mode-research.md index 7ddc923c3..dda6ea233 100644 --- a/docs/plans/mcp-code-mode-research.md +++ b/docs/plans/mcp-code-mode-research.md @@ -4,7 +4,7 @@ Reviewed November 27–28, 2026. Vendor measurements describe their workloads. T ## 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. 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. +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/) @@ -22,7 +22,7 @@ Inside `execute`, a program can call `tools.search({query, namespace})`, page wi | --- | --- | | 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. Native skill resources remain available to clients that negotiate the extension. | +| 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. | @@ -37,7 +37,7 @@ Recoup's direct interface advertises `search` and `execute`. Approving a purchas | `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. | Return the guide and operation for one release-review query. Open just the selected file. Exercise same-name matches, missing files, native Skills, and public/staff/selected scopes against the same reader. | +| `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) @@ -45,7 +45,7 @@ Recoup's direct interface advertises `search` and `execute`. Approving a purchas **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. A capable host can list skills, request a manifest and read selected resources without advertising a named model tool. 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/) +**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) @@ -64,8 +64,8 @@ Choose the broker contract before choosing a runtime library. A runtime adapter ## 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. Include an exact-name collision. 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. +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 wire bytes, actual or explicitly estimated prompt tokens, discovery 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. +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-user-stories.md b/docs/plans/mcp-code-mode-user-stories.md index a3fd640bb..e4336f68d 100644 --- a/docs/plans/mcp-code-mode-user-stories.md +++ b/docs/plans/mcp-code-mode-user-stories.md @@ -1,12 +1,13 @@ # What tools does a Recoup Records agent need? -The proposed direct connection has exactly two tools. `search` finds related guides and API operations, opens a contract or reads an exact guide or packaged file. `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. +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 | | --- | --- | --- | --- | -| 1 | As a new label operator, I ask “How does Recoup check release metadata?” before assigning the job. | 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. | +| 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. | @@ -20,7 +21,7 @@ The proposed direct connection has exactly two tools. `search` finds related gui | Candidate | Decision for the standard direct connection | Evidence that would change the decision | | --- | --- | --- | -| Guide discovery and reading | `search` finds guides alongside operations and opens an exact guide or packaged supporting file. A guide-only browse is available through `search({})`. | A future shortcut would need evidence of a supported client workflow that these modes cannot serve. | +| 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. | diff --git a/docs/plans/mcp-code-mode.md b/docs/plans/mcp-code-mode.md index f8c06f8bc..d5a7731f4 100644 --- a/docs/plans/mcp-code-mode.md +++ b/docs/plans/mcp-code-mode.md @@ -2,7 +2,7 @@ **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. With `search` it finds both workflow guides and API operations. It can open an exact guide or supporting file with the same tool. 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. +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. @@ -10,7 +10,7 @@ The target is every music-company operation a human with equivalent access can p | --- | --- | | [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) | Nine jobs covering workflow guidance, real changes, approvals, resume, cancellation and finding lost work. | +| [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 | @@ -18,14 +18,16 @@ The target is every music-company operation a human with equivalent access can p ## 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. Verify actual startup text, latency and task cost per client. +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` | `search` finds authorized guides and API operations and opens a selected guide or supporting file. `execute` runs permitted reads. Clients that support native skills and resources may use the same guide library through those methods. | -| Direct, signed in with access to act | `/mcp/code` | `search` and `execute`. An allowed `recoup.act` inside `execute` changes the record through the API. `execute` also checks status or explicitly resumes authorized saved work. | +| 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. | @@ -51,6 +53,9 @@ 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"] @@ -78,7 +83,17 @@ flowchart LR ## Interaction contract -`search` is the direct connection’s single place to find useful guides and API operations. 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. +### 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) @@ -138,17 +153,18 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan **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, skill 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. +**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 | | --- | --- | -| Startup | At most 1,500 descriptor tokens for the write-capable direct profile, at least 90% below full OAuth's model-visible reference list. Verify actual first-turn token delta on controlled hosts and report measured vs unavailable separately. For a narrow/deferred client already below that target, require no material startup or task-success regression before migrating. | +| 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. Verify one mixed search result and an explicit guide/file read and 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. +**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. @@ -162,21 +178,21 @@ Return structured domain failures with a bounded `code`, `traceId`, retry guidan | [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) | Ship unified guide/operation search and execute with read and action profiles | [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) | +| [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) | Migrate first-party consumers and display API-required approvals | [api#1307](https://github.com/recoupable/api/issues/1307) | +| [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 startup context, completed work, interruptions, latency and cost | [api#1308](https://github.com/recoupable/api/issues/1308) | -| [mono#752](https://github.com/recoupable/mono/issues/752) | Qualify unattended label operations, real hosts 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) | Publish versioned account sign-in, Directory and legacy migration guides | [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. \ No newline at end of file +**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_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/verify-mcp-code-mode.py b/docs/plans/verify-mcp-code-mode.py index 836134f62..36d51b10c 100644 --- a/docs/plans/verify-mcp-code-mode.py +++ b/docs/plans/verify-mcp-code-mode.py @@ -22,6 +22,8 @@ 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") @@ -62,6 +64,7 @@ def main(): 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()) @@ -79,6 +82,7 @@ def main(): 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: