Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 20 additions & 17 deletions lib/artist/runArtistSocialsScrape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result> {
/** 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<Result>;
}

export type RunArtistSocialsScrapeResult =
Expand All @@ -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<Result = never>({
accountId,
artistAccountId,
posts,
}: RunArtistSocialsScrapeParams): Promise<RunArtistSocialsScrapeResult> {
execute,
}: RunArtistSocialsScrapeParams<Result>): Promise<RunArtistSocialsScrapeResult | Result> {
if (!(await checkAccountArtistAccess(accountId, artistAccountId))) {
return { kind: "forbidden" };
}
Expand All @@ -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);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

const gate = await checkCreditsAvailable({
accountId,
creditsToDeduct: costPerProfile * socials.length,
Expand All @@ -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 };
}
48 changes: 30 additions & 18 deletions lib/catalog/__tests__/analyzeFullCatalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof generateObject>
>;
});
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 () => {
Expand Down
6 changes: 4 additions & 2 deletions lib/catalog/analyzeCatalogBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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,
Expand Down
25 changes: 15 additions & 10 deletions lib/catalog/analyzeFullCatalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/analyzeFullCatalog.ts, line 11:

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

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

}

/**
* 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
Expand All @@ -50,5 +54,6 @@ export async function analyzeFullCatalog({
results,
totalSongs,
totalPages,
...(startPage + pageCount <= totalPages ? { nextPage: startPage + pageCount } : {}),
};
}
72 changes: 51 additions & 21 deletions lib/mcp/oauth/__tests__/catalogSelectionDescription.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,56 @@ 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();
const server = { registerTool } as unknown as McpServer;
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();
});

Expand All @@ -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();
});
3 changes: 2 additions & 1 deletion lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,9 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => {
const expectedAnnotations: Record<string, [boolean, boolean, boolean]> = {
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],
Expand Down
16 changes: 2 additions & 14 deletions lib/mcp/oauth/fullOAuthToolPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,8 @@ export const fullOAuthToolPolicy: Record<string, ToolPolicy> = {
},
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 },
Expand Down
13 changes: 5 additions & 8 deletions lib/mcp/oauth/prepareFullOAuthTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
Expand Down
Loading
Loading