Skip to content

Harden Recoup MCP tools for OpenAI review - #1297

Merged
sidneyswift merged 4 commits into
mainfrom
codex/recoup-mcp-review
Nov 25, 2026
Merged

sidneyswift merged 4 commits into
mainfrom
codex/recoup-mcp-review

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Social refresh now previews the maximum credit charge. The execution call requires an unexpired account-bound Redis quote. Redis claims it once and serializes MCP refreshes for the account through the available-credit check and dispatch. Pricing and charging for successfully started profiles still use the existing scrape handler.
  • Scrape status and results are scoped to the connected account's recorded artist refresh batches. MCP returns public platform links and aggregate counts in place of raw provider data and omits the Apify dataset ID.
  • Saved post lookups describe their existing artist access check and use of stored data. Catalog matching checks catalog access at the tool handler, sends the stated fields to the AI provider, and processes up to 1,000 tracks per call. Larger searches can pass the returned nextPage as start_page. Catalog matching does not debit Recoup credits.
  • Add display titles and update the tool descriptions and OAuth annotations to reflect these behaviors.

Evidence

  • Before the changes, the added quote-only, scrape ownership and catalog continuation cases failed.
  • After the changes, 333 OAuth tests and 118 focused tool, route, billing and extension tests passed on Node 22 before the review follow-up. Six OAuth tests skipped. Pinned MCP skills build, extension build, OAuth typecheck, lint and diff checks passed.
  • Full API suite before the review follow-up passed 10,537 tests, with 79 skipped. The review follow-up passed 53 focused tests and the production typecheck.
  • Before the publisher rescan, smoke-test the deployed build with the review account. Preview and approve one refresh, verify that replay cannot dispatch it again, retrieve the run and saved posts, and test continued catalog matching. Use a different account to verify that it cannot read the run.

Merge Danger

Door Two-way. API change with no migration. The paid quote flow uses the existing REDIS_URL configuration. Verify Redis on the target deployment before invoking a paid refresh.

Blast radius MCP social refresh, scrape results and catalog matching. Callers need to handle the new approval preview, reduced scrape result fields and catalog pagination. Historical scrape runs without ownership records cannot be read through MCP. REST social scrape pricing and execution are covered by existing regression tests.

The OpenAI draft has not been submitted. Rescan after the API changes are deployed and the reviewer account smoke tests pass.

@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Nov 25, 2026 10:37pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Solid & Clean Code Warning The PR (recoupable/api #1297, author sidneyswift, head codex/recoup-mcp-review, base main) adds code that breaks explicit SOLID and clean-code limits in the check. I compared the diff against main (17… Refactor before merge: 1. Split project() in projectPublicScrapeResults.ts into small single-purpose functions. Examples: a URL sanitizer, a count picker, and a related-field projector. Each function needs its own file named after it, p…
Full details: Solid & Clean Code

Explanation

The PR (recoupable/api #1297, author sidneyswift, head codex/recoup-mcp-review, base main) adds code that breaks explicit SOLID and clean-code limits in the check. I compared the diff against main (17 files) and read the current code. Concrete findings: 1. project() in lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts (lines 78–123, about 46 lines). The guideline is functions of 20 lines or fewer. The function also mixes three jobs: URL sanitizing, count filtering, and recursive projection of related fields. It takes a boolean includeRelated flag that changes its behavior. The URL branch (lines 86–100) nests for → try → if → for → if, which is five levels. The limit is three. 2. scrape_artist_socials handler in lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts (lines 44–107, about 64 lines). On main the handler was about 41 lines. The PR adds quote, invalid-quote, and busy branches, plus the execute callback. The handler now maps eight result kinds to responses in one function. 3. executeQuotedSocialRefresh() in executeQuotedSocialRefresh.ts (about 42 lines). One function builds the quote fingerprint, issues quotes, claims the lock, checks credits, dispatches jobs, and releases the lock. These are separate responsibilities. Its name matches the file, so the file-name rule passes. 4. socialRefreshQuoteStore() in socialRefreshQuoteStore.ts (the 75-line file is mostly this factory). One factory manages the Redis connection lifecycle and the quote lifecycle. Each operation creates a new Redis client. The repo already has a shared connection module at lib/redis/connection.ts, and the PR does not use it. The code also hard-codes timeouts (3000, 5000) and TTLs (600, 900) inline, where the guidance asks for named configuration. 5. Catalog access check, DRY. registerGetCatalogSongsTool.ts (lines 47–52) now repeats the getCatalogOwnerIds + selectAccountCatalogs + some(id match) pattern from prepareFullOAuthTool.ts (lines 47–51, still used for insert_catalog_songs). The check should be one shared helper. The handler body is also about 25 lines. Checks that passed: - File-function name match: each new file exports one function whose name matches the file name. The PR adds no new top-level function to an existing file. - OCP: the execute callback in runArtistSocialsScrape.ts is a reasonable extension point. - Named constants: MAX_PAGES_PER_SEARCH and the URL and count allow-lists are named. The standing prior FAIL has no details. Its concerns cannot be checked separately. The findings above remain in the current code, so no prior failure is cleared.

Resolution

Refactor before merge: 1. Split project() in projectPublicScrapeResults.ts into small single-purpose functions. Examples: a URL sanitizer, a count picker, and a related-field projector. Each function needs its own file named after it, per the file-function rule. Replace the includeRelated flag with separate functions. Flatten the URL branch to three levels or fewer. 2. Move the quote, invalid-quote, and busy response mapping out of the scrape_artist_socials handler into small helpers, or a result-to-response mapper. Keep the handler body under about 20 lines. 3. Split executeQuotedSocialRefresh() so that quote issuance and quote claim/dispatch/release are separate functions. Keep the orchestration in the top-level function. 4. In socialRefreshQuoteStore, reuse the shared Redis connection in lib/redis/connection.ts or a single client per store. Move timeouts and TTLs into one named configuration object. 5. Move the catalog ownership check into one shared helper (for example assertCatalogAccess). Use it from both registerGetCatalogSongsTool.ts and prepareFullOAuthTool.ts. After the refactor, rerun this check. Re-review the new helpers for the 20-line and three-level limits.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T22:21:54.521317Z bf13010 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bf13010ebd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +15 to +16
const key = Buffer.from(process.env.OAUTH_INDEX_KEY ?? "", "base64");
if (key.length !== 32) throw new Error("Social refresh quote signing unavailable");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Decouple refresh quotes from optional OAuth secrets

When OAuth is disabled or an API-key/Privy deployment does not provision OAuth secrets, every scrape_artist_socials preview now fails with the generic scrape error because the standard MCP path still registers this tool through baseHandler (app/mcp/route.ts), while OAUTH_INDEX_KEY is documented as configuration for the separately enabled OAuth runtime. This turns a previously usable standard MCP tool into a complete outage in a supported non-OAuth configuration; sign quotes with a secret required by the standard MCP runtime or explicitly introduce and validate a generally required quote-signing secret.

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 issues found and verified against the latest diff

Confidence score: 2/5

  • executeQuotedSocialRefresh.ts can dispatch multiple distinct quotes against the same unreserved balance, leaving some work unbilled under concurrent execution. Reserve credits atomically before dispatch.
  • registerGetCatalogSongsTool.ts accepts start_page values near one billion, which can trigger an impractically large offset. Cap the page range or reject pages beyond the catalog total.
  • registerGetCatalogSongsTool.ts can return a raw Supabase error when the catalog-membership query fails. Log the diagnostic server-side and return a generic access error.
  • registerScrapeArtistSocialsTool.ts and projectPublicScrapeResults.ts exceed the stated 100-line limit. Move the quote-result mapping and projection helpers or allowlists into focused modules.
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="lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts">

<violation number="1" location="lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts:54">
P1: This read-only gate does not reserve credits across distinct quotes. Concurrent executions can each see the same balance, claim separate quotes, and dispatch before either debit; the account can receive extra unbilled scrapes or be charged after the approved balance is exhausted. Replace this check with an atomic reservation/charge or an account-scoped lock covering dispatch.</violation>
</file>

<file name="lib/catalog/analyzeFullCatalog.ts">

<violation number="1" location="lib/catalog/analyzeFullCatalog.ts:11">
P3: The new pagination options leave `analyzeFullCatalog`'s public documentation inaccurate: it still promises to fetch all songs and omits the 1-based `startPage`/`nextPage` contract. Update the JSDoc so callers do not assume a single call analyzes the entire catalog.</violation>
</file>

<file name="lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts">

<violation number="1" location="lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts:18">
P2: `start_page` permits an offset of nearly one billion rows. Cap page requests to a realistic bound or obtain the total before applying the offset and reject pages beyond the catalog.</violation>

<violation number="2" location="lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts:46">
P3: Move the account and catalog-access checks into a dedicated `validateGetCatalogSongs...` operation validator, then have this callback consume its validated result before running `analyzeFullCatalog`; keeping authorization in the orchestration handler makes this entry point’s access contract easy to bypass or diverge when reused.

(Based on your team's feedback about centralizing handler validation.)</violation>

<violation number="3" location="lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts:46">
P2: A catalog-membership query failure can propagate the raw Supabase error through this MCP callback. Catch the authorization/read failure, log the diagnostic server-side, and return a generic catalog-access-unavailable error.</violation>
</file>

<file name="lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts">

<violation number="1" location="lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts:69">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This module is now 117 lines, exceeding Rule 3’s under-100-line limit. Move the quote-result mapping into a focused helper so the registration module stays below the limit.</violation>
</file>

<file name="lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts">

<violation number="1" location="lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts:1">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This module is 123 lines, exceeding the rule’s under-100-line limit. Move the allowlists or projection helpers into a separate module to bring it below the limit.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

const claims = quote.verify(approvedQuote);
if (!claims) return { kind: "invalid_quote" };

const gate = await checkCreditsAvailable({ accountId, creditsToDeduct: maximumCredits });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This read-only gate does not reserve credits across distinct quotes. Concurrent executions can each see the same balance, claim separate quotes, and dispatch before either debit; the account can receive extra unbilled scrapes or be charged after the approved balance is exhausted. Replace this check with an atomic reservation/charge or an account-scoped lock covering dispatch.

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 lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts, line 54:

<comment>This read-only gate does not reserve credits across distinct quotes. Concurrent executions can each see the same balance, claim separate quotes, and dispatch before either debit; the account can receive extra unbilled scrapes or be charged after the approved balance is exhausted. Replace this check with an atomic reservation/charge or an account-scoped lock covering dispatch.</comment>

<file context>
@@ -0,0 +1,60 @@
+  const claims = quote.verify(approvedQuote);
+  if (!claims) return { kind: "invalid_quote" };
+
+  const gate = await checkCreditsAvailable({ accountId, creditsToDeduct: maximumCredits });
+  if (gate.kind === "insufficient_credits") return gate;
+  if (!(await claimSocialRefreshQuote(claims.id, claims.expiresAt))) return { kind: "used_quote" };
</file context>

Comment thread lib/mcp/oauth/fullOAuthToolPolicy.ts Resolved
Comment thread lib/catalog/analyzeCatalogBatch.ts Resolved
Comment thread lib/artist/runArtistSocialsScrape.ts Resolved
@@ -0,0 +1,123 @@
interface PublicScrapeItem {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This module is 123 lines, exceeding the rule’s under-100-line limit. Move the allowlists or projection helpers into a separate module to bring it below the limit.

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 lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts, line 1:

<comment>This module is 123 lines, exceeding the rule’s under-100-line limit. Move the allowlists or projection helpers into a separate module to bring it below the limit.</comment>

<file context>
@@ -0,0 +1,123 @@
+interface PublicScrapeItem {
+  [key: string]: string | number | PublicScrapeItem | PublicScrapeItem[];
+}
</file context>

execute: params =>
executeQuotedSocialRefresh(params, args.artist_account_id, args.approved_quote),
});
if (result.kind === "quote") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This module is now 117 lines, exceeding Rule 3’s under-100-line limit. Move the quote-result mapping into a focused helper so the registration module stays below the limit.

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 lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts, line 69:

<comment>This module is now 117 lines, exceeding Rule 3’s under-100-line limit. Move the quote-result mapping into a focused helper so the registration module stays below the limit.</comment>

<file context>
@@ -52,7 +63,30 @@ export function registerScrapeArtistSocialsTool(server: McpServer): void {
+          execute: params =>
+            executeQuotedSocialRefresh(params, args.artist_account_id, args.approved_quote),
         });
+        if (result.kind === "quote") {
+          return getToolResultSuccess({
+            success: true,
</file context>

export interface AnalyzeFullCatalogOptions {
catalogId: string;
criteria: string;
startPage?: number;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The new pagination options leave analyzeFullCatalog's public documentation inaccurate: it still promises to fetch all songs and omits the 1-based startPage/nextPage contract. Update the JSDoc so callers do not assume a single call analyzes the entire catalog.

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 lib/catalog/analyzeFullCatalog.ts, line 11:

<comment>The new pagination options leave `analyzeFullCatalog`'s public documentation inaccurate: it still promises to fetch all songs and omits the 1-based `startPage`/`nextPage` contract. Update the JSDoc so callers do not assume a single call analyzes the entire catalog.</comment>

<file context>
@@ -3,10 +3,12 @@ import { type CatalogSongWithArtists } from "@/lib/supabase/catalog_songs/select
 export interface AnalyzeFullCatalogOptions {
   catalogId: string;
   criteria: string;
+  startPage?: number;
 }
 
</file context>

accountIdOverride: undefined,
});
if (!accountId) return getToolResultError(error ?? "Authentication required.");
const catalogs = await selectAccountCatalogs(await getCatalogOwnerIds(accountId), {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Move the account and catalog-access checks into a dedicated validateGetCatalogSongs... operation validator, then have this callback consume its validated result before running analyzeFullCatalog; keeping authorization in the orchestration handler makes this entry point’s access contract easy to bypass or diverge when reused.

(Based on your team's feedback about centralizing handler validation.)

View Feedback

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 lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts, line 46:

<comment>Move the account and catalog-access checks into a dedicated `validateGetCatalogSongs...` operation validator, then have this callback consume its validated result before running `analyzeFullCatalog`; keeping authorization in the orchestration handler makes this entry point’s access contract easy to bypass or diverge when reused.

(Based on your team's feedback about centralizing handler validation.) </comment>

<file context>
@@ -16,19 +32,27 @@ export function registerGetCatalogSongsTool(server: McpServer): void {
+        accountIdOverride: undefined,
+      });
+      if (!accountId) return getToolResultError(error ?? "Authentication required.");
+      const catalogs = await selectAccountCatalogs(await getCatalogOwnerIds(accountId), {
+        catalogIds: [args.catalog_id],
+      });
</file context>

@sidneyswift
sidneyswift merged commit da16249 into main Nov 25, 2026
9 checks passed

This branch was successfully deployed

1 active deployment
Preview — 31ad0eec Deployed Nov 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant