diff --git a/lib/artist/runArtistSocialsScrape.ts b/lib/artist/runArtistSocialsScrape.ts index 49b448b03..975956901 100644 --- a/lib/artist/runArtistSocialsScrape.ts +++ b/lib/artist/runArtistSocialsScrape.ts @@ -5,16 +5,19 @@ import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; import { startArtistSocialsScrape, type StartedArtistSocialsScrape, + type StartArtistSocialsScrapeParams, } from "@/lib/artist/startArtistSocialsScrape"; import { ARTIST_SOCIALS_SCRAPE_MODEL_ID } from "@/lib/const"; -export interface RunArtistSocialsScrapeParams { +export interface RunArtistSocialsScrapeParams { /** The authenticated account that pays for and owns the scrape runs. */ accountId: string; /** The artist whose linked socials should be scraped. */ artistAccountId: string; /** Optional recent-posts depth forwarded to each platform scraper. */ posts?: number; + /** Lets MCP quote and gate credits before dispatch while REST keeps its existing flow. */ + execute?: (params: StartArtistSocialsScrapeParams) => Promise; } export type RunArtistSocialsScrapeResult = @@ -23,21 +26,18 @@ export type RunArtistSocialsScrapeResult = | { kind: "started"; runs: StartedArtistSocialsScrape[] }; /** - * Runs an artist socials scrape end to end: checks the caller can access the - * artist, loads the linked socials, gates credits for every linked profile, - * then starts the scrape (which charges only the profiles that started). - * Shared by `POST /api/artist/socials/scrape` and the `scrape_artist_socials` - * MCP tool, which map the result to their own response shapes. + * Authorize artist access and load the linked profiles and per-profile price. + * REST checks the balance and starts the work. MCP delegates to its quote flow. * * @param params - See {@link RunArtistSocialsScrapeParams}. - * @returns `forbidden`, the credit shortfall, or the started runs (empty when - * the artist has no linked socials). + * @returns The authorization, quote or scrape outcome. */ -export async function runArtistSocialsScrape({ +export async function runArtistSocialsScrape({ accountId, artistAccountId, posts, -}: RunArtistSocialsScrapeParams): Promise { + execute, +}: RunArtistSocialsScrapeParams): Promise { if (!(await checkAccountArtistAccess(accountId, artistAccountId))) { return { kind: "forbidden" }; } @@ -46,6 +46,15 @@ export async function runArtistSocialsScrape({ if (!socials.length) return { kind: "started", runs: [] }; const costPerProfile = getSocialScrapeCreditCost(posts); + const params = { + accountId, + socials, + posts, + costPerProfile, + modelId: ARTIST_SOCIALS_SCRAPE_MODEL_ID, + }; + if (execute) return execute(params); + const gate = await checkCreditsAvailable({ accountId, creditsToDeduct: costPerProfile * socials.length, @@ -58,12 +67,6 @@ export async function runArtistSocialsScrape({ }; } - const runs = await startArtistSocialsScrape({ - accountId, - socials, - posts, - costPerProfile, - modelId: ARTIST_SOCIALS_SCRAPE_MODEL_ID, - }); + const runs = await startArtistSocialsScrape(params); return { kind: "started", runs }; } diff --git a/lib/catalog/__tests__/analyzeFullCatalog.test.ts b/lib/catalog/__tests__/analyzeFullCatalog.test.ts index 92a308157..e004a6bfe 100644 --- a/lib/catalog/__tests__/analyzeFullCatalog.test.ts +++ b/lib/catalog/__tests__/analyzeFullCatalog.test.ts @@ -65,36 +65,48 @@ describe("analyzeFullCatalog filtering", () => { } }); + it("limits each search to ten pages and continues from the returned page", async () => { + const songs = catalog(1001); + select([songs[1000].isrc]); + const first = await analyzeFullCatalog({ ...options, startPage: 1 }); + expect(first).toMatchObject({ results: [], totalSongs: 1001, totalPages: 11, nextPage: 11 }); + expect(generateObject).toHaveBeenCalledTimes(10); + const last = await analyzeFullCatalog({ + ...options, + startPage: first.nextPage, + }); + expect(last.results).toEqual([songs[1000]]); + expect(last.nextPage).toBeUndefined(); + expect(generateObject).toHaveBeenCalledTimes(11); + }); + + it("checks the catalog size before asking for an out-of-range offset", async () => { + catalog(1); + expect((await analyzeFullCatalog({ ...options, startPage: 10_000_000 })).results).toEqual([]); + expect(selectCatalogSongsWithArtists).toHaveBeenCalledExactlyOnceWith({ + catalogId: "catalog", + limit: 100, + page: 1, + }); + expect(generateObject).not.toHaveBeenCalled(); + }); + it("returns no results when no songs match", async () => { catalog(5); select([]); expect((await analyzeFullCatalog(options)).results).toEqual([]); }); - it("filters before limiting, so a match on the last page is retained", async () => { + it("returns the bounded matching window in catalog order", async () => { const songs = catalog(1001); - select([songs[1000].isrc]); - expect((await analyzeFullCatalog(options)).results).toEqual([songs[1000]]); - expect(generateObject).toHaveBeenCalledTimes(11); - }); - - it("caps all-matching results without reprocessing batches", async () => { - const songs = catalog(1001); - const isrcs = songs.map(song => song.isrc); - let calls = 0; - vi.mocked(generateObject).mockImplementation(async () => { - // Fail quickly on the old recursion instead of hanging the test runner. - if (++calls > 11) throw new Error("Catalog was analyzed more than once"); - return { object: { selected_song_isrcs: isrcs } } as Awaited< - ReturnType - >; - }); + select(songs.map(song => song.isrc)); expect(await analyzeFullCatalog(options)).toEqual({ results: songs.slice(0, 1000), totalSongs: 1001, totalPages: 11, + nextPage: 11, }); - expect(generateObject).toHaveBeenCalledTimes(11); + expect(generateObject).toHaveBeenCalledTimes(10); }); it("ignores invented identifiers and duplicate model selections", async () => { diff --git a/lib/catalog/analyzeCatalogBatch.ts b/lib/catalog/analyzeCatalogBatch.ts index 15a4a7aac..4fc47f7a7 100644 --- a/lib/catalog/analyzeCatalogBatch.ts +++ b/lib/catalog/analyzeCatalogBatch.ts @@ -18,6 +18,8 @@ export async function analyzeCatalogBatch( // Use AI to select relevant songs from this batch const { object } = await generateObject({ model: DEFAULT_MODEL, + maxRetries: 1, + maxOutputTokens: 8192, schema: z.object({ selected_song_isrcs: z .array(z.string()) @@ -29,8 +31,8 @@ Songs: ${JSON.stringify( songs.map(s => ({ isrc: s.isrc, - name: s.name, - artist: s.artists.map(a => a.name).join(", "), + name: s.name?.slice(0, 300), + artists: s.artists.slice(0, 20).map(artist => artist.name?.slice(0, 100)), })), null, 2, diff --git a/lib/catalog/analyzeFullCatalog.ts b/lib/catalog/analyzeFullCatalog.ts index 2ddbfc211..169800588 100644 --- a/lib/catalog/analyzeFullCatalog.ts +++ b/lib/catalog/analyzeFullCatalog.ts @@ -3,36 +3,40 @@ import { type CatalogSongWithArtists } from "@/lib/supabase/catalog_songs/select import { refineResults } from "./refineResults"; const BATCH_SIZE = 100; +const MAX_PAGES_PER_SEARCH = 10; export interface AnalyzeFullCatalogOptions { catalogId: string; criteria: string; + startPage?: number; } /** - * Fetches all songs from a catalog and filters them using AI in parallel batches - * Following Open-Closed Principle: open for extension (custom filtering logic), closed for modification - * - * @param catalog - The catalog to analyze - * @param catalog.catalogId - The ID of the catalog to analyze - * @param catalog.criteria - The criteria to use to filter the songs - * @returns The results of the analysis + * Analyze up to ten 100-track pages, starting at the one-based startPage. + * A nextPage value resumes the search when additional catalog rows remain. */ export async function analyzeFullCatalog({ catalogId, criteria, + startPage = 1, }: AnalyzeFullCatalogOptions): Promise<{ results: CatalogSongWithArtists[]; totalSongs: number; totalPages: number; + nextPage?: number; }> { // Fetch first page to get total count - const firstPage = await selectCatalogSongsWithArtists({ catalogId, limit: BATCH_SIZE, page: 1 }); + const firstPage = await selectCatalogSongsWithArtists({ + catalogId, + limit: BATCH_SIZE, + page: 1, + }); const totalPages = Math.ceil(firstPage.total_count / BATCH_SIZE); const totalSongs = firstPage.total_count; - // Fetch all pages in parallel - const pageNumbers = Array.from({ length: totalPages }, (_, i) => i + 1); + // Fetch one bounded window of pages in parallel + const pageCount = Math.max(0, Math.min(MAX_PAGES_PER_SEARCH, totalPages - startPage + 1)); + const pageNumbers = Array.from({ length: pageCount }, (_, i) => i + startPage); const pagePromises = pageNumbers.map(async pageNum => pageNum === 1 ? firstPage.songs @@ -50,5 +54,6 @@ export async function analyzeFullCatalog({ results, totalSongs, totalPages, + ...(startPage + pageCount <= totalPages ? { nextPage: startPage + pageCount } : {}), }; } diff --git a/lib/mcp/oauth/__tests__/catalogSelectionDescription.test.ts b/lib/mcp/oauth/__tests__/catalogSelectionDescription.test.ts index 38fa44994..91e3fe286 100644 --- a/lib/mcp/oauth/__tests__/catalogSelectionDescription.test.ts +++ b/lib/mcp/oauth/__tests__/catalogSelectionDescription.test.ts @@ -3,16 +3,30 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { registerFullOAuthTools } from "../registerFullOAuthTools"; import { registerGetCatalogSongsTool } from "../../tools/catalogs/registerGetCatalogSongsTool"; -const mocks = vi.hoisted(() => ({ analyze: vi.fn() })); +const mocks = vi.hoisted(() => ({ analyze: vi.fn(), catalogs: vi.fn(), owners: vi.fn() })); vi.mock("@/lib/catalog/analyzeFullCatalog", () => ({ analyzeFullCatalog: mocks.analyze })); -vi.mock("@/lib/mcp/resolveAccountId", () => ({ resolveAccountId: vi.fn() })); +vi.mock("@/lib/mcp/resolveAccountId", () => ({ + resolveAccountId: vi.fn().mockResolvedValue({ accountId: "account", error: null }), +})); +vi.mock("@/lib/catalog/getCatalogOwnerIds", () => ({ + getCatalogOwnerIds: mocks.owners, +})); +vi.mock("@/lib/supabase/account_catalogs/selectAccountCatalogs", () => ({ + selectAccountCatalogs: mocks.catalogs, +})); vi.mock("../../tools", async () => { const { registerGetCatalogSongsTool } = await import( "../../tools/catalogs/registerGetCatalogSongsTool" ); return { registerAllTools: registerGetCatalogSongsTool }; }); -beforeEach(() => vi.clearAllMocks()); +beforeEach(() => { + vi.clearAllMocks(); + mocks.owners.mockImplementation(async id => (id === "account" ? [id, "organization"] : [id])); + mocks.catalogs.mockImplementation(async (owners, { catalogIds }) => + owners.includes("organization") && catalogIds.includes("catalog") ? [{ id: "catalog" }] : [], + ); +}); it.each([false, true])("describes AI selection boundaries with OAuth=%s", oauth => { const registerTool = vi.fn(); @@ -20,31 +34,25 @@ it.each([false, true])("describes AI selection boundaries with OAuth=%s", oauth if (oauth) registerFullOAuthTools(server, vi.fn(), { prepare: vi.fn(), listArtists: vi.fn() }); else registerGetCatalogSongsTool(server); const config = registerTool.mock.calls.find(([name]) => name === "select_catalog_songs")![1]; - expect(config.description).toContain("catalog candidates"); + expect(config.title).toBe("Find Matching Catalog Tracks"); expect(config.description).toContain("AI provider"); - expect(config.description).toContain("ISRCs, song names, artist names, and your criteria"); - expect(config.description).toContain("up to 100 songs per model call"); - expect(config.description).toContain( - "All batches are analyzed before the 1,000-match output cap", - ); - expect(config.description).toContain("catalog order, not relevance rank"); - expect(config.description).toContain("Read-only does not mean free"); - expect(config.description).toContain("Repeated calls can repeat provider work and cost"); - expect(config.description).toContain("billing idempotency is not established"); - expect(config.description).toContain( - "Charges, approval requirements, spending ceilings, and retry handling remain unmeasured or unapproved", - ); + expect(config.description).toContain("track titles, artist names, ISRCs, and your brief"); + expect(config.description).toContain("up to 1,000 tracks per call"); + expect(config.description).toContain("without deducting Recoup credits"); + expect(config.description).toContain("Use nextPage"); expect(config.description).toContain("does not establish licensing clearance"); - expect(config.description).toContain("does not authorize spending or use of a song"); - expect(config.description).not.toMatch(/ALWAYS|MANDATORY|can actually be used/); - expect(Object.keys(config.inputSchema.shape)).toEqual(["catalog_id", "criteria"]); + expect(Object.keys(config.inputSchema.shape)).toEqual(["catalog_id", "criteria", "start_page"]); expect(config.inputSchema.safeParse({ catalog_id: "catalog", criteria: "theme" }).success).toBe( true, ); expect(config.inputSchema.safeParse({ catalog_id: "", criteria: "theme" }).success).toBe(false); expect(config.inputSchema.safeParse({ catalog_id: "catalog", criteria: "" }).success).toBe(false); if (oauth) - expect(config.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + expect(config.annotations).toMatchObject({ + readOnlyHint: true, + destructiveHint: false, + openWorldHint: false, + }); expect(mocks.analyze).not.toHaveBeenCalled(); }); @@ -53,10 +61,32 @@ it("preserves the real registered callback arguments and result envelope", async registerGetCatalogSongsTool({ registerTool } as unknown as McpServer); const response = { results: [{ isrc: "saved-isrc" }], totalSongs: 250, totalPages: 3 }; mocks.analyze.mockResolvedValue(response); - const result = await registerTool.mock.calls[0][2]({ catalog_id: "catalog", criteria: "theme" }); + const result = await registerTool.mock.calls[0][2]( + { catalog_id: "catalog", criteria: "theme", start_page: 11 }, + {}, + ); + expect(mocks.owners).toHaveBeenCalledWith("account"); + expect(mocks.catalogs).toHaveBeenCalledWith(["account", "organization"], { + catalogIds: ["catalog"], + }); expect(mocks.analyze).toHaveBeenCalledExactlyOnceWith({ catalogId: "catalog", criteria: "theme", + startPage: 11, }); expect(result).toEqual({ content: [{ type: "text", text: JSON.stringify(response) }] }); }); + +it("denies an inaccessible catalog before sending a brief to the provider", async () => { + const registerTool = vi.fn(); + registerGetCatalogSongsTool({ registerTool } as unknown as McpServer); + const result = await registerTool.mock.calls[0][2]( + { catalog_id: "foreign", criteria: "theme" }, + {}, + ); + expect(JSON.parse(result.content[0].text)).toEqual({ + success: false, + message: "Catalog access denied.", + }); + expect(mocks.analyze).not.toHaveBeenCalled(); +}); diff --git a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts index 199a2dbdc..e488c90f4 100644 --- a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts +++ b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts @@ -86,8 +86,9 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => { const expectedAnnotations: Record = { list_artists: [true, false, false], get_artist_posts: [true, false, false], - get_scraper_results: [true, false, true], + get_scraper_results: [true, false, false], scrape_artist_socials: [false, true, true], + select_catalog_songs: [true, false, false], get_tasks: [true, false, false], get_youtube_revenue: [true, false, false], search_web: [true, false, true], diff --git a/lib/mcp/oauth/fullOAuthToolPolicy.ts b/lib/mcp/oauth/fullOAuthToolPolicy.ts index 77926a862..e9d45695f 100644 --- a/lib/mcp/oauth/fullOAuthToolPolicy.ts +++ b/lib/mcp/oauth/fullOAuthToolPolicy.ts @@ -38,20 +38,8 @@ export const fullOAuthToolPolicy: Record = { }, list_artists: { readOnly: true, destructive: false, openWorld: false }, get_artist_posts: { readOnly: true, destructive: false, openWorld: false }, - get_scraper_results: { - readOnly: true, - destructive: false, - openWorld: true, - notice: - "Reads public social scrape data by run ID; this lookup is not scoped to the connected account’s runs.", - }, - scrape_artist_socials: { - readOnly: false, - destructive: true, - openWorld: true, - notice: - "Spends account credits: $0.05 per linked profile plus $0.01 per requested post. Confirm before scraping.", - }, + get_scraper_results: { readOnly: true, destructive: false, openWorld: false }, + scrape_artist_socials: { readOnly: false, destructive: true, openWorld: true }, get_artist_socials: { readOnly: true, destructive: false, openWorld: false }, artist_deep_research: { readOnly: true, destructive: false, openWorld: false }, spotify_deep_research: { readOnly: true, destructive: false, openWorld: false }, diff --git a/lib/mcp/oauth/prepareFullOAuthTool.ts b/lib/mcp/oauth/prepareFullOAuthTool.ts index 19d239660..e8993607c 100644 --- a/lib/mcp/oauth/prepareFullOAuthTool.ts +++ b/lib/mcp/oauth/prepareFullOAuthTool.ts @@ -39,14 +39,11 @@ export async function prepareFullOAuthTool( ); if (organizationIds.some(id => !accessible.has(id))) throw new Error("Workspace access denied"); } - if (name === "select_catalog_songs" || name === "insert_catalog_songs") { - const ids = - name === "select_catalog_songs" - ? [z.string().parse(args.catalog_id)] - : z - .array(z.object({ catalog_id: z.string() })) - .parse(args.songs) - .map(song => song.catalog_id); + if (name === "insert_catalog_songs") { + const ids = z + .array(z.object({ catalog_id: z.string() })) + .parse(args.songs) + .map(song => song.catalog_id); const catalogs = await selectAccountCatalogs(await getCatalogOwnerIds(accountId), { catalogIds: ids, }); diff --git a/lib/mcp/tools/artistSocials/__tests__/registerGetScraperResultsTool.test.ts b/lib/mcp/tools/artistSocials/__tests__/registerGetScraperResultsTool.test.ts index be0d6aecc..18b9a9547 100644 --- a/lib/mcp/tools/artistSocials/__tests__/registerGetScraperResultsTool.test.ts +++ b/lib/mcp/tools/artistSocials/__tests__/registerGetScraperResultsTool.test.ts @@ -3,6 +3,11 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { registerGetScraperResultsTool } from "../registerGetScraperResultsTool"; import { getScraperRunResults } from "@/lib/apify/getScraperRunResults"; +import { selectApifyScraperRun } from "@/lib/supabase/apify_scraper_runs/selectApifyScraperRun"; + +vi.mock("@/lib/supabase/apify_scraper_runs/selectApifyScraperRun", () => ({ + selectApifyScraperRun: vi.fn(), +})); vi.mock("@/lib/supabase/serverClient", () => ({ default: {} })); vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); vi.mock("@/lib/apify/getScraperRunResults", () => ({ getScraperRunResults: vi.fn() })); @@ -21,7 +26,10 @@ describe("registerGetScraperResultsTool", () => { let handler: (args: unknown, extra: unknown) => Promise<{ content: Array<{ text: string }> }>; beforeEach(() => { - vi.clearAllMocks(); + vi.resetAllMocks(); + vi.mocked(selectApifyScraperRun).mockResolvedValue([ + { account_id: "acct", origin: "artist", batch_id: "batch" }, + ] as never); const server = { registerTool: vi.fn((name, c, h) => { expect(name).toBe("get_scraper_results"); @@ -41,21 +49,59 @@ describe("registerGetScraperResultsTool", () => { vi.mocked(getScraperRunResults).mockResolvedValue({ status: "SUCCEEDED", dataset_id: "d1", - data: [{ url: "https://x.com/a/status/1" }], + data: [{ url: "https://x.com/a/status/1", likesCount: 4, internalField: "hidden" }], }); const result = await handler({ runId: "r1" }, extra("acct")); expect(getScraperRunResults).toHaveBeenCalledWith("r1"); expect(text(result)).toEqual({ status: "SUCCEEDED", - dataset_id: "d1", - data: [{ url: "https://x.com/a/status/1" }], + data: [{ url: "https://x.com/a/status/1", likesCount: 4 }], + }); + }); + + it("keeps platform links and counts without provider metadata or arbitrary URLs", async () => { + vi.mocked(getScraperRunResults).mockResolvedValue({ + status: "SUCCEEDED", + dataset_id: "internal", + data: [ + { + url: "https://www.youtube.com/watch?v=video-1&secret=private", + profileUrl: "https://example.com/private", + aboutChannelInfo: { numberOfSubscribers: 42, channelLocation: "omitted" }, + latestPosts: [ + { url: "https://www.instagram.com/p/post/", likesCount: 3, caption: "omitted" }, + ], + }, + ], + }); + expect(text(await handler({ runId: "r1" }, extra("acct")))).toEqual({ + status: "SUCCEEDED", + data: [ + { + url: "https://www.youtube.com/watch?v=video-1", + aboutChannelInfo: { numberOfSubscribers: 42 }, + latestPosts: [{ url: "https://www.instagram.com/p/post/", likesCount: 3 }], + }, + ], }); }); it("reports a still-running run without data", async () => { vi.mocked(getScraperRunResults).mockResolvedValue({ status: "RUNNING", dataset_id: "d1" }); const result = await handler({ runId: "r1" }, extra("acct")); - expect(text(result)).toEqual({ status: "RUNNING", dataset_id: "d1" }); + expect(text(result)).toEqual({ status: "RUNNING" }); + }); + + it.each([ + { rows: [] }, + { rows: [{ account_id: "other", origin: "artist", batch_id: "batch" }] }, + { rows: [{ account_id: "acct", origin: "fan", batch_id: "batch" }] }, + { rows: [{ account_id: "acct", origin: "artist", batch_id: null }] }, + ])("denies runs outside the account's artist refreshes (%j)", async ({ rows }) => { + vi.mocked(selectApifyScraperRun).mockResolvedValue(rows as never); + const result = await handler({ runId: "r1" }, extra("acct")); + expect(text(result)).toMatchObject({ success: false }); + expect(getScraperRunResults).not.toHaveBeenCalled(); }); it("requires authentication", async () => { diff --git a/lib/mcp/tools/artistSocials/__tests__/registerScrapeArtistSocialsTool.test.ts b/lib/mcp/tools/artistSocials/__tests__/registerScrapeArtistSocialsTool.test.ts index c6d069e86..73f59f5f2 100644 --- a/lib/mcp/tools/artistSocials/__tests__/registerScrapeArtistSocialsTool.test.ts +++ b/lib/mcp/tools/artistSocials/__tests__/registerScrapeArtistSocialsTool.test.ts @@ -6,6 +6,11 @@ import { selectAccountSocials } from "@/lib/supabase/account_socials/selectAccou import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; import { startArtistSocialsScrape } from "@/lib/artist/startArtistSocialsScrape"; +const redis = vi.hoisted(() => ({ + values: new Map(), + eval: vi.fn(), +})); + vi.mock("@/lib/artists/checkAccountArtistAccess", () => ({ checkAccountArtistAccess: vi.fn() })); vi.mock("@/lib/supabase/account_socials/selectAccountSocials", () => ({ selectAccountSocials: vi.fn(), @@ -13,6 +18,18 @@ vi.mock("@/lib/supabase/account_socials/selectAccountSocials", () => ({ vi.mock("@/lib/credits/checkCreditsAvailable", () => ({ checkCreditsAvailable: vi.fn() })); vi.mock("@/lib/artist/startArtistSocialsScrape", () => ({ startArtistSocialsScrape: vi.fn() })); vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn() })); +vi.mock("ioredis", () => ({ + Redis: class { + eval = redis.eval; + on() {} + async connect() {} + disconnect() {} + async set(key: string, value: string, _ex: string, ttl: number) { + redis.values.set(key, { value, until: Date.now() + ttl * 1000 }); + return "OK"; + } + }, +})); const ARTIST_ID = "660e8400-e29b-41d4-a716-446655440000"; const SOCIALS = [ @@ -35,7 +52,22 @@ describe("registerScrapeArtistSocialsTool", () => { let handler: (args: unknown, extra: unknown) => Promise<{ content: Array<{ text: string }> }>; beforeEach(() => { - vi.clearAllMocks(); + vi.resetAllMocks(); + vi.stubEnv("OAUTH_INDEX_KEY", undefined); + vi.stubEnv("REDIS_URL", "redis://fixture.invalid:6379"); + redis.values.clear(); + redis.eval.mockImplementation(async (_script, keys, quoteKey, lockKey, scope, token) => { + const entry = redis.values.get(quoteKey); + if (keys === 1) { + if (entry?.value === lockKey) redis.values.delete(quoteKey); + return 1; + } + if (!entry || entry.until <= Date.now() || entry.value !== scope) return 0; + if (redis.values.has(lockKey)) return 1; + redis.values.set(lockKey, { value: token, until: Infinity }); + redis.values.delete(quoteKey); + return 2; + }); const server = { registerTool: vi.fn((name, c, h) => { expect(name).toBe("scrape_artist_socials"); @@ -53,9 +85,8 @@ describe("registerScrapeArtistSocialsTool", () => { ]); }); - it("keeps the description to three sentences and states the cost", () => { - const sentences = config.description.split(/(?<=[.!?])\s+/).filter(Boolean); - expect(sentences.length).toBeLessThanOrEqual(3); + it("describes the quoted price and explicit approval", () => { + expect(config.description).toContain("explicit approval"); expect(config.description).toContain("$0.05 per profile plus $0.01 per requested post"); }); @@ -69,14 +100,21 @@ describe("registerScrapeArtistSocialsTool", () => { expect(config.inputSchema.safeParse({}).success).toBe(false); }); - it("gates credits for every linked profile, then starts the scrape for the caller", async () => { - const result = await handler({ artist_account_id: ARTIST_ID, posts: 5 }, extra("acct")); + async function quote(posts?: number) { + const args = { artist_account_id: ARTIST_ID, posts }; + const result = await handler(args, extra("acct")); + return { ...args, approved_quote: text(result).quote as string }; + } + + it("checks the approved maximum and dispatches with the existing per-profile price", async () => { + const result = await handler(await quote(5), extra("acct")); expect(checkAccountArtistAccess).toHaveBeenCalledWith("acct", ARTIST_ID); // (50,000 + 5 × 10,000) × 2 profiles expect(checkCreditsAvailable).toHaveBeenCalledWith({ accountId: "acct", creditsToDeduct: 200_000, }); + expect(redis.eval).toHaveBeenCalledTimes(2); expect(startArtistSocialsScrape).toHaveBeenCalledWith({ accountId: "acct", socials: SOCIALS, @@ -93,6 +131,77 @@ describe("registerScrapeArtistSocialsTool", () => { }); }); + it("quotes the maximum without starting work or charging credits", async () => { + const result = await handler({ artist_account_id: ARTIST_ID, posts: 5 }, extra("acct")); + expect(text(result)).toMatchObject({ + approval_required: true, + profile_count: 2, + maximum_credits: 200_000, + maximum_usd: 0.2, + }); + expect(startArtistSocialsScrape).not.toHaveBeenCalled(); + expect(checkCreditsAvailable).not.toHaveBeenCalled(); + }); + + it("rejects a quote used with different targets, post depth or billing account", async () => { + const approved = await quote(5); + await handler({ ...approved, posts: 6 }, extra("acct")); + await handler(approved, extra("different")); + vi.mocked(selectAccountSocials).mockResolvedValue([ + SOCIALS[0], + { social: { ...SOCIALS[1].social, username: "different" } }, + ] as never); + const result = await handler(approved, extra("acct")); + expect(text(result).success).toBe(false); + expect(checkCreditsAvailable).not.toHaveBeenCalled(); + expect(startArtistSocialsScrape).not.toHaveBeenCalled(); + }); + + it("rejects a replay without starting another provider job", async () => { + const approved = await quote(5); + await Promise.all([handler(approved, extra("acct")), handler(approved, extra("acct"))]); + expect(startArtistSocialsScrape).toHaveBeenCalledOnce(); + }); + + it("serializes separate quotes through the balance check and dispatch", async () => { + const first = await quote(5); + const second = await quote(5); + let finish!: (runs: Awaited>) => void; + let markStarted!: () => void; + const started = new Promise(resolve => { + markStarted = resolve; + }); + vi.mocked(startArtistSocialsScrape).mockImplementationOnce(() => { + markStarted(); + return new Promise(resolve => { + finish = resolve; + }); + }); + const pending = handler(first, extra("acct")); + await started; + const busy = await handler(second, extra("acct")); + expect(text(busy).message).toContain("being started"); + expect(checkCreditsAvailable).toHaveBeenCalledOnce(); + finish([{ runId: "r1", datasetId: null, error: null }]); + await pending; + const next = await handler(second, extra("acct")); + expect(text(next).success).toBe(true); + expect(checkCreditsAvailable).toHaveBeenCalledTimes(2); + }); + + it("expires an unused quote before spending credits", async () => { + const approved = await quote(5); + const now = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 11 * 60 * 1000); + try { + const result = await handler(approved, extra("acct")); + expect(text(result).success).toBe(false); + expect(checkCreditsAvailable).not.toHaveBeenCalled(); + expect(startArtistSocialsScrape).not.toHaveBeenCalled(); + } finally { + now.mockRestore(); + } + }); + it("requires authentication", async () => { const result = await handler({ artist_account_id: ARTIST_ID }, extra()); expect(text(result).success).toBe(false); @@ -123,7 +232,7 @@ describe("registerScrapeArtistSocialsTool", () => { remainingCredits: 10, requiredCredits: 100_000, }); - const result = await handler({ artist_account_id: ARTIST_ID }, extra("acct")); + const result = await handler(await quote(), extra("acct")); expect(text(result).message).toBe("Insufficient credits: 10 remaining, 100000 required"); expect(startArtistSocialsScrape).not.toHaveBeenCalled(); }); @@ -133,7 +242,7 @@ describe("registerScrapeArtistSocialsTool", () => { { runId: null, datasetId: null, error: "Failed to start scrape" }, { runId: null, datasetId: null, error: "Unsupported platform" }, ]); - const result = await handler({ artist_account_id: ARTIST_ID }, extra("acct")); + const result = await handler(await quote(), extra("acct")); expect(text(result)).toEqual({ success: false, message: @@ -143,7 +252,7 @@ describe("registerScrapeArtistSocialsTool", () => { it("returns a redacted error when the scrape throws", async () => { vi.mocked(startArtistSocialsScrape).mockRejectedValue(new Error("apify token bad")); - const result = await handler({ artist_account_id: ARTIST_ID }, extra("acct")); + const result = await handler(await quote(), extra("acct")); expect(text(result)).toEqual({ success: false, message: "Failed to start the artist socials scrape.", diff --git a/lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts b/lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts new file mode 100644 index 000000000..d1a5f1dcc --- /dev/null +++ b/lib/mcp/tools/artistSocials/executeQuotedSocialRefresh.ts @@ -0,0 +1,64 @@ +import { startArtistSocialsScrape } from "@/lib/artist/startArtistSocialsScrape"; +import type { StartArtistSocialsScrapeParams } from "@/lib/artist/startArtistSocialsScrape"; +import type { RunArtistSocialsScrapeResult } from "@/lib/artist/runArtistSocialsScrape"; +import { creditsToUsd } from "@/lib/credits/creditsToUsd"; +import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; +import { socialRefreshQuoteStore } from "./socialRefreshQuoteStore"; + +export type QuotedSocialRefreshResult = + | RunArtistSocialsScrapeResult + | { + kind: "quote"; + token: string; + expiresAt: number; + profileCount: number; + maximumCredits: number; + maximumUsd: number; + } + | { kind: "invalid_quote" } + | { kind: "busy" }; + +/** Validate the approved maximum and consume the quote before dispatching jobs. */ +export async function executeQuotedSocialRefresh( + params: StartArtistSocialsScrapeParams, + artistId: string, + approvedQuote: string | undefined, +): Promise { + const { accountId, socials, posts, costPerProfile } = params; + const profileCount = socials.length; + const maximumCredits = costPerProfile * profileCount; + const targets = socials + .map(({ social }) => JSON.stringify([social?.id, social?.profile_url, social?.username])) + .sort(); + const quote = socialRefreshQuoteStore( + accountId, + JSON.stringify({ artistId, targets, posts, maximumCredits }), + ); + + if (!approvedQuote) { + return { + kind: "quote", + ...(await quote.issue()), + profileCount, + maximumCredits, + maximumUsd: creditsToUsd(maximumCredits), + }; + } + + const claim = await quote.claim(approvedQuote); + if (claim === "invalid") return { kind: "invalid_quote" }; + if (claim === "busy") return { kind: "busy" }; + + try { + const gate = await checkCreditsAvailable({ accountId, creditsToDeduct: maximumCredits }); + if (gate.kind === "insufficient_credits") return gate; + const runs = await startArtistSocialsScrape(params); + return { kind: "started", runs }; + } finally { + try { + await quote.release(approvedQuote); + } catch (error) { + console.error("[social refresh] could not release execution lock", error); + } + } +} diff --git a/lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts b/lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts new file mode 100644 index 000000000..c021c19fe --- /dev/null +++ b/lib/mcp/tools/artistSocials/projectPublicScrapeResults.ts @@ -0,0 +1,123 @@ +interface PublicScrapeItem { + [key: string]: string | number | PublicScrapeItem | PublicScrapeItem[]; +} + +const links = [ + "url", + "profileUrl", + "webVideoUrl", + "postUrl", + "videoUrl", + "channelUrl", + "inputChannelUrl", + "linkedinUrl", + "pageUrl", + "facebookUrl", +]; +const socialHosts = [ + "facebook.com", + "instagram.com", + "linkedin.com", + "threads.com", + "threads.net", + "tiktok.com", + "twitter.com", + "x.com", + "youtube.com", + "youtu.be", +]; +const counts = [ + "followers", + "followersCount", + "followerCount", + "follower_count", + "fans", + "following", + "followingCount", + "postsCount", + "postCount", + "video", + "statusesCount", + "subscribers", + "numberOfSubscribers", + "channelTotalVideos", + "shares", + "viewCount", + "views", + "videoViewCount", + "videoPlayCount", + "playCount", + "likeCount", + "likesCount", + "likes", + "diggCount", + "commentsCount", + "commentCount", + "comments", + "replyCount", + "retweetCount", + "shareCount", + "sharesCount", + "reposts", +]; +const related = [ + "author", + "authorMeta", + "latestPosts", + "posts", + "videos", + "aboutChannelInfo", + "engagement", +]; + +/** Project provider data to public links and aggregate counts used by the social tools. */ +export function projectPublicScrapeResults(items: unknown[]): PublicScrapeItem[] { + return items.flatMap(item => project(item, true)); +} + +function project(item: unknown, includeRelated: boolean): PublicScrapeItem[] { + if (!item || typeof item !== "object" || Array.isArray(item)) return []; + const source = item as Record; + const result: PublicScrapeItem = {}; + + for (const field of links) { + const value = source[field]; + if (typeof value !== "string" || value.length > 2048) continue; + try { + const url = new URL(value); + const socialHost = socialHosts.some( + host => url.hostname === host || url.hostname.endsWith(`.${host}`), + ); + if (url.protocol === "https:" && socialHost && !url.username && !url.password && !url.port) { + const parameters = new URLSearchParams(); + for (const key of ["v", "story_fbid", "id"]) { + const parameter = url.searchParams.get(key); + if (parameter && /^[a-zA-Z0-9_-]{1,64}$/.test(parameter)) parameters.set(key, parameter); + } + url.search = parameters.toString(); + url.hash = ""; + result[field] = url.toString(); + } + } catch { + // Omit malformed provider URLs. + } + } + for (const field of counts) { + const value = source[field]; + if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) + result[field] = value; + } + if (includeRelated) { + for (const field of related) { + const value = source[field]; + if (Array.isArray(value)) { + const projected = value.flatMap(entry => project(entry, false)); + if (projected.length) result[field] = projected; + } else { + const projected = project(value, false); + if (projected.length) result[field] = projected[0]; + } + } + } + return Object.keys(result).length ? [result] : []; +} diff --git a/lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts b/lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts index 0d6d6a4ff..7e31cf263 100644 --- a/lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts +++ b/lib/mcp/tools/artistSocials/registerGetArtistPostsTool.ts @@ -37,8 +37,9 @@ export function registerGetArtistPostsTool(server: McpServer): void { server.registerTool( "get_artist_posts", { + title: "List Saved Artist Social Posts", description: - "List an artist's saved social posts across all linked socials, most recently updated first, with post URL, views, likes, comments and reposts. Posts are saved by scrapes; run scrape_artist_socials first for the latest posts.", + "List saved public post URLs and engagement counts for an artist your connected Recoup account can access. Results are ordered by most recently updated and read from previously collected data.", inputSchema: getArtistPostsSchema, }, async ( diff --git a/lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts b/lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts index 28fe61c3b..c6395d3aa 100644 --- a/lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts +++ b/lib/mcp/tools/artistSocials/registerGetScraperResultsTool.ts @@ -7,6 +7,8 @@ import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; import { getToolResultError } from "@/lib/mcp/getToolResultError"; import { getScraperResultsParamsSchema } from "@/lib/apify/validateGetScraperResultsRequest"; +import { selectApifyScraperRun } from "@/lib/supabase/apify_scraper_runs/selectApifyScraperRun"; +import { projectPublicScrapeResults } from "./projectPublicScrapeResults"; import { getScraperRunResults } from "@/lib/apify/getScraperRunResults"; const getScraperResultsSchema = getScraperResultsParamsSchema.extend({ @@ -18,10 +20,7 @@ const getScraperResultsSchema = getScraperResultsParamsSchema.extend({ type GetScraperResultsArgs = z.infer; /** - * Registers the "get_scraper_results" tool, the MCP counterpart of - * `GET /api/apify/runs/{runId}`. Like the REST route it requires any valid - * credential but is not owner-scoped (chat#1840): datasets are public social - * content and run ids are unguessable. + * Registers the account-scoped MCP lookup for previously started artist refreshes. * * @param server - The MCP server instance to register the tool on. */ @@ -29,8 +28,9 @@ export function registerGetScraperResultsTool(server: McpServer): void { server.registerTool( "get_scraper_results", { + title: "Get Artist Social Refresh 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.", + "Check a social refresh started by your connected Recoup account. Pass a run ID from scrape_artist_socials. When the refresh succeeds, returns available public profile and post links and aggregate engagement counts.", inputSchema: getScraperResultsSchema, }, async ( @@ -45,7 +45,15 @@ export function registerGetScraperResultsTool(server: McpServer): void { if (!accountId) return getToolResultError("Authentication required."); try { - return getToolResultSuccess(await getScraperRunResults(args.runId)); + const [run] = await selectApifyScraperRun({ runId: args.runId }); + if (run?.account_id !== accountId || run.origin !== "artist" || !run.batch_id) { + return getToolResultError("Artist social refresh run not found."); + } + const { status, data } = await getScraperRunResults(args.runId); + return getToolResultSuccess({ + status, + ...(data ? { data: projectPublicScrapeResults(data) } : {}), + }); } catch (err) { console.error("[get_scraper_results] failed:", err); return getToolResultError("Failed to read the scrape run."); diff --git a/lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts b/lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts index 317fc8112..c3ba1df4d 100644 --- a/lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts +++ b/lib/mcp/tools/artistSocials/registerScrapeArtistSocialsTool.ts @@ -7,9 +7,17 @@ import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; import { getToolResultError } from "@/lib/mcp/getToolResultError"; import { artistSocialsScrapeBodySchema } from "@/lib/artist/validateArtistSocialsScrapeBody"; +import { executeQuotedSocialRefresh } from "./executeQuotedSocialRefresh"; import { runArtistSocialsScrape } from "@/lib/artist/runArtistSocialsScrape"; const scrapeArtistSocialsSchema = artistSocialsScrapeBodySchema.extend({ + approved_quote: z + .string() + .uuid() + .optional() + .describe( + "Omit to preview the maximum charge. Pass the returned quote only after the user explicitly approves that amount.", + ), artist_account_id: artistSocialsScrapeBodySchema.shape.artist_account_id.describe( "The artist account ID whose linked social profiles should be scraped.", ), @@ -21,20 +29,17 @@ const scrapeArtistSocialsSchema = artistSocialsScrapeBodySchema.extend({ type ScrapeArtistSocialsArgs = z.infer; /** - * Registers the "scrape_artist_socials" tool, the MCP counterpart of - * `POST /api/artist/socials/scrape`. Starts a fresh scrape of every social - * profile linked to the artist and returns one Apify run per profile; read - * each run with `get_scraper_results`. Costs credits per profile started. - * - * @param server - The MCP server instance to register the tool on. + * Register the two-step MCP social refresh. Use get_scraper_results to read the returned runs. */ export function registerScrapeArtistSocialsTool(server: McpServer): void { server.registerTool( "scrape_artist_socials", { + title: "Refresh Artist Social Profiles", description: - "Start a fresh scrape of every social profile linked to an artist (profile stats and recent posts), costing $0.05 per profile plus $0.01 per requested post. Returns one run per profile; pass each runId to get_scraper_results to check status and read the scraped data. Scraped posts are also saved and can be listed later with get_artist_posts.", + "Refresh public profile stats and recent posts for an artist you can access. The first call quotes the maximum at $0.05 per profile plus $0.01 per requested post. After explicit approval, pass the quote to start the refresh and receive run IDs; Recoup saves collected posts and charges only for profiles whose jobs start.", inputSchema: scrapeArtistSocialsSchema, + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, }, async ( args: ScrapeArtistSocialsArgs, @@ -52,7 +57,28 @@ export function registerScrapeArtistSocialsTool(server: McpServer): void { accountId, artistAccountId: args.artist_account_id, posts: args.posts, + execute: params => + executeQuotedSocialRefresh(params, args.artist_account_id, args.approved_quote), }); + if (result.kind === "quote") { + return getToolResultSuccess({ + success: true, + approval_required: true, + quote: result.token, + expires_at: new Date(result.expiresAt).toISOString(), + profile_count: result.profileCount, + maximum_credits: result.maximumCredits, + maximum_usd: result.maximumUsd, + }); + } + if (result.kind === "invalid_quote") { + return getToolResultError("This quote expired, was already used, or its scope changed."); + } + if (result.kind === "busy") { + return getToolResultError( + "A social refresh is being started for this account. Wait for it to finish before retrying this quote.", + ); + } if (result.kind === "forbidden") { return getToolResultError("Access denied to specified artist_account_id"); } diff --git a/lib/mcp/tools/artistSocials/socialRefreshQuoteStore.ts b/lib/mcp/tools/artistSocials/socialRefreshQuoteStore.ts new file mode 100644 index 000000000..865e35fbf --- /dev/null +++ b/lib/mcp/tools/artistSocials/socialRefreshQuoteStore.ts @@ -0,0 +1,75 @@ +import { randomUUID } from "node:crypto"; +import { Redis } from "ioredis"; + +const QUOTE_TTL_SECONDS = 600; +// Longer than the MCP route's 800-second maximum duration. +const EXECUTION_TTL_SECONDS = 900; +const claim = ` + if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end + if not redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3], 'NX') then return 1 end + redis.call('DEL', KEYS[1]) + return 2 +`; +const release = ` + if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end + return 0 +`; + +/** Issue and consume short-lived, account-bound quotes in Redis. */ +export function socialRefreshQuoteStore(accountId: string, scope: string) { + const prefix = `recoup:mcp:social-refresh:{${accountId}}`; + const lockKey = `${prefix}:execution`; + + async function withRedis(action: (redis: Redis) => Promise) { + const url = process.env.REDIS_URL; + if (!url) throw new Error("Social refresh quote storage unavailable"); + const redis = new Redis(url, { + lazyConnect: true, + connectTimeout: 3000, + commandTimeout: 5000, + maxRetriesPerRequest: 0, + retryStrategy: () => null, + }); + redis.on("error", () => console.error("[social refresh] quote storage failed")); + try { + await redis.connect(); + return await action(redis); + } finally { + redis.disconnect(); + } + } + + return { + issue: () => + withRedis(async redis => { + const token = randomUUID(); + const expiresAt = Date.now() + QUOTE_TTL_SECONDS * 1000; + const result = await redis.set( + `${prefix}:quote:${token}`, + scope, + "EX", + QUOTE_TTL_SECONDS, + "NX", + ); + if (result !== "OK") throw new Error("Could not save social refresh quote"); + return { token, expiresAt }; + }), + claim: (token: string) => + withRedis(async redis => { + const result = await redis.eval( + claim, + 2, + `${prefix}:quote:${token}`, + lockKey, + scope, + token, + EXECUTION_TTL_SECONDS, + ); + if (result === 0) return "invalid"; + if (result === 1) return "busy"; + if (result === 2) return "claimed"; + throw new Error("Could not claim social refresh quote"); + }), + release: (token: string) => withRedis(redis => redis.eval(release, 1, lockKey, token)), + }; +} diff --git a/lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts b/lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts index 708904757..945f04dee 100644 --- a/lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts +++ b/lib/mcp/tools/catalogs/registerGetCatalogSongsTool.ts @@ -1,11 +1,27 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +import type { McpAuthInfo } from "@/lib/mcp/verifyApiKey"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { getCatalogOwnerIds } from "@/lib/catalog/getCatalogOwnerIds"; +import { selectAccountCatalogs } from "@/lib/supabase/account_catalogs/selectAccountCatalogs"; import { analyzeFullCatalog } from "@/lib/catalog/analyzeFullCatalog"; -import { - getCatalogSongsQuerySchema, - type GetCatalogSongsQuery, -} from "@/lib/catalog/validateGetCatalogSongsQuery"; +import { getCatalogSongsQuerySchema } from "@/lib/catalog/validateGetCatalogSongsQuery"; import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +const catalogSearchSchema = getCatalogSongsQuerySchema.extend({ + criteria: getCatalogSongsQuerySchema.shape.criteria.max(2000), + start_page: z + .number() + .int() + .positive() + .max(10_000_000) + .optional() + .describe( + "Start at page 1 or use nextPage returned by the previous search. Each page covers up to 100 tracks.", + ), +}); + /** * Registers the "select_catalog_songs" tool on the MCP server. * Use this tool to find ACTUAL SONGS from the available catalog for any playlist or music recommendation request. @@ -16,22 +32,35 @@ export function registerGetCatalogSongsTool(server: McpServer): void { server.registerTool( "select_catalog_songs", { - description: `Find catalog candidates matching your criteria through AI batch analysis. Get catalog_id from select_catalogs. - -For a nonempty catalog, sends ISRCs, song names, artist names, and your criteria to an AI provider in batches of up to 100 songs per model call. All batches are analyzed before the 1,000-match output cap; results preserve catalog order, not relevance rank. Empty catalogs return without model analysis. - -Read-only does not mean free. Repeated calls can repeat provider work and cost; billing idempotency is not established. Charges, approval requirements, spending ceilings, and retry handling remain unmeasured or unapproved for this operation. This description does not authorize spending or use of a song. - -Catalog presence does not establish licensing clearance or permission for a proposed use.`, - inputSchema: getCatalogSongsQuerySchema, + title: "Find Matching Catalog Tracks", + description: + "Find tracks that match a brief in a catalog your connected Recoup account can access. Recoup sends track titles, artist names, ISRCs, and your brief to an AI provider and analyzes up to 1,000 tracks per call without deducting Recoup credits. Results follow catalog order. Use nextPage to continue a larger catalog. A match does not establish licensing clearance.", + inputSchema: catalogSearchSchema, }, - async (args: GetCatalogSongsQuery) => { - const response = await analyzeFullCatalog({ - catalogId: args.catalog_id, - criteria: args.criteria, + async (args, extra) => { + const { accountId, error } = await resolveAccountId({ + authInfo: extra.authInfo as McpAuthInfo | undefined, + accountIdOverride: undefined, }); - - return getToolResultSuccess(response); + if (!accountId) return getToolResultError(error ?? "Authentication required."); + try { + const catalogs = await selectAccountCatalogs(await getCatalogOwnerIds(accountId), { + catalogIds: [args.catalog_id], + }); + if (!catalogs.some(catalog => catalog.id === args.catalog_id)) { + return getToolResultError("Catalog access denied."); + } + return getToolResultSuccess( + await analyzeFullCatalog({ + catalogId: args.catalog_id, + criteria: args.criteria, + startPage: args.start_page ?? 1, + }), + ); + } catch (error) { + console.error("[select_catalog_songs] failed:", error); + return getToolResultError("Could not search the catalog."); + } }, ); }