Skip to content

feat(mcp): add scrape_artist_socials, get_scraper_results, get_artist_posts tools - #1243

Merged
sweetmantech merged 5 commits into
mainfrom
feat/mcp-social-scrape-posts-tools
Nov 14, 2026
Merged

sweetmantech merged 5 commits into
mainfrom
feat/mcp-social-scrape-posts-tools

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Before: an agent connected to the Recoup MCP server could read an artist's social profiles but had no way to start a socials scrape, check a scrape run, or read the artist's posts. Those only existed as REST routes.

After: three MCP tools expose them:

  • scrape_artist_socials (write, spends credits): starts a scrape of every social linked to the artist. Checks artist access, gates credits for all linked profiles ($0.05 each + $0.01 per requested post), charges only the runs that started, and registers them as one batch, exactly like POST /api/artist/socials/scrape.
  • get_scraper_results (read): run status, plus the dataset once SUCCEEDED. Same as GET /api/apify/runs/{runId}: requires a credential but is not owner-scoped (chat#1840).
  • get_artist_posts (read): saved posts across the artist's socials with the REST pagination defaults (page 1, limit 20, max 100). Same as GET /api/artists/{id}/posts.

Tracking and merge order

How

  • Shared domain logic for REST and MCP: lib/artist/runArtistSocialsScrape.ts (access check, socials lookup, credit gate, start via startArtistSocialsScrape), lib/apify/getScraperRunResults.ts, and lib/posts/getArtistPosts.ts (posts envelope). The REST handlers and tools only map results to their own response shapes; REST responses are unchanged. The usage label is ARTIST_SOCIALS_SCRAPE_MODEL_ID in lib/const.ts.
  • Tools live in lib/mcp/tools/artistSocials/ and are registered via registerAllArtistSocialsTools, so they are available to API-key callers and to full OAuth (mcp:tools) grants. Full OAuth also runs the existing prepareFullOAuthTool artist gate on artist_account_id.
  • Classified in fullOAuthToolPolicy (scrape is readOnly: false with a credit notice), scripts/mcp-oauth/tool-policy.json (scrape: mcp:write + mcp:spend) and docs/mcp-oauth-tool-qualification.md. Full catalog count 89 → 92.
  • Not added to the limited mcp:read/mcp:write grant (registerOAuthTools), which keeps its existing five-tool contract.

Tests

  • New: tool tests for all three tools, runArtistSocialsScrape, startArtistSocialsScrape, getScraperRunResults, getArtistPosts.
  • pnpm test: 1485 files / 9462 tests pass.
  • tsc -p tsconfig.build.json and pnpm typecheck:mcp-oauth: clean. eslint and prettier clean on changed files.

Generated by Claude Code


Summary by cubic

Adds MCP tools for starting artist social scrapes, checking scrape runs, and listing saved posts—capabilities previously only available through REST.

  • scrape_artist_socials checks artist access, gates the full credit cost, charges only runs that started, and returns an error listing every failure when no run started (nothing was charged); MCP charges use the REST route label so usage groups together.
  • get_scraper_results returns run status and the dataset after success; like the REST route, it requires a credential but is not owner-scoped.
  • get_artist_posts uses the REST pagination defaults.
  • REST and MCP share the scrape orchestration (runArtistSocialsScrape), run-result logic, and posts envelope; REST responses are unchanged.
  • The tools are included in full OAuth policies but not the limited OAuth grant.

Written for commit 6c1a165. Summary will update on new commits.

View guided diff Turn on auto-fix


Generated by Claude Code

Summary by CodeRabbit

  • New Features
    • Added tools to start social-profile scrapes for an artist, retrieve scrape results, and browse artist posts with pagination.
    • Scrapes report their status and results, account for profile and post credit costs, and save retrieved posts.
    • Scrape requests now provide clear responses for access restrictions, insufficient credits, and profiles that could not be started.

…_posts tools

Expose the existing socials scrape, Apify run results and artist posts
REST capabilities as MCP tools so agents can pull an artist's recent
social posts.

- Extract startArtistSocialsScrape and getScraperRunResults so the REST
  handlers and the MCP tools share the same domain logic.
- scrape_artist_socials: artist access check, credit gate for every
  linked profile, charges only runs that started (write, spends credits).
- get_scraper_results: run status plus dataset once SUCCEEDED (read;
  credential required, not owner-scoped, matching chat#1840).
- get_artist_posts: saved posts with the REST pagination defaults (read).
- Classify all three in the full OAuth policy and tool inventory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 13, 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 14, 2026 5:18am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds artist-social scrape orchestration and MCP tools for starting scrapes, retrieving scraper results, and reading artist posts. Existing API handlers now use shared helpers for scrape results and post responses.

Changes: Artist Socials

Layer / File(s) Summary
Scrape orchestration and run registration
lib/artist/runArtistSocialsScrape.ts, lib/artist/startArtistSocialsScrape.ts, lib/artist/postArtistSocialsScrapeHandler.ts, lib/const.ts
The handler delegates to a runner that checks artist access and available credits. The runner starts scrapes for linked socials. The starter charges for started runs and registers their metadata.
Scraper results and artist posts
lib/apify/getScraperRunResults.ts, lib/apify/getScraperResultsHandler.ts, lib/posts/getArtistPosts.ts, lib/posts/getArtistPostsHandler.ts
New helpers retrieve scraper results and artist posts. The existing handlers use the helpers to form their responses.
MCP tool registration and policy
lib/mcp/tools/artistSocials/*, lib/mcp/oauth/fullOAuthToolPolicy.ts
Registers MCP tools for scraping socials, retrieving scraper results, and reading artist posts. OAuth policy entries classify the tools and describe scrape costs and confirmation requirements.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant scrape_artist_socials
  participant runArtistSocialsScrape
  participant startArtistSocialsScrape
  participant scrapeProfileUrlBatch
  Caller->>scrape_artist_socials: Submit artist_account_id and posts
  scrape_artist_socials->>runArtistSocialsScrape: Pass account and scrape parameters
  runArtistSocialsScrape->>startArtistSocialsScrape: Pass socials, post depth, and cost
  startArtistSocialsScrape->>scrapeProfileUrlBatch: Submit profile URLs and usernames
  startArtistSocialsScrape-->>runArtistSocialsScrape: Return run IDs, dataset IDs, and errors
  runArtistSocialsScrape-->>scrape_artist_socials: Return started runs or an error result
Loading

Suggested reviewers: arpitgupta1214, sidneyswift

Merge Risk: Minimal · up to 6c1a1

This PR exposes scraping, scraper results and artist posts through MCP tools, reusing the existing REST logic. No concrete merge-blocking risk was found, and access, credit and response-shape behavior appear preserved.

Pre-merge checks: Passed 3

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Solid & Clean Code Passed The PR moves the scrape, run-result, and posts logic into single-purpose modules that REST and MCP both call. Each new module exports one primary function whose name matches its file: getScraperRunRes…
Full details: Solid & Clean Code

Explanation

The PR moves the scrape, run-result, and posts logic into single-purpose modules that REST and MCP both call. Each new module exports one primary function whose name matches its file: getScraperRunResults.ts, runArtistSocialsScrape.ts, startArtistSocialsScrape.ts, getArtistPosts.ts, and the three register*Tool.ts files. No new function was added to an existing file, so the file-function name rule is not triggered. The REST handlers are now thin wrappers. For example, postArtistSocialsScrapeHandler.ts dropped from about 120 lines of inline orchestration to a delegation plus result-to-response mapping. Minor observations, none of which meets an explicit failure condition: - registerScrapeArtistSocialsTool.ts has a handler callback of roughly 40 lines (lines 39-81). It exceeds the 20-line guideline and branches on several result kinds. Splitting out the result-to-tool-response mapping would improve it. - The resolveAccountId and "Authentication required." boilerplate repeats across the three new tools. The repo already uses this pattern in about 26 tool call sites, so it follows an existing convention. - The $0.05 and $0.01 cost figures appear as literal text in tool descriptions and the policy notice. They are not derived from the cost constants. Overall the design follows SRP, DRY for the shared domain logic, and clean naming.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • 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

Social profiles start their run,
Credit checks are counted one by one.
Results return with status in view,
Artist posts arrive with pages too.
MCP tools connect each part,
A tidy path from start to chart.

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f7188f4 and 6c1a165.

Files ignored due to path filters: 13

  • docs/mcp-oauth-tool-qualification.md is excluded by none and included by none
  • lib/apify/__tests__/getScraperRunResults.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/apify/__tests__/socialScrapeBillingRoutes.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/artist/__tests__/postArtistSocialsScrapeHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/artist/__tests__/runArtistSocialsScrape.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/artist/__tests__/startArtistSocialsScrape.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/contracts/__tests__/scrapeErrorSafety.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/mcp/tools/artistSocials/__tests__/registerGetArtistPostsTool.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/mcp/tools/artistSocials/__tests__/registerGetScraperResultsTool.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/mcp/tools/artistSocials/__tests__/registerScrapeArtistSocialsTool.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/posts/__tests__/getArtistPosts.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • scripts/mcp-oauth/tool-policy.json is excluded by none and included by none
Files selected for processing: 13

  • lib/apify/getScraperResultsHandler.ts
  • lib/apify/getScraperRunResults.ts
  • lib/artist/postArtistSocialsScrapeHandler.ts
  • lib/artist/runArtistSocialsScrape.ts
  • lib/artist/startArtistSocialsScrape.ts
  • lib/const.ts
  • lib/mcp/oauth/fullOAuthToolPolicy.ts
  • lib/mcp/tools/artistSocials/index.ts
  • lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts
  • lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts
  • lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts
  • lib/posts/getArtistPosts.ts
  • lib/posts/getArtistPostsHandler.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

usage_events.model_id is documented as METHOD /route/pattern for API
charges; use the REST route's label so MCP and REST scrapes group together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ith REST

Address the CodeRabbit Solid & Clean Code finding on #1243:

- runArtistSocialsScrape now owns the access check, socials lookup, credit
  gate and start; POST /api/artist/socials/scrape and scrape_artist_socials
  both call it and only map its result (403/402/200 vs tool result). One
  credit gate path (checkCreditsAvailable) for one rule.
- getArtistPosts builds the { status, posts, pagination } envelope for both
  GET /api/artists/{id}/posts and get_artist_posts.
- ARTIST_SOCIALS_SCRAPE_MODEL_ID replaces the hardcoded usage label.

REST wire shapes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor Author

Preview verification (api-cl5c7asqh-recoup.vercel.app, a23eae9)

Run from a Vercel Sandbox against the PR preview. API key minted on the preview itself via POST /api/agents/signup + /api/agents/verify (email code flow), used as Authorization: Bearer on /mcp and x-api-key on REST. The key was never printed.

Check Documented / expected Actual
initialize 200, server info 200, recoup-mcp
tools/list includes scrape_artist_socials inputs artist_account_id, posts listed, inputs match
tools/list includes get_scraper_results input runId listed, input matches
tools/list includes get_artist_posts inputs artist_account_id, page, limit listed, inputs match
get_artist_posts on new artist same shape as GET /api/artists/{id}/posts {status:"success", posts:[], pagination:{...}}, identical to REST
scrape_artist_socials on artist with no socials no runs, no charge success:true, runs:[], "no linked social profiles" (REST returns [])
get_scraper_results with unknown runId error success:false, "Failed to read the scrape run."
get_artist_posts with nonexistent artist UUID error success:false, "Failed to list artist posts."
tools/list with no auth 401 401

Notes

  • The test account is in the Recoup org, so checkAccountArtistAccess passes for any artist id. The forbidden path was not exercised here; it is covered by unit tests.
  • Not covered: a scrape that actually starts Apify runs and get_scraper_results on a real runId (the test artist has no linked socials, so no credits were spent).
  • MCP scrape_artist_socials returns {success, runs} while REST returns a bare array. Intentional for the tool wrapper, flagging for review.
  • Preview env: agent+ instant signup returns 500 because the preview Privy app hit max_accounts_reached. Unrelated to this PR.

Generated by Claude Code

Every profile's start can fail (bad Apify token, unsupported platform). The
tool used to report success:true with all-null runs, so an agent could not
tell nothing happened. Return an error listing each failure instead; credits
are charged only for started runs, so the message says none were charged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor Author

Real scrape on the preview (api-gq45fkp8y-recoup.vercel.app, 2b67e27)

Run from a non-persistent Vercel Sandbox (network limited to the preview host) after the preview's APIFY_TOKEN fix. Fresh agent+ key minted on the preview via POST /api/agents/signup (instant, no email). Key never printed.

Step Expected Actual
agent+ signup 200 + key 200, key returned
create_new_artist new artist 200, artist created
update_artist_socials (one public Instagram profile) linked 200, linked
scrape_artist_socials (posts: 1) one run started success:true, 1 run with runId + datasetId, error:null
get_scraper_results on that runId RUNNING then a final status with data RUNNING x3, then SUCCEEDED with {status, dataset_id, data} and the profile data

Not verified in this run

  • get_artist_posts returning the scraped post: the script's output was cut off before that call's result, and a second key can't read the artist (403, owner-scoped as expected). Not rerun, to avoid a second charge.
  • Credit deduction for the started run was not read back.

The no-run fix in 2b67e27 (a tool error when every profile fails to start) is covered by unit tests; this run took the started path.


Generated by Claude Code

Folds the cost into the first sentence and adds a test that the description
stays at three sentences or fewer and still states the cost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor Author

Remaining preview checks (api-ojbhaxpom-recoup.vercel.app, 6c1a165)

Run from a non-persistent Vercel Sandbox (network limited to the preview host), with fresh agent+ keys minted on the preview. Keys never printed. One real scrape: one public Instagram profile, posts: 1.

Check Expected Actual
Account B calls scrape_artist_socials on account A's artist refused, no charge tool error "Access denied to specified artist_account_id"; B's credits unchanged
Account B calls get_artist_posts on A's artist refused tool error "Access denied to specified artist_account_id"
Account B, REST POST /api/artist/socials/scrape on A's artist 403 403 "Unauthorized artist socials scrape attempt"
Account B, REST GET /api/artists/{id}/posts on A's artist 403 403
A runs scrape_artist_socials (1 profile, posts: 1) 1 run started 1 run, error: null; get_scraper_results RUNNING then SUCCEEDED with data
A's credits after the scrape down 60,000 ($0.05 + $0.01) remaining_credits 300,000,000 to 299,940,000, exactly 60,000
A's usage for the period one 60,000 charge GET /api/accounts/{id}/usage total 60,000
get_artist_posts after the scrape the scraped posts 12 saved posts; the newest three match the run's dataset exactly (same URLs, timestamps and like counts)

Notes

  • The usage line's model_id was not read back: the run's output was cut off before that field and the owner key was not kept. The label comes from ARTIST_SOCIALS_SCRAPE_MODEL_ID, which unit tests cover.
  • The posts read-back used a new account's artist linked to the same Instagram profile, because posts are stored per social profile, not per artist. Read-only, no charge (that account's usage stayed at 0).
  • Instagram's profile scraper returned 12 latest posts even with posts: 1, and all 12 were saved. Pre-existing scraper behavior, not changed by this PR.

Generated by Claude Code

@sweetmantech
sweetmantech marked this pull request as ready for review November 14, 2026 06:37

@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.

11 issues found across 26 files

Confidence score: 3/5

  • The API-key paths in registerGetScraperResultsTool and registerScrapeArtistSocialsTool have no account-scoped request limit, so repeated polling or scrape launches can drive unbounded work. Add per-account limits to both handlers.
  • fullOAuthToolPolicy.ts underquotes multi-profile runs because the $0.01-per-post surcharge applies to each profile that actually starts. State the per-started-profile formula so callers can assess the cost.
  • runArtistSocialsScrape.ts uses the default 100-social limit, so artists with more linked socials can have profiles silently skipped. Pass the higher limit used by the sibling call sites.
  • startArtistSocialsScrape.ts classifies platforms from the raw URL, so mixed-case URLs like X.com/... can be stored as none even when the run starts. Normalize the URL before classification.
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/oauth/fullOAuthToolPolicy.ts">

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

These policy entries add 11 lines to an already oversized module, bringing it to 141 lines against Rule 3’s under-100-line limit. Split the policy inventory into cohesive modules and keep this file under 100 lines.</violation>

<violation number="2" location="lib/mcp/oauth/fullOAuthToolPolicy.ts:97">
P2: This underquotes multi-profile runs: the `$0.01 × posts` surcharge applies per profile, and charges apply only to profiles that actually start. State the per-started-profile formula so OAuth callers can evaluate the cost before confirming.</violation>
</file>

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

<violation number="1" location="lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts:33">
P2: Custom agent: **API Design Consistency and Maintainability**

API-key callers can launch scrapes through this tool without a request-velocity limit. Add an account-scoped limiter before `runArtistSocialsScrape` so repeated calls cannot bypass throttling.</violation>

<violation number="2" location="lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts:68">
P2: This message is wrong when the artist has linked socials, but none are on a scrapable platform: `scrapeProfileUrl` returns null for them and they are dropped, so `runs` comes back empty. Report that unsupported profiles were skipped instead of saying no socials are linked. The tool description's "Returns one run per profile" also overstates this.</violation>
</file>

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

<violation number="1" location="lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts:32">
P2: Custom agent: **API Design Consistency and Maintainability**

This polling tool invites repeated calls, but its API-key handler has no rate limit; enforce a per-account limit before fetching run results to prevent unbounded polling.</violation>
</file>

<file name="lib/mcp/tools/artistSocials/__tests__/registerGetArtistPostsTool.test.ts">

<violation number="1" location="lib/mcp/tools/artistSocials/__tests__/registerGetArtistPostsTool.test.ts:77">
P3: This test only checks `success === false`, so it would still pass if the error message changed or the envelope were wrong. Assert the full error envelope with the `Authentication required.` message, as the other error-path tests do.</violation>
</file>

<file name="lib/apify/__tests__/getScraperRunResults.test.ts">

<violation number="1" location="lib/apify/__tests__/getScraperRunResults.test.ts:31">
P3: The new tests don't cover the SUCCEEDED branch where the dataset returns no items or `defaultDatasetId` is missing, even though the JSDoc promises `data` is omitted in that case. Add a case that mocks a SUCCEEDED run with no `defaultDatasetId` (or `listItems` returning no `items`) and asserts `data` is absent.</violation>
</file>

<file name="docs/mcp-oauth-tool-qualification.md">

<violation number="1" location="docs/mcp-oauth-tool-qualification.md:59">
P3: The source link for this row points to `startArtistSocialsScrape.ts`, which does not contain the artist access check or the pre-scrape credit gate this row describes. Link to `runArtistSocialsScrape.ts` instead, since that is where both gates run.</violation>
</file>

<file name="lib/artist/runArtistSocialsScrape.ts">

<violation number="1" location="lib/artist/runArtistSocialsScrape.ts:45">
P2: This call uses the default `limit` of 100 in `selectAccountSocials`, so an artist with more linked socials gets only the first 100 scraped and gated without any signal. Pass `limit: 10000`, as the sibling call sites do.</violation>
</file>

<file name="lib/artist/startArtistSocialsScrape.ts">

<violation number="1" location="lib/artist/startArtistSocialsScrape.ts:65">
P2: The platform is classified from the raw URL, so a mixed-case profile URL such as `X.com/...` is stored as `none` for a run that started. Lowercase the URL before classifying it, as `registerRootApifyRun` does.</violation>
</file>

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

<violation number="1" location="lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts:57">
P3: The MCP handler repeats the REST access gate inline but skips the artist-existence check, so the two surfaces diverge. An org admin querying a nonexistent artist ID gets an empty success here, while REST returns 404 "Artist not found". Move the artist lookup and access check into a shared validator that both `validateGetArtistPostsRequest` and this tool call, as `runArtistSocialsScrape` does for the scrape tool.

(Based on your team's feedback about centralizing handler validation.)</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Agent as AI Agent (MCP Client)
    participant McpServer as MCP Server
    participant ApiKey as API Key / OAuth Auth
    participant ToolReg as Tool Registry
    participant ShareLogic as Shared Domain Logic
    participant Db as Supabase DB
    participant Credits as Credit Service
    participant Api as External APIs

    Note over Agent,Api: MCP Tools for Artist Social Scraping - Current State Flow

    %% Tool Registration Phase
    Agent->>ApiKey: Connect with API key or OAuth token
    ApiKey->>McpServer: Authenticate request
    McpServer->>ToolReg: Initialize with grants (OAuth mcp:read/mcp:write/mcp:spend)
    ToolReg->>McpServer: Register scrape_artist_socials, get_scraper_results, get_artist_posts
    McpServer-->>Agent: Tool list available

    %% scrape_artist_socials - Write tool with credit gating
    Agent->>McpServer: call scrape_artist_socials(artist_account_id, posts?)
    
    alt API Key caller
        McpServer->>McpServer: Resolve accountId from API key
    else Full OAuth caller
        McpServer->>McpServer: Resolve accountId + check mcp:write/mcp:spend scope
    end

    McpServer->>ShareLogic: runArtistSocialsScrape(accountId, artistAccountId, posts)
    
    ShareLogic->>ShareLogic: checkAccountArtistAccess(accountId, artistAccountId)
    alt Access denied
        ShareLogic-->>McpServer: { kind: "forbidden" }
        McpServer-->>Agent: Error "Access denied"
    else Access granted
        ShareLogic->>Db: selectAccountSocials(artistAccountId)
        Db-->>ShareLogic: Linked social profiles
        
        alt No linked socials
            ShareLogic-->>McpServer: { kind: "started", runs: [] }
            McpServer-->>Agent: Success with no runs
        else Credits gate
            ShareLogic->>Credits: checkCreditsAvailable(accountId, cost × profiles)
            
            alt Insufficient credits
                Credits-->>ShareLogic: { kind: "insufficient_credits" }
                ShareLogic-->>McpServer: Shortfall details
                McpServer-->>Agent: Error "Insufficient credits"
            else Credits available
                ShareLogic->>ShareLogic: startArtistSocialsScrape()
                ShareLogic->>Api: Launch Apify scrape per profile
                
                loop Each social profile
                    Api-->>ShareLogic: Started | Failed result per profile
                end
                
                alt At least one run started
                    ShareLogic->>Credits: deduct per started run (only if actually started)
                    ShareLogic->>Db: upsertApifyScraperRuns(batch)
                    ShareLogic-->>McpServer: { kind: "started", runs }
                    McpServer-->>Agent: Success with per-profile run results
                else All runs failed
                    ShareLogic->>Credits: No deduction (no runs started)
                    ShareLogic-->>McpServer: { kind: "started", runs (all errors) }
                    McpServer-->>Agent: Error "No runs started. No credits charged."
                end
            end
        end
    end

    %% get_scraper_results - Read tool (not owner-scoped, credential only)
    Agent->>McpServer: call get_scraper_results(runId)
    McpServer->>McpServer: Resolve accountId from auth
    McpServer->>ShareLogic: getScraperRunResults(runId)
    ShareLogic->>Api: Fetch Apify run status
    
    alt Run SUCCEEDED
        Api-->>ShareLogic: Status + defaultDatasetId
        ShareLogic->>Api: Fetch dataset items
        Api-->>ShareLogic: Scraped data
        ShareLogic-->>McpServer: { status, dataset_id, data }
    else Run still RUNNING/READY
        Api-->>ShareLogic: Status + datasetId
        ShareLogic-->>McpServer: { status, dataset_id } (no data)
    else Run FAILED/ABORTED/TIMED-OUT
        Api-->>ShareLogic: Error status
        ShareLogic-->>McpServer: { status, dataset_id }
    end
    
    McpServer-->>Agent: Run status + data (when SUCCEEDED)

    %% get_artist_posts - Read tool with artist gate
    Agent->>McpServer: call get_artist_posts(artist_account_id, page?, limit?)
    McpServer->>McpServer: Resolve accountId from auth
    McpServer->>ShareLogic: checkAccountArtistAccess(accountId, artistAccountId)
    
    alt Access denied
        ShareLogic-->>McpServer: Denied
        McpServer-->>Agent: Error "Access denied"
    else Access granted
        McpServer->>ShareLogic: getArtistPosts(artistAccountId, page=1, limit=20)
        ShareLogic->>Db: selectPosts(artistAccountId, page, limit)
        Db-->>ShareLogic: Posts + totalCount
        ShareLogic-->>McpServer: Posts envelope { status, posts, pagination }
        McpServer-->>Agent: Paginated posts with total_pages
    end

    %% Error handling for all tools
    opt Any tool throws
        ShareLogic-->>McpServer: Exception caught
        McpServer-->>Agent: Redacted error message
    end

    Note over ShareLogic,Api: Shared domain logic across REST + MCP routes
    Note over ShareLogic: Usage label: POST /api/artist/socials/scrape
Loading

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

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

export_release_pack: { readOnly: true },
list_artists: { readOnly: true },
get_artist_socials: { readOnly: true },
get_artist_posts: { readOnly: true },

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

These policy entries add 11 lines to an already oversized module, bringing it to 141 lines against Rule 3’s under-100-line limit. Split the policy inventory into cohesive modules and keep this file under 100 lines.

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/oauth/fullOAuthToolPolicy.ts, line 26:

<comment>These policy entries add 11 lines to an already oversized module, bringing it to 141 lines against Rule 3’s under-100-line limit. Split the policy inventory into cohesive modules and keep this file under 100 lines.</comment>

<file context>
@@ -23,6 +23,11 @@ export const fullOAuthToolPolicy: Record<string, ToolPolicy> = {
   export_release_pack: { readOnly: true },
   list_artists: { readOnly: true },
   get_artist_socials: { readOnly: true },
+  get_artist_posts: { readOnly: true },
+  get_scraper_results: {
+    readOnly: true,
</file context>

*/
export function registerScrapeArtistSocialsTool(server: McpServer): void {
server.registerTool(
"scrape_artist_socials",

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: API Design Consistency and Maintainability

API-key callers can launch scrapes through this tool without a request-velocity limit. Add an account-scoped limiter before runArtistSocialsScrape so repeated calls cannot bypass throttling.

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 33:

<comment>API-key callers can launch scrapes through this tool without a request-velocity limit. Add an account-scoped limiter before `runArtistSocialsScrape` so repeated calls cannot bypass throttling.</comment>

<file context>
@@ -0,0 +1,83 @@
+ */
+export function registerScrapeArtistSocialsTool(server: McpServer): void {
+  server.registerTool(
+    "scrape_artist_socials",
+    {
+      description:
</file context>

server.registerTool(
"get_scraper_results",
{
description:

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: API Design Consistency and Maintainability

This polling tool invites repeated calls, but its API-key handler has no rate limit; enforce a per-account limit before fetching run results to prevent unbounded polling.

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/registerGetScraperResultsTool.ts, line 32:

<comment>This polling tool invites repeated calls, but its API-key handler has no rate limit; enforce a per-account limit before fetching run results to prevent unbounded polling.</comment>

<file context>
@@ -0,0 +1,55 @@
+  server.registerTool(
+    "get_scraper_results",
+    {
+      description:
+        "Check a social scrape run started by scrape_artist_socials. Returns the run status (READY, RUNNING, SUCCEEDED, FAILED, ABORTED, TIMED-OUT) and, once SUCCEEDED, the scraped profile and post data. Call again later while the run is still RUNNING.",
+      inputSchema: getScraperResultsSchema,
</file context>

return { kind: "forbidden" };
}

const socials = await selectAccountSocials({ accountId: artistAccountId });

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: This call uses the default limit of 100 in selectAccountSocials, so an artist with more linked socials gets only the first 100 scraped and gated without any signal. Pass limit: 10000, as the sibling call sites do.

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/artist/runArtistSocialsScrape.ts, line 45:

<comment>This call uses the default `limit` of 100 in `selectAccountSocials`, so an artist with more linked socials gets only the first 100 scraped and gated without any signal. Pass `limit: 10000`, as the sibling call sites do.</comment>

<file context>
@@ -0,0 +1,69 @@
+    return { kind: "forbidden" };
+  }
+
+  const socials = await selectAccountSocials({ accountId: artistAccountId });
+  if (!socials.length) return { kind: "started", runs: [] };
+
</file context>
Suggested change
const socials = await selectAccountSocials({ accountId: artistAccountId });
const socials = await selectAccountSocials({ accountId: artistAccountId, limit: 10000 });

return getToolResultSuccess({
success: true,
runs: [],
message: "This artist has no linked social profiles to scrape.",

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: This message is wrong when the artist has linked socials, but none are on a scrapable platform: scrapeProfileUrl returns null for them and they are dropped, so runs comes back empty. Report that unsupported profiles were skipped instead of saying no socials are linked. The tool description's "Returns one run per profile" also overstates this.

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 68:

<comment>This message is wrong when the artist has linked socials, but none are on a scrapable platform: `scrapeProfileUrl` returns null for them and they are dropped, so `runs` comes back empty. Report that unsupported profiles were skipped instead of saying no socials are linked. The tool description's "Returns one run per profile" also overstates this.</comment>

<file context>
@@ -0,0 +1,83 @@
+          return getToolResultSuccess({
+            success: true,
+            runs: [],
+            message: "This artist has no linked social profiles to scrape.",
+          });
+        }
</file context>
Suggested change
message: "This artist has no linked social profiles to scrape.",
message: "No scrapable social profiles were found. Linked profiles on unsupported platforms or without a profile URL were skipped.",

readOnly: false,
destructive: false,
notice:
"Spends account credits: $0.05 per linked profile plus $0.01 per requested post. Confirm before scraping.",

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: This underquotes multi-profile runs: the $0.01 × posts surcharge applies per profile, and charges apply only to profiles that actually start. State the per-started-profile formula so OAuth callers can evaluate the cost before confirming.

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/oauth/fullOAuthToolPolicy.ts, line 97:

<comment>This underquotes multi-profile runs: the `$0.01 × posts` surcharge applies per profile, and charges apply only to profiles that actually start. State the per-started-profile formula so OAuth callers can evaluate the cost before confirming.</comment>

<file context>
@@ -85,6 +90,12 @@ export const fullOAuthToolPolicy: Record<string, ToolPolicy> = {
+    readOnly: false,
+    destructive: false,
+    notice:
+      "Spends account credits: $0.05 per linked profile plus $0.01 per requested post. Confirm before scraping.",
+  },
   update_pulse: { readOnly: false },
</file context>
Suggested change
"Spends account credits: $0.05 per linked profile plus $0.01 per requested post. Confirm before scraping.",
"Spends account credits: ($0.05 + $0.01 per requested post) per started profile. Confirm before scraping.",


it("requires authentication", async () => {
const result = await handler({ artist_account_id: ARTIST_ID }, extra());
expect(text(result).success).toBe(false);

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: This test only checks success === false, so it would still pass if the error message changed or the envelope were wrong. Assert the full error envelope with the Authentication required. message, as the other error-path tests do.

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/__tests__/registerGetArtistPostsTool.test.ts, line 77:

<comment>This test only checks `success === false`, so it would still pass if the error message changed or the envelope were wrong. Assert the full error envelope with the `Authentication required.` message, as the other error-path tests do.</comment>

<file context>
@@ -0,0 +1,93 @@
+
+  it("requires authentication", async () => {
+    const result = await handler({ artist_account_id: ARTIST_ID }, extra());
+    expect(text(result).success).toBe(false);
+    expect(selectPosts).not.toHaveBeenCalled();
+  });
</file context>


it("returns only the status for a run still in progress", async () => {
mockRun({ status: "RUNNING", defaultDatasetId: "d1" });
expect(await getScraperRunResults("r1")).toEqual({ status: "RUNNING", dataset_id: "d1" });

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 tests don't cover the SUCCEEDED branch where the dataset returns no items or defaultDatasetId is missing, even though the JSDoc promises data is omitted in that case. Add a case that mocks a SUCCEEDED run with no defaultDatasetId (or listItems returning no items) and asserts data is absent.

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/apify/__tests__/getScraperRunResults.test.ts, line 31:

<comment>The new tests don't cover the SUCCEEDED branch where the dataset returns no items or `defaultDatasetId` is missing, even though the JSDoc promises `data` is omitted in that case. Add a case that mocks a SUCCEEDED run with no `defaultDatasetId` (or `listItems` returning no `items`) and asserts `data` is absent.</comment>

<file context>
@@ -0,0 +1,39 @@
+
+  it("returns only the status for a run still in progress", async () => {
+    mockRun({ status: "RUNNING", defaultDatasetId: "d1" });
+    expect(await getScraperRunResults("r1")).toEqual({ status: "RUNNING", dataset_id: "d1" });
+    expect(apifyClient.dataset).not.toHaveBeenCalled();
+  });
</file context>

| `create_new_artist` | W | Create artist; wrapper strips conversation-copy input; optional org gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/artists/registerCreateNewArtistTool.ts) |
| `update_account_info` | W | Update artist profile; artist ID gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/registerUpdateAccountInfoTool.ts) |
| `update_artist_socials` | W | Update artist social records; artist ID gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/artistSocials/registerUpdateArtistSocialsTool.ts) |
| `scrape_artist_socials` | W | Start one Apify scrape per linked artist social; artist ID gate; register runs as one batch | Credit availability gate for all linked profiles ($0.05 each + $0.01 per requested post); charges only runs that started | Apify social scrapers; no message recipient | Unknown: each call starts new paid runs; no wrapper idempotency | [source](../lib/artist/startArtistSocialsScrape.ts) |

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 source link for this row points to startArtistSocialsScrape.ts, which does not contain the artist access check or the pre-scrape credit gate this row describes. Link to runArtistSocialsScrape.ts instead, since that is where both gates run.

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/mcp-oauth-tool-qualification.md, line 59:

<comment>The source link for this row points to `startArtistSocialsScrape.ts`, which does not contain the artist access check or the pre-scrape credit gate this row describes. Link to `runArtistSocialsScrape.ts` instead, since that is where both gates run.</comment>

<file context>
@@ -56,6 +56,9 @@ Each source link identifies the registration callback or shared domain/executor
 | `create_new_artist` | W | Create artist; wrapper strips conversation-copy input; optional org gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/artists/registerCreateNewArtistTool.ts) |
 | `update_account_info` | W | Update artist profile; artist ID gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/registerUpdateAccountInfoTool.ts) |
 | `update_artist_socials` | W | Update artist social records; artist ID gate | Unknown: no per-call quote/ceiling established at this boundary | No outbound recipient; authenticated response only | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/artistSocials/registerUpdateArtistSocialsTool.ts) |
+| `scrape_artist_socials` | W | Start one Apify scrape per linked artist social; artist ID gate; register runs as one batch | Credit availability gate for all linked profiles ($0.05 each + $0.01 per requested post); charges only runs that started | Apify social scrapers; no message recipient | Unknown: each call starts new paid runs; no wrapper idempotency | [source](../lib/artist/startArtistSocialsScrape.ts) |
+| `get_scraper_results` | RO | Read an Apify run status and, once SUCCEEDED, its dataset; credential required, not owner-scoped (chat#1840) | No credit charge at this boundary | Apify API read; no message recipient | Repeat read; external billing/retry behavior remains unqualified | [source](../lib/apify/getScraperRunResults.ts) |
+| `get_artist_posts` | RO | Read saved posts across the artist's linked socials; artist ID gate | No credit charge at this boundary | No outbound recipient; authenticated response only | Repeat read | [source](../lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts) |
</file context>
Suggested change
| `scrape_artist_socials` | W | Start one Apify scrape per linked artist social; artist ID gate; register runs as one batch | Credit availability gate for all linked profiles ($0.05 each + $0.01 per requested post); charges only runs that started | Apify social scrapers; no message recipient | Unknown: each call starts new paid runs; no wrapper idempotency | [source](../lib/artist/startArtistSocialsScrape.ts) |
| `scrape_artist_socials` | W | Start one Apify scrape per linked artist social; artist ID gate; register runs as one batch | Credit availability gate for all linked profiles ($0.05 each + $0.01 per requested post); charges only runs that started | Apify social scrapers; no message recipient | Unknown: each call starts new paid runs; no wrapper idempotency | [source](../lib/artist/runArtistSocialsScrape.ts) |


try {
const params = getArtistPostsParamsSchema.parse(args);
if (!(await checkAccountArtistAccess(accountId, params.artist_account_id))) {

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 MCP handler repeats the REST access gate inline but skips the artist-existence check, so the two surfaces diverge. An org admin querying a nonexistent artist ID gets an empty success here, while REST returns 404 "Artist not found". Move the artist lookup and access check into a shared validator that both validateGetArtistPostsRequest and this tool call, as runArtistSocialsScrape does for the scrape tool.

(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/artistSocials/registerGetArtistPostsTool.ts, line 57:

<comment>The MCP handler repeats the REST access gate inline but skips the artist-existence check, so the two surfaces diverge. An org admin querying a nonexistent artist ID gets an empty success here, while REST returns 404 "Artist not found". Move the artist lookup and access check into a shared validator that both `validateGetArtistPostsRequest` and this tool call, as `runArtistSocialsScrape` does for the scrape tool.

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

<file context>
@@ -0,0 +1,74 @@
+
+      try {
+        const params = getArtistPostsParamsSchema.parse(args);
+        if (!(await checkAccountArtistAccess(accountId, params.artist_account_id))) {
+          return getToolResultError("Access denied to specified artist_account_id");
+        }
</file context>

@sweetmantech
sweetmantech merged commit 60af564 into main Nov 14, 2026
7 checks passed

This branch was successfully deployed

1 active deployment
Preview — 6c1a165e Deployed Nov 14, 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.

2 participants