Skip to content
Draft
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
2 changes: 2 additions & 0 deletions docs/mcp-oauth-tool-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,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) |
Expand Down
6 changes: 4 additions & 2 deletions lib/mcp/oauth/__tests__/fullOAuthCatalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,12 @@ 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(94);
expect(tools).toHaveLength(96);
expect(
tools.filter(
tool => !(tool._meta?.ui as { visibility?: string[] })?.visibility?.includes("app"),
),
).toHaveLength(93);
).toHaveLength(95);
expect(verify).not.toHaveBeenCalled();
for (const service of Object.values(services)) expect(service).not.toHaveBeenCalled();
expect(contextToolOperations.prepare_catalog_audit).toMatchObject({
Expand All @@ -87,6 +87,8 @@ it("discovers the entire delegated catalog over the real MCP SDK", async () => {
list_artists: [true, false, false],
get_artist_posts: [true, false, false],
get_scraper_results: [true, false, true],
get_published_posts: [true, false, false],
get_published_post_stats: [true, false, true],
scrape_artist_socials: [false, true, true],
get_tasks: [true, false, false],
get_youtube_revenue: [true, false, false],
Expand Down
8 changes: 8 additions & 0 deletions lib/mcp/oauth/fullOAuthToolPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ export const fullOAuthToolPolicy: Record<string, ToolPolicy> = {
notice:
"Spends account credits: $0.05 per linked profile plus $0.01 per requested post. Confirm before scraping.",
},
get_published_posts: { readOnly: true, destructive: false, openWorld: false },
get_published_post_stats: {
readOnly: true,
destructive: false,
openWorld: true,
notice:
"Spends account credits: $0.001 per successful read. Read each post once and keep the result.",
},
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
2 changes: 2 additions & 0 deletions lib/mcp/tools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -50,6 +51,7 @@ export const registerAllTools = (server: McpServer): void => {
registerAllFileTools(server);
registerAllFlamingoTools(server);
registerAllImageTools(server);
registerAllPostsTools(server);
registerAllPulseTools(server);
registerAllSearchTools(server);
registerAllSora2Tools(server);
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
});
});
104 changes: 104 additions & 0 deletions lib/mcp/tools/posts/__tests__/registerGetPublishedPostsTool.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
13 changes: 13 additions & 0 deletions lib/mcp/tools/posts/index.ts
Original file line number Diff line number Diff line change
@@ -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);
};
58 changes: 58 additions & 0 deletions lib/mcp/tools/posts/registerGetPublishedPostStatsTool.ts
Original file line number Diff line number Diff line change
@@ -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<typeof getPublishedPostStatsSchema>;

/**
* 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<ServerRequest, ServerNotification>,
) => {
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.");
}
},
);
}
Loading
Loading