From 39db5107db3acbd2f209e50a56a44b0af6f7571f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:49:26 +0000 Subject: [PATCH] feat(mcp): get_published_posts and get_published_post_stats tools Extract getPosts and getPostStats from the GET /api/posts and GET /api/posts/{id}/stats handlers so REST and MCP share one read each. Register both tools, classify them in the full OAuth policy, the OAuth tool inventory and the qualification map. Tracking: recoupable/app#2399 Contract: recoupable/docs#40 Co-Authored-By: Claude Opus 5.5 --- docs/mcp-oauth-tool-qualification.md | 2 + .../oauth/__tests__/fullOAuthCatalog.test.ts | 2 +- lib/mcp/oauth/fullOAuthToolPolicy.ts | 6 + lib/mcp/tools/index.ts | 2 + .../registerGetPublishedPostStatsTool.test.ts | 98 ++++++++++ .../registerGetPublishedPostsTool.test.ts | 104 ++++++++++ lib/mcp/tools/posts/index.ts | 13 ++ .../registerGetPublishedPostStatsTool.ts | 58 ++++++ .../posts/registerGetPublishedPostsTool.ts | 82 ++++++++ lib/publishing/__tests__/getPosts.test.ts | 55 ++++++ lib/publishing/getPosts.ts | 40 ++++ lib/publishing/getPostsHandler.ts | 10 +- .../stats/__tests__/getPostStats.test.ts | 181 ++++++++++++++++++ .../getPostStatsHandler.credits.test.ts | 27 +-- .../__tests__/getPostStatsHandler.test.ts | 4 +- .../getPostStatsHandler.video.test.ts | 8 +- lib/publishing/stats/getPostStats.ts | 109 +++++++++++ lib/publishing/stats/getPostStatsHandler.ts | 78 ++------ scripts/mcp-oauth/tool-policy.json | 19 ++ 19 files changed, 810 insertions(+), 88 deletions(-) create mode 100644 lib/mcp/tools/posts/__tests__/registerGetPublishedPostStatsTool.test.ts create mode 100644 lib/mcp/tools/posts/__tests__/registerGetPublishedPostsTool.test.ts create mode 100644 lib/mcp/tools/posts/index.ts create mode 100644 lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts create mode 100644 lib/mcp/tools/posts/registerGetPublishedPostsTool.ts create mode 100644 lib/publishing/__tests__/getPosts.test.ts create mode 100644 lib/publishing/getPosts.ts create mode 100644 lib/publishing/stats/__tests__/getPostStats.test.ts create mode 100644 lib/publishing/stats/getPostStats.ts diff --git a/docs/mcp-oauth-tool-qualification.md b/docs/mcp-oauth-tool-qualification.md index ce6744cb4..12903bdef 100644 --- a/docs/mcp-oauth-tool-qualification.md +++ b/docs/mcp-oauth-tool-qualification.md @@ -59,6 +59,8 @@ Each source link identifies the registration callback or shared domain/executor | `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) | +| `get_published_posts` | RO | Read the credential account's posts from `scheduled_posts`, newest first; optional artist filter through the artist gate | No credit charge at this boundary | No outbound recipient; authenticated response only | Repeat read | [source](../lib/publishing/getPosts.ts) | +| `get_published_post_stats` | RO | Read one published LinkedIn company-page post's analytics through the connection that published it; post account access gate | Credit gate before the LinkedIn read; $0.001 charged only after a successful read | LinkedIn via Composio proxy; no message recipient | Each repeat is a new paid read; no wrapper idempotency | [source](../lib/publishing/stats/getPostStats.ts) | | `set_daily_email_status` | W | Upsert daily email active flag | Future delivery cost not qualified | Connected account daily-email preference; not arbitrary recipient permission | Upsert flag; downstream email retry behavior unknown | [source](../lib/mcp/tools/pulse/registerUpdatePulseTool.ts) | | `create_task` | W | Create task/schedule under resolved account | Future task execution cost unknown | Future effects depend on task contents; not qualified | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/tasks/registerCreateTaskTool.ts) | | `update_task` | W | Exact delegated task owner before shared update domain | Unknown: no per-call quote/ceiling established at this boundary | Future task effects not qualified | Unknown: no wrapper idempotency/accepted-work guarantee | [source](../lib/mcp/tools/tasks/registerUpdateTaskTool.ts) | diff --git a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts index 2f644dfd1..99a45f2dd 100644 --- a/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts +++ b/lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts @@ -59,7 +59,7 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => { ].sort(), ); for (const tool of tools) expect(tool.inputSchema.properties).not.toHaveProperty("account_id"); - expect(tools).toHaveLength(92); + expect(tools).toHaveLength(94); expect(tools.map(tool => tool.name)).toContain("get_artist_socials"); expect(tools.map(tool => tool.name)).not.toContain("artist_deep_research"); expect(tools.map(tool => tool.name)).not.toContain("spotify_deep_research"); diff --git a/lib/mcp/oauth/fullOAuthToolPolicy.ts b/lib/mcp/oauth/fullOAuthToolPolicy.ts index a31fff5df..110e6ff1a 100644 --- a/lib/mcp/oauth/fullOAuthToolPolicy.ts +++ b/lib/mcp/oauth/fullOAuthToolPolicy.ts @@ -28,6 +28,12 @@ export const fullOAuthToolPolicy: Record = { readOnly: true, notice: "Reads a run started by scrape_artist_socials. Scraped data is public social content.", }, + get_published_posts: { readOnly: true }, + get_published_post_stats: { + readOnly: true, + notice: + "Spends account credits: $0.001 per successful read. Read each post once and keep the result.", + }, artist_deep_research: { readOnly: true }, spotify_deep_research: { readOnly: true }, get_spotify_album: { readOnly: true }, diff --git a/lib/mcp/tools/index.ts b/lib/mcp/tools/index.ts index 31bbad08d..5b7751eef 100644 --- a/lib/mcp/tools/index.ts +++ b/lib/mcp/tools/index.ts @@ -15,6 +15,7 @@ import { registerAllSpotifyTools } from "./spotify"; import { registerContactTeamTool } from "./registerContactTeamTool"; import { registerUpdateAccountInfoTool } from "./registerUpdateAccountInfoTool"; import { registerAllArtistSocialsTools } from "./artistSocials"; +import { registerAllPostsTools } from "./posts"; import { registerAllSearchTools } from "./search"; import { registerWebDeepResearchTool } from "./registerWebDeepResearchTool"; import { registerArtistDeepResearchTool } from "./registerArtistDeepResearchTool"; @@ -50,6 +51,7 @@ export const registerAllTools = (server: McpServer): void => { registerAllFileTools(server); registerAllFlamingoTools(server); registerAllImageTools(server); + registerAllPostsTools(server); registerAllPulseTools(server); registerAllSearchTools(server); registerAllSora2Tools(server); diff --git a/lib/mcp/tools/posts/__tests__/registerGetPublishedPostStatsTool.test.ts b/lib/mcp/tools/posts/__tests__/registerGetPublishedPostStatsTool.test.ts new file mode 100644 index 000000000..8844c5c29 --- /dev/null +++ b/lib/mcp/tools/posts/__tests__/registerGetPublishedPostStatsTool.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { registerGetPublishedPostStatsTool } from "../registerGetPublishedPostStatsTool"; +import { getPostStats } from "@/lib/publishing/stats/getPostStats"; + +vi.mock("@/lib/publishing/stats/getPostStats", () => ({ getPostStats: vi.fn() })); +vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn() })); + +const POST_ID = "3f1c2b7e-8a4d-4c1e-9b2a-6d5e4f3a2b1c"; +const STATS = { post_id: POST_ID, platform: "linkedin", impressions: 900 }; +const extra = (accountId?: string) => + ({ + authInfo: accountId + ? { token: "t", clientId: accountId, scopes: [], extra: { accountId, orgId: null } } + : undefined, + }) as never; +const text = (result: { content: Array<{ text: string }> }) => JSON.parse(result.content[0].text); + +describe("registerGetPublishedPostStatsTool", () => { + let config: { + description: string; + inputSchema: { safeParse: (v: unknown) => { success: boolean }; shape: object }; + }; + let handler: (args: unknown, extra: unknown) => Promise<{ content: Array<{ text: string }> }>; + + beforeEach(() => { + vi.clearAllMocks(); + const server = { + registerTool: vi.fn((name, c, h) => { + expect(name).toBe("get_published_post_stats"); + config = c; + handler = h; + }), + } as unknown as McpServer; + registerGetPublishedPostStatsTool(server); + vi.mocked(getPostStats).mockResolvedValue({ kind: "ok", stats: STATS } as never); + }); + + it("keeps the description to three sentences and states the cost and the LinkedIn limit", () => { + const sentences = config.description.split(/(?<=[.!?])\s+/).filter(Boolean); + expect(sentences.length).toBeLessThanOrEqual(3); + expect(config.description).toContain("$0.001"); + expect(config.description).toContain("LinkedIn company-page"); + }); + + it("takes only a uuid id", () => { + expect(config.inputSchema.shape).not.toHaveProperty("account_id"); + expect(config.inputSchema.safeParse({ id: POST_ID }).success).toBe(true); + expect(config.inputSchema.safeParse({ id: "not-a-uuid" }).success).toBe(false); + expect(config.inputSchema.safeParse({}).success).toBe(false); + }); + + it("reads the stats for the caller and returns the REST envelope", async () => { + const result = await handler({ id: POST_ID }, extra("acct")); + expect(getPostStats).toHaveBeenCalledWith({ accountId: "acct", postId: POST_ID }); + expect(text(result)).toEqual({ status: "success", stats: STATS }); + }); + + it("returns a rejection's REST message as a tool error", async () => { + vi.mocked(getPostStats).mockResolvedValue({ + kind: "rejected", + status: 422, + message: "Stats are not available for youtube posts yet", + }); + expect(text(await handler({ id: POST_ID }, extra("acct")))).toEqual({ + success: false, + message: "Stats are not available for youtube posts yet", + }); + }); + + it("reports a credit shortfall", async () => { + vi.mocked(getPostStats).mockResolvedValue({ + kind: "insufficient_credits", + remainingCredits: 10, + requiredCredits: 1000, + }); + expect(text(await handler({ id: POST_ID }, extra("acct")))).toEqual({ + success: false, + message: "Insufficient credits: 10 remaining, 1000 required", + }); + }); + + it("requires authentication", async () => { + const result = await handler({ id: POST_ID }, extra()); + expect(text(result).success).toBe(false); + expect(getPostStats).not.toHaveBeenCalled(); + }); + + it("returns a generic tool error when the read throws", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(getPostStats).mockRejectedValue(new Error("db down")); + expect(text(await handler({ id: POST_ID }, extra("acct")))).toEqual({ + success: false, + message: "Failed to read post stats.", + }); + spy.mockRestore(); + }); +}); diff --git a/lib/mcp/tools/posts/__tests__/registerGetPublishedPostsTool.test.ts b/lib/mcp/tools/posts/__tests__/registerGetPublishedPostsTool.test.ts new file mode 100644 index 000000000..4b937b7ee --- /dev/null +++ b/lib/mcp/tools/posts/__tests__/registerGetPublishedPostsTool.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { registerGetPublishedPostsTool } from "../registerGetPublishedPostsTool"; +import { getPosts } from "@/lib/publishing/getPosts"; + +vi.mock("@/lib/publishing/getPosts", () => ({ getPosts: vi.fn() })); +vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn() })); + +const ARTIST_ID = "660e8400-e29b-41d4-a716-446655440000"; +const POST = { id: "3f1c2b7e-8a4d-4c1e-9b2a-6d5e4f3a2b1c", platform: "linkedin" }; +const extra = (accountId?: string) => + ({ + authInfo: accountId + ? { token: "t", clientId: accountId, scopes: [], extra: { accountId, orgId: null } } + : undefined, + }) as never; +const text = (result: { content: Array<{ text: string }> }) => JSON.parse(result.content[0].text); + +describe("registerGetPublishedPostsTool", () => { + let config: { + description: string; + inputSchema: { safeParse: (v: unknown) => { success: boolean }; shape: object }; + }; + let handler: (args: unknown, extra: unknown) => Promise<{ content: Array<{ text: string }> }>; + + beforeEach(() => { + vi.clearAllMocks(); + const server = { + registerTool: vi.fn((name, c, h) => { + expect(name).toBe("get_published_posts"); + config = c; + handler = h; + }), + } as unknown as McpServer; + registerGetPublishedPostsTool(server); + vi.mocked(getPosts).mockResolvedValue([POST] as never); + }); + + it("says it is free, separates itself from scraped posts and points at the stats tool", () => { + expect(config.description).toContain("get_published_post_stats"); + expect(config.description).toContain("get_artist_posts"); + expect(config.description).not.toContain("$"); + }); + + it("takes no account_id and reuses the REST limits", () => { + expect(config.inputSchema.shape).not.toHaveProperty("account_id"); + expect(config.inputSchema.safeParse({}).success).toBe(true); + expect(config.inputSchema.safeParse({ platform: "linkedin", limit: 50 }).success).toBe(true); + expect(config.inputSchema.safeParse({ limit: 51 }).success).toBe(false); + expect(config.inputSchema.safeParse({ platform: "myspace" }).success).toBe(false); + expect(config.inputSchema.safeParse({ status: "lost" }).success).toBe(false); + expect(config.inputSchema.safeParse({ artist_account_id: "nope" }).success).toBe(false); + }); + + it("lists the caller's posts with REST defaults and the REST envelope", async () => { + const result = await handler({}, extra("acct")); + expect(getPosts).toHaveBeenCalledWith({ + accountId: "acct", + artistAccountId: undefined, + status: undefined, + platform: undefined, + limit: 20, + offset: 0, + }); + expect(text(result)).toEqual({ status: "success", posts: [POST] }); + }); + + it("passes every filter through", async () => { + await handler( + { + artist_account_id: ARTIST_ID, + status: "posted", + platform: "linkedin", + limit: 7, + offset: 14, + }, + extra("acct"), + ); + expect(getPosts).toHaveBeenCalledWith({ + accountId: "acct", + artistAccountId: ARTIST_ID, + status: "posted", + platform: "linkedin", + limit: 7, + offset: 14, + }); + }); + + it("requires authentication", async () => { + const result = await handler({}, extra()); + expect(text(result).success).toBe(false); + expect(getPosts).not.toHaveBeenCalled(); + }); + + it("returns a tool error when the read fails", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(getPosts).mockRejectedValue(new Error("db down")); + expect(text(await handler({}, extra("acct")))).toEqual({ + success: false, + message: "Failed to list published posts.", + }); + spy.mockRestore(); + }); +}); diff --git a/lib/mcp/tools/posts/index.ts b/lib/mcp/tools/posts/index.ts new file mode 100644 index 000000000..80df0e640 --- /dev/null +++ b/lib/mcp/tools/posts/index.ts @@ -0,0 +1,13 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { registerGetPublishedPostsTool } from "./registerGetPublishedPostsTool"; +import { registerGetPublishedPostStatsTool } from "./registerGetPublishedPostStatsTool"; + +/** + * Registers the published posts MCP tools on the server. + * + * @param server - The MCP server instance to register tools on. + */ +export const registerAllPostsTools = (server: McpServer): void => { + registerGetPublishedPostsTool(server); + registerGetPublishedPostStatsTool(server); +}; diff --git a/lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts b/lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts new file mode 100644 index 000000000..e4d534b97 --- /dev/null +++ b/lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts @@ -0,0 +1,58 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; +import type { ServerRequest, ServerNotification } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import type { McpAuthInfo } from "@/lib/mcp/verifyApiKey"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { getPostStats } from "@/lib/publishing/stats/getPostStats"; + +const getPublishedPostStatsSchema = z.object({ + id: z.string().uuid().describe("The post id, from get_published_posts."), +}); + +type GetPublishedPostStatsArgs = z.infer; + +/** + * Registers the "get_published_post_stats" tool, the MCP counterpart of + * `GET /api/posts/{id}/stats`: a published post's platform analytics, read + * live. Each successful read costs $0.001. + * + * @param server - The MCP server instance to register the tool on. + */ +export function registerGetPublishedPostStatsTool(server: McpServer): void { + server.registerTool( + "get_published_post_stats", + { + description: + "Read a published post's live analytics (impressions, unique impressions, clicks, likes, comments, shares, engagement, and video views, viewers and watch time) for a post id from get_published_posts. Only published LinkedIn company-page posts have stats. Each successful read costs $0.001, so keep the result rather than polling.", + inputSchema: getPublishedPostStatsSchema, + }, + async ( + args: GetPublishedPostStatsArgs, + extra: RequestHandlerExtra, + ) => { + const { accountId, error } = await resolveAccountId({ + authInfo: extra.authInfo as McpAuthInfo | undefined, + accountIdOverride: undefined, + }); + if (error) return getToolResultError(error); + if (!accountId) return getToolResultError("Authentication required."); + + try { + const result = await getPostStats({ accountId, postId: args.id }); + if (result.kind === "rejected") return getToolResultError(result.message); + if (result.kind === "insufficient_credits") { + return getToolResultError( + `Insufficient credits: ${result.remainingCredits} remaining, ${result.requiredCredits} required`, + ); + } + return getToolResultSuccess({ status: "success", stats: result.stats }); + } catch (err) { + console.error("[get_published_post_stats] failed:", err); + return getToolResultError("Failed to read post stats."); + } + }, + ); +} diff --git a/lib/mcp/tools/posts/registerGetPublishedPostsTool.ts b/lib/mcp/tools/posts/registerGetPublishedPostsTool.ts new file mode 100644 index 000000000..46a5c4295 --- /dev/null +++ b/lib/mcp/tools/posts/registerGetPublishedPostsTool.ts @@ -0,0 +1,82 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; +import type { ServerRequest, ServerNotification } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import type { McpAuthInfo } from "@/lib/mcp/verifyApiKey"; +import { resolveAccountId } from "@/lib/mcp/resolveAccountId"; +import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess"; +import { getToolResultError } from "@/lib/mcp/getToolResultError"; +import { getPostsQuerySchema } from "@/lib/publishing/validateGetPostsQuery"; +import { POST_PLATFORMS, POST_STATUSES } from "@/lib/publishing/const"; +import { getPosts } from "@/lib/publishing/getPosts"; + +// Plain numeric fields keep the published JSON schema typed; the REST query +// schema then applies the same defaults (limit 20, offset 0) and cap (50). +// No account_id: the account always comes from the credential. +const getPublishedPostsSchema = z.object({ + artist_account_id: z + .string() + .uuid() + .optional() + .describe("Only posts published for this artist account."), + platform: z.enum(POST_PLATFORMS).optional().describe("Only posts on this platform."), + status: z + .enum(POST_STATUSES) + .optional() + .describe("Only posts in this status; published posts are `posted`."), + limit: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe("Posts to return (default 20, max 50)."), + offset: z.number().int().min(0).optional().describe("Posts to skip, for paging (default 0)."), +}); + +type GetPublishedPostsArgs = z.infer; + +/** + * Registers the "get_published_posts" tool, the MCP counterpart of + * `GET /api/posts`: the account's posts that Recoup published or scheduled, + * newest first. Each post's id feeds `get_published_post_stats`. + * + * @param server - The MCP server instance to register the tool on. + */ +export function registerGetPublishedPostsTool(server: McpServer): void { + server.registerTool( + "get_published_posts", + { + description: + "List the posts Recoup published or scheduled for your account, newest first, with each post's id, platform, status, post_url and publish time. Pass a post's id to get_published_post_stats for its analytics. For scraped posts from an artist's social profiles, use get_artist_posts instead.", + inputSchema: getPublishedPostsSchema, + }, + async ( + args: GetPublishedPostsArgs, + extra: RequestHandlerExtra, + ) => { + const { accountId, error } = await resolveAccountId({ + authInfo: extra.authInfo as McpAuthInfo | undefined, + accountIdOverride: undefined, + }); + if (error) return getToolResultError(error); + if (!accountId) return getToolResultError("Authentication required."); + + try { + const query = getPostsQuerySchema.parse(args); + const posts = await getPosts({ + accountId, + artistAccountId: query.artist_account_id, + status: query.status, + platform: query.platform, + limit: query.limit, + offset: query.offset, + }); + return getToolResultSuccess({ status: "success", posts }); + } catch (err) { + console.error("[get_published_posts] failed:", err); + return getToolResultError("Failed to list published posts."); + } + }, + ); +} diff --git a/lib/publishing/__tests__/getPosts.test.ts b/lib/publishing/__tests__/getPosts.test.ts new file mode 100644 index 000000000..b1f92e3df --- /dev/null +++ b/lib/publishing/__tests__/getPosts.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { getPosts } from "../getPosts"; +import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; + +vi.mock("@/lib/supabase/scheduled_posts/selectScheduledPosts", () => ({ + selectScheduledPosts: vi.fn(), +})); + +const accountId = "550e8400-e29b-41d4-a716-446655440000"; +const artistId = "660e8400-e29b-41d4-a716-446655440000"; +const row = { + id: "3f1c2b7e-8a4d-4c1e-9b2a-6d5e4f3a2b1c", + account_id: accountId, + artist_account_id: artistId, + platform: "linkedin", + status: "posted", + post_url: "https://www.linkedin.com/feed/update/urn:li:ugcPost:77/", + workflow_run_id: "wrun_internal", + created_by_account_id: accountId, +}; + +describe("getPosts", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(selectScheduledPosts).mockResolvedValue([row] as never); + }); + + it("reads the account's posts with every filter and maps them to the public shape", async () => { + const posts = await getPosts({ + accountId, + artistAccountId: artistId, + status: "posted", + platform: "linkedin", + limit: 5, + offset: 10, + }); + expect(selectScheduledPosts).toHaveBeenCalledWith({ + accountId, + artistAccountId: artistId, + status: "posted", + platform: "linkedin", + limit: 5, + offset: 10, + }); + expect(posts).toHaveLength(1); + expect(posts[0]).toMatchObject({ id: row.id, platform: "linkedin", post_url: row.post_url }); + expect(posts[0]).not.toHaveProperty("workflow_run_id"); + expect(posts[0]).not.toHaveProperty("created_by_account_id"); + }); + + it("propagates database errors to the caller", async () => { + vi.mocked(selectScheduledPosts).mockRejectedValue(new Error("db down")); + await expect(getPosts({ accountId, limit: 20, offset: 0 })).rejects.toThrow("db down"); + }); +}); diff --git a/lib/publishing/getPosts.ts b/lib/publishing/getPosts.ts new file mode 100644 index 000000000..e8f5d5fe8 --- /dev/null +++ b/lib/publishing/getPosts.ts @@ -0,0 +1,40 @@ +import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; +import { toPost } from "@/lib/publishing/toPost"; + +export interface GetPostsParams { + /** The account whose posts are listed. */ + accountId: string; + /** Optional artist the posts were published for. */ + artistAccountId?: string; + status?: string; + platform?: string; + limit: number; + offset: number; +} + +/** + * The account's posts, newest first, in the public `Post` shape. Shared by + * `GET /api/posts` and the `get_published_posts` MCP tool, which resolve and + * authorize the account themselves. + * + * @param params - See {@link GetPostsParams}. + * @returns The matching posts. + */ +export async function getPosts({ + accountId, + artistAccountId, + status, + platform, + limit, + offset, +}: GetPostsParams) { + const rows = await selectScheduledPosts({ + accountId, + artistAccountId, + status, + platform, + limit, + offset, + }); + return rows.map(toPost); +} diff --git a/lib/publishing/getPostsHandler.ts b/lib/publishing/getPostsHandler.ts index 922cf2f6b..4650d60e1 100644 --- a/lib/publishing/getPostsHandler.ts +++ b/lib/publishing/getPostsHandler.ts @@ -3,15 +3,15 @@ import { NextResponse } from "next/server"; import { errorResponse } from "@/lib/networking/errorResponse"; import { successResponse } from "@/lib/networking/successResponse"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; -import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; import { validateGetPostsQuery } from "@/lib/publishing/validateGetPostsQuery"; -import { toPost } from "@/lib/publishing/toPost"; +import { getPosts } from "@/lib/publishing/getPosts"; /** * GET /api/posts * * The account's posts, newest first. `account_id` is a scoped override: a - * caller who cannot reach the account gets a 403, not an empty list. + * caller who cannot reach the account gets a 403, not an empty list. The read + * is shared with the `get_published_posts` MCP tool through getPosts. * * @param request - The request carrying the query parameters. * @returns `{ status, posts }`. @@ -24,7 +24,7 @@ export async function getPostsHandler(request: NextRequest): Promise ({ canAccessAccount: vi.fn() })); +vi.mock("@/lib/supabase/scheduled_posts/selectScheduledPosts", () => ({ + selectScheduledPosts: vi.fn(), +})); +vi.mock("@/lib/publishing/findConnectedAccountId", () => ({ findConnectedAccountId: vi.fn() })); +vi.mock("@/lib/publishing/stats/getLinkedInPostAnalytics", () => ({ + getLinkedInPostAnalytics: vi.fn(), +})); +vi.mock("@/lib/credits/checkCreditsAvailable", () => ({ checkCreditsAvailable: vi.fn() })); +vi.mock("@/lib/publishing/stats/chargePostStatsRead", () => ({ chargePostStatsRead: vi.fn() })); + +const callerId = "550e8400-e29b-41d4-a716-446655440000"; +const ownerId = "770e8400-e29b-41d4-a716-446655440000"; +const artistId = "660e8400-e29b-41d4-a716-446655440000"; +const postId = "3f1c2b7e-8a4d-4c1e-9b2a-6d5e4f3a2b1c"; +const postUrl = "https://www.linkedin.com/feed/update/urn:li:ugcPost:77/"; +const row = { + id: postId, + account_id: ownerId, + artist_account_id: artistId, + platform: "linkedin", + status: "posted", + post_url: postUrl, + sub_account_id: "urn:li:organization:42", +}; +const metrics = { + impressions: 900, + unique_impressions: 700, + clicks: 30, + likes: 12, + comments: 3, + shares: 2, + engagement: 0.05, + video_views: null, + viewers: null, + watch_time_ms: null, +}; +const withRow = (patch: Record) => + vi.mocked(selectScheduledPosts).mockResolvedValueOnce([{ ...row, ...patch }] as never); +const run = () => getPostStats({ accountId: callerId, postId }); + +describe("getPostStats", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(canAccessAccount).mockResolvedValue(true); + vi.mocked(selectScheduledPosts).mockResolvedValue([row] as never); + vi.mocked(findConnectedAccountId).mockResolvedValue("ca_1"); + vi.mocked(checkCreditsAvailable).mockResolvedValue({ kind: "available" }); + vi.mocked(getLinkedInPostAnalytics).mockResolvedValue(metrics); + }); + + it("reads the post's numbers through the publishing connection and charges the caller once", async () => { + const result = await run(); + expect(selectScheduledPosts).toHaveBeenCalledWith({ id: postId }); + expect(canAccessAccount).toHaveBeenCalledWith({ + currentAccountId: callerId, + targetAccountId: ownerId, + }); + expect(findConnectedAccountId).toHaveBeenCalledWith(artistId, "linkedin"); + expect(checkCreditsAvailable).toHaveBeenCalledWith({ + accountId: callerId, + creditsToDeduct: POST_STATS_CREDITS, + }); + expect(getLinkedInPostAnalytics).toHaveBeenCalledWith( + "ca_1", + "urn:li:organization:42", + expect.objectContaining({ urn: "urn:li:ugcPost:77" }), + ); + expect(chargePostStatsRead).toHaveBeenCalledTimes(1); + expect(chargePostStatsRead).toHaveBeenCalledWith(callerId, "linkedin", postUrl); + expect(result).toEqual({ + kind: "ok", + stats: { + post_id: postId, + platform: "linkedin", + post_url: postUrl, + ...metrics, + as_of: expect.any(String), + }, + }); + }); + + it("uses the owner's connection when the post has no artist", async () => { + withRow({ artist_account_id: null }); + await run(); + expect(findConnectedAccountId).toHaveBeenCalledWith(ownerId, "linkedin"); + }); + + it.each([ + [ + "an unknown post", + () => vi.mocked(selectScheduledPosts).mockResolvedValueOnce([]), + 404, + "Post not found", + ], + [ + "a post the caller cannot reach", + () => vi.mocked(canAccessAccount).mockResolvedValueOnce(false), + 403, + "Access denied to this post's account", + ], + [ + "an unpublished post", + () => withRow({ status: "scheduled", post_url: null }), + 409, + "Post is not published yet, so it has no stats", + ], + [ + "another platform", + () => withRow({ platform: "youtube" }), + 422, + "Stats are not available for youtube posts yet", + ], + [ + "a member post", + () => withRow({ sub_account_id: "urn:li:person:9" }), + 422, + "Stats are available for LinkedIn company-page posts only", + ], + [ + "a URL that names no post", + () => withRow({ post_url: "https://www.linkedin.com/company/recoup/" }), + 422, + "post_url does not name a LinkedIn post", + ], + [ + "a missing LinkedIn connection", + () => vi.mocked(findConnectedAccountId).mockResolvedValueOnce(null), + 409, + "linkedin is not connected for this account", + ], + ])("rejects %s without checking or charging credits", async (_name, arrange, status, message) => { + arrange(); + expect(await run()).toEqual({ kind: "rejected", status, message }); + expect(checkCreditsAvailable).not.toHaveBeenCalled(); + expect(getLinkedInPostAnalytics).not.toHaveBeenCalled(); + expect(chargePostStatsRead).not.toHaveBeenCalled(); + }); + + it("reports a credit shortfall without reading LinkedIn", async () => { + vi.mocked(checkCreditsAvailable).mockResolvedValueOnce({ + kind: "insufficient_credits", + remainingCredits: 10, + requiredCredits: POST_STATS_CREDITS, + }); + expect(await run()).toEqual({ + kind: "insufficient_credits", + remainingCredits: 10, + requiredCredits: POST_STATS_CREDITS, + }); + expect(getLinkedInPostAnalytics).not.toHaveBeenCalled(); + expect(chargePostStatsRead).not.toHaveBeenCalled(); + }); + + it("reports a LinkedIn rejection as a 502 without leaking its message or charging", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(getLinkedInPostAnalytics).mockRejectedValueOnce(new Error("returned 403: token abc")); + expect(await run()).toEqual({ + kind: "rejected", + status: 502, + message: "LinkedIn rejected the stats read for this post", + }); + expect(chargePostStatsRead).not.toHaveBeenCalled(); + spy.mockRestore(); + }); + + it("propagates database errors to the caller", async () => { + vi.mocked(selectScheduledPosts).mockRejectedValueOnce(new Error("db down")); + await expect(run()).rejects.toThrow("db down"); + }); +}); diff --git a/lib/publishing/stats/__tests__/getPostStatsHandler.credits.test.ts b/lib/publishing/stats/__tests__/getPostStatsHandler.credits.test.ts index 8320b2707..a76ce4466 100644 --- a/lib/publishing/stats/__tests__/getPostStatsHandler.credits.test.ts +++ b/lib/publishing/stats/__tests__/getPostStatsHandler.credits.test.ts @@ -1,12 +1,12 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { NextRequest, NextResponse } from "next/server"; +import { NextRequest } from "next/server"; import { getPostStatsHandler } from "../getPostStatsHandler"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; import { findConnectedAccountId } from "@/lib/publishing/findConnectedAccountId"; import { getLinkedInPostStats } from "@/lib/publishing/stats/getLinkedInPostStats"; -import { ensureCreditsOrShortCircuit } from "@/lib/credits/ensureCreditsOrShortCircuit"; +import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; import { chargePostStatsRead } from "@/lib/publishing/stats/chargePostStatsRead"; import { POST_STATS_CREDITS } from "@/lib/publishing/stats/postStatsCredits"; @@ -21,9 +21,7 @@ vi.mock("@/lib/publishing/stats/getLinkedInPostStats", () => ({ getLinkedInPostS vi.mock("@/lib/publishing/stats/getLinkedInVideoStats", () => ({ getLinkedInVideoStats: vi.fn(), })); -vi.mock("@/lib/credits/ensureCreditsOrShortCircuit", () => ({ - ensureCreditsOrShortCircuit: vi.fn(), -})); +vi.mock("@/lib/credits/checkCreditsAvailable", () => ({ checkCreditsAvailable: vi.fn() })); vi.mock("@/lib/publishing/stats/chargePostStatsRead", () => ({ chargePostStatsRead: vi.fn() })); const callerId = "550e8400-e29b-41d4-a716-446655440000"; @@ -60,7 +58,7 @@ describe("getPostStatsHandler: credits", () => { shares: 0, engagement: 0, }); - vi.mocked(ensureCreditsOrShortCircuit).mockResolvedValue(null); + vi.mocked(checkCreditsAvailable).mockResolvedValue({ kind: "available" }); }); it("costs $0.001", () => { @@ -70,7 +68,7 @@ describe("getPostStatsHandler: credits", () => { it("checks the caller's credits, then charges them once after a successful read", async () => { const res = await getPostStatsHandler(request(), postId); expect(res.status).toBe(200); - expect(ensureCreditsOrShortCircuit).toHaveBeenCalledWith({ + expect(checkCreditsAvailable).toHaveBeenCalledWith({ accountId: callerId, creditsToDeduct: POST_STATS_CREDITS, }); @@ -79,11 +77,18 @@ describe("getPostStatsHandler: credits", () => { }); it("returns the 402 without reading LinkedIn when credits are short", async () => { - vi.mocked(ensureCreditsOrShortCircuit).mockResolvedValue( - NextResponse.json({ status: "error" }, { status: 402 }), - ); + vi.mocked(checkCreditsAvailable).mockResolvedValue({ + kind: "insufficient_credits", + remainingCredits: 10, + requiredCredits: POST_STATS_CREDITS, + }); const res = await getPostStatsHandler(request(), postId); expect(res.status).toBe(402); + expect(await res.json()).toMatchObject({ + error: "insufficient_credits", + remaining_credits: 10, + required_credits: POST_STATS_CREDITS, + }); expect(getLinkedInPostStats).not.toHaveBeenCalled(); expect(chargePostStatsRead).not.toHaveBeenCalled(); }); @@ -99,7 +104,7 @@ describe("getPostStatsHandler: credits", () => { vi.mocked(selectScheduledPosts).mockResolvedValue([{ ...row, platform: "youtube" }] as never); const res = await getPostStatsHandler(request(), postId); expect(res.status).toBe(422); - expect(ensureCreditsOrShortCircuit).not.toHaveBeenCalled(); + expect(checkCreditsAvailable).not.toHaveBeenCalled(); expect(chargePostStatsRead).not.toHaveBeenCalled(); }); }); diff --git a/lib/publishing/stats/__tests__/getPostStatsHandler.test.ts b/lib/publishing/stats/__tests__/getPostStatsHandler.test.ts index c8de08c1a..ae72fe91d 100644 --- a/lib/publishing/stats/__tests__/getPostStatsHandler.test.ts +++ b/lib/publishing/stats/__tests__/getPostStatsHandler.test.ts @@ -18,8 +18,8 @@ vi.mock("@/lib/publishing/stats/getLinkedInPostStats", () => ({ getLinkedInPostS vi.mock("@/lib/publishing/stats/getLinkedInVideoStats", () => ({ getLinkedInVideoStats: vi.fn(), })); -vi.mock("@/lib/credits/ensureCreditsOrShortCircuit", () => ({ - ensureCreditsOrShortCircuit: vi.fn().mockResolvedValue(null), +vi.mock("@/lib/credits/checkCreditsAvailable", () => ({ + checkCreditsAvailable: vi.fn().mockResolvedValue({ kind: "available" }), })); vi.mock("@/lib/publishing/stats/chargePostStatsRead", () => ({ chargePostStatsRead: vi.fn() })); diff --git a/lib/publishing/stats/__tests__/getPostStatsHandler.video.test.ts b/lib/publishing/stats/__tests__/getPostStatsHandler.video.test.ts index eba029c58..432c4ea08 100644 --- a/lib/publishing/stats/__tests__/getPostStatsHandler.video.test.ts +++ b/lib/publishing/stats/__tests__/getPostStatsHandler.video.test.ts @@ -6,7 +6,7 @@ import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; import { findConnectedAccountId } from "@/lib/publishing/findConnectedAccountId"; import { getLinkedInPostAnalytics } from "@/lib/publishing/stats/getLinkedInPostAnalytics"; -import { ensureCreditsOrShortCircuit } from "@/lib/credits/ensureCreditsOrShortCircuit"; +import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; import { chargePostStatsRead } from "@/lib/publishing/stats/chargePostStatsRead"; vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({})) })); @@ -19,8 +19,8 @@ vi.mock("@/lib/publishing/findConnectedAccountId", () => ({ findConnectedAccount vi.mock("@/lib/publishing/stats/getLinkedInPostAnalytics", () => ({ getLinkedInPostAnalytics: vi.fn(), })); -vi.mock("@/lib/credits/ensureCreditsOrShortCircuit", () => ({ - ensureCreditsOrShortCircuit: vi.fn(), +vi.mock("@/lib/credits/checkCreditsAvailable", () => ({ + checkCreditsAvailable: vi.fn().mockResolvedValue({ kind: "available" }), })); vi.mock("@/lib/publishing/stats/chargePostStatsRead", () => ({ chargePostStatsRead: vi.fn() })); @@ -57,7 +57,7 @@ describe("getPostStatsHandler: video analytics", () => { vi.mocked(canAccessAccount).mockResolvedValue(true); vi.mocked(selectScheduledPosts).mockResolvedValue([row] as never); vi.mocked(findConnectedAccountId).mockResolvedValue("ca_1"); - vi.mocked(ensureCreditsOrShortCircuit).mockResolvedValue(null); + vi.mocked(checkCreditsAvailable).mockResolvedValue({ kind: "available" }); vi.mocked(getLinkedInPostAnalytics).mockResolvedValue(analytics); }); diff --git a/lib/publishing/stats/getPostStats.ts b/lib/publishing/stats/getPostStats.ts new file mode 100644 index 000000000..099e841c3 --- /dev/null +++ b/lib/publishing/stats/getPostStats.ts @@ -0,0 +1,109 @@ +import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; +import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; +import { findConnectedAccountId } from "@/lib/publishing/findConnectedAccountId"; +import { parseLinkedInPostUrn } from "@/lib/publishing/stats/parseLinkedInPostUrn"; +import { getLinkedInPostAnalytics } from "@/lib/publishing/stats/getLinkedInPostAnalytics"; +import { checkCreditsAvailable } from "@/lib/credits/checkCreditsAvailable"; +import { chargePostStatsRead } from "@/lib/publishing/stats/chargePostStatsRead"; +import { POST_STATS_CREDITS } from "@/lib/publishing/stats/postStatsCredits"; + +const ORGANIZATION_PREFIX = "urn:li:organization:"; + +export interface GetPostStatsParams { + /** The authenticated caller, who must reach the post's account and pays for the read. */ + accountId: string; + /** The post's id. */ + postId: string; +} + +export type PostStats = { + post_id: string; + platform: string; + post_url: string; + as_of: string; +} & Awaited>; + +export type GetPostStatsResult = + | { kind: "ok"; stats: PostStats } + | { kind: "insufficient_credits"; remainingCredits: number; requiredCredits: number } + | { kind: "rejected"; status: 403 | 404 | 409 | 422 | 502; message: string }; + +const reject = (status: 403 | 404 | 409 | 422 | 502, message: string): GetPostStatsResult => ({ + kind: "rejected", + status, + message, +}); + +/** + * A published post's own platform numbers, read live through the connection + * that published it. LinkedIn company-page posts only. Credits ($0.001) are + * checked before LinkedIn is called and charged only after a successful read. + * Shared by `GET /api/posts/{id}/stats` and the `get_published_post_stats` MCP + * tool, which map the result to their own response shapes. Database errors + * propagate to the caller. + * + * @param params - See {@link GetPostStatsParams}. + * @returns The stats, the credit shortfall, or a rejection with its REST status and message. + */ +export async function getPostStats({ + accountId, + postId, +}: GetPostStatsParams): Promise { + const [row] = await selectScheduledPosts({ id: postId }); + if (!row) return reject(404, "Post not found"); + + const allowed = await canAccessAccount({ + currentAccountId: accountId, + targetAccountId: row.account_id, + }); + if (!allowed) return reject(403, "Access denied to this post's account"); + + if (row.status !== "posted" || !row.post_url) { + return reject(409, "Post is not published yet, so it has no stats"); + } + if (row.platform !== "linkedin") { + return reject(422, `Stats are not available for ${row.platform} posts yet`); + } + const organization = row.sub_account_id; + if (!organization?.startsWith(ORGANIZATION_PREFIX)) { + return reject(422, "Stats are available for LinkedIn company-page posts only"); + } + const post = parseLinkedInPostUrn(row.post_url); + if (!post) return reject(422, "post_url does not name a LinkedIn post"); + + const connectedAccountId = await findConnectedAccountId( + row.artist_account_id ?? row.account_id, + "linkedin", + ); + if (!connectedAccountId) return reject(409, "linkedin is not connected for this account"); + + const gate = await checkCreditsAvailable({ accountId, creditsToDeduct: POST_STATS_CREDITS }); + if (gate.kind === "insufficient_credits") { + return { + kind: "insufficient_credits", + remainingCredits: gate.remainingCredits, + requiredCredits: gate.requiredCredits, + }; + } + + let metrics; + try { + metrics = await getLinkedInPostAnalytics(connectedAccountId, organization, post); + } catch (error) { + console.error("LinkedIn rejected the post stats read:", error); + return reject(502, "LinkedIn rejected the stats read for this post"); + } + + await chargePostStatsRead(accountId, row.platform, row.post_url); + + return { + kind: "ok", + stats: { + post_id: row.id, + platform: row.platform, + post_url: row.post_url, + ...metrics, + as_of: new Date().toISOString(), + }, + }; +} diff --git a/lib/publishing/stats/getPostStatsHandler.ts b/lib/publishing/stats/getPostStatsHandler.ts index b1edfdbec..dfbfe7fd6 100644 --- a/lib/publishing/stats/getPostStatsHandler.ts +++ b/lib/publishing/stats/getPostStatsHandler.ts @@ -3,17 +3,10 @@ import { NextResponse } from "next/server"; import { z } from "zod"; import { errorResponse } from "@/lib/networking/errorResponse"; import { successResponse } from "@/lib/networking/successResponse"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; -import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; -import { selectScheduledPosts } from "@/lib/supabase/scheduled_posts/selectScheduledPosts"; -import { findConnectedAccountId } from "@/lib/publishing/findConnectedAccountId"; -import { parseLinkedInPostUrn } from "@/lib/publishing/stats/parseLinkedInPostUrn"; -import { getLinkedInPostAnalytics } from "@/lib/publishing/stats/getLinkedInPostAnalytics"; -import { ensureCreditsOrShortCircuit } from "@/lib/credits/ensureCreditsOrShortCircuit"; -import { chargePostStatsRead } from "@/lib/publishing/stats/chargePostStatsRead"; -import { POST_STATS_CREDITS } from "@/lib/publishing/stats/postStatsCredits"; - -const ORGANIZATION_PREFIX = "urn:li:organization:"; +import { buildInsufficientCreditsResponse } from "@/lib/credits/buildInsufficientCreditsResponse"; +import { getPostStats } from "@/lib/publishing/stats/getPostStats"; /** * GET /api/posts/{id}/stats @@ -22,7 +15,8 @@ const ORGANIZATION_PREFIX = "urn:li:organization:"; * that published it. LinkedIn company-page posts only; other platforms and * member posts answer 422. A read costs $0.001: credits are checked (402) * before LinkedIn is called and charged only after a successful read. Uuid, auth and access checks - * match getPostHandler. + * match getPostHandler. The read itself is shared with the + * `get_published_post_stats` MCP tool through getPostStats. * * @param request - The incoming request. * @param id - Post id from the route segment. @@ -37,61 +31,15 @@ export async function getPostStatsHandler(request: NextRequest, id: string): Pro if (authResult instanceof NextResponse) return authResult; try { - const [row] = await selectScheduledPosts({ id }); - if (!row) return errorResponse("Post not found", 404); - - const allowed = await canAccessAccount({ - currentAccountId: authResult.accountId, - targetAccountId: row.account_id, - }); - if (!allowed) return errorResponse("Access denied to this post's account", 403); - - if (row.status !== "posted" || !row.post_url) { - return errorResponse("Post is not published yet, so it has no stats", 409); - } - if (row.platform !== "linkedin") { - return errorResponse(`Stats are not available for ${row.platform} posts yet`, 422); - } - const organization = row.sub_account_id; - if (!organization?.startsWith(ORGANIZATION_PREFIX)) { - return errorResponse("Stats are available for LinkedIn company-page posts only", 422); - } - const post = parseLinkedInPostUrn(row.post_url); - if (!post) return errorResponse("post_url does not name a LinkedIn post", 422); - - const connectedAccountId = await findConnectedAccountId( - row.artist_account_id ?? row.account_id, - "linkedin", - ); - if (!connectedAccountId) { - return errorResponse("linkedin is not connected for this account", 409); - } - - const short = await ensureCreditsOrShortCircuit({ - accountId: authResult.accountId, - creditsToDeduct: POST_STATS_CREDITS, - }); - if (short) return short; - - let metrics; - try { - metrics = await getLinkedInPostAnalytics(connectedAccountId, organization, post); - } catch (error) { - console.error("LinkedIn rejected the post stats read:", error); - return errorResponse("LinkedIn rejected the stats read for this post", 502); + const result = await getPostStats({ accountId: authResult.accountId, postId: id }); + if (result.kind === "rejected") return errorResponse(result.message, result.status); + if (result.kind === "insufficient_credits") { + return NextResponse.json(buildInsufficientCreditsResponse(result), { + status: 402, + headers: getCorsHeaders(), + }); } - - await chargePostStatsRead(authResult.accountId, row.platform, row.post_url); - - return successResponse({ - stats: { - post_id: row.id, - platform: row.platform, - post_url: row.post_url, - ...metrics, - as_of: new Date().toISOString(), - }, - }); + return successResponse({ stats: result.stats }); } catch (error) { console.error("Error fetching post stats:", error); return errorResponse("Internal server error", 500); diff --git a/scripts/mcp-oauth/tool-policy.json b/scripts/mcp-oauth/tool-policy.json index 37806db06..7aa4dc19b 100644 --- a/scripts/mcp-oauth/tool-policy.json +++ b/scripts/mcp-oauth/tool-policy.json @@ -196,6 +196,25 @@ "status": "requires OAuth execution audit before enablement", "authorizationWork": "Bind account and requested resources to the selected grant context; enforce scopes, current access, and redacted errors at execution. Check the target artist/resource through an authorized relationship, not a system-prompt assertion." }, + { + "name": "get_published_post_stats", + "file": "lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts", + "scopes": [ + "mcp:read", + "mcp:spend" + ], + "status": "requires OAuth execution audit before enablement", + "authorizationWork": "Bind account and requested resources to the selected grant context; enforce scopes, current access, and redacted errors at execution. Check the post's account through an authorized relationship; gate credits before the LinkedIn read and charge $0.001 only after it succeeds." + }, + { + "name": "get_published_posts", + "file": "lib/mcp/tools/posts/registerGetPublishedPostsTool.ts", + "scopes": [ + "mcp:read" + ], + "status": "requires OAuth execution audit before enablement", + "authorizationWork": "Bind account and requested resources to the selected grant context; enforce scopes, current access, and redacted errors at execution. Scope the list to the credential's account; check any artist filter through an authorized relationship, not a system-prompt assertion." + }, { "name": "get_catalog_playcount_history", "file": "lib/mcp/tools/catalogs/registerGetCatalogPlaycountHistoryTool.ts",