Repository navigation
Specify Recoup MCP code mode for the signed-in account and the Directory cutover - #1312
sidneyswift wants to merge 13 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Pre-merge checks:
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
2 issues found across 5 files
Confidence score: 4/5
docs/plans/mcp-code-mode-tools.jsonis over the 100-line limit and combines three tool contracts, making it harder to maintain. Split the schemas.docs/plans/mcp-code-mode.mdproposes/mcp/codeand/mcp/directoryroutes that don't follow the required/apiprefix convention. Add the prefix.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode-tools.json">
<violation number="1" location="docs/plans/mcp-code-mode-tools.json:2">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
This 440-line descriptor file exceeds the rule’s 100-line limit and combines three independently defined tool contracts. Split the tool schemas into smaller files and keep a concise catalog/index here.</violation>
</file>
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:25">
P2: Custom agent: **API Design Consistency and Maintainability**
Prefix the new MCP endpoints with `/api`; the proposed `/mcp/code` and `/mcp/directory` routes otherwise violate the required API path convention.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Client as Direct MCP Client (Host Model)
participant Gateway as MCP Gateway (/mcp/code)
participant Auth as Auth & Principal Resolver
participant Catalog as Operation Catalog Compiler
participant Search as Search & Discovery Index
participant Runner as Per-Run JS Isolate
participant Broker as Operation Broker
participant Ledger as Receipts & Reconciliation Store
participant Domain as Recoup API Domain Services
participant Directory as OpenAI Directory (/mcp/directory)
Note over Gateway,Catalog: NEW: Code mode cutover - design scope
Gateway->>Auth: Authenticate request (OAuth/API key)
Auth-->>Gateway: Verified principal + grant scope
alt Refresh catalog / compile manifest
Catalog->>Catalog: Pin Docs + API source commits
Catalog->>Catalog: Generate versioned operation records
Catalog-->>Gateway: Signed manifest (search/execute descriptors)
end
Client->>Gateway: tools/list (MCP)
Gateway->>Search: Query authorized catalog index
Search-->>Gateway: Return search + execute (commit if write-entitled)
Gateway-->>Client: Compact descriptors (~732 tokens read-only / 1,097 with commit)
Client->>Gateway: execute(source, revision, params)
Gateway->>Auth: Validate principal + operation authorization
Gateway->>Runner: Spin up isolated JS runtime
Runner->>Broker: recoup.read(id, args) / recoup.prepare(id, args)
Broker->>Domain: Dispatch authorized operation
Domain-->>Broker: Bounded result
Broker->>Ledger: NEW: Write scoped receipt (runId, traceId)
Ledger-->>Broker: Receipt metadata
Broker-->>Runner: Return value + state
Runner-->>Gateway: Bounded JSON result
Gateway-->>Client: execute response
alt Write-entitled connection with commit
Client->>Gateway: commit(intent, requestKey)
Gateway->>Auth: Fresh authority + per-effect approval check
Auth-->>Gateway: Approval status
alt Approval required
Gateway-->>Client: approval_required + runId + approvalUrl
Client->>Gateway: Recover with same requestKey
else Approved
Gateway->>Broker: Apply exact prepared change
Broker->>Domain: Execute mutation
Broker->>Ledger: Update receipt (succeeded/failed)
Gateway-->>Client: commit response (state=accepted/succeeded)
end
else Read-only execute failure path
Broker-->>Runner: Error with retry hint (rediscover/narrow)
Runner-->>Gateway: Error object
Gateway-->>Client: state=failed + error object
end
Note over Directory,Client: NEW: Open
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| @@ -0,0 +1,440 @@ | |||
| { | |||
There was a problem hiding this comment.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
This 440-line descriptor file exceeds the rule’s 100-line limit and combines three independently defined tool contracts. Split the tool schemas into smaller files and keep a concise catalog/index here.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-tools.json, line 2:
<comment>This 440-line descriptor file exceeds the rule’s 100-line limit and combines three independently defined tool contracts. Split the tool schemas into smaller files and keep a concise catalog/index here.</comment>
<file context>
@@ -0,0 +1,440 @@
+{
+ "tools": [
+ {
+ "name": "search",
</file context>
|
|
||
| | 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. | |
There was a problem hiding this comment.
P2: Custom agent: API Design Consistency and Maintainability
Prefix the new MCP endpoints with /api; the proposed /mcp/code and /mcp/directory routes otherwise violate the required API path convention.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 25:
<comment>Prefix the new MCP endpoints with `/api`; the proposed `/mcp/code` and `/mcp/directory` routes otherwise violate the required API path convention.</comment>
<file context>
@@ -0,0 +1,159 @@
+
+| 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. |
</file context>
| | 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, read-only | `/api/mcp/code` | Exactly `search` and `execute`. Native skills/resources use negotiated protocol methods. Text-only hosts can find permitted skills through search. | |
There was a problem hiding this comment.
3 issues found across 3 files (changes from recent commits).
Confidence score: 3/5
- In
mcp-code-mode-tools.json, any non-emptyapprovalUrlcan satisfy the approval contract, so an off-site link could be shown as the confirmation link. Restrict it to the HTTPS Recoup approval origin. verify-mcp-code-mode.pyexceeds the 100-line limit. Split the schema and contract checks from token-budget measurement.mcp-code-mode.mdreports obsolete token measurements. Update the PR evidence to match the revised fixture’s 912/1,277 tokens.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode-tools.json">
<violation number="1" location="docs/plans/mcp-code-mode-tools.json:264">
P2: `approvalUrl` accepts any non-empty string, so an unsafe or off-site value can satisfy the `approval_required` contract and be surfaced as the confirmation link. Enforce the actual HTTPS Recoup approval origin in the broker and add a negative fixture for non-Recoup URLs.</violation>
</file>
<file name="docs/plans/verify-mcp-code-mode.py">
<violation number="1" location="docs/plans/verify-mcp-code-mode.py:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
This verification script is 135 lines, exceeding the rule's 100-line limit. Split the schema/contract checks from token-budget measurement into focused modules.</violation>
</file>
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:19">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**
The PR description still reports 732/1,097 tokens, but this revised fixture reports 912/1,277; update the PR evidence so it does not present obsolete measurements.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| ], | ||
| "additionalProperties": false | ||
| }, | ||
| "approvalUrl": { |
There was a problem hiding this comment.
P2: approvalUrl accepts any non-empty string, so an unsafe or off-site value can satisfy the approval_required contract and be surfaced as the confirmation link. Enforce the actual HTTPS Recoup approval origin in the broker and add a negative fixture for non-Recoup URLs.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-tools.json, line 264:
<comment>`approvalUrl` accepts any non-empty string, so an unsafe or off-site value can satisfy the `approval_required` contract and be surfaced as the confirmation link. Enforce the actual HTTPS Recoup approval origin in the broker and add a negative fixture for non-Recoup URLs.</comment>
<file context>
@@ -232,6 +260,11 @@
],
"additionalProperties": false
+ },
+ "approvalUrl": {
+ "type": "string",
+ "minLength": 1,
</file context>
| @@ -0,0 +1,135 @@ | |||
| """Verify the proposed direct MCP descriptors and their reference token budget. | |||
There was a problem hiding this comment.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
This verification script is 135 lines, exceeding the rule's 100-line limit. Split the schema/contract checks from token-budget measurement into focused modules.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/verify-mcp-code-mode.py, line 1:
<comment>This verification script is 135 lines, exceeding the rule's 100-line limit. Split the schema/contract checks from token-budget measurement into focused modules.</comment>
<file context>
@@ -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).
</file context>
|
|
||
| ## 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. |
There was a problem hiding this comment.
P2: Custom agent: Flag AI Slop and Fabricated Changes
The PR description still reports 732/1,097 tokens, but this revised fixture reports 912/1,277; update the PR evidence so it does not present obsolete measurements.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 19:
<comment>The PR description still reports 732/1,097 tokens, but this revised fixture reports 912/1,277; update the PR evidence so it does not present obsolete measurements.</comment>
<file context>
@@ -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)
</file context>
There was a problem hiding this comment.
1 existing issue remains and no new issues found across 3 files (changes from recent commits).
Confidence score: 4/5
- In
docs/plans/mcp-code-mode.md, the approval URL useschat.recoupable.dev, but that host redirects consent toapp.recoupable.dev, so the/mcp/approvalsroute may not be served where the link expects. Clarify which host and app route handle approvals.
Requires human review: Auto-approval blocked by 5 unresolved issues from previous reviews.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
1 issue found across 3 files (changes from recent commits).
Confidence score: 4/5
docs/plans/mcp-code-mode.mddoes not track the new App approval route, so it could be missed in delivery planning. Add it to an existing tracking issue.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:92">
P2: The new App approval route `app/mcp/approvals/[runId]/page.tsx` has no tracking issue. The delivery table assigns App only app#2411, which covers chat, transcript, Skills and gallery migration. Add the route to an existing issue or a new one so the qualification gate covers it.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
|
||
| 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. |
There was a problem hiding this comment.
P2: The new App approval route app/mcp/approvals/[runId]/page.tsx has no tracking issue. The delivery table assigns App only app#2411, which covers chat, transcript, Skills and gallery migration. Add the route to an existing issue or a new one so the qualification gate covers it.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 92:
<comment>The new App approval route `app/mcp/approvals/[runId]/page.tsx` has no tracking issue. The delivery table assigns App only app#2411, which covers chat, transcript, Skills and gallery migration. Add the route to an existing issue or a new one so the qualification gate covers it.</comment>
<file context>
@@ -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.
</file context>
There was a problem hiding this comment.
2 existing issues remain and 1 new issue found across 8 files (changes from recent commits).
Confidence score: 4/5
mcp-code-mode-baseline.mdroutes catalog reads through the POST-only/api/contextendpoint, leaving the planned API inconsistent. Define GET routes for retrieval and keep POST for writes.verify-mcp-code-mode.pyis 157 lines, over the stated 100-line limit. Split it into smaller modules or helpers.mcp-code-mode-tools.jsonis 757 lines, over the stated 100-line limit. Move thereadOnlyExecuteschema into a separate file.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode-baseline.md">
<violation number="1" location="docs/plans/mcp-code-mode-baseline.md:46">
P2: Custom agent: **API Design Consistency and Maintainability**
This mapping sends `read_catalog_case` and `list_catalog_cases` through the POST-only `/api/context` route. Expose retrieval through GET routes and keep POST for saving cases.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 2 unresolved issues already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
| | 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) | |
There was a problem hiding this comment.
P2: Custom agent: API Design Consistency and Maintainability
This mapping sends read_catalog_case and list_catalog_cases through the POST-only /api/context route. Expose retrieval through GET routes and keep POST for saving cases.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-baseline.md, line 46:
<comment>This mapping sends `read_catalog_case` and `list_catalog_cases` through the POST-only `/api/context` route. Expose retrieval through GET routes and keep POST for saving cases.</comment>
<file context>
@@ -34,13 +34,16 @@ The connected Codex Recoup connector independently exposed 94 tool names in this
| 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) |
</file context>
There was a problem hiding this comment.
1 existing issue remains and no new issues found across 10 files (changes from recent commits).
Confidence score: 4/5
docs/plans/mcp-code-mode-baseline.mdkeeps reads and lists behind POST actions while making GET optional, leaving retrieval semantics inconsistent. Make GET the required retrieval path in the plan.
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Requires human review: Auto-approval blocked by 8 unresolved issues from previous reviews.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
3 issues found across 9 files (changes from recent commits).
Confidence score: 3/5
mcp-code-mode-autonomy.mdrelies on REST auth context that can returnorgId: nullfor bearer or API-key requests and does not check organization membership. Specify how the selected organization is carried into the request and membership is verified.mcp-code-mode.mdasks implementers to verify a canonical HTTPS origin but never names it, leaving the requirement ambiguous. State the expected origin and path:https://app.recoupable.dev/mcp/approvals/{runId}.mcp-code-mode.mdleaves the receipt-uniquenesscompany business keyundefined, so implementations may choose inconsistent scopes. Define it using the initiating account, organization/workspace, target, and effect step.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:103">
P2: The spec now asks implementers to verify 'the canonical HTTPS origin' without stating what it is. The validation fixtures still require https://app.recoupable.dev/mcp/approvals/{runId}. Name that origin and path in this paragraph, and use the same term ('approval URL' or 'Recoup link') as the Interaction contract.</violation>
<violation number="2" location="docs/plans/mcp-code-mode.md:123">
P2: The account cutover still requires an undefined `company business key` for receipt uniqueness. Define the key from the initiating account, organization/workspace, target and effect step, and use that same scope for duplicate-job checks instead of retaining the legacy company key.</violation>
</file>
<file name="docs/plans/mcp-code-mode-autonomy.md">
<violation number="1" location="docs/plans/mcp-code-mode-autonomy.md:9">
P2: The existing REST auth context does not resolve an organization from a bearer or API key: without an explicit `organizationId`, it returns `orgId: null` and performs no organization membership check. Carry the selected workspace through the direct operation and validate it before treating ordinary sign-in as sufficient.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
|
||
| **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) |
There was a problem hiding this comment.
P2: The spec now asks implementers to verify 'the canonical HTTPS origin' without stating what it is. The validation fixtures still require https://app.recoupable.dev/mcp/approvals/{runId}. Name that origin and path in this paragraph, and use the same term ('approval URL' or 'Recoup link') as the Interaction contract.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 103:
<comment>The spec now asks implementers to verify 'the canonical HTTPS origin' without stating what it is. The validation fixtures still require https://app.recoupable.dev/mcp/approvals/{runId}. Name that origin and path in this paragraph, and use the same term ('approval URL' or 'Recoup link') as the Interaction contract.</comment>
<file context>
@@ -96,13 +96,13 @@ async (recoup, params) => {
+**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.
</file context>
| **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 an approval URL at `https://app.recoupable.dev/mcp/approvals/{runId}`. 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 that the URL exactly equals that origin and path with the 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) |
|
|
||
| **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. |
There was a problem hiding this comment.
P2: The account cutover still requires an undefined company business key for receipt uniqueness. Define the key from the initiating account, organization/workspace, target and effect step, and use that same scope for duplicate-job checks instead of retaining the legacy company key.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 123:
<comment>The account cutover still requires an undefined `company business key` for receipt uniqueness. Define the key from the initiating account, organization/workspace, target and effect step, and use that same scope for duplicate-job checks instead of retaining the legacy company key.</comment>
<file context>
@@ -115,32 +115,34 @@ 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`, 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.
</file context>
|
|
||
| | 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) | |
There was a problem hiding this comment.
P2: The existing REST auth context does not resolve an organization from a bearer or API key: without an explicit organizationId, it returns orgId: null and performs no organization membership check. Carry the selected workspace through the direct operation and validate it before treating ordinary sign-in as sufficient.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-autonomy.md, line 9:
<comment>The existing REST auth context does not resolve an organization from a bearer or API key: without an explicit `organizationId`, it returns `orgId: null` and performs no organization membership check. Carry the selected workspace through the direct operation and validate it before treating ordinary sign-in as sufficient.</comment>
<file context>
@@ -1,35 +1,30 @@
-| 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. |
</file context>
| | 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 API validates a supported bearer or API key, then validates an explicitly supplied organization selection against that account. 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) | |
There was a problem hiding this comment.
2 issues found across 3 files (changes from recent commits).
Confidence score: 3/5
- In
docs/plans/mcp-code-mode.md, requests for the same resource and occurrence but different changes can share a receipt because the deduplication key omits the canonical arguments and approval/quote terms. Include those values in the key. docs/plans/mcp-code-mode.mddescribes/mcp/approvals/{runId}as an existing route, though no matching route is implemented and approval completion is still planned. Mark the route as planned.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:103">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**
This presents `/mcp/approvals/{runId}` as an existing review route, but no matching route is implemented here and approval completion is a planned deliverable. Mark the URL as proposed or reference an implemented route.</violation>
<violation number="2" location="docs/plans/mcp-code-mode.md:123">
P2: The underlying-work deduplication key omits the canonical arguments and approval/quote terms. Two requests for the same resource and occurrence can therefore share one receipt despite requesting different changes, causing the second request to skip or inherit the first effect. Require an owner-defined equivalence key that proves canonical arguments and authorization terms are compatible before coalescing claims.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
|
||
| **Identity across requests.** Validate the connection’s audience, scope and client using Recoup authentication. Take account identity from verified server context. Check current organization and artist access, selected resource and operation requirements in the API. Scope private caches, cursors and receipt lookup accordingly. Retain the existing `/mcp` audience and API-key/Privy, narrow, full, selected-context and staff behavior. Qualify the proposed direct and Directory resources with the authorization server through ordinary Recoup sign-in. Directory uses catalog-read access. New URLs grant no additional permissions. Durable jobs retain their initiating account, connection authorization reference, target and checkpoint. Every resume and dispatch rechecks current access. On lost access, stop the affected work. Use the standard reconnect flow when required. [Resource metadata](../../lib/oauth/getOAuthResourceMetadata.ts) · [Current sign-in runtime](../mcp-oauth-runtime.md) | ||
|
|
||
| Persist only the data necessary to apply or reconcile a write. Use Supabase via its existing repository layer. Define receipt rows with `run_id`, account/connection/profile, operation/release, intent digest, request key, lease and timestamps, approved ceiling, state, safe result digest/reference, downstream idempotency handle and outcome evidence. Deduplicate submissions by initiating account, connection, profile and request key. Deduplicate the underlying work by its API owner (the verified organization/workspace for shared work or the verified account for personal work), stable resource ID, operation, and domain-specific occurrence or effect step. Use the same business identity in duplicate-job checks. For example, two authorized members correcting the same recording and issue share one correction case, while each attempt retains its initiating account. Keep a separate unique claim for any sealed approval intent. An identical authorized retry returns the prior receipt. Reusing a key for a different request conflicts. An authenticated receipt records the initiating account, selected resource and API decision basis even when no individual approval exists. Distinct keys cannot consume the same intent twice. Atomically claim/record the ledger and enqueue an outbox entry for service dispatch. Immediately before a queued worker actually dispatches, revalidate grant, membership, kill switch, destination, quote, any required approval and remaining shared budget against the claimed receipt. If any expired during queueing, terminally deny or expire it without an external effect. Test revocation and quote expiry after enqueue. Integrate existing domain transaction/idempotency keys where available. If the upstream cannot deduplicate, a worker crash after dispatch enters reconciliation; never automatically replay that submission. |
There was a problem hiding this comment.
P2: The underlying-work deduplication key omits the canonical arguments and approval/quote terms. Two requests for the same resource and occurrence can therefore share one receipt despite requesting different changes, causing the second request to skip or inherit the first effect. Require an owner-defined equivalence key that proves canonical arguments and authorization terms are compatible before coalescing claims.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 123:
<comment>The underlying-work deduplication key omits the canonical arguments and approval/quote terms. Two requests for the same resource and occurrence can therefore share one receipt despite requesting different changes, causing the second request to skip or inherit the first effect. Require an owner-defined equivalence key that proves canonical arguments and authorization terms are compatible before coalescing claims.</comment>
<file context>
@@ -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.
</file context>
|
|
||
| **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) |
There was a problem hiding this comment.
P2: Custom agent: Flag AI Slop and Fabricated Changes
This presents /mcp/approvals/{runId} as an existing review route, but no matching route is implemented here and approval completion is a planned deliverable. Mark the URL as proposed or reference an implemented route.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 103:
<comment>This presents `/mcp/approvals/{runId}` as an existing review route, but no matching route is implemented here and approval completion is a planned deliverable. Mark the URL as proposed or reference an implemented route.</comment>
<file context>
@@ -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.
</file context>
There was a problem hiding this comment.
1 issue found across 13 files (changes from recent commits).
Confidence score: 4/5
- In
docs/plans/mcp-code-mode-user-stories.md, theresumerow could lead readers to expectexecute({runId})to continue a run, but continuation requiresresume: true. Update the row to name that flag.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode-user-stories.md">
<violation number="1" location="docs/plans/mcp-code-mode-user-stories.md:26">
P2: The `resume` row says "One call with the run ID is sufficient," but `execute({runId})` only checks status here and in the technical spec. Continuation requires `execute({runId,resume:true})`. Name the `resume:true` flag in this row so it matches story 6 and the spec.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| | `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. | |
There was a problem hiding this comment.
P2: The resume row says "One call with the run ID is sufficient," but execute({runId}) only checks status here and in the technical spec. Continuation requires execute({runId,resume:true}). Name the resume:true flag in this row so it matches story 6 and the spec.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-user-stories.md, line 26:
<comment>The `resume` row says "One call with the run ID is sufficient," but `execute({runId})` only checks status here and in the technical spec. Continuation requires `execute({runId,resume:true})`. Name the `resume:true` flag in this row so it matches story 6 and the spec.</comment>
<file context>
@@ -0,0 +1,30 @@
+| `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. |
</file context>
| | `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. | | |
| | `resume` | Support continuing a saved run through `execute` with `{runId, resume: true}` from the first release that supports paused work. One call with the run ID and `resume: true` 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. | |
There was a problem hiding this comment.
6 issues found across 17 files (changes from recent commits).
Confidence score: 3/5
docs/plans/mcp_code_mode_discovery.pyexposesvalid_discovery,valid_file, andwire_bytesinstead of one primary function named for the module. Align the exports with the expected module shape.docs/plans/mcp-code-mode.mdno longer says that hidden and unknown IDs receive the same denial, which can let exact-ID lookups reveal whether an item exists. Restore that rule for exact lookups.docs/plans/verify-mcp-code-mode.pyaccepts a handbook revision without checking it against authorized manifest metadata, so a stale or substituted revision can pass verification. Compare the revision with the authorized metadata.- The new validation cases leave several gaps:
docs/plans/mcp_code_mode_skill_cases.pydoes not reject offset-only, empty-cursor, or over-length-cursor inputs, anddocs/plans/mcp_code_mode_discovery_checks.pydoes not exercise its size, mismatch, or envelope-size checks. Add negative cases for these paths.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp_code_mode_discovery.py">
<violation number="1" location="docs/plans/mcp_code_mode_discovery.py:11">
P2: Custom agent: **Module should export a single primary function whose name matches the filename**
This module exposes separate `valid_discovery` and `valid_file` validators, plus `wire_bytes`, so it has no single primary export matching its basename. Split the validators into appropriately named modules and keep the byte-count helper private.</violation>
</file>
<file name="docs/plans/mcp_code_mode_skill_cases.py">
<violation number="1" location="docs/plans/mcp_code_mode_skill_cases.py:8">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**
Add an invalid `{"offset": 25}` case: the cursor example exercises the new input, but no case verifies that a valid offset-only request is rejected.</violation>
<violation number="2" location="docs/plans/mcp_code_mode_skill_cases.py:19">
P3: The new `cursor` input has no empty-value or over-length invalid case, though the schema bounds it to 1–256 characters. Add `("empty cursor", {"cursor": ""})` and `("long cursor", {"cursor": "c" * 257})` to the invalid list, matching the existing `empty file` and `long file` cases.</violation>
</file>
<file name="docs/plans/verify-mcp-code-mode.py">
<violation number="1" location="docs/plans/verify-mcp-code-mode.py:82">
P2: The new guide-read check accepts any handbook revision as verified. `discovery_checks` hardcodes `revision: "v1"`, and `valid_file` never compares that value with authorized manifest metadata, so stale or substituted handbook versions pass. Carry the expected source and revision in the manifest and compare them before accepting the envelope.</violation>
</file>
<file name="docs/plans/mcp-code-mode.md">
<violation number="1" location="docs/plans/mcp-code-mode.md:83">
P2: The rewrite drops the rule that hidden and unknown IDs return the same denial. The new text only covers empty and hidden cases, so exact-ID lookups can leak existence. Restore the rule for exact lookups, including unknown IDs.</violation>
</file>
<file name="docs/plans/mcp_code_mode_discovery_checks.py">
<violation number="1" location="docs/plans/mcp_code_mode_discovery_checks.py:30">
P3: The new cases never reach the size-budget branch, the detail/effect mismatch checks, or the envelope-size check in `valid_file`. Add one negative case for each so these branches are verified.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| @@ -0,0 +1,50 @@ | |||
| """Check discovery and file results against independent, synthetic authorized catalog data.""" | |||
There was a problem hiding this comment.
P2: Custom agent: Module should export a single primary function whose name matches the filename
This module exposes separate valid_discovery and valid_file validators, plus wire_bytes, so it has no single primary export matching its basename. Split the validators into appropriately named modules and keep the byte-count helper private.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_discovery.py, line 11:
<comment>This module exposes separate `valid_discovery` and `valid_file` validators, plus `wire_bytes`, so it has no single primary export matching its basename. Split the validators into appropriately named modules and keep the byte-count helper private.</comment>
<file context>
@@ -0,0 +1,50 @@
+ 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
</file context>
| read = {"skill": "release-guide"} | ||
| guide = {"skill": "release-guide", "file": "SKILL.md"} | ||
| for reason, request in [ | ||
| ("list", {}), ("topic", {"query": "release"}), ("next page", {"cursor": "next"}), |
There was a problem hiding this comment.
P2: Custom agent: Flag AI Slop and Fabricated Changes
Add an invalid {"offset": 25} case: the cursor example exercises the new input, but no case verifies that a valid offset-only request is rejected.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_skill_cases.py, line 8:
<comment>Add an invalid `{"offset": 25}` case: the cursor example exercises the new input, but no case verifies that a valid offset-only request is rejected.</comment>
<file context>
@@ -1,20 +1,22 @@
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"}),
</file context>
| 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()), | ||
| ("Scoped search and guide reads", discovery_checks(search_output))]: |
There was a problem hiding this comment.
P2: The new guide-read check accepts any handbook revision as verified. discovery_checks hardcodes revision: "v1", and valid_file never compares that value with authorized manifest metadata, so stale or substituted handbook versions pass. Carry the expected source and revision in the manifest and compare them before accepting the envelope.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/verify-mcp-code-mode.py, line 82:
<comment>The new guide-read check accepts any handbook revision as verified. `discovery_checks` hardcodes `revision: "v1"`, and `valid_file` never compares that value with authorized manifest metadata, so stale or substituted handbook versions pass. Carry the expected source and revision in the manifest and compare them before accepting the envelope.</comment>
<file context>
@@ -79,11 +77,14 @@ def main():
- 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:
</file context>
|
|
||
| `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({})` 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) |
There was a problem hiding this comment.
P2: The rewrite drops the rule that hidden and unknown IDs return the same denial. The new text only covers empty and hidden cases, so exact-ID lookups can leak existence. Restore the rule for exact lookups, including unknown IDs.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode.md, line 83:
<comment>The rewrite drops the rule that hidden and unknown IDs return the same denial. The new text only covers empty and hidden cases, so exact-ID lookups can leak existence. Restore the rule for exact lookups, including unknown IDs.</comment>
<file context>
@@ -78,9 +78,9 @@ flowchart LR
+`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.
</file 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) | |
| `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. Return the same denial for hidden and unknown IDs. [Existing catalog reader](../../lib/mcp/skills/registerRecoupSkillsTool.ts) · [Audience checks](../../lib/mcp/skills/resolveRecoupSkillsAudience.ts) |
| ("relative file without skill", {"file": "SKILL.md"}), | ||
| ("query with selected skill", {"query": "release", **read}), | ||
| ("exact id with selected skill", {"id": "release-guide", **read}), | ||
| ("cursor with selected skill", {"cursor": "next", **read}), |
There was a problem hiding this comment.
P3: The new cursor input has no empty-value or over-length invalid case, though the schema bounds it to 1–256 characters. Add ("empty cursor", {"cursor": ""}) and ("long cursor", {"cursor": "c" * 257}) to the invalid list, matching the existing empty file and long file cases.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_skill_cases.py, line 19:
<comment>The new `cursor` input has no empty-value or over-length invalid case, though the schema bounds it to 1–256 characters. Add `("empty cursor", {"cursor": ""})` and `("long cursor", {"cursor": "c" * 257})` to the invalid list, matching the existing `empty file` and `long file` cases.</comment>
<file context>
@@ -1,20 +1,22 @@
- ("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"}),
</file context>
| ("cursor with selected skill", {"cursor": "next", **read}), | |
| ("cursor with selected skill", {"cursor": "next", **read}), | |
| ("empty cursor", {"cursor": ""}), ("long cursor", {"cursor": "c" * 257}), |
| page = {"revision": "v1", "items": items} | ||
| if cursor: | ||
| page["nextCursor"] = cursor | ||
| yield label, output_schema.is_valid(page) and valid_discovery( |
There was a problem hiding this comment.
P3: The new cases never reach the size-budget branch, the detail/effect mismatch checks, or the envelope-size check in valid_file. Add one negative case for each so these branches are verified.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_discovery_checks.py, line 30:
<comment>The new cases never reach the size-budget branch, the detail/effect mismatch checks, or the envelope-size check in `valid_file`. Add one negative case for each so these branches are verified.</comment>
<file context>
@@ -0,0 +1,58 @@
+ 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
</file context>
There was a problem hiding this comment.
6 issues found across 9 files (changes from recent commits).
Confidence score: 4/5
valid_startupaccepts a supporting-file read before the selectedSKILL.mdis loaded, so it can approve a startup sequence that violates the intended order. Track the activated guide and reject supporting-file demands until it has been read.- The startup cases don’t fully exercise the protocol checks:
wrong file bytesfails the size check before digest verification, and there’s no case for reading aRELEASEfile after the last page. Use same-length wrong bytes and add the last-page positive and negative cases. docs/plans/mcp_code_mode_startup.pyexposes two functions without a primary function matching the module name. Split the functions or choose a matching primary export.docs/plans/mcp-code-mode-research.mdpresents early guide-name exposure as fact, while the protocol doc says client timing and presentation need confirmation. Align the claim with that uncertainty; the Native Skills section also pushesdocs/plans/mcp-code-mode-protocol.mdpast its 100-line limit.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/plans/mcp-code-mode-protocol.md">
<violation number="1" location="docs/plans/mcp-code-mode-protocol.md:56">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
This section takes the document from 91 to 109 lines, exceeding Rule 3’s 100-line limit. Move the Native Skills material into a separate document and link to it here.</violation>
</file>
<file name="docs/plans/mcp_code_mode_startup.py">
<violation number="1" location="docs/plans/mcp_code_mode_startup.py:55">
P2: `valid_startup` accepts a supporting-file read before the selected `SKILL.md` is loaded. Track the activated guide for each skill and reject supporting-file demands until that guide has been read.</violation>
<violation number="2" location="docs/plans/mcp_code_mode_startup.py:69">
P2: Custom agent: **Module should export a single primary function whose name matches the filename**
This module exposes both `valid_startup` and `report_startup_size`, and neither matches `mcpCodeModeStartup`. Split them into separate modules whose filenames match their primary functions.</violation>
</file>
<file name="docs/plans/mcp-code-mode-research.md">
<violation number="1" location="docs/plans/mcp-code-mode-research.md:25">
P2: This row states that qualifying native clients automatically expose guide names before the first prompt as fact. The Interoperability paragraph says timing and presentation belong to each client and must be confirmed per installed host. Reword the row as a target to verify, for example 'Qualifying native clients are expected to expose ... before the first prompt, to be confirmed per installed host.'</violation>
</file>
<file name="docs/plans/mcp_code_mode_startup_cases.py">
<violation number="1" location="docs/plans/mcp_code_mode_startup_cases.py:50">
P3: The offline cases never read a skill that is only on the last page, even though the protocol doc asks for that check. Add a case that demands a file from `RELEASE` after the last page, with a matching negative variant.</violation>
<violation number="2" location="docs/plans/mcp_code_mode_startup_cases.py:67">
P2: The `wrong file bytes` case uses `b"wrong"`, which fails the size check before the digest check runs. Use bytes of the same length so this case actually tests digest verification.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| | 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 |
There was a problem hiding this comment.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
This section takes the document from 91 to 109 lines, exceeding Rule 3’s 100-line limit. Move the Native Skills material into a separate document and link to it here.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-protocol.md, line 56:
<comment>This section takes the document from 91 to 109 lines, exceeding Rule 3’s 100-line limit. Move the Native Skills material into a separate document and link to it here.</comment>
<file context>
@@ -48,11 +48,29 @@ Negotiate each optional extension using the peer's advertised capabilities. Test
| 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)
</file context>
| return True | ||
|
|
||
|
|
||
| def report_startup_size(pages, summaries, encoding): |
There was a problem hiding this comment.
P2: Custom agent: Module should export a single primary function whose name matches the filename
This module exposes both valid_startup and report_startup_size, and neither matches mcpCodeModeStartup. Split them into separate modules whose filenames match their primary functions.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_startup.py, line 69:
<comment>This module exposes both `valid_startup` and `report_startup_size`, and neither matches `mcpCodeModeStartup`. Split them into separate modules whose filenames match their primary functions.</comment>
<file context>
@@ -0,0 +1,78 @@
+ return True
+
+
+def report_startup_size(pages, summaries, encoding):
+ """Report a reproducible projection separately from tool descriptors or hosted prompt usage."""
+ def compact(value):
</file context>
| | --- | --- | | ||
| | V1 plugins compile OpenAPI into two representations. Tool definitions describe inputs and outputs. HTTP bindings retain method, path, parameters and serialization. A host invoker handles the sandbox's `{path,args}` requests. [Compiler and bindings](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/plugins/openapi/src/sdk/backing.ts#L196-L250) · [QuickJS bridge](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/kernel/runtime-quickjs/src/index.ts#L304-L331) | Generate discoverable declarations and server-only dispatch bindings from the same admitted artifact. Compare each generated request with its route contract, including nested parameter references, escaping, arrays and pagination. Check the actual response at runtime. | | ||
| | V1 resolves credentials after argument and policy checks. V2 groups tools by app/version and supports per-user account selection. Its OpenAPI builder filters for account availability and validates input, and its code-mode broker sends an account-bound call with a query/mutation classification. [V1 dispatch](https://github.com/UsefulSoftwareCo/executor/blob/3cf6e54659cb34ac731fe3cf747ca139be769b93/packages/core/sdk/src/executor.ts#L6788-L6865) · [V2 OpenAPI](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/apps/src/implementation/openapi.ts#L161-L208) · [V2 dispatch](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/mcp/src/implementation/execute.ts#L783-L814) | Bind the signed-in Recoup account and its selected organization outside guest code. The API checks current permissions for the selected operation and resource just as it does for a direct caller. | | ||
| | V2's native toolkit contains five tools. The default and browser toolkits contain six, adding an explicit resume path. In addition to skills and execution, they expose search, exact description and direct invocation. [Implemented toolkits](https://github.com/UsefulSoftwareCo/executor/blob/95c6b6bd46df8e1836d3f0eb94601be0c5c9bcdf/packages/mcp/src/contracts/tools.ts#L21-L45) | Recoup proposes two direct tools. `search` returns operation and guide previews, exact contract details or a selected guide or packaged file. `execute` composes authorized API calls, observes status and explicitly resumes a saved checkpoint. Qualifying native clients automatically expose authorized guide names and descriptions before the first prompt and retrieve selected files on demand. Direct search supplies guide discovery and reading for other clients. | |
There was a problem hiding this comment.
P2: This row states that qualifying native clients automatically expose guide names before the first prompt as fact. The Interoperability paragraph says timing and presentation belong to each client and must be confirmed per installed host. Reword the row as a target to verify, for example 'Qualifying native clients are expected to expose ... before the first prompt, to be confirmed per installed host.'
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp-code-mode-research.md, line 25:
<comment>This row states that qualifying native clients automatically expose guide names before the first prompt as fact. The Interoperability paragraph says timing and presentation belong to each client and must be confirmed per installed host. Reword the row as a target to verify, for example 'Qualifying native clients are expected to expose ... before the first prompt, to be confirmed per installed host.'</comment>
<file context>
@@ -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. |
</file context>
| | 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. | | |
| | 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 are expected to list authorized guide names and descriptions before the first prompt, pending per-host confirmation, and retrieve selected files on demand. Direct search supplies guide discovery and reading for other clients. | |
| if sorted(pairs) != expected: | ||
| return False | ||
|
|
||
| for event in events: |
There was a problem hiding this comment.
P2: valid_startup accepts a supporting-file read before the selected SKILL.md is loaded. Track the activated guide for each skill and reject supporting-file demands until that guide has been read.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_startup.py, line 55:
<comment>`valid_startup` accepts a supporting-file read before the selected `SKILL.md` is loaded. Track the activated guide for each skill and reject supporting-file demands until that guide has been read.</comment>
<file context>
@@ -0,0 +1,78 @@
+ 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
</file context>
| ("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), |
There was a problem hiding this comment.
P2: The wrong file bytes case uses b"wrong", which fails the size check before the digest check runs. Use bytes of the same length so this case actually tests digest verification.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_startup_cases.py, line 67:
<comment>The `wrong file bytes` case uses `b"wrong"`, which fails the size check before the digest check runs. Use bytes of the same length so this case actually tests digest verification.</comment>
<file context>
@@ -0,0 +1,71 @@
+ ("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
</file context>
| 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), |
There was a problem hiding this comment.
P3: The offline cases never read a skill that is only on the last page, even though the protocol doc asks for that check. Add a case that demands a file from RELEASE after the last page, with a matching negative variant.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/plans/mcp_code_mode_startup_cases.py, line 50:
<comment>The offline cases never read a skill that is only on the last page, even though the protocol doc asks for that check. Add a case that demands a file from `RELEASE` after the last page, with a matching negative variant.</comment>
<file context>
@@ -0,0 +1,71 @@
+ 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),
</file context>
What changes for the user
Sign in with an existing Recoup account and ask the agent to do work. On a compatible direct connection, the host automatically lists skills via the MCP Skills extension and supplies the name and short description of every authorized skill to the agent before its first task decision. The agent can recognize the right skill from the user’s request and load its instructions only when needed. Supporting files are read individually as needed. The direct MCP has exactly two tools,
searchandexecute.searchfinds guides and operations together and can open a guide or file on hosts that need the fallback. Insideexecuteit calls the Recoup API, changes the selected resource and can independently verify the result. The API applies the account’s existing organization, artist and resource permissions and the scope of the connection. It owns business rules and approvals for all clients.Label user stories and tool decisions · Technical specification · Account access and first label job · Delivery epic and 18 tickets
execute({runId,resume:true})can finish the exact saved step once and continue the job. If the API already applied it, the agent uses the receipt and skips the completed step.execute({runId})always checks status without doing more work. Direct actions, saved instructions, App migration and the named public Directory package have distinct release paths. Approval integration · Protocol and OpenAI reviewMeasurements and verification
The two account-action tools use 96.5% fewer reference tokens than the measured full baseline. The previous three-tool draft used 1,077 reference tokens. The listed token counts cover tool descriptions. Measure the actual skill names and descriptions given to the model, server instructions, full manifest traffic to the host, total first-turn model input and subsequent file reads separately. Verify the result on cold and warm connections. Real host prompt size, first-turn visibility and completed business outcomes are implementation gates. On the pinned Recoup bundle, names and descriptions alone measured 4,966 reference tokens for 47 customer skills and 15,069 for the combined 132-skill staff catalog, using compact JSON. Claude Code documents a 100-skill limit per server. Require a second-page check on the first-party host and label third-party coverage by audience. Claude Code limits
The design verifier passed 325 cases covering skill and operation inputs, account and approval overrides, guest calls, errors and recovery. These include 21 new simulated first-turn skill checks, 15 simulated approval-continuation checks and 20 scoped search and guide-result examples. API lint passed and all 90 local references resolved. The epic has 18 child issues and 28 verified blocking relationships.
This is a specification PR. The first installed sign-in and write, production rollout, and Directory submission are tracked in the epic.