bundlesocial-mcp 1.2.2 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/server.ts","../package.json","../src/client.ts","../src/errors.ts","../src/tools/integrations.ts","../src/platforms.ts","../src/register-tool.ts","../src/tools/posts.ts","../src/media.ts","../src/post-data.ts","../src/tools/comments.ts","../src/tools/media.ts","../src/tools/analytics.ts","../src/tools/integration-tools.ts","../src/integration-tools.ts","../src/tools/teams.ts","../src/tools/organization.ts","../src/tools/post-imports.ts","../src/tools/post-csv.ts","../src/tools/diagnostics.ts","../src/tools/platform-reference.ts","../src/platform-reference.ts","../src/tools/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createServer, VERSION } from \"./server\";\nimport { DASHBOARD_API_KEYS_URL } from \"./client\";\n\n/** Read a `--flag value` pair from argv (CLI overrides for the env vars). */\nfunction readFlag(name: string): string | undefined {\n const index = process.argv.indexOf(`--${name}`);\n if (index !== -1 && index + 1 < process.argv.length) return process.argv[index + 1];\n const inline = process.argv.find((arg) => arg.startsWith(`--${name}=`));\n return inline ? inline.slice(`--${name}=`.length) : undefined;\n}\n\nfunction log(message: string): void {\n // stdio transport owns stdout — all logging must go to stderr.\n process.stderr.write(`bundlesocial-mcp: ${message}\\n`);\n}\n\nasync function main(): Promise<void> {\n if (process.argv.includes(\"--version\") || process.argv.includes(\"-v\")) {\n process.stdout.write(`${VERSION}\\n`);\n return;\n }\n if (process.argv.includes(\"--help\") || process.argv.includes(\"-h\")) {\n process.stdout.write(\n `bundlesocial-mcp ${VERSION} — Model Context Protocol server for the bundle.social API.\\n\\n` +\n `Usage: bundlesocial-mcp [--api-key <key>] [--api-url <url>] [--team-id <id>]\\n\\n` +\n `Reads BUNDLESOCIAL_API_KEY (required), BUNDLESOCIAL_API_URL and BUNDLESOCIAL_TEAM_ID from the environment;\\n` +\n `the flags above override them. Communicates over stdio (MCP). Create an API key at ${DASHBOARD_API_KEYS_URL}\\n`,\n );\n return;\n }\n\n const apiKey = readFlag(\"api-key\") ?? process.env.BUNDLESOCIAL_API_KEY;\n if (!apiKey) {\n log(`missing API key. Set BUNDLESOCIAL_API_KEY (or pass --api-key). Create one at ${DASHBOARD_API_KEYS_URL}`);\n process.exit(1);\n }\n\n const server = createServer({\n apiKey,\n apiUrl: readFlag(\"api-url\") ?? process.env.BUNDLESOCIAL_API_URL,\n defaultTeamId: readFlag(\"team-id\") ?? process.env.BUNDLESOCIAL_TEAM_ID,\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n log(\"running on stdio\");\n\n const shutdown = () => {\n void server.close().finally(() => process.exit(0));\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((error) => {\n log(`fatal: ${(error as Error)?.stack ?? error}`);\n process.exit(1);\n});\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport pkg from \"../package.json\";\nimport { type ServerContext, DEFAULT_API_URL, createClient } from \"./client\";\nimport { registerAllTools } from \"./tools\";\n\nexport const VERSION: string = pkg.version;\n\nexport interface CreateServerOptions {\n apiKey: string;\n apiUrl?: string;\n /** Default team id (from BUNDLESOCIAL_TEAM_ID / --team-id). */\n defaultTeamId?: string;\n}\n\n/** Build an MCP server exposing the bundle.social tools. Transport-agnostic. */\nexport function createServer(options: CreateServerOptions): McpServer {\n const server = new McpServer(\n { name: \"bundlesocial\", version: VERSION },\n {\n capabilities: { tools: {} },\n instructions:\n \"Tools for the bundle.social API: posting/scheduling to 14+ social platforms, comments, media uploads, analytics, team & integration management, and bulk/history imports (post-history, comment, CSV). Run check_setup first to verify the API key, org access and team. Use list_integrations to see connected accounts and their ids. create_post / schedule_post target platforms by name (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, gbp) or by integration id; put platform-required fields (Reddit `sr`, Pinterest `boardName`, TikTok `privacy`, YouTube `madeForKids`/`privacyStatus`) under `platformSettings` keyed by platform. Call describe_platform to get the exact per-platform `data.<PLATFORM>` field schema (for posts and comments) before building a `data` / `platformSettings` object; the same fields are documented at https://docs.bundle.social/api-reference/platform-parameters. Team-scoped tools take an optional `teamId` (resolved automatically when the org has one team or BUNDLESOCIAL_TEAM_ID is set). Errors come back as { error: { code, message, details } } with isError: true.\",\n },\n );\n\n const ctx: ServerContext = {\n client: createClient(options.apiKey, options.apiUrl ?? DEFAULT_API_URL),\n defaultTeamId: options.defaultTeamId,\n };\n registerAllTools(server, ctx);\n return server;\n}\n","{\n \"name\": \"bundlesocial-mcp\",\n \"version\": \"1.2.2\",\n \"mcpName\": \"io.github.bundleglobal/bundlesocial-mcp\",\n \"description\": \"Model Context Protocol server for the bundle.social social-media API — post to 14+ platforms from Claude, Cursor and other MCP clients.\",\n \"keywords\": [\n \"bundle.social\",\n \"bundlesocial\",\n \"mcp\",\n \"model context protocol\",\n \"social media\",\n \"api\",\n \"agents\",\n \"claude\",\n \"cursor\"\n ],\n \"author\": \"bundle.global\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/bundleglobal/bundlesocial-mcp#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/bundleglobal/bundlesocial-mcp/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/bundleglobal/bundlesocial-mcp.git\"\n },\n \"type\": \"module\",\n \"bin\": {\n \"bundlesocial-mcp\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist/**\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"start\": \"node dist/index.js\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.12.0\",\n \"bundlesocial\": \"^2.68.0\",\n \"zod\": \"^3.23.8\"\n },\n \"devDependencies\": {\n \"@semantic-release/changelog\": \"^6.0.3\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@types/node\": \"^20.14.0\",\n \"semantic-release\": \"^25.0.2\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.0.5\"\n }\n}\n","import { Bundlesocial, OpenAPI, type TeamGetListResponse } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\nexport const DEFAULT_API_URL = \"https://api.bundle.social\";\nexport const DASHBOARD_API_KEYS_URL = \"https://bundle.social/dashboard/organization/api-keys\";\nexport const DASHBOARD_SOCIAL_ACCOUNTS_URL = \"https://bundle.social/dashboard/general/social-accounts\";\n\nexport interface ServerContext {\n client: Bundlesocial;\n /** Team id from BUNDLESOCIAL_TEAM_ID / --team-id, if configured. */\n defaultTeamId?: string;\n}\n\nexport type TeamListItem = TeamGetListResponse[\"items\"][number];\n\n/** Page size used when walking the team list (the `list_teams` tool caps at the same value). */\nexport const TEAM_PAGE_SIZE = 100;\n/** Safety cap so a misbehaving `total` can't loop forever (100 pages x 100 = 10k teams). */\nexport const TEAM_MAX_PAGES = 100;\n\n/**\n * Fetch every team in the organization via the paginated team list. Replaces\n * the deprecated `organization.teams` array (removed from the API on 2026-11-15).\n */\nexport async function listAllTeams(client: Bundlesocial): Promise<TeamListItem[]> {\n const teams: TeamListItem[] = [];\n for (let page = 0; page < TEAM_MAX_PAGES; page++) {\n const { items, total } = await client.team.teamGetList({ offset: teams.length, limit: TEAM_PAGE_SIZE });\n teams.push(...(items ?? []));\n if (!items?.length || teams.length >= total) return teams;\n }\n // stdio transport owns stdout, so warnings go to stderr.\n process.stderr.write(`bundlesocial-mcp: team list truncated at ${teams.length} teams (page cap ${TEAM_MAX_PAGES} reached)\\n`);\n return teams;\n}\n\nexport function createClient(apiKey: string, apiUrl: string = DEFAULT_API_URL): Bundlesocial {\n return new Bundlesocial(apiKey, { ...OpenAPI, BASE: apiUrl });\n}\n\n/**\n * Resolve the team to operate on: explicit `teamId` argument > server's\n * configured default > the organization's only team. Throws when ambiguous.\n */\nexport async function resolveTeamId(ctx: ServerContext, teamIdArg?: string): Promise<string> {\n if (teamIdArg) return teamIdArg;\n if (ctx.defaultTeamId) return ctx.defaultTeamId;\n const teams = await listAllTeams(ctx.client);\n if (teams.length === 1) return teams[0].id;\n if (teams.length === 0) {\n throw new McpToolError(\"NO_TEAMS\", \"This organization has no teams yet. Create one in the bundle.social dashboard first.\");\n }\n throw new McpToolError(\n \"TEAM_ID_REQUIRED\",\n `This organization has ${teams.length} teams. Pass a \"teamId\" argument (or set BUNDLESOCIAL_TEAM_ID when starting the server).`,\n { teams: teams.map((team) => ({ id: team.id, name: team.name })) },\n );\n}\n","import { ApiError } from \"bundlesocial\";\n\n/** An error with a stable machine-readable `code`, surfaced in the tool error result. */\nexport class McpToolError extends Error {\n readonly code: string;\n readonly details?: unknown;\n\n constructor(code: string, message: string, details?: unknown) {\n super(message);\n this.name = \"McpToolError\";\n this.code = code;\n this.details = details;\n }\n}\n\nexport interface NormalizedError {\n code: string;\n message: string;\n details?: unknown;\n}\n\nexport function normalizeError(error: unknown): NormalizedError {\n if (error instanceof McpToolError) {\n return { code: error.code, message: error.message, details: error.details };\n }\n if (error instanceof ApiError) {\n const body = error.body as Record<string, unknown> | string | undefined;\n const message =\n (typeof body === \"object\" && body && typeof body.message === \"string\" && body.message) ||\n (typeof body === \"object\" && body && typeof body.error === \"string\" && body.error) ||\n error.statusText ||\n error.message ||\n `HTTP ${error.status}`;\n return { code: `HTTP_${error.status}`, message, details: { status: error.status, url: error.url, body: error.body } };\n }\n if (error instanceof Error) {\n return {\n code: \"UNEXPECTED_ERROR\",\n message: error.message || \"Unexpected error\",\n details: process.env.BUNDLESOCIAL_DEBUG ? { stack: error.stack } : undefined,\n };\n }\n return { code: \"UNEXPECTED_ERROR\", message: String(error) };\n}\n\nexport function errorSummary(error: unknown): string {\n if (error instanceof ApiError) return `HTTP ${error.status}${error.statusText ? ` ${error.statusText}` : \"\"}`;\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\ntype TextContent = { type: \"text\"; text: string };\nexport interface ToolResult {\n content: TextContent[];\n isError?: boolean;\n}\n\n/** Wrap a value as a successful tool result (pretty JSON in a text block). */\nexport function jsonResult(data: unknown): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify(data, null, 2) }] };\n}\n\n/** Wrap an error as a tool error result with the `{ error: { code, message, details? } }` envelope. */\nexport function errorResult(error: unknown): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify({ error: normalizeError(error) }, null, 2) }], isError: true };\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n SocialAccountConnectData,\n SocialAccountCreatePortalLinkData,\n} from \"bundlesocial\";\nimport { type ServerContext, listAllTeams, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { normalizePlatform, type Platform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nconst platformSchema = z\n .string()\n .min(1)\n .describe('Platform name/alias (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, gbp).');\n\ntype ConnectBody = NonNullable<SocialAccountConnectData[\"requestBody\"]>;\ntype PortalLinkBody = NonNullable<SocialAccountCreatePortalLinkData[\"requestBody\"]>;\n\ntype SocialAccount = {\n id: string;\n type: string;\n username?: string | null;\n displayName?: string | null;\n avatarUrl?: string | null;\n channels?: Array<{ id: string; name?: string | null; username?: string | null; address?: string | null }> | null;\n};\n\nfunction mapAccounts(accounts: SocialAccount[] | undefined) {\n return (accounts ?? []).map((account) => ({\n id: account.id,\n type: account.type,\n username: account.username ?? null,\n displayName: account.displayName ?? null,\n avatarUrl: account.avatarUrl ?? null,\n channels: (account.channels ?? []).map((channel) => ({\n id: channel.id,\n name: channel.name ?? null,\n username: channel.username ?? null,\n address: channel.address ?? null,\n })),\n }));\n}\n\nexport function registerIntegrationTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_integrations\",\n {\n title: \"List connected integrations\",\n description:\n \"List the social-media integrations (accounts) connected to a bundle.social team — each with its `id`, `type` (platform), `username` and channels. Use this to discover which platforms are available and to get integration ids. Without a team id it lists every team in the organization.\",\n inputSchema: { teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId }) => {\n if (teamId ?? ctx.defaultTeamId) {\n const id = (teamId ?? ctx.defaultTeamId) as string;\n const team = await ctx.client.team.teamGetTeam({ id });\n return jsonResult({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n const teams = await listAllTeams(ctx.client);\n if (teams.length === 1) {\n const team = await ctx.client.team.teamGetTeam({ id: teams[0].id });\n return jsonResult({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n const organization = await ctx.client.organization.organizationGetOrganization();\n const perTeam = [];\n for (const summary of teams) {\n const team = await ctx.client.team.teamGetTeam({ id: summary.id });\n perTeam.push({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n return jsonResult({ organizationId: organization.id, organizationName: organization.name ?? null, teams: perTeam });\n },\n );\n\n registerTool(\n server,\n \"connect_integration\",\n {\n title: \"Connect a social account\",\n description:\n \"Start connecting a social account to a team. Returns an OAuth `url` — open it in a browser to authorize the account; bundle.social redirects back to `redirectUrl` afterwards. For Mastodon/Bluesky pass `serverUrl`.\",\n inputSchema: {\n platform: platformSchema,\n redirectUrl: z.string().min(1).describe(\"URL bundle.social redirects to after the user finishes (or cancels) the OAuth flow.\"),\n serverUrl: z.string().optional().describe(\"Mastodon/Bluesky instance URL (required for those platforms).\"),\n teamId: teamIdSchema,\n options: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Advanced provider flags, e.g. {\\\"instagramConnectionMethod\\\":\\\"INSTAGRAM\\\",\\\"withBusinessScope\\\":true,\\\"disableAutoLogin\\\":true,\\\"forceBrowserOAuth\\\":true,\\\"tiktokForceLogin\\\":true}. `withBusinessScope` also unlocks YouTube monetization analytics; `tiktokForceLogin` (experimental) forces TikTok's account picker when it keeps reusing the wrong active account.\",\n ),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platform, redirectUrl, serverUrl, teamId, options }) => {\n const id = await resolveTeamId(ctx, teamId);\n const requestBody = {\n type: normalizePlatform(platform) as ConnectBody[\"type\"],\n teamId: id,\n redirectUrl,\n ...(serverUrl ? { serverUrl } : {}),\n ...(options ?? {}),\n } as ConnectBody;\n return jsonResult(await ctx.client.socialAccount.socialAccountConnect({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"disconnect_integration\",\n {\n title: \"Disconnect a social account\",\n description: \"Disconnect a social account of the given platform from a team. Destructive — also removes it from scheduled posts.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountDisconnect({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"set_integration_channel\",\n {\n title: \"Set a social account's channel/page\",\n description: \"Select the page/channel for a connected account (needed for FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, GOOGLE_BUSINESS). Get channel ids from list_integrations / refresh_integration_channels.\",\n inputSchema: { platform: platformSchema, channelId: z.string().min(1).describe(\"Channel/page id to select.\"), teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, channelId, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountSetChannel({ requestBody: { type: normalizePlatform(platform) as never, teamId: id, channelId } }));\n },\n );\n\n registerTool(\n server,\n \"unset_integration_channel\",\n {\n title: \"Clear a social account's channel/page\",\n description: \"Clear the selected page/channel for a connected account (FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, GOOGLE_BUSINESS) while keeping the authorization.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountUnsetChannel({ requestBody: { type: normalizePlatform(platform) as never, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"refresh_integration_channels\",\n {\n title: \"Refresh a social account's channels\",\n description: \"Re-fetch the available channels for a connected account (needed for REDDIT, DISCORD, SLACK, PINTEREST and the page-based platforms).\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountRefreshChannels({ requestBody: { type: normalizePlatform(platform) as never, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"create_integration_portal_link\",\n {\n title: \"Create a connect-portal link\",\n description:\n \"Create a hosted bundle.social portal link a user can open to connect/manage social accounts without you implementing the OAuth flow. Returns a `url`.\",\n inputSchema: {\n platforms: z.array(z.string().min(1)).min(1).describe(\"Platforms the portal should offer to connect (names/aliases).\"),\n redirectUrl: z.string().optional().describe(\"URL to redirect to when the user finishes.\"),\n teamId: teamIdSchema,\n expiresInMinutes: z.number().int().min(5).max(2880).optional().describe(\"Link lifetime in minutes (5 min – 48 h).\"),\n options: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Advanced portal options — branding (logoUrl, userLogoUrl, userName, goBackButtonText, hidePoweredBy, hideGoBackButton, hideUserLogo, hideUserName, hideLanguageSwitcher, showModalOnConnectSuccess, language, maxSocialAccountsConnected) and the same OAuth flags as connect_integration (serverUrl, instagramConnectionMethod, withBusinessScope, disableAutoLogin, forceBrowserOAuth, tiktokForceLogin).\",\n ),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platforms, redirectUrl, teamId, expiresInMinutes, options }) => {\n const id = await resolveTeamId(ctx, teamId);\n const requestBody = {\n teamId: id,\n socialAccountTypes: platforms.map((p) => normalizePlatform(p)) as PortalLinkBody[\"socialAccountTypes\"],\n ...(redirectUrl ? { redirectUrl } : {}),\n ...(expiresInMinutes ? { expiresIn: expiresInMinutes } : {}),\n ...(options ?? {}),\n } as PortalLinkBody;\n return jsonResult(await ctx.client.socialAccount.socialAccountCreatePortalLink({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"check_integration_connection\",\n {\n title: \"Check a social account's connection\",\n description: \"Run an on-demand connection/disconnect health check for a connected account of the given platform.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountConnectionCheck({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"refresh_integration_profile\",\n {\n title: \"Refresh a social account's profile\",\n description: \"Re-fetch the profile info (username, display name, avatar) for a connected account of the given platform.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountProfileRefresh({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"get_integration_by_type\",\n {\n title: \"Get a social account by platform\",\n description: \"Fetch the connected social account of a given platform for a team (including its channels).\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountGetByType({ teamId: id, type: normalizePlatform(platform) as Platform }));\n },\n );\n\n registerTool(\n server,\n \"copy_integration\",\n {\n title: \"Copy social accounts between teams\",\n description: \"Copy connected social accounts of the given platforms from one team to another. Set `resetChannel` to require re-picking the page (Facebook/Instagram/LinkedIn/YouTube).\",\n inputSchema: {\n fromTeamId: z.string().min(1).describe(\"Source team id.\"),\n toTeamId: z.string().min(1).describe(\"Destination team id.\"),\n platforms: z.array(z.string().min(1)).min(1).describe(\"Platforms to copy (names/aliases).\"),\n resetChannel: z.boolean().optional().describe(\"If true, the destination must re-select the page/channel.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ fromTeamId, toTeamId, platforms, resetChannel }) =>\n jsonResult(\n await ctx.client.socialAccount.socialAccountCopy({\n requestBody: {\n fromTeamId,\n toTeamId,\n ...(resetChannel !== undefined ? { resetChannel } : {}),\n socialAccountTypes: platforms.map((p) => normalizePlatform(p)) as Platform[],\n },\n }),\n ),\n );\n\n registerTool(\n server,\n \"list_integrations_to_delete\",\n {\n title: \"List social accounts pending deletion\",\n description: \"List social accounts scheduled to be deleted (paginated) across the organization.\",\n inputSchema: {\n page: z.number().int().positive().optional().describe(\"Page (1-based).\"),\n pageSize: z.number().int().positive().max(100).optional().describe(\"Page size.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ page, pageSize }) => jsonResult(await ctx.client.socialAccount.socialAccountGetAccountsToDelete({ page, pageSize })),\n );\n}\n","import { McpToolError } from \"./errors\";\n\n/** Every platform bundle.social can post to. Mirrors the API's `socialAccountTypes` enum. */\nexport const PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"TWITTER\",\n \"THREADS\",\n \"LINKEDIN\",\n \"PINTEREST\",\n \"REDDIT\",\n \"MASTODON\",\n \"DISCORD\",\n \"SLACK\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n] as const;\n\nexport type Platform = (typeof PLATFORMS)[number];\n\n/** Platforms for which the API exposes analytics (X/Twitter, Discord and Slack are absent). */\nexport const ANALYTICS_PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"REDDIT\",\n \"PINTEREST\",\n \"MASTODON\",\n \"LINKEDIN\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n] as const;\n\nexport type AnalyticsPlatform = (typeof ANALYTICS_PLATFORMS)[number];\n\nconst ALIASES: Record<string, Platform> = {\n X: \"TWITTER\",\n TWITTER: \"TWITTER\",\n TIKTOK: \"TIKTOK\",\n TT: \"TIKTOK\",\n YOUTUBE: \"YOUTUBE\",\n YT: \"YOUTUBE\",\n INSTAGRAM: \"INSTAGRAM\",\n IG: \"INSTAGRAM\",\n INSTA: \"INSTAGRAM\",\n FACEBOOK: \"FACEBOOK\",\n FB: \"FACEBOOK\",\n THREADS: \"THREADS\",\n LINKEDIN: \"LINKEDIN\",\n LI: \"LINKEDIN\",\n PINTEREST: \"PINTEREST\",\n PIN: \"PINTEREST\",\n REDDIT: \"REDDIT\",\n MASTODON: \"MASTODON\",\n MASTO: \"MASTODON\",\n DISCORD: \"DISCORD\",\n SLACK: \"SLACK\",\n BLUESKY: \"BLUESKY\",\n BSKY: \"BLUESKY\",\n GOOGLE_BUSINESS: \"GOOGLE_BUSINESS\",\n \"GOOGLE-BUSINESS\": \"GOOGLE_BUSINESS\",\n GBP: \"GOOGLE_BUSINESS\",\n GOOGLEBUSINESS: \"GOOGLE_BUSINESS\",\n GMB: \"GOOGLE_BUSINESS\",\n SNAPCHAT: \"SNAPCHAT\",\n SNAP: \"SNAPCHAT\",\n};\n\nexport function tryNormalizePlatform(input: string): Platform | undefined {\n return ALIASES[input.trim().toUpperCase().replace(/\\s+/g, \"_\")];\n}\n\nexport function normalizePlatform(input: string): Platform {\n const platform = tryNormalizePlatform(input);\n if (!platform) {\n throw new McpToolError(\n \"UNKNOWN_PLATFORM\",\n `Unknown platform \"${input}\". Supported: ${PLATFORMS.join(\", \")} (aliases like \"x\" and \"gbp\" are accepted too).`,\n );\n }\n return platform;\n}\n\nexport function isAnalyticsPlatform(platform: string): platform is AnalyticsPlatform {\n return (ANALYTICS_PLATFORMS as readonly string[]).includes(platform);\n}\n\n/**\n * Platforms on which the API can post comments. TWITTER/X, PINTEREST and\n * GOOGLE_BUSINESS are intentionally absent.\n */\nexport const COMMENT_PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"LINKEDIN\",\n \"REDDIT\",\n \"MASTODON\",\n \"DISCORD\",\n \"SLACK\",\n \"BLUESKY\",\n] as const;\n\nexport type CommentPlatform = (typeof COMMENT_PLATFORMS)[number];\n\nexport function isCommentPlatform(platform: string): platform is CommentPlatform {\n return (COMMENT_PLATFORMS as readonly string[]).includes(platform);\n}\n\nexport function normalizeAnalyticsPlatform(input: string): AnalyticsPlatform {\n const platform = normalizePlatform(input);\n if (!isAnalyticsPlatform(platform)) {\n throw new McpToolError(\n \"ANALYTICS_NOT_SUPPORTED\",\n `Analytics are not available for ${platform}. Supported: ${ANALYTICS_PLATFORMS.join(\", \")}.`,\n );\n }\n return platform;\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { z, ZodRawShape } from \"zod\";\nimport { errorResult, type ToolResult } from \"./errors\";\n\ntype InferShape<Shape extends ZodRawShape> = { [K in keyof Shape]: z.infer<Shape[K]> };\n\nexport interface ToolConfig<Shape extends ZodRawShape> {\n title?: string;\n description: string;\n inputSchema?: Shape;\n annotations?: {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n };\n}\n\n/**\n * Register a tool whose handler always returns a structured result — thrown\n * errors (incl. SDK `ApiError`s and `McpToolError`s) become the standard\n * `{ error: { code, message, details? } }` envelope with `isError: true`.\n */\nexport function registerTool<Shape extends ZodRawShape>(\n server: McpServer,\n name: string,\n config: ToolConfig<Shape>,\n handler: (args: InferShape<Shape>) => Promise<ToolResult>,\n): void {\n // The MCP SDK's overloads can't statically tie our handler's arg type to the\n // zod shape here, so the cast is confined to this single boundary.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n server.registerTool(name, config as any, (async (args: any) => {\n try {\n return await handler(args ?? {});\n } catch (error) {\n return errorResult(error);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any);\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n PostCreateData,\n PostGetListData,\n PostGetReconnectSocialAccountCandidatesData,\n PostReconnectSocialAccountData,\n PostUpdateData,\n} from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { COMMENT_PLATFORMS, isCommentPlatform, normalizePlatform, type Platform } from \"../platforms\";\nimport { uploadMediaRefs } from \"../media\";\nimport { buildPostData, deriveTitle, platformsFromData, resolveTargetPlatforms, toIsoDate } from \"../post-data\";\nimport { registerTool } from \"../register-tool\";\n\ntype PostCreateBody = NonNullable<PostCreateData[\"requestBody\"]>;\ntype PostData = PostCreateBody[\"data\"];\ntype PostUpdateBody = NonNullable<PostUpdateData[\"requestBody\"]>;\ntype ReconnectPlatform = NonNullable<PostReconnectSocialAccountData[\"requestBody\"]>[\"type\"];\ntype PostFirstComment = NonNullable<NonNullable<PostCreateBody[\"firstComment\"]>>;\n\n/**\n * Normalize the `firstComment` argument into the per-platform object the API\n * expects: either a platform-keyed map, or one string applied to every\n * comment-capable platform the post targets.\n */\nfunction buildFirstComment(\n firstComment: string | Record<string, string> | undefined,\n targets: Platform[],\n): PostFirstComment | undefined {\n if (firstComment === undefined) return undefined;\n if (typeof firstComment === \"string\") {\n const commentable = targets.filter(isCommentPlatform);\n if (commentable.length === 0) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `None of the targeted platforms support comments, so firstComment has no effect. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n const perPlatform: PostFirstComment = {};\n for (const platform of commentable) perPlatform[platform] = firstComment;\n return perPlatform;\n }\n const result: PostFirstComment = {};\n for (const [key, value] of Object.entries(firstComment)) {\n const platform = normalizePlatform(key);\n if (!isCommentPlatform(platform)) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `A first comment is not supported on ${platform}. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n result[platform] = value;\n }\n return result;\n}\n\nconst referenceKeySchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"Your own identifier for this post. Look the post up later with get_post_by_reference_key.\");\n\nconst firstCommentSchema = z\n .union([z.string().min(1), z.record(z.string(), z.string())])\n .optional()\n .describe(\n 'Comment published as soon as the post itself goes live. A string applies to every comment-capable target; a platform-keyed object targets specific platforms, e.g. {\"INSTAGRAM\":\"more below 👇\"}. Supported on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, LINKEDIN, REDDIT, MASTODON, DISCORD, SLACK, BLUESKY.',\n );\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nconst platformsSchema = z\n .array(z.string().min(1))\n .optional()\n .describe(\n 'Target platforms — names/aliases (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, bluesky, gbp, snapchat) and/or connected integration ids from list_integrations. Required unless \"data\" is provided with platform keys.',\n );\n\nconst mediaSchema = z\n .array(z.string().min(1))\n .optional()\n .describe(\n \"Media to attach: public https:// URLs (or local file paths when this server runs in stdio mode). Uploaded automatically and attached to every targeted platform. For per-platform media, use upload_media + the `data` argument instead.\",\n );\n\nconst platformSettingsSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Per-platform options. Either keyed by platform name, e.g. {\"TIKTOK\":{\"privacy\":\"PUBLIC_TO_EVERYONE\"},\"YOUTUBE\":{\"type\":\"SHORT\",\"privacyStatus\":\"PUBLIC\",\"madeForKids\":false}}, or a flat object applied to every targeted platform. Use this for platform-required fields (Reddit `sr`, Pinterest `boardName`, TikTok `privacy`, YouTube `madeForKids`/`privacyStatus`, Instagram/Facebook `type`).',\n );\n\nconst dataSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Advanced: the full post `data` object keyed by platform, e.g. {\"REDDIT\":{\"sr\":\"r/test\",\"text\":\"hello\",\"uploadIds\":[\"<uploadId>\"]}}. Overrides content/media/platformSettings. Targeted platforms are inferred from its keys unless `platforms` is also given.',\n );\n\nconst titleSchema = z.string().min(1).optional().describe(\"Post title. Defaults to the first line of `content`. Also used as the YouTube video title.\");\n\ninterface ComposeArgs {\n teamId?: string;\n content?: string;\n platforms?: string[];\n media?: string[];\n platformSettings?: Record<string, unknown>;\n data?: Record<string, unknown>;\n title?: string;\n}\n\nasync function composePost(ctx: ServerContext, args: ComposeArgs) {\n const teamId = await resolveTeamId(ctx, args.teamId);\n\n let targets: Platform[];\n if (args.platforms && args.platforms.length > 0) {\n targets = await resolveTargetPlatforms(ctx.client, teamId, args.platforms);\n } else if (args.data) {\n targets = platformsFromData(args.data);\n } else {\n throw new McpToolError(\n \"NO_TARGET\",\n 'Provide \"platforms\" (platform names or integration ids), or a \"data\" object keyed by platform.',\n );\n }\n if (targets.length === 0) throw new McpToolError(\"NO_TARGET\", \"Could not determine any target platform for this post.\");\n\n const mediaUploadIds = await uploadMediaRefs(ctx.client, teamId, args.media ?? []);\n const data = buildPostData(targets, {\n content: args.content,\n mediaUploadIds,\n platformSettings: args.platformSettings,\n data: args.data,\n }) as unknown as PostData;\n\n return {\n teamId,\n socialAccountTypes: targets,\n data,\n title: args.title ?? deriveTitle(args.content, \"Untitled post\"),\n };\n}\n\nexport function registerPostTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post\",\n {\n title: \"Create a post (publish now)\",\n description:\n \"Publish a post immediately to one or more connected social-media integrations. Returns the created post (with its id and status). Set `draft: true` to save it as a draft instead of publishing. For a future-dated post use schedule_post.\",\n inputSchema: {\n teamId: teamIdSchema,\n content: z.string().optional().describe(\"Post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n title: titleSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n draft: z.boolean().optional().default(false).describe(\"If true, save as a DRAFT instead of publishing now.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, content, platforms, media, platformSettings, data, title, referenceKey, firstComment, draft }) => {\n const composed = await composePost(ctx, { teamId, content, platforms, media, platformSettings, data, title });\n const requestBody: PostCreateBody = {\n teamId: composed.teamId,\n title: composed.title,\n postDate: new Date().toISOString(),\n status: draft ? \"DRAFT\" : \"SCHEDULED\",\n socialAccountTypes: composed.socialAccountTypes,\n data: composed.data,\n };\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n const resolvedFirstComment = buildFirstComment(firstComment, composed.socialAccountTypes);\n if (resolvedFirstComment) requestBody.firstComment = resolvedFirstComment;\n return jsonResult(await ctx.client.post.postCreate({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"schedule_post\",\n {\n title: \"Schedule a post for later\",\n description:\n \"Schedule a post to be published at a specific date/time on one or more connected integrations. Same inputs as create_post plus a required ISO-8601 `date`. Returns the scheduled post.\",\n inputSchema: {\n teamId: teamIdSchema,\n date: z.string().min(1).describe(\"When to publish — ISO 8601, e.g. 2026-06-01T09:00:00Z.\"),\n content: z.string().optional().describe(\"Post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n title: titleSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, date, content, platforms, media, platformSettings, data, title, referenceKey, firstComment }) => {\n const postDate = toIsoDate(date, \"date\");\n const composed = await composePost(ctx, { teamId, content, platforms, media, platformSettings, data, title });\n const requestBody: PostCreateBody = {\n teamId: composed.teamId,\n title: composed.title,\n postDate,\n status: \"SCHEDULED\",\n socialAccountTypes: composed.socialAccountTypes,\n data: composed.data,\n };\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n const resolvedFirstComment = buildFirstComment(firstComment, composed.socialAccountTypes);\n if (resolvedFirstComment) requestBody.firstComment = resolvedFirstComment;\n return jsonResult(await ctx.client.post.postCreate({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"list_posts\",\n {\n title: \"List recent posts\",\n description: \"List recent posts for a team, newest first, with optional filters by status, platform, date range and free-text query.\",\n inputSchema: {\n teamId: teamIdSchema,\n limit: z.number().int().positive().max(100).optional().default(20).describe(\"Max number of posts to return (default 20, max 100).\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of posts to skip (for pagination).\"),\n status: z\n .enum([\"DRAFT\", \"SCHEDULED\", \"POSTED\", \"ERROR\", \"DELETED\", \"PROCESSING\", \"REVIEW\", \"RETRYING\"])\n .optional()\n .describe(\"Filter by post status.\"),\n platforms: z.array(z.string().min(1)).optional().describe(\"Filter by platform name/alias.\"),\n from: z.string().optional().describe(\"Only posts with postDate on/after this ISO-8601 date.\"),\n to: z.string().optional().describe(\"Only posts with postDate on/before this ISO-8601 date.\"),\n query: z.string().optional().describe(\"Free-text search over post titles/content.\"),\n order: z.enum([\"ASC\", \"DESC\"]).optional().describe(\"Sort direction (default DESC).\"),\n orderBy: z.enum([\"createdAt\", \"updatedAt\", \"postDate\", \"postedDate\", \"deletedAt\"]).optional().describe(\"Sort field (default postDate).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, limit, offset, status, platforms, from, to, query, order, orderBy }) => {\n const id = await resolveTeamId(ctx, teamId);\n const normalizedPlatforms = (platforms ?? []).map(normalizePlatform);\n const params: PostGetListData = {\n teamId: id,\n limit,\n offset,\n status: status ?? undefined,\n platforms: normalizedPlatforms.length > 0 ? (normalizedPlatforms as PostGetListData[\"platforms\"]) : undefined,\n postDateFrom: from ? toIsoDate(from, \"from\") : undefined,\n postDateTo: to ? toIsoDate(to, \"to\") : undefined,\n q: query,\n order: order ?? undefined,\n orderBy: orderBy ?? undefined,\n };\n return jsonResult(await ctx.client.post.postGetList(params));\n },\n );\n\n registerTool(\n server,\n \"get_post\",\n {\n title: \"Get a post by id\",\n description: \"Fetch a single post by its bundle.social id, including its per-platform data and status.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_post\",\n {\n title: \"Delete a post\",\n description: \"Delete a post by its bundle.social id. This is destructive and cannot be undone.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postDelete({ id })),\n );\n\n registerTool(\n server,\n \"update_post\",\n {\n title: \"Update a post\",\n description:\n \"Update an existing post by id — change its title, publish date, status (DRAFT/SCHEDULED), targeted platforms and/or per-platform content. Only the fields you pass are changed. If you change content/media without `platforms`, the post's current platforms are reused.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Post id.\"),\n title: z.string().optional().describe(\"New post title.\"),\n date: z.string().optional().describe(\"New publish date, ISO 8601.\"),\n status: z.enum([\"DRAFT\", \"SCHEDULED\"]).optional().describe(\"New status.\"),\n content: z.string().optional().describe(\"New post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, title, date, status, content, platforms, media, platformSettings, data, referenceKey, firstComment, teamId }) => {\n const resolvedTeamId = await resolveTeamId(ctx, teamId);\n const wantsDataChange =\n content !== undefined || (media?.length ?? 0) > 0 || platformSettings !== undefined || data !== undefined;\n\n let targets: Platform[] | undefined;\n if (platforms && platforms.length > 0) {\n targets = await resolveTargetPlatforms(ctx.client, resolvedTeamId, platforms);\n } else if (data) {\n targets = platformsFromData(data);\n } else if (wantsDataChange) {\n const existing = await ctx.client.post.postGet({ id });\n targets = Object.keys(existing.data ?? {}) as Platform[];\n if (targets.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Could not determine the post's platforms — pass `platforms`.\");\n }\n }\n\n const requestBody: PostUpdateBody = {};\n if (title !== undefined) requestBody.title = title;\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n if (firstComment !== undefined) {\n const commentTargets = targets ?? (Object.keys((await ctx.client.post.postGet({ id })).data ?? {}) as Platform[]);\n requestBody.firstComment = buildFirstComment(firstComment, commentTargets);\n }\n if (date) requestBody.postDate = toIsoDate(date, \"date\");\n if (status) requestBody.status = status;\n if (targets && targets.length > 0) requestBody.socialAccountTypes = targets as PostUpdateBody[\"socialAccountTypes\"];\n if (wantsDataChange && targets && targets.length > 0) {\n const mediaUploadIds = await uploadMediaRefs(ctx.client, resolvedTeamId, media ?? []);\n requestBody.data = buildPostData(targets, {\n content,\n mediaUploadIds,\n platformSettings,\n data,\n }) as unknown as PostUpdateBody[\"data\"];\n }\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\n \"NOTHING_TO_UPDATE\",\n \"Nothing to update — pass at least one of title, date, status, content, media, platformSettings, data, referenceKey, firstComment, platforms.\",\n );\n }\n return jsonResult(await ctx.client.post.postUpdate({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"retry_post\",\n {\n title: \"Retry a failed post\",\n description: \"Retry publishing a post that ended in the ERROR state.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postRetry({ id })),\n );\n\n registerTool(\n server,\n \"get_post_by_reference_key\",\n {\n title: \"Get a post by reference key\",\n description:\n \"Fetch a single post by the `referenceKey` set when it was created, instead of by bundle.social post id. Use this when you track posts under your own identifiers.\",\n inputSchema: { referenceKey: z.string().min(1).describe(\"The reference key you set on the post.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ referenceKey }) => jsonResult(await ctx.client.post.postGetByReferenceKey({ referenceKey })),\n );\n\n registerTool(\n server,\n \"list_reconnect_candidates\",\n {\n title: \"List posts waiting for a reconnected account\",\n description:\n \"List draft/scheduled posts that lost their link to a social account after a disconnect and can be reattached to a newly connected account of the same platform. Pair with reconnect_posts.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().min(1).describe(\"Platform of the reconnected account (name or alias).\"),\n limit: z.number().int().positive().max(100).optional().describe(\"Max number of posts to return.\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of posts to skip.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n const params: PostGetReconnectSocialAccountCandidatesData = {\n teamId: id,\n type: normalizePlatform(platform) as PostGetReconnectSocialAccountCandidatesData[\"type\"],\n limit,\n offset,\n };\n return jsonResult(await ctx.client.post.postGetReconnectSocialAccountCandidates(params));\n },\n );\n\n registerTool(\n server,\n \"reconnect_posts\",\n {\n title: \"Reattach posts to a reconnected account\",\n description:\n \"Attach a newly connected social account to posts that lost their link to the previous account of that platform. Without `postIds`, every candidate is reattached.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().min(1).describe(\"Platform of the reconnected account (name or alias).\"),\n postIds: z.array(z.string().min(1)).optional().describe(\"Only reattach these post ids. Defaults to every candidate.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, platform, postIds }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.post.postReconnectSocialAccount({\n requestBody: {\n teamId: id,\n type: normalizePlatform(platform) as ReconnectPlatform,\n ...(postIds && postIds.length > 0 ? { postIds } : {}),\n },\n }),\n );\n },\n );\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\nconst MIME_BY_EXT: Record<string, string> = {\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".bmp\": \"image/bmp\",\n \".tif\": \"image/tiff\",\n \".tiff\": \"image/tiff\",\n \".heic\": \"image/heic\",\n \".heif\": \"image/heif\",\n \".mp4\": \"video/mp4\",\n \".m4v\": \"video/x-m4v\",\n \".mov\": \"video/quicktime\",\n \".webm\": \"video/webm\",\n \".avi\": \"video/x-msvideo\",\n \".mkv\": \"video/x-matroska\",\n \".pdf\": \"application/pdf\",\n \".mp3\": \"audio/mpeg\",\n \".m4a\": \"audio/mp4\",\n \".wav\": \"audio/wav\",\n};\n\nfunction isUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value.trim());\n}\n\n/** Files larger than this must use the chunked/large-upload flow (init + signed PUT + finalize). */\nexport const LARGE_UPLOAD_THRESHOLD_BYTES = 90 * 1024 * 1024;\n\n/** MIME types accepted by the large-upload (init) endpoint. */\nconst LARGE_UPLOAD_MIME_BY_EXT: Record<string, \"image/jpg\" | \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"video/mp4\" | \"application/pdf\"> = {\n \".jpg\": \"image/jpg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".mp4\": \"video/mp4\",\n \".pdf\": \"application/pdf\",\n};\n\n/**\n * Upload one media reference (a public URL, or — in stdio mode — a local file\n * path) and return the resulting upload object. Local files larger than ~90 MB\n * are uploaded via the large-upload flow automatically.\n */\nexport async function uploadMediaRef(client: Bundlesocial, teamId: string, ref: string) {\n if (isUrl(ref)) {\n return client.upload.uploadCreateFromUrl({ requestBody: { teamId, url: ref.trim() } });\n }\n const absolutePath = path.resolve(ref);\n let buffer: Buffer;\n try {\n buffer = await fs.readFile(absolutePath);\n } catch {\n throw new McpToolError(\n \"MEDIA_NOT_FOUND\",\n `Could not read media \"${ref}\". Provide a public https:// URL, or a local file path that exists on the machine running this MCP server (stdio mode only).`,\n { path: absolutePath },\n );\n }\n if (buffer.byteLength > LARGE_UPLOAD_THRESHOLD_BYTES) {\n return uploadLargeMedia(client, teamId, absolutePath, buffer);\n }\n const mime = MIME_BY_EXT[path.extname(absolutePath).toLowerCase()] ?? \"application/octet-stream\";\n const file = new File([buffer], path.basename(absolutePath), { type: mime });\n return client.upload.uploadCreate({ formData: { teamId, file } });\n}\n\n/**\n * Upload a (large) local file via the init → signed PUT → finalize flow.\n * Only `image/jpg|jpeg|png|gif`, `video/mp4` and `application/pdf` are supported.\n */\nasync function uploadLargeMedia(client: Bundlesocial, teamId: string, absolutePath: string, buffer: Buffer) {\n const ext = path.extname(absolutePath).toLowerCase();\n const mimeType = LARGE_UPLOAD_MIME_BY_EXT[ext];\n if (!mimeType) {\n throw new McpToolError(\n \"LARGE_UPLOAD_UNSUPPORTED_TYPE\",\n `Large uploads (>90 MB) only support .jpg, .jpeg, .png, .gif, .mp4 and .pdf — got \"${ext || \"no extension\"}\".`,\n { path: absolutePath },\n );\n }\n const init = await client.upload.uploadInitLargeUpload({ requestBody: { teamId, fileName: path.basename(absolutePath), mimeType } });\n const put = await fetch(init.url, { method: \"PUT\", headers: { \"content-type\": mimeType }, body: new Uint8Array(buffer) });\n if (!put.ok) {\n throw new McpToolError(\"LARGE_UPLOAD_FAILED\", `Uploading the file to storage failed (HTTP ${put.status}).`, { status: put.status });\n }\n return client.upload.uploadFinalizeLargeUpload({ requestBody: { teamId, path: init.path } });\n}\n\nexport async function uploadMediaRefs(client: Bundlesocial, teamId: string, refs: string[]): Promise<string[]> {\n const ids: string[] = [];\n for (const ref of refs) {\n const upload = await uploadMediaRef(client, teamId, ref);\n ids.push(upload.id);\n }\n return ids;\n}\n","import type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\nimport { PLATFORMS, type Platform, normalizePlatform, tryNormalizePlatform } from \"./platforms\";\n\nfunction asPlainObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new McpToolError(\"INVALID_INPUT\", `${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * Resolve `platforms` arguments to a unique platform list. A value is used\n * directly when it is a recognised platform name/alias; otherwise it is treated\n * as a connected social-account id and resolved via the team's integrations.\n */\nexport async function resolveTargetPlatforms(client: Bundlesocial, teamId: string, rawTargets: string[]): Promise<Platform[]> {\n const resolved = new Set<Platform>();\n const accountIds: string[] = [];\n\n for (const raw of rawTargets) {\n const platform = tryNormalizePlatform(raw);\n if (platform) resolved.add(platform);\n else accountIds.push(raw.trim());\n }\n\n if (accountIds.length > 0) {\n const team = await client.team.teamGetTeam({ id: teamId });\n const accounts = team.socialAccounts ?? [];\n for (const id of accountIds) {\n const account = accounts.find((candidate) => candidate.id === id);\n if (!account) {\n throw new McpToolError(\n \"INTEGRATION_NOT_FOUND\",\n `No connected integration with id \"${id}\" in team ${teamId}. Call list_integrations to see ids, or use a platform name like \"x\" or \"tiktok\".`,\n { availableIntegrations: accounts.map((a) => ({ id: a.id, type: a.type, username: a.username })) },\n );\n }\n resolved.add(account.type as Platform);\n }\n }\n\n return [...resolved];\n}\n\nfunction isPlatformKeyedObject(value: Record<string, unknown>): boolean {\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key) => PLATFORMS.includes(key.trim().toUpperCase() as Platform));\n}\n\nfunction expandPlatformSettings(\n settings: Record<string, unknown> | undefined,\n platforms: Platform[],\n): Record<Platform, Record<string, unknown>> {\n const result = Object.fromEntries(platforms.map((p) => [p, {}])) as Record<Platform, Record<string, unknown>>;\n if (!settings) return result;\n if (isPlatformKeyedObject(settings)) {\n for (const [key, value] of Object.entries(settings)) {\n const platform = key.trim().toUpperCase() as Platform;\n if (platform in result) result[platform] = { ...result[platform], ...asPlainObject(value, `platformSettings.${key}`) };\n }\n return result;\n }\n for (const platform of platforms) result[platform] = { ...settings };\n return result;\n}\n\nexport interface BuildPostDataInput {\n content?: string;\n mediaUploadIds: string[];\n platformSettings?: Record<string, unknown>;\n /** Advanced escape hatch: the full `data` object keyed by platform. */\n data?: Record<string, unknown>;\n}\n\n/** Build the API's `data` object, one entry per targeted platform. */\nexport function buildPostData(platforms: Platform[], input: BuildPostDataInput): Record<string, unknown> {\n if (input.data) return input.data;\n const perPlatform = expandPlatformSettings(input.platformSettings, platforms);\n const data: Record<string, unknown> = {};\n for (const platform of platforms) {\n data[platform] = {\n ...(input.content !== undefined ? { text: input.content } : {}),\n ...(input.mediaUploadIds.length > 0 ? { uploadIds: input.mediaUploadIds } : {}),\n ...perPlatform[platform],\n };\n }\n return data;\n}\n\n/** Determine targeted platforms when only `data` is given (use its keys). */\nexport function platformsFromData(data: Record<string, unknown>): Platform[] {\n return Object.keys(data).map((key) => normalizePlatform(key));\n}\n\nexport function deriveTitle(content: string | undefined, fallback: string): string {\n const firstLine = (content ?? \"\").split(\"\\n\").map((line) => line.trim()).find((line) => line.length > 0);\n if (!firstLine) return fallback;\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine;\n}\n\nexport function toIsoDate(value: string, label: string): string {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `${label} is not a valid ISO 8601 date/time: \"${value}\". Example: 2026-06-01T09:00:00Z`);\n }\n return date.toISOString();\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { CommentCreateData, CommentGetListData, CommentImportCreateData, CommentUpdateData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { COMMENT_PLATFORMS, type CommentPlatform, isCommentPlatform, normalizePlatform } from \"../platforms\";\nimport { resolveTargetPlatforms } from \"../post-data\";\nimport { registerTool } from \"../register-tool\";\n\ntype CommentImportPlatform = NonNullable<CommentImportCreateData[\"requestBody\"]>[\"socialAccountType\"];\n\nconst commentImportStatusSchema = z.enum([\"PENDING\", \"FETCHING\", \"RETRYING\", \"COMPLETED\", \"SKIPPED\", \"FAILED\", \"RATE_LIMITED\"]);\n\ntype CommentCreateBody = NonNullable<CommentCreateData[\"requestBody\"]>;\ntype CommentUpdateBody = NonNullable<CommentUpdateData[\"requestBody\"]>;\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nfunction assertCommentPlatforms(platforms: string[]): CommentPlatform[] {\n const bad = platforms.filter((platform) => !isCommentPlatform(platform));\n if (bad.length > 0) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `Comments are not available for ${bad.join(\", \")}. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n return platforms as CommentPlatform[];\n}\n\nfunction toIso(value: string): string {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `date is not a valid ISO 8601 date/time: \"${value}\". Example: 2026-06-01T09:00:00Z`);\n }\n return date.toISOString();\n}\n\nexport function registerCommentTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_comment\",\n {\n title: \"Comment on a post\",\n description:\n \"Post one or more comments on a post you created (`postId`) or on a post brought in by create_post_import (`importedPostId`). Pass `content` multiple times to create a chain (the first replies to the post, each subsequent one replies to the previous comment) — useful for X-style threads via comments. Use `fetchedParentCommentId` to reply to a comment pulled in by create_comment_import. Comments are supported on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, LINKEDIN, REDDIT, MASTODON, DISCORD, SLACK, BLUESKY. Returns the created comment(s).\",\n inputSchema: {\n postId: z.string().min(1).optional().describe(\"Id of the bundle.social post to comment on. Either this or importedPostId is required.\"),\n importedPostId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Id of an imported (post-history) post to comment on instead of postId. Requires `platforms`.\"),\n fetchedParentCommentId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Reply to a comment fetched by create_comment_import (its imported-comment id) instead of to the post itself.\"),\n content: z.array(z.string().min(1)).min(1).describe(\"Comment text. Pass multiple to create a chain of replies.\"),\n platforms: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Target comment-capable platform names/aliases and/or integration ids. Defaults to the post's platforms (filtered to comment-capable ones).\"),\n date: z.string().optional().describe(\"When to post the (first) comment, ISO 8601. Default: now.\"),\n delayMinutes: z.number().int().nonnegative().optional().default(0).describe(\"For a chain, minutes to wait between each comment.\"),\n draft: z.boolean().optional().default(false).describe(\"If true, create the comment(s) as DRAFT instead of posting.\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, importedPostId, fetchedParentCommentId, content, platforms, date, delayMinutes, draft, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n if (!postId && !importedPostId) {\n throw new McpToolError(\"NO_POST\", \"Pass `postId` (a bundle.social post) or `importedPostId` (a post brought in by create_post_import).\");\n }\n let resolved: CommentPlatform[];\n if (platforms && platforms.length > 0) {\n resolved = assertCommentPlatforms(await resolveTargetPlatforms(ctx.client, id, platforms));\n } else if (postId) {\n // An imported post has no bundle.social `data` to infer platforms from, so targets are explicit there.\n const post = await ctx.client.post.postGet({ id: postId });\n resolved = Object.keys(post.data ?? {}).filter(isCommentPlatform);\n if (resolved.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Could not determine comment platforms from the post — pass `platforms` (comment-capable only).\");\n }\n } else {\n throw new McpToolError(\"NO_TARGET\", \"Pass `platforms` when commenting on an imported post (comment-capable only).\");\n }\n const status: CommentCreateBody[\"status\"] = draft ? \"DRAFT\" : \"SCHEDULED\";\n const baseDate = date ? new Date(toIso(date)) : new Date();\n\n const created = [];\n let parentCommentId: string | undefined;\n for (let index = 0; index < content.length; index += 1) {\n const text = content[index];\n const postDate = new Date(baseDate.getTime() + index * (delayMinutes ?? 0) * 60_000).toISOString();\n const perPlatform = Object.fromEntries(resolved.map((platform) => [platform, { text }]));\n const comment = await ctx.client.comment.commentCreate({\n requestBody: {\n teamId: id,\n ...(postId ? { internalPostId: postId } : { importedPostId: importedPostId as string }),\n ...(parentCommentId ? { internalParentCommentId: parentCommentId } : {}),\n // Only the first comment of a chain replies to the fetched comment; the rest chain off each other.\n ...(!parentCommentId && fetchedParentCommentId ? { fetchedParentCommentId } : {}),\n status,\n postDate,\n socialAccountTypes: resolved as never,\n data: perPlatform as never,\n text,\n },\n });\n created.push(comment);\n parentCommentId = comment.id;\n }\n return jsonResult(created.length === 1 ? created[0] : created);\n },\n );\n\n registerTool(\n server,\n \"list_comments\",\n {\n title: \"List comments\",\n description: \"List comments for a team, optionally filtered by post, status and platform.\",\n inputSchema: {\n postId: z.string().optional().describe(\"Only comments on this post.\"),\n limit: z.number().int().positive().max(100).optional().default(20),\n offset: z.number().int().nonnegative().optional(),\n status: z.enum([\"DRAFT\", \"SCHEDULED\", \"POSTED\", \"ERROR\", \"DELETED\", \"PROCESSING\", \"RETRYING\"]).optional(),\n platforms: z.array(z.string().min(1)).optional().describe(\"Filter by comment-capable platform name/alias.\"),\n query: z.string().optional(),\n order: z.enum([\"ASC\", \"DESC\"]).optional(),\n orderBy: z.enum([\"createdAt\", \"updatedAt\", \"deletedAt\"]).optional(),\n teamId: teamIdSchema,\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postId, limit, offset, status, platforms, query, order, orderBy, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n const normalized = assertCommentPlatforms((platforms ?? []).map(normalizePlatform));\n const params: CommentGetListData = {\n teamId: id,\n postId,\n limit,\n offset,\n status: status ?? undefined,\n platforms: normalized.length > 0 ? (normalized as CommentGetListData[\"platforms\"]) : undefined,\n q: query,\n order: order ?? undefined,\n orderBy: orderBy ?? undefined,\n };\n return jsonResult(await ctx.client.comment.commentGetList(params));\n },\n );\n\n registerTool(\n server,\n \"get_comment\",\n {\n title: \"Get a comment by id\",\n description: \"Fetch a single comment by its bundle.social id.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_comment\",\n {\n title: \"Delete a comment\",\n description: \"Delete a comment by its bundle.social id. Destructive.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentDelete({ id })),\n );\n\n registerTool(\n server,\n \"update_comment\",\n {\n title: \"Update a comment\",\n description:\n \"Update an existing comment by id — change its title, scheduled date, status (DRAFT/SCHEDULED), targeted platforms and/or per-platform text. Only the fields you pass are changed. Use `data` for the full per-platform object, or `content` + `platforms` for a same-text-everywhere change.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Comment id.\"),\n title: z.string().optional().describe(\"New title.\"),\n date: z.string().optional().describe(\"New scheduled date, ISO 8601.\"),\n status: z.enum([\"DRAFT\", \"SCHEDULED\"]).optional().describe(\"New status.\"),\n content: z.string().optional().describe(\"New comment text, applied to every platform in `platforms`.\"),\n platforms: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Comment-capable platform name/alias. Required when changing `content` without supplying `data`.\"),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Advanced: the full comment `data` object keyed by platform, e.g. {\"LINKEDIN\":{\"text\":\"new\"}}.'),\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, title, date, status, content, platforms, data }) => {\n const normalized = assertCommentPlatforms((platforms ?? []).map(normalizePlatform));\n const wantsDataChange = content !== undefined || data !== undefined;\n\n const requestBody: CommentUpdateBody = {};\n if (title !== undefined) requestBody.title = title;\n if (date) {\n const parsed = new Date(date);\n if (Number.isNaN(parsed.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `date is not a valid ISO 8601 date/time: \"${date}\". Example: 2026-06-01T09:00:00Z`);\n }\n requestBody.postDate = parsed.toISOString();\n }\n if (status) requestBody.status = status;\n if (normalized.length > 0) requestBody.socialAccountTypes = normalized as CommentUpdateBody[\"socialAccountTypes\"];\n if (wantsDataChange) {\n if (data) {\n requestBody.data = data as unknown as CommentUpdateBody[\"data\"];\n } else {\n if (normalized.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Pass `platforms` when changing `content` (the per-platform comment text needs to know which platforms to target).\");\n }\n const perPlatform = Object.fromEntries(normalized.map((platform) => [platform, { text: content as string }]));\n requestBody.data = perPlatform as unknown as CommentUpdateBody[\"data\"];\n }\n }\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\n \"NOTHING_TO_UPDATE\",\n \"Nothing to update — pass at least one of title, date, status, content (+ platforms), data.\",\n );\n }\n return jsonResult(await ctx.client.comment.commentUpdate({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"retry_comment\",\n {\n title: \"Retry a failed comment\",\n description: \"Retry publishing a comment that ended in the ERROR state.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentRetry({ id })),\n );\n\n // --- comment imports (fetch incoming comments on a published post) ---------\n\n registerTool(\n server,\n \"create_comment_import\",\n {\n title: \"Import comments on a post\",\n description:\n \"Start an async import of the (incoming) comments on a published post for one platform. Comment imports are available on FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, TIKTOK, REDDIT, THREADS, MASTODON, BLUESKY. Poll get_comment_import / list_comment_imports for status and list_imported_comments for the fetched comments.\",\n inputSchema: {\n postId: z.string().min(1).describe(\"Id of the published post to import comments for.\"),\n platform: z.string().min(1).describe(\"Platform name/alias to import comments from.\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportCreate({\n requestBody: { teamId: id, postId, socialAccountType: normalizePlatform(platform) as CommentImportPlatform },\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"list_comment_imports\",\n {\n title: \"List comment imports\",\n description: \"List comment-import jobs for a team, optionally filtered by post and status.\",\n inputSchema: {\n teamId: teamIdSchema,\n postId: z.string().optional().describe(\"Only imports for this post.\"),\n status: commentImportStatusSchema.optional().describe(\"Filter by import status.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, postId, status, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.comment.commentImportGetList({ teamId: id, postId, status, limit: limit ?? null, offset: offset ?? null }));\n },\n );\n\n registerTool(\n server,\n \"get_comment_import\",\n {\n title: \"Get a comment import by id\",\n description: \"Fetch a single comment-import job by its id, including its status and the number of comments imported.\",\n inputSchema: { importId: z.string().min(1).describe(\"Comment import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.comment.commentImportGetById({ importId })),\n );\n\n registerTool(\n server,\n \"list_imported_comments\",\n {\n title: \"List imported comments for a post\",\n description: \"List the comments fetched by comment imports for a post, optionally filtered by platform / social account.\",\n inputSchema: {\n postId: z.string().min(1).describe(\"Id of the post whose imported comments to list.\"),\n platform: z.string().optional().describe(\"Filter by platform name/alias.\"),\n socialAccountId: z.string().optional().describe(\"Filter by social-account id.\"),\n teamId: teamIdSchema,\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postId, platform, socialAccountId, teamId, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportGetFetchedComments({\n teamId: id,\n postId,\n platform: platform ? (normalizePlatform(platform) as CommentImportPlatform) : undefined,\n socialAccountId,\n limit: limit ?? null,\n offset: offset ?? null,\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"act_on_imported_comment\",\n {\n title: \"Moderate an imported comment\",\n description:\n \"Act on a comment fetched by a comment import — delete, hide/unhide, like/unlike, or approve/reject it. Supported actions vary by platform; DELETE and HIDE are the widely available ones.\",\n inputSchema: {\n commentId: z.string().min(1).describe(\"Id of the fetched (imported) comment.\"),\n action: z\n .enum([\"DELETE\", \"HIDE\", \"UNHIDE\", \"LIKE\", \"UNLIKE\", \"APPROVE\", \"REJECT\"])\n .describe(\"What to do with the comment.\"),\n reason: z.string().optional().describe(\"Optional reason recorded with the action.\"),\n banAuthor: z.boolean().optional().describe(\"Also ban the comment's author, where the platform supports it.\"),\n teamId: teamIdSchema,\n },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ commentId, action, reason, banAuthor, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportActionFetchedComment({\n commentId,\n requestBody: {\n teamId: id,\n action,\n ...(reason !== undefined ? { reason } : {}),\n ...(banAuthor ? { banAuthor: true } : {}),\n },\n }),\n );\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { uploadMediaRef } from \"../media\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerMediaTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"upload_media\",\n {\n title: \"Upload media\",\n description:\n \"Upload a media file (image, video or document) to a bundle.social team from a public https:// URL — or, when this server runs in stdio mode, a local file path. Local files larger than ~90 MB are uploaded via the large-upload flow automatically (only .jpg/.jpeg/.png/.gif/.mp4/.pdf are supported above that size). Returns the upload object; pass its `id` to create_post/schedule_post via the `data` argument (e.g. {\\\"TWITTER\\\":{\\\"text\\\":\\\"hi\\\",\\\"uploadIds\\\":[\\\"<id>\\\"]}}).\",\n inputSchema: {\n teamId: teamIdSchema,\n source: z.string().min(1).describe(\"A public https:// URL, or a local file path (stdio mode only).\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, source }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await uploadMediaRef(ctx.client, id, source));\n },\n );\n\n registerTool(\n server,\n \"list_media\",\n {\n title: \"List uploaded media\",\n description: \"List media uploads for a team, optionally filtered by type (image/video/document) and usage status (USED/UNUSED).\",\n inputSchema: {\n teamId: teamIdSchema,\n type: z.enum([\"image\", \"video\", \"document\"]).optional().describe(\"Filter by media type.\"),\n status: z.enum([\"USED\", \"UNUSED\"]).optional().describe(\"Filter by whether the upload is attached to a post.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, type, status }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadGetList({ teamId: id, type: type ?? null, status: status ?? null }));\n },\n );\n\n registerTool(\n server,\n \"get_media\",\n {\n title: \"Get an upload by id\",\n description: \"Fetch a single media upload by its bundle.social id.\",\n inputSchema: { id: z.string().min(1).describe(\"Upload id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.upload.uploadGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_media\",\n {\n title: \"Delete an upload\",\n description: \"Delete a media upload by its bundle.social id. Destructive.\",\n inputSchema: { id: z.string().min(1).describe(\"Upload id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.upload.uploadDelete({ id })),\n );\n\n registerTool(\n server,\n \"delete_media_many\",\n {\n title: \"Delete multiple uploads\",\n description: \"Delete several media uploads at once by their ids. Destructive.\",\n inputSchema: { ids: z.array(z.string().min(1)).min(1).describe(\"Upload ids to delete.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ ids }) => jsonResult(await ctx.client.upload.uploadDeleteMany({ requestBody: { ids } })),\n );\n\n registerTool(\n server,\n \"init_large_upload\",\n {\n title: \"Initialize a large upload\",\n description:\n \"Low-level: start a >90 MB upload. Returns a signed `url` (PUT the file bytes there with the matching content-type) and a `path` to pass to finalize_large_upload. Prefer `upload_media` with a local file path in stdio mode — it does this automatically.\",\n inputSchema: {\n teamId: teamIdSchema,\n fileName: z.string().min(1).describe(\"File name.\"),\n mimeType: z.enum([\"image/jpg\", \"image/jpeg\", \"image/png\", \"image/gif\", \"video/mp4\", \"application/pdf\"]).describe(\"File MIME type.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, fileName, mimeType }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadInitLargeUpload({ requestBody: { teamId: id, fileName, mimeType } }));\n },\n );\n\n registerTool(\n server,\n \"finalize_large_upload\",\n {\n title: \"Finalize a large upload\",\n description: \"Low-level: finalize a >90 MB upload after the bytes have been PUT to the signed URL from init_large_upload. Returns the upload object.\",\n inputSchema: {\n teamId: teamIdSchema,\n path: z.string().min(1).describe(\"The `path` returned by init_large_upload.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, path }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadFinalizeLargeUpload({ requestBody: { teamId: id, path } }));\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { AnalyticsGetSocialAccountAnalyticsData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, errorSummary, jsonResult } from \"../errors\";\nimport { isAnalyticsPlatform, normalizeAnalyticsPlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype AnalyticsPlatform = AnalyticsGetSocialAccountAnalyticsData[\"platformType\"];\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nfunction withinRange(value: string | null | undefined, from?: string, to?: string): boolean {\n if (!from && !to) return true;\n if (!value) return false;\n const time = new Date(value).getTime();\n if (Number.isNaN(time)) return false;\n if (from && time < new Date(from).getTime()) return false;\n if (to && time > new Date(to).getTime()) return false;\n return true;\n}\n\nexport function registerAnalyticsTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"get_post_analytics\",\n {\n title: \"Get post analytics\",\n description: \"Get engagement metrics (impressions, views, likes, comments, …) for a single post by its bundle.social id. Optionally limit to one platform. Set `raw: true` for the unprocessed provider payload.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Post id.\"),\n platform: z.string().optional().describe(\"Limit to a single platform name/alias (e.g. instagram, tiktok, youtube). Analytics are not available for X/Twitter, Discord or Slack.\"),\n raw: z.boolean().optional().default(false).describe(\"If true, return the raw provider analytics payload instead of the normalized metrics.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id, platform, raw }) => {\n const platformType = platform ? normalizeAnalyticsPlatform(platform) : undefined;\n const response = raw\n ? await ctx.client.analytics.analyticsGetPostAnalyticsRaw({ postId: id, platformType })\n : await ctx.client.analytics.analyticsGetPostAnalytics({ postId: id, platformType });\n return jsonResult(response);\n },\n );\n\n registerTool(\n server,\n \"get_account_analytics\",\n {\n title: \"Get social-account analytics\",\n description:\n \"Get the analytics time-series (followers, impressions, likes, …) for a connected account on the given platform. Analytics are available on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, REDDIT, PINTEREST, MASTODON, LINKEDIN, BLUESKY, GOOGLE_BUSINESS. Set `raw: true` for the unprocessed provider payload.\",\n inputSchema: {\n platform: z.string().min(1).describe(\"Platform name/alias.\"),\n teamId: teamIdSchema,\n raw: z.boolean().optional().default(false).describe(\"If true, return the raw provider analytics payload.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId, raw }) => {\n const id = await resolveTeamId(ctx, teamId);\n const platformType = normalizeAnalyticsPlatform(platform);\n const response = raw\n ? await ctx.client.analytics.analyticsGetSocialAccountAnalyticsRaw({ teamId: id, platformType })\n : await ctx.client.analytics.analyticsGetSocialAccountAnalytics({ teamId: id, platformType });\n return jsonResult(response);\n },\n );\n\n registerTool(\n server,\n \"get_bulk_post_analytics\",\n {\n title: \"Get analytics for multiple posts\",\n description: \"Get analytics for up to 60 posts in one request (paginated, 20 per page) for a single platform.\",\n inputSchema: {\n postIds: z.array(z.string().min(1)).min(1).max(60).describe(\"Post ids (max 60).\"),\n platform: z.string().min(1).describe(\"Platform name/alias the posts belong to.\"),\n page: z.number().int().positive().optional().describe(\"Page (1-based).\"),\n limit: z.number().int().positive().max(20).optional().describe(\"Page size (max 20).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postIds, platform, page, limit }) =>\n jsonResult(\n await ctx.client.analytics.analyticsGetBulkPostAnalytics({\n postIds,\n platformType: normalizeAnalyticsPlatform(platform),\n page,\n limit,\n }),\n ),\n );\n\n registerTool(\n server,\n \"refresh_analytics\",\n {\n title: \"Force-refresh analytics\",\n description:\n \"Force an immediate analytics refresh. Pass `postId` to refresh that post's analytics; otherwise pass `platform` to refresh a connected account's analytics for the team.\",\n inputSchema: {\n postId: z.string().optional().describe(\"Post id to refresh analytics for.\"),\n importedPostId: z.string().optional().describe(\"Imported-post id to refresh analytics for (alternative to postId).\"),\n platform: z.string().optional().describe(\"Platform name/alias to refresh a social-account's analytics for (used when postId/importedPostId are omitted).\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, importedPostId, platform, teamId }) => {\n if (postId || importedPostId) {\n return jsonResult(\n await ctx.client.analytics.analyticsForcePostAnalytics({\n requestBody: {\n postId: postId ?? null,\n importedPostId: importedPostId ?? null,\n platformType: platform ? normalizeAnalyticsPlatform(platform) : null,\n },\n }),\n );\n }\n if (!platform) {\n throw new McpToolError(\"REFRESH_TARGET_REQUIRED\", \"Pass either `postId`/`importedPostId` (to refresh a post) or `platform` (to refresh a social account).\");\n }\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.analytics.analyticsForceSocialAccountAnalytics({ requestBody: { teamId: id, platformType: normalizeAnalyticsPlatform(platform) } }));\n },\n );\n\n registerTool(\n server,\n \"get_analytics_summary\",\n {\n title: \"Get analytics summary\",\n description:\n \"Organization-level analytics summary: posts/comments/uploads usage quotas for the organization, plus the latest analytics snapshot (followers, impressions, likes, …) for each connected integration on the team. Use `from`/`to` to select the snapshot from a date range.\",\n inputSchema: {\n teamId: z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n from: z.string().optional().describe(\"Start of the range used to select analytics snapshots (ISO 8601).\"),\n to: z.string().optional().describe(\"End of the range used to select analytics snapshots (ISO 8601).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, from, to }) => {\n const id = await resolveTeamId(ctx, teamId);\n const [organization, team, postsUsage, commentsUsage, uploadsUsage] = await Promise.all([\n ctx.client.organization.organizationGetOrganization(),\n ctx.client.team.teamGetTeam({ id }),\n ctx.client.organization.organizationGetPostsUsage().catch(() => null),\n ctx.client.organization.organizationGetCommentsUsage().catch(() => null),\n ctx.client.organization.organizationGetUploadsUsage().catch(() => null),\n ]);\n\n const accounts = team.socialAccounts ?? [];\n const integrations: Array<Record<string, unknown>> = [];\n for (const account of accounts) {\n const base = { id: account.id, type: account.type, username: account.username ?? null };\n if (!isAnalyticsPlatform(account.type)) {\n integrations.push({ ...base, analytics: null, note: \"analytics not available for this platform\" });\n continue;\n }\n try {\n const result = await ctx.client.analytics.analyticsGetSocialAccountAnalytics({\n teamId: id,\n platformType: account.type as AnalyticsPlatform,\n });\n const items = (result.items ?? []).filter((item) => withinRange(item.createdAt, from, to));\n integrations.push({ ...base, latest: items[items.length - 1] ?? null, dataPoints: items.length });\n } catch (error) {\n integrations.push({ ...base, analytics: null, error: errorSummary(error) });\n }\n }\n\n return jsonResult({\n organization: { id: organization.id, name: organization.name ?? null },\n team: { id: team.id, name: team.name },\n range: { from: from ?? null, to: to ?? null },\n usage: { posts: postsUsage, comments: commentsUsage, uploads: uploadsUsage },\n integrations,\n });\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { listIntegrationTools, runIntegrationTool } from \"../integration-tools\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerIntegrationToolHelpers(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_integration_tools\",\n {\n title: \"List integration helper tools\",\n description:\n \"List the read-only platform helper tools callable via trigger_integration_tool — e.g. fetch subreddit flairs, YouTube categories/playlists/regions, LinkedIn mentions, Instagram locations, Google Business categories, TikTok trending music. Each entry has a `method` id and the params it accepts. Use these to discover values the API needs (flair ids, category ids, mention URNs, …).\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => jsonResult({ tools: listIntegrationTools() }),\n );\n\n registerTool(\n server,\n \"trigger_integration_tool\",\n {\n title: \"Call an integration helper tool\",\n description:\n 'Call one of the platform helper tools (see list_integration_tools), e.g. method \"reddit:flairs\" with params {\"subreddit\":\"r/test\"}. Returns the raw result.',\n inputSchema: {\n method: z.string().min(1).describe('Tool method id, e.g. \"reddit:flairs\", \"youtube:categories\", \"linkedin:mentions\" (call list_integration_tools first).'),\n params: z.record(z.string(), z.unknown()).optional().describe(\"Parameters for the tool as a JSON object, e.g. {\\\"subreddit\\\":\\\"r/test\\\"}.\"),\n teamId: teamIdSchema,\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ method, params, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await runIntegrationTool(ctx.client, id, method, params ?? {}));\n },\n );\n}\n","import type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\n/**\n * Curated, read-only \"what value goes here?\" helpers — the bundle.social\n * equivalent of fetching subreddit flairs, YouTube categories, LinkedIn\n * mentions, Google Business categories, etc. The platform is implied by the\n * method name; all are team-scoped, with extra parameters supplied as a JSON\n * object.\n */\nexport interface IntegrationTool {\n id: string;\n platform: string;\n description: string;\n requiredParams?: string[];\n optionalParams?: string[];\n run: (client: Bundlesocial, teamId: string, params: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport const INTEGRATION_TOOLS: IntegrationTool[] = [\n {\n id: \"reddit:flairs\",\n platform: \"REDDIT\",\n description: \"List the post flairs available in a subreddit (use the returned flair id when creating a Reddit post that requires a flair).\",\n requiredParams: [\"subreddit\"],\n run: (client, teamId, p) => client.misc.miscRedditGetSubredditFlairs({ teamId, subreddit: String(p.subreddit) }),\n },\n {\n id: \"reddit:requirements\",\n platform: \"REDDIT\",\n description: \"Get a subreddit's posting requirements (title length, flair requirement, allowed post types, etc.).\",\n requiredParams: [\"subreddit\"],\n run: (client, teamId, p) => client.misc.miscRedditGetPostRequirements({ teamId, subreddit: String(p.subreddit) }),\n },\n {\n id: \"youtube:categories\",\n platform: \"YOUTUBE\",\n description: \"List YouTube video categories for a region (use the returned category id as `categoryId` when posting a YouTube video).\",\n optionalParams: [\"regionCode\"],\n run: (client, teamId, p) =>\n client.misc.miscYoutubeGetVideoCategories({ teamId, ...(p.regionCode ? { regionCode: String(p.regionCode) } : {}) }),\n },\n {\n id: \"youtube:playlists\",\n platform: \"YOUTUBE\",\n description: \"List the connected YouTube channel's playlists (use a playlist id to add the posted video to it).\",\n optionalParams: [\"maxResults\"],\n run: (client, teamId, p) =>\n client.misc.miscYoutubeGetChannelPlaylist({ teamId, ...(p.maxResults !== undefined ? { maxResults: Number(p.maxResults) } : {}) }),\n },\n {\n id: \"youtube:regions\",\n platform: \"YOUTUBE\",\n description: \"List YouTube content regions (i18n region codes).\",\n run: (client, teamId) => client.misc.miscYoutubeGetRegions({ teamId }),\n },\n {\n id: \"linkedin:mentions\",\n platform: \"LINKEDIN\",\n description: \"Search LinkedIn people/organizations to mention in a post (use the returned URN in the post text).\",\n requiredParams: [\"q\"],\n optionalParams: [\"scope\"],\n run: (client, teamId, p) =>\n client.misc.miscLinkedinGetTags({\n teamId,\n q: String(p.q),\n ...(p.scope ? { scope: String(p.scope) as \"people\" | \"organizations\" | \"all\" } : {}),\n }),\n },\n {\n id: \"instagram:locations\",\n platform: \"INSTAGRAM\",\n description: \"Search Instagram locations (use the returned location id as `locationId` when posting).\",\n requiredParams: [\"q\"],\n optionalParams: [\"limit\"],\n run: (client, teamId, p) =>\n client.misc.miscInstagramSearchLocations({ teamId, q: String(p.q), ...(p.limit !== undefined ? { limit: Number(p.limit) } : {}) }),\n },\n {\n id: \"gbp:location\",\n platform: \"GOOGLE_BUSINESS\",\n description: \"Get the connected Google Business Profile location's details.\",\n optionalParams: [\"fields\"],\n run: (client, teamId, p) =>\n client.misc.miscGoogleBusinessGetLocation({ teamId, ...(Array.isArray(p.fields) ? { fields: p.fields as never } : {}) }),\n },\n {\n id: \"gbp:categories\",\n platform: \"GOOGLE_BUSINESS\",\n description: \"List Google Business Profile categories for a region/language (use a category id when updating the location).\",\n requiredParams: [\"languageCode\", \"regionCode\"],\n optionalParams: [\"filter\", \"pageSize\", \"pageToken\", \"view\"],\n run: (client, teamId, p) =>\n client.misc.miscGoogleBusinessListCategories({\n teamId,\n languageCode: String(p.languageCode),\n regionCode: String(p.regionCode),\n ...(p.filter ? { filter: String(p.filter) } : {}),\n ...(p.pageSize !== undefined ? { pageSize: Number(p.pageSize) } : {}),\n ...(p.pageToken ? { pageToken: String(p.pageToken) } : {}),\n ...(p.view ? { view: String(p.view) as never } : {}),\n }),\n },\n {\n id: \"instagram:audio\",\n platform: \"INSTAGRAM\",\n description:\n \"Search the Instagram audio catalogue (use the returned audio_id as `musicSoundInfo.musicSoundId` when posting a Reel).\",\n requiredParams: [\"audioType\"],\n optionalParams: [\"searchQuery\"],\n run: (client, teamId, p) =>\n client.misc.miscInstagramSearchAudio({\n teamId,\n audioType: String(p.audioType) as \"original_sound\" | \"music\",\n ...(p.searchQuery ? { searchQuery: String(p.searchQuery) } : {}),\n }),\n },\n {\n id: \"instagram:business-discovery\",\n platform: \"INSTAGRAM\",\n description:\n \"Look up a public Instagram Business/Creator profile by username (followers, media count, recent public media). Requires an account connected via Facebook Login.\",\n requiredParams: [\"username\"],\n run: (client, teamId, p) => client.misc.miscInstagramBusinessDiscovery({ teamId, username: String(p.username) }),\n },\n {\n id: \"tiktok:trending-music\",\n platform: \"TIKTOK\",\n description: \"List trending tracks from TikTok's commercial music library (use a track id in the TikTok post settings).\",\n optionalParams: [\"dateRange\", \"genre\"],\n run: (client, teamId, p) =>\n client.misc.miscTiktokGetCommercialMusicTrendingList({\n teamId,\n ...(p.dateRange ? { dateRange: String(p.dateRange) as \"1DAY\" | \"7DAY\" | \"30DAY\" } : {}),\n ...(p.genre ? { genre: String(p.genre) as never } : {}),\n }),\n },\n];\n\nexport function listIntegrationTools() {\n return INTEGRATION_TOOLS.map((tool) => ({\n method: tool.id,\n platform: tool.platform,\n description: tool.description,\n requiredParams: tool.requiredParams ?? [],\n optionalParams: tool.optionalParams ?? [],\n }));\n}\n\nexport async function runIntegrationTool(\n client: Bundlesocial,\n teamId: string,\n method: string,\n params: Record<string, unknown>,\n): Promise<unknown> {\n const tool = INTEGRATION_TOOLS.find((candidate) => candidate.id === method.trim().toLowerCase());\n if (!tool) {\n throw new McpToolError(\n \"UNKNOWN_INTEGRATION_TOOL\",\n `Unknown integration tool \"${method}\". Available: ${INTEGRATION_TOOLS.map((t) => t.id).join(\", \")}.`,\n { available: INTEGRATION_TOOLS.map((t) => t.id) },\n );\n }\n const missing = (tool.requiredParams ?? []).filter((key) => params[key] === undefined || params[key] === null || params[key] === \"\");\n if (missing.length > 0) {\n throw new McpToolError(\n \"MISSING_PARAMS\",\n `Integration tool \"${tool.id}\" requires: ${missing.join(\", \")}. Provide them in the params object.`,\n { method: tool.id, requiredParams: tool.requiredParams },\n );\n }\n return tool.run(client, teamId, params);\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { TeamUpdateTeamData } from \"bundlesocial\";\nimport type { ServerContext } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\ntype TeamUpdateBody = NonNullable<TeamUpdateTeamData[\"requestBody\"]>;\n\nexport function registerTeamTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_teams\",\n {\n title: \"List teams\",\n description: \"List the teams in the organization (paginated). Use this to discover team ids for the optional `teamId` argument on other tools.\",\n inputSchema: {\n limit: z.number().int().positive().max(100).optional().describe(\"Max number of teams to return.\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of teams to skip (for pagination).\"),\n search: z.string().optional().describe(\"Free-text search over team names.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ limit, offset, search }) =>\n jsonResult(await ctx.client.team.teamGetList({ limit: limit ?? null, offset: offset ?? null, search: search ?? null })),\n );\n\n registerTool(\n server,\n \"get_team\",\n {\n title: \"Get a team by id\",\n description: \"Fetch a single team by id, including its connected social accounts/integrations.\",\n inputSchema: { id: z.string().min(1).describe(\"Team id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.team.teamGetTeam({ id })),\n );\n\n registerTool(\n server,\n \"create_team\",\n {\n title: \"Create a team\",\n description: \"Create a new team in the organization.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Team name.\"),\n avatarUrl: z.string().optional().describe(\"Optional avatar image URL.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ name, avatarUrl }) =>\n jsonResult(\n await ctx.client.team.teamCreateTeam({\n requestBody: { name, avatarUrl: avatarUrl ?? null },\n }),\n ),\n );\n\n registerTool(\n server,\n \"update_team\",\n {\n title: \"Update a team\",\n description: \"Update a team's name and/or avatar. Only the fields you pass are changed.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Team id.\"),\n name: z.string().optional().describe(\"New team name.\"),\n avatarUrl: z.string().nullable().optional().describe(\"New avatar image URL, or null to clear it.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, name, avatarUrl }) => {\n const requestBody: TeamUpdateBody = {};\n if (name !== undefined) requestBody.name = name;\n if (avatarUrl !== undefined) requestBody.avatarUrl = avatarUrl;\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\"NOTHING_TO_UPDATE\", \"Nothing to update — pass at least one of name, avatarUrl.\");\n }\n return jsonResult(await ctx.client.team.teamUpdateTeam({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"delete_team\",\n {\n title: \"Delete a team\",\n description: \"Delete a team by id. This is destructive and cannot be undone — it removes the team and its scheduled content.\",\n inputSchema: { id: z.string().min(1).describe(\"Team id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.team.teamDeleteTeam({ id })),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { errorSummary, jsonResult } from \"../errors\";\nimport { normalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerOrganizationTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"get_organization\",\n {\n title: \"Get the organization\",\n description: \"Fetch the current organization — its id, name, API-access flag and plan limits. Its `teams` array is deprecated (removed 2026-11-15); use `list_teams` to enumerate teams.\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => jsonResult(await ctx.client.organization.organizationGetOrganization()),\n );\n\n registerTool(\n server,\n \"get_usage\",\n {\n title: \"Get usage quotas\",\n description:\n \"Organization usage quotas: posts, comments and uploads (used/limit/remaining), plus a paginated per-social-account breakdown of post-history import usage. Use the pagination/filter args for the imports breakdown.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().optional().describe(\"Filter the imports breakdown to one platform name/alias (e.g. instagram, tiktok).\"),\n socialAccountId: z.string().optional().describe(\"Filter the imports breakdown to one social-account id.\"),\n page: z.number().int().positive().optional().describe(\"Page of the imports breakdown (1-based).\"),\n pageSize: z.number().int().positive().max(100).optional().describe(\"Page size of the imports breakdown.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform, socialAccountId, page, pageSize }) => {\n const id = teamId ?? ctx.defaultTeamId;\n const resolvedTeamId = id ?? (await resolveTeamId(ctx, teamId).catch(() => undefined));\n const [posts, comments, uploads, imports] = await Promise.all([\n ctx.client.organization.organizationGetPostsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization.organizationGetCommentsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization.organizationGetUploadsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization\n .organizationGetImportsUsage({\n page,\n pageSize,\n teamId: resolvedTeamId,\n socialAccountType: platform ? normalizePlatform(platform) : undefined,\n socialAccountId,\n })\n .catch((error) => ({ error: errorSummary(error) })),\n ]);\n return jsonResult({ posts, comments, uploads, imports });\n },\n );\n\n registerTool(\n server,\n \"get_daily_limits_usage\",\n {\n title: \"Get a connected account's daily limits\",\n description:\n \"How much of one connected account's daily post and comment allowance has been used on a given day (defaults to today, UTC). Use it before bulk-scheduling to avoid hitting a per-account daily cap.\",\n inputSchema: {\n socialAccountId: z.string().min(1).describe(\"Connected social account id (see list_integrations).\"),\n date: z.string().optional().describe(\"Day to report on, YYYY-MM-DD. Defaults to today.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ socialAccountId, date }) =>\n jsonResult(\n await ctx.client.organization.organizationGetDailyLimitsUsage({\n socialAccountId,\n ...(date ? { date } : {}),\n }),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { PostImportCreateData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { normalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype PostImportPlatform = NonNullable<PostImportCreateData[\"requestBody\"]>[\"socialAccountType\"];\n\nconst platformSchema = z.string().min(1).describe(\"Platform name/alias. Post-history import is available on FACEBOOK, INSTAGRAM, THREADS, TIKTOK, YOUTUBE, LINKEDIN, PINTEREST, REDDIT, MASTODON, BLUESKY.\");\n\nexport function registerPostImportTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post_import\",\n {\n title: \"Import post history\",\n description:\n \"Start an async import of a connected account's recent posts (optionally with analytics) for one platform. Poll list_post_imports / get_post_import for status and list_imported_posts for the imported posts.\",\n inputSchema: {\n platform: platformSchema,\n count: z.number().int().positive().describe(\"How many recent posts to import.\"),\n withAnalytics: z.boolean().optional().describe(\"Also fetch analytics for the imported posts.\"),\n importCarousels: z.boolean().optional().describe(\"Include carousel/album posts (Instagram).\"),\n surface: z.enum([\"PROFILE_GRID\", \"NON_GRID\", \"STORY\", \"ALL\"]).optional().describe(\"Which surface to import from (Instagram).\"),\n mediaType: z.enum([\"VIDEO\", \"IMAGE\"]).optional().describe(\"Restrict to one media type.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platform, count, withAnalytics, importCarousels, surface, mediaType, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.postImport.postImportCreate({\n requestBody: {\n teamId: id,\n socialAccountType: normalizePlatform(platform) as PostImportPlatform,\n count,\n ...(withAnalytics !== undefined ? { withAnalytics } : {}),\n ...(importCarousels !== undefined ? { importCarousels } : {}),\n ...(surface ? { surface } : {}),\n ...(mediaType ? { mediaType } : {}),\n },\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"list_post_imports\",\n {\n title: \"List post-history imports\",\n description: \"List post-history import jobs for a team, optionally filtered by platform.\",\n inputSchema: {\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n platform: z.string().optional().describe(\"Filter by platform name/alias.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportGetStatus({ teamId: id, socialAccountType: platform ? (normalizePlatform(platform) as PostImportPlatform) : undefined }));\n },\n );\n\n registerTool(\n server,\n \"get_post_import\",\n {\n title: \"Get a post-history import by id\",\n description: \"Fetch a single post-history import job by its id, including its status and counts.\",\n inputSchema: { importId: z.string().min(1).describe(\"Post import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postImport.postImportGetById({ importId })),\n );\n\n registerTool(\n server,\n \"list_imported_posts\",\n {\n title: \"List imported posts for a platform\",\n description: \"List the posts imported (with analytics, when available) for a connected account on the given platform.\",\n inputSchema: {\n platform: platformSchema,\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportGetImportedPosts({ teamId: id, socialAccountType: normalizePlatform(platform) as PostImportPlatform, limit, offset: offset ?? null }));\n },\n );\n\n registerTool(\n server,\n \"delete_imported_posts\",\n {\n title: \"Delete imported posts\",\n description: \"Bulk-delete imported posts (and their analytics) by id. Destructive.\",\n inputSchema: {\n postIds: z.array(z.string().min(1)).min(1).describe(\"Imported-post ids to delete.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ postIds, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportDeleteImportedPosts({ requestBody: { teamId: id, postIds } }));\n },\n );\n\n registerTool(\n server,\n \"retry_post_import\",\n {\n title: \"Retry a post-history import\",\n description: \"Retry a post-history import job that ended in FAILED / RATE_LIMITED.\",\n inputSchema: {\n importId: z.string().min(1).describe(\"Post import id.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ importId, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportRetryImport({ importId, requestBody: { teamId: id } }));\n },\n );\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\nfunction isUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value.trim());\n}\n\nasync function readCsvFile(source: string): Promise<File> {\n if (isUrl(source)) {\n const response = await fetch(source.trim());\n if (!response.ok) {\n throw new McpToolError(\"CSV_FETCH_FAILED\", `Could not download the CSV from \"${source}\" (HTTP ${response.status}).`, { status: response.status });\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n const name = path.basename(new URL(source).pathname) || \"import.csv\";\n return new File([buffer], name, { type: \"text/csv\" });\n }\n const absolutePath = path.resolve(source);\n let buffer: Buffer;\n try {\n buffer = await fs.readFile(absolutePath);\n } catch {\n throw new McpToolError(\n \"CSV_NOT_FOUND\",\n `Could not read CSV \"${source}\". Provide a public https:// URL, or a local file path that exists on the machine running this MCP server (stdio mode only).`,\n { path: absolutePath },\n );\n }\n return new File([buffer], path.basename(absolutePath), { type: \"text/csv\" });\n}\n\nexport function registerPostCsvTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post_csv_import\",\n {\n title: \"Bulk-import posts from a CSV\",\n description:\n \"Upload a CSV for async bulk post import. Accepts a public https:// URL to the CSV, or a local file path when this server runs in stdio mode. Poll get_post_csv_import_status / get_post_csv_import_rows for progress and per-row results.\",\n inputSchema: {\n source: z.string().min(1).describe(\"Public https:// URL of the CSV, or a local file path (stdio mode only).\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ source }) => {\n const file = await readCsvFile(source);\n return jsonResult(await ctx.client.postCsv.postCsvCreate({ formData: { file } }));\n },\n );\n\n registerTool(\n server,\n \"list_post_csv_imports\",\n {\n title: \"List CSV imports\",\n description: \"List the post-CSV import history (paginated).\",\n inputSchema: {\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ limit, offset }) => jsonResult(await ctx.client.postCsv.postCsvGetList({ limit: limit ?? null, offset: offset ?? null })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import\",\n {\n title: \"Get a CSV import by id\",\n description: \"Fetch a single post-CSV import by its id, including counts and status.\",\n inputSchema: { importId: z.string().min(1).describe(\"CSV import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postCsv.postCsvGetById({ importId })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import_status\",\n {\n title: \"Get a CSV import's processing status\",\n description: \"Fetch the processing status of a post-CSV import (rows processed/succeeded/failed).\",\n inputSchema: { importId: z.string().min(1).describe(\"CSV import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postCsv.postCsvGetStatus({ importId })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import_rows\",\n {\n title: \"Get a CSV import's row results\",\n description: \"List per-row results of a post-CSV import (the raw row, normalized payload, created post id or error), optionally filtered by SUCCESS/FAILED.\",\n inputSchema: {\n importId: z.string().min(1).describe(\"CSV import id.\"),\n status: z.enum([\"SUCCESS\", \"FAILED\"]).optional().describe(\"Filter rows by outcome.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId, status, limit, offset }) =>\n jsonResult(await ctx.client.postCsv.postCsvGetRows({ importId, status, limit: limit ?? null, offset: offset ?? null })),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport pkg from \"../../package.json\";\nimport { type ServerContext, DASHBOARD_SOCIAL_ACCOUNTS_URL, listAllTeams } from \"../client\";\nimport { errorSummary, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\nconst VERSION: string = pkg.version;\n\ntype CheckStatus = \"ok\" | \"warn\" | \"fail\";\ninterface Check {\n name: string;\n status: CheckStatus;\n message: string;\n [key: string]: unknown;\n}\n\nexport function registerDiagnosticsTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"check_setup\",\n {\n title: \"Check the bundle.social setup\",\n description:\n \"Diagnose this MCP server's setup: API key present, API reachable, API key valid, organization API access, team resolution, connected integrations and posts quota. Always returns a structured diagnostic object ({ ok, checks: [...] }).\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => {\n const checks: Check[] = [];\n const add = (name: string, status: CheckStatus, message: string, extra: Record<string, unknown> = {}) =>\n checks.push({ name, status, message, ...extra });\n const finish = () => jsonResult({ ok: checks.every((check) => check.status !== \"fail\"), mcpVersion: VERSION, node: process.version, checks });\n\n // The server is only constructed with a non-empty API key, so by the time\n // a tool runs the key is always present — record it for completeness.\n add(\"api_key\", \"ok\", \"API key configured\");\n\n try {\n const health = await ctx.client.app.appGetHealth();\n add(\"api_reachable\", \"ok\", \"API reachable\", { health });\n } catch (error) {\n add(\"api_reachable\", \"fail\", \"Could not reach the bundle.social API\", { error: errorSummary(error) });\n return finish();\n }\n\n let teams: Array<{ id: string; name: string }> = [];\n let organizationApiAccess: boolean | undefined;\n try {\n const organization = await ctx.client.organization.organizationGetOrganization();\n organizationApiAccess = organization.apiAccess;\n add(\"authentication\", \"ok\", \"API key is valid\", { organizationId: organization.id, organizationName: organization.name ?? null });\n } catch (error) {\n add(\"authentication\", \"fail\", \"API key was rejected by the API\", { error: errorSummary(error) });\n return finish();\n }\n if (!ctx.defaultTeamId) {\n try {\n teams = (await listAllTeams(ctx.client)).map((team) => ({ id: team.id, name: team.name }));\n } catch (error) {\n add(\"team\", \"fail\", \"Could not list the organization's teams\", { error: errorSummary(error) });\n return finish();\n }\n }\n add(\n \"api_access\",\n organizationApiAccess ? \"ok\" : \"fail\",\n organizationApiAccess\n ? \"Organization has API access enabled\"\n : \"Organization does not have API access enabled — upgrade your plan or contact bundle.social support\",\n );\n\n let teamId: string | undefined;\n if (ctx.defaultTeamId) {\n teamId = ctx.defaultTeamId;\n add(\"team\", \"ok\", \"Using team from BUNDLESOCIAL_TEAM_ID / --team-id\", { teamId });\n } else if (teams.length === 1) {\n teamId = teams[0].id;\n add(\"team\", \"ok\", \"Using the organization's only team\", { teamId, teamName: teams[0].name });\n } else if (teams.length === 0) {\n add(\"team\", \"fail\", \"Organization has no teams — create one in the dashboard\");\n } else {\n add(\"team\", \"warn\", `Organization has ${teams.length} teams; tools need a teamId argument (or set BUNDLESOCIAL_TEAM_ID)`, { teams });\n }\n\n if (teamId) {\n try {\n const team = await ctx.client.team.teamGetTeam({ id: teamId });\n const accounts = team.socialAccounts ?? [];\n add(\n \"integrations\",\n accounts.length > 0 ? \"ok\" : \"warn\",\n accounts.length > 0 ? `${accounts.length} connected integration(s)` : \"No integrations connected — connect one in the dashboard before posting\",\n { count: accounts.length, platforms: accounts.map((account) => account.type), connectUrl: DASHBOARD_SOCIAL_ACCOUNTS_URL },\n );\n } catch (error) {\n add(\"integrations\", \"fail\", \"Could not load the team's integrations\", { teamId, error: errorSummary(error) });\n }\n }\n\n try {\n const usage = await ctx.client.organization.organizationGetPostsUsage();\n add(\"posts_quota\", usage.remaining > 0 ? \"ok\" : \"warn\", `Posts quota: ${usage.used}/${usage.limit} used, ${usage.remaining} remaining`, {\n used: usage.used,\n limit: usage.limit,\n remaining: usage.remaining,\n });\n } catch (error) {\n add(\"posts_quota\", \"warn\", \"Could not read posts quota\", { error: errorSummary(error) });\n }\n\n return finish();\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport {\n MEDIA_NOTES,\n PLATFORM_REFERENCE,\n type PlatformReferenceEntry,\n} from \"../platform-reference\";\nimport { PLATFORMS, tryNormalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype Operation = \"post\" | \"comment\";\n\n/** Narrow an entry to a single operation, or return it whole. */\nfunction projectEntry(entry: PlatformReferenceEntry, operation?: Operation): Record<string, unknown> {\n const base = {\n platform: entry.platform,\n label: entry.label,\n aliases: entry.aliases,\n capabilities: entry.capabilities,\n notes: entry.notes,\n };\n if (operation === \"post\") {\n return { ...base, post: entry.post };\n }\n if (operation === \"comment\") {\n return {\n ...base,\n comment: entry.comment ?? {\n supported: false,\n message: `Comments are not available on ${entry.label} via the bundle.social API.`,\n },\n };\n }\n return { ...base, post: entry.post, ...(entry.comment ? { comment: entry.comment } : {}) };\n}\n\nexport function registerPlatformReferenceTools(server: McpServer, ctx: ServerContext): void {\n // ctx is unused — this tool serves a static reference, but the signature is\n // kept uniform with the other register* functions.\n void ctx;\n\n registerTool(\n server,\n \"describe_platform\",\n {\n title: \"Describe a platform's field schema\",\n description:\n \"Look up the exact per-platform `data.<PLATFORM>` fields the bundle.social API accepts — for posting AND commenting — so you can build a correct `data` / `platformSettings` object instead of guessing. \" +\n \"Pass `platform` (name or alias, e.g. \\\"reddit\\\", \\\"x\\\", \\\"gbp\\\") for one platform, or omit it to get every platform. \" +\n \"Pass `operation` (\\\"post\\\" or \\\"comment\\\") to narrow the response. \" +\n \"Each field lists its name, type, whether it is required, and notes; each platform also reports its capabilities (posting / comments / analytics / comment imports) and a ready-to-use example. \" +\n \"Call this before create_post / schedule_post / update_post / create_comment / update_comment whenever you are unsure which fields a platform needs.\",\n inputSchema: {\n platform: z\n .string()\n .min(1)\n .optional()\n .describe('Platform name or alias (e.g. \"reddit\", \"x\", \"tiktok\", \"gbp\"). Omit to describe every platform.'),\n operation: z\n .enum([\"post\", \"comment\"])\n .optional()\n .describe('Which operation to describe. \"post\" = create/schedule/update a post; \"comment\" = create/update a comment. Omit for both.'),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ platform, operation }) => {\n if (platform) {\n const normalized = tryNormalizePlatform(platform);\n if (!normalized) {\n return jsonResult({\n error: {\n code: \"UNKNOWN_PLATFORM\",\n message: `Unknown platform \"${platform}\". Supported: ${PLATFORMS.join(\", \")} (aliases like \"x\" and \"gbp\" are accepted too).`,\n supportedPlatforms: PLATFORMS,\n },\n });\n }\n return jsonResult({\n platform: projectEntry(PLATFORM_REFERENCE[normalized], operation),\n mediaNotes: MEDIA_NOTES,\n });\n }\n\n return jsonResult({\n platforms: PLATFORMS.map((name) => projectEntry(PLATFORM_REFERENCE[name], operation)),\n mediaNotes: MEDIA_NOTES,\n hint: 'Pass `platform` (e.g. \"reddit\") to focus on one platform, or `operation` (\"post\" | \"comment\") to narrow the response.',\n });\n },\n );\n}\n","import { COMMENT_PLATFORMS, type Platform, PLATFORMS } from \"./platforms\";\n\n/**\n * Structured per-platform field reference for the `data.<PLATFORM>` objects the\n * bundle.social API accepts. Exposed to MCP clients via the `describe_platform`\n * tool so an agent can look up exactly which fields a platform needs without\n * guessing or relying on stale training data.\n *\n * SYNC: the field tables here mirror bundlesocial-cli/PROVIDER_SETTINGS.md and\n * https://docs.bundle.social/api-reference/platform-parameters — when the API\n * gains/removes/changes a `data.<PLATFORM>` field, update all three.\n */\n\nexport interface ReferenceField {\n /** Field name as it appears under `data.<PLATFORM>`. */\n name: string;\n /** Human-readable type, e.g. `string`, `string[]`, an enum union, or an object shape. */\n type: string;\n /** Whether the platform requires this field for a post/comment to succeed. */\n required: boolean;\n /** What the field does and any limits/caveats. */\n notes: string;\n}\n\nexport interface OperationReference {\n /** Where the object lives in the request body, e.g. `data.REDDIT`. */\n dataKey: string;\n /** One-line description of the operation for this platform. */\n summary: string;\n /** Every field the operation accepts for this platform. */\n fields: ReferenceField[];\n /** A minimal, valid example object for this platform. */\n example: Record<string, unknown>;\n}\n\nexport interface PlatformReferenceEntry {\n platform: Platform;\n /** Display name, e.g. `X / Twitter`. */\n label: string;\n /** Accepted names/aliases (lower-cased) for this platform. */\n aliases: string[];\n capabilities: {\n /** Can create/schedule posts. */\n posting: boolean;\n /** Can create comments/replies on a post. */\n comments: boolean;\n /** Exposes post & account analytics. */\n analytics: boolean;\n /** Supports importing the (incoming) comments on a published post. */\n commentImports: boolean;\n };\n /** The `data.<PLATFORM>` schema used by create_post / schedule_post / update_post. */\n post: OperationReference;\n /** The `data.<PLATFORM>` schema used by create_comment / update_comment (omitted when unsupported). */\n comment?: OperationReference;\n /** Extra platform-specific guidance. */\n notes: string[];\n}\n\nconst COMMENT_IMPORT_PLATFORMS: Platform[] = [\n \"FACEBOOK\",\n \"INSTAGRAM\",\n \"LINKEDIN\",\n \"YOUTUBE\",\n \"TIKTOK\",\n \"REDDIT\",\n \"THREADS\",\n \"MASTODON\",\n \"BLUESKY\",\n];\n\nconst ANALYTICS: Platform[] = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"REDDIT\",\n \"PINTEREST\",\n \"MASTODON\",\n \"LINKEDIN\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n];\n\n/** A comment's `data.<PLATFORM>` only ever carries the comment body text. */\nfunction commentOperation(platform: Platform): OperationReference {\n return {\n dataKey: `data.${platform}`,\n summary: `Comment/reply on a post. The per-platform comment object only carries the comment body.`,\n fields: [{ name: \"text\", type: \"string\", required: true, notes: \"The comment body.\" }],\n example: { [platform]: { text: \"Great write-up — thanks for sharing!\" } },\n };\n}\n\n/** Per-platform post-field tables. Keyed by platform; comment data is added below. */\nconst POST: Record<Platform, OperationReference> = {\n TWITTER: {\n dataKey: \"data.TWITTER\",\n summary: \"Post a tweet. For a thread, post the first tweet then add replies via create_comment.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"Post text. ~280 chars (longer if the connected account is X Premium).\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images OR 1 video/GIF.\" },\n {\n name: \"replySettings\",\n type: \"EVERYONE | FOLLOWING | MENTIONED_USERS | SUBSCRIBERS | VERIFIED\",\n required: false,\n notes: \"Who can reply to the tweet.\",\n },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: 'Adds X\\'s \"made with AI\" label to a post with AI-generated media.' },\n ],\n example: { TWITTER: { text: \"Shipping day 🚀\", replySettings: \"EVERYONE\" } },\n },\n BLUESKY: {\n dataKey: \"data.BLUESKY\",\n summary: \"Post to Bluesky.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"~300 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images, or 1 video (set videoAlt).\" },\n { name: \"tags\", type: \"string[]\", required: false, notes: \"Extra hashtags (without `#`), up to 8.\" },\n {\n name: \"labels\",\n type: \"(!no-unauthenticated | porn | sexual | nudity | graphic-media)[]\",\n required: false,\n notes: \"Self-labels / content warnings.\",\n },\n { name: \"quoteUri\", type: \"string\", required: false, notes: \"AT-URI of a post to quote (at://…/app.bsky.feed.post/<rkey>).\" },\n { name: \"externalUrl\", type: \"string (URL)\", required: false, notes: \"External link card URL.\" },\n { name: \"externalTitle\", type: \"string\", required: false, notes: \"External link card title.\" },\n { name: \"externalDescription\", type: \"string\", required: false, notes: \"External link card description.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Image for the external link card (a public bundle.social upload URL).\" },\n { name: \"videoAlt\", type: \"string\", required: false, notes: \"Alt text for a video embed.\" },\n ],\n example: { BLUESKY: { text: \"New post\", tags: [\"launch\", \"indie\"], externalUrl: \"https://bundle.social\" } },\n },\n MASTODON: {\n dataKey: \"data.MASTODON\",\n summary: \"Post a status to Mastodon.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"Length depends on the connected instance (commonly ~500).\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images OR 1 video.\" },\n { name: \"privacy\", type: \"PUBLIC | UNLISTED | PRIVATE | DIRECT\", required: false, notes: \"Visibility.\" },\n { name: \"spoiler\", type: \"string\", required: false, notes: \"Content-warning text (collapses the post behind it).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image for a video.\" },\n ],\n example: { MASTODON: { text: \"Hello fediverse\", privacy: \"PUBLIC\", spoiler: \"long read\" } },\n },\n THREADS: {\n dataKey: \"data.THREADS\",\n summary: \"Post to Threads.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"~500 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to ~10 images, or 1 video.\" },\n {\n name: \"mediaItems\",\n type: \"{ uploadId: string, altText?: string }[]\",\n required: false,\n notes: \"Per-image alt text (alternative to uploadIds).\",\n },\n {\n name: \"topicTag\",\n type: \"string\",\n required: false,\n notes: \"One topic tag shown in the post header. 1–50 chars, no periods (.) or ampersands (&).\",\n },\n {\n name: \"replyControl\",\n type: \"everyone | accounts_you_follow | mentioned_only | parent_post_author_only | followers_only\",\n required: false,\n notes: \"Who can reply. Threads defaults to everyone.\",\n },\n {\n name: \"linkAttachment\",\n type: \"string (URL)\",\n required: false,\n notes: \"Link preview card. Text-only posts (no uploadIds).\",\n },\n {\n name: \"poll\",\n type: \"{ optionA: string, optionB: string, optionC?: string, optionD?: string }\",\n required: false,\n notes: \"2–4 options, 1–25 chars each. Text-only posts, and not together with `gif`.\",\n },\n {\n name: \"gif\",\n type: '{ gifId: string, provider?: \"GIPHY\" }',\n required: false,\n notes: \"GIF attachment (GIPHY is the only provider). Text-only posts, and not together with `poll`.\",\n },\n {\n name: \"allowlistedCountryCodes\",\n type: \"string[]\",\n required: false,\n notes: \"Restrict visibility to these ISO 3166-1 alpha-2 codes. Requires Meta account eligibility.\",\n },\n {\n name: \"crosspostToInstagramStory\",\n type: \"boolean\",\n required: false,\n notes: \"Also share the post to the linked Instagram account as a Story.\",\n },\n {\n name: \"crosspostToInstagramStoryDarkMode\",\n type: \"boolean\",\n required: false,\n notes: \"Cross-post the Instagram Story in dark mode.\",\n },\n ],\n example: { THREADS: { text: \"Quick thought\", topicTag: \"shipping\", replyControl: \"everyone\" } },\n },\n LINKEDIN: {\n dataKey: \"data.LINKEDIN\",\n summary: \"Post to a LinkedIn personal profile or company page (depends on the connected account).\",\n fields: [\n { name: \"text\", type: \"string\", required: true, notes: \"Required. ~3000 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images, a single video, or a document/PDF.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"For an article-preview post.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (a public bundle.social upload URL).\" },\n { name: \"mediaTitle\", type: \"string\", required: false, notes: \"Title for a video or document post.\" },\n { name: \"privacy\", type: \"CONNECTIONS | PUBLIC | LOGGED_IN | CONTAINER\", required: false, notes: \"Visibility.\" },\n { name: \"hideFromFeed\", type: \"boolean\", required: false, notes: \"Don't show in the main feed.\" },\n { name: \"disableReshare\", type: \"boolean\", required: false, notes: \"Disallow resharing.\" },\n ],\n example: { LINKEDIN: { text: \"We just shipped X.\", privacy: \"PUBLIC\", mediaTitle: \"Demo\" } },\n },\n FACEBOOK: {\n dataKey: \"data.FACEBOOK\",\n summary: \"Post to a Facebook Page.\",\n fields: [\n { name: \"type\", type: \"POST | REEL | STORY\", required: false, notes: \"Default POST.\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption / message.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images, or a single video.\" },\n { name: \"mediaItems\", type: \"{ uploadId: string, altText?: string }[]\", required: false, notes: \"Per-image alt text.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Link attachment — `type: POST` only.\" },\n { name: \"mediaTitle\", type: \"string\", required: false, notes: \"Video title — `type: POST` with a video only (not REEL/STORY).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Video cover image.\" },\n {\n name: \"nativeScheduleTime\",\n type: \"string (ISO 8601, local)\",\n required: false,\n notes: \"Schedule directly in Meta's scheduler instead of publishing now; max 30 days ahead.\",\n },\n ],\n example: { FACEBOOK: { type: \"POST\", text: \"Look at this\", link: \"https://bundle.social\" } },\n },\n INSTAGRAM: {\n dataKey: \"data.INSTAGRAM\",\n summary: \"Post to Instagram (feed post, carousel, Reel or Story).\",\n fields: [\n {\n name: \"type\",\n type: \"POST | REEL | STORY\",\n required: false,\n notes: \"POST = single image, carousel (carouselItems) or feed video; REEL = single video; STORY = image or short video.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"Single image/video for POST/REEL/STORY. Square ≥1080×1080 or portrait 4:5; Reels 9:16, up to 90s.\",\n },\n { name: \"altText\", type: \"string\", required: false, notes: \"Alt text for a single-image post.\" },\n {\n name: \"carouselItems\",\n type: \"{ uploadId: string, altText?: string, tagged?: { username, x, y }[] }[]\",\n required: false,\n notes: \"Carousel slides (for `type: POST`).\",\n },\n { name: \"thumbnailOffset\", type: \"number (ms)\", required: false, notes: \"Frame to use as the published video's cover.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (alternative to thumbnailOffset).\" },\n { name: \"shareToFeed\", type: \"boolean\", required: false, notes: \"Reels only — also show in the Feed tab.\" },\n { name: \"collaborators\", type: \"string[]\", required: false, notes: \"Usernames to invite as collaborators.\" },\n { name: \"tagged\", type: \"{ username: string, x?: number, y?: number }[]\", required: false, notes: \"People tags for a single-image post.\" },\n {\n name: \"locationId\",\n type: \"string\",\n required: false,\n notes: 'A location id — discover with trigger_integration_tool method \"instagram:locations\".',\n },\n { name: \"autoFitImage\", type: \"boolean\", required: false, notes: \"Let bundle.social fit the image to a valid aspect ratio.\" },\n { name: \"autoCropImage\", type: \"boolean\", required: false, notes: \"Let bundle.social crop the image to a valid aspect ratio.\" },\n {\n name: \"trialParams\",\n type: '{ graduationStrategy: \"MANUAL\" | \"SS_PERFORMANCE\" }',\n required: false,\n notes: \"Reels only — trial reels are shown to non-followers first.\",\n },\n {\n name: \"isPaidPartnership\",\n type: \"boolean\",\n required: false,\n notes: 'Adds the native \"Paid partnership\" label. Implied by brandedContentSponsors; use alone for a label without a named sponsor.',\n },\n {\n name: \"brandedContentSponsors\",\n type: \"string[]\",\n required: false,\n notes: \"Up to 2 Instagram usernames to tag as paid-partnership sponsors. Accounts connected via Facebook Login only.\",\n },\n {\n name: \"musicSoundInfo\",\n type: \"{ musicSoundId, musicSoundVolume?, videoOriginalSoundVolume? }\",\n required: false,\n notes: 'Reels only — get an audio_id from trigger_integration_tool method \"instagram:audio\". Volumes 0–100.',\n },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Adds Instagram's AI content label.\" },\n ],\n example: { INSTAGRAM: { type: \"REEL\", text: \"BTS\", shareToFeed: true, thumbnailOffset: 1500 } },\n },\n TIKTOK: {\n dataKey: \"data.TIKTOK\",\n summary: \"Post a video or photo carousel to TikTok.\",\n fields: [\n { name: \"type\", type: \"VIDEO | IMAGE\", required: false, notes: \"VIDEO = 1 video; IMAGE = photo carousel.\" },\n {\n name: \"privacy\",\n type: \"PUBLIC_TO_EVERYONE | MUTUAL_FOLLOW_FRIENDS | FOLLOWER_OF_CREATOR | SELF_ONLY\",\n required: true,\n notes: \"Effectively required by TikTok.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"The video, or the photos for `type: IMAGE`. Video: MP4/MOV/WEBM, ≥540p, portrait 9:16 recommended, up to ~10 min.\",\n },\n { name: \"photoCoverIndex\", type: \"number\", required: false, notes: \"Which photo is the cover (for `type: IMAGE`).\" },\n { name: \"thumbnailOffset\", type: \"number (ms)\", required: false, notes: \"Frame to use as the video cover.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (alternative to thumbnailOffset).\" },\n { name: \"isBrandContent\", type: \"boolean\", required: false, notes: \"Disclosure: paid third-party partnership.\" },\n { name: \"isOrganicBrandContent\", type: \"boolean\", required: false, notes: \"Disclosure: promoting your own business.\" },\n { name: \"disableComments\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"disableDuet\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"disableStitch\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Mark the video as AI-generated.\" },\n { name: \"autoAddMusic\", type: \"boolean\", required: false, notes: \"Let TikTok add music to photos.\" },\n { name: \"autoScale\", type: \"boolean\", required: false, notes: \"Auto-scale the video.\" },\n { name: \"uploadToDraft\", type: \"boolean\", required: false, notes: \"Upload as a TikTok draft instead of publishing.\" },\n {\n name: \"musicSoundInfo\",\n type: \"{ musicSoundId, musicSoundVolume?, musicSoundStart?, musicSoundEnd?, videoOriginalSoundVolume? }\",\n required: false,\n notes:\n 'Commercial music — get a song_clip_id from trigger_integration_tool method \"tiktok:trending-music\". Volumes 0–100; start/end in ms.',\n },\n ],\n example: { TIKTOK: { type: \"VIDEO\", text: \"Launch BTS\", privacy: \"PUBLIC_TO_EVERYONE\", disableStitch: true } },\n },\n YOUTUBE: {\n dataKey: \"data.YOUTUBE\",\n summary: \"Upload a video or Short to YouTube.\",\n fields: [\n { name: \"type\", type: \"VIDEO | SHORT\", required: false, notes: \"SHORT = vertical ≤60s; VIDEO = full upload.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"One video.\" },\n { name: \"text\", type: \"string\", required: false, notes: \"The video TITLE (the post `title` field also maps here).\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Video description.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Custom thumbnail (`type: VIDEO`).\" },\n { name: \"privacy\", type: \"PUBLIC | UNLISTED | PRIVATE\", required: false, notes: \"Visibility.\" },\n {\n name: \"defaultLanguage\",\n type: \"string (BCP-47)\",\n required: false,\n notes: 'Language of the title and description, e.g. \"en\" or \"pl\".',\n },\n {\n name: \"defaultAudioLanguage\",\n type: \"string (BCP-47)\",\n required: false,\n notes: 'Language of the video\\'s default audio track, e.g. \"en\" or \"pl\".',\n },\n { name: \"madeForKids\", type: \"boolean\", required: true, notes: \"Required-ish — YouTube needs you to declare this.\" },\n { name: \"containsSyntheticMedia\", type: \"boolean\", required: false, notes: \"Mark AI-generated content.\" },\n { name: \"hasPaidProductPlacement\", type: \"boolean\", required: false, notes: \"Declare paid placements.\" },\n ],\n example: { YOUTUBE: { type: \"SHORT\", text: \"Launch BTS\", description: \"Behind the scenes…\", privacy: \"PUBLIC\", madeForKids: false } },\n },\n REDDIT: {\n dataKey: \"data.REDDIT\",\n summary: \"Submit a post to a subreddit (or your profile).\",\n fields: [\n { name: \"sr\", type: \"string\", required: true, notes: \"Subreddit (`r/subredditName`) or `u/username`.\" },\n { name: \"text\", type: \"string\", required: true, notes: \"The post title for link/text posts (Reddit's \\\"title\\\").\" },\n { name: \"description\", type: \"string\", required: false, notes: \"The body for a self post.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"An image or video.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Link post target.\" },\n { name: \"nsfw\", type: \"boolean\", required: false, notes: \"Mark NSFW.\" },\n {\n name: \"flairId\",\n type: \"string\",\n required: false,\n notes: 'Required if the subreddit requires a flair — get options with trigger_integration_tool method \"reddit:flairs\".',\n },\n ],\n example: { REDDIT: { sr: \"r/dataisbeautiful\", text: \"Our 2026 growth, visualized\", uploadIds: [\"<id>\"], flairId: \"<flair-id>\" } },\n },\n DISCORD: {\n dataKey: \"data.DISCORD\",\n summary: \"Post a message to a connected Discord channel.\",\n fields: [\n { name: \"channelId\", type: \"string\", required: true, notes: \"The connected server channel (an integration \\\"channel\\\" id — see list_integrations).\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Message content. ≤2000 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Attachments.\" },\n { name: \"username\", type: \"string\", required: false, notes: \"Override the author name shown (webhook).\" },\n { name: \"avatarUrl\", type: \"string (URL)\", required: false, notes: \"Override the author avatar (webhook).\" },\n ],\n example: { DISCORD: { channelId: \"<channel-id>\", text: \"New release 🎉\" } },\n },\n SLACK: {\n dataKey: \"data.SLACK\",\n summary: \"Post a message to a connected Slack channel.\",\n fields: [\n { name: \"channelId\", type: \"string\", required: true, notes: \"The connected workspace channel (an integration \\\"channel\\\" id — see list_integrations).\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Message text.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Attachments.\" },\n { name: \"username\", type: \"string\", required: false, notes: \"Override the author name shown.\" },\n { name: \"avatarUrl\", type: \"string (URL)\", required: false, notes: \"Override the author avatar.\" },\n ],\n example: { SLACK: { channelId: \"<channel-id>\", text: \"Standup notes…\" } },\n },\n GOOGLE_BUSINESS: {\n dataKey: \"data.GOOGLE_BUSINESS\",\n summary: \"Publish an update to a Google Business Profile location.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"The update body.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images/videos.\" },\n { name: \"topicType\", type: \"STANDARD | EVENT | OFFER | ALERT\", required: false, notes: \"Post kind.\" },\n { name: \"languageCode\", type: \"string\", required: false, notes: \"Language tag like `en` / `en-US`.\" },\n {\n name: \"callToActionType\",\n type: \"BOOK | ORDER | SHOP | LEARN_MORE | SIGN_UP | CALL\",\n required: false,\n notes: \"CTA button.\",\n },\n { name: \"callToActionUrl\", type: \"string (URL)\", required: false, notes: \"CTA target.\" },\n { name: \"eventTitle\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"eventStartDate\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"eventEndDate\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"offerCouponCode\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"offerRedeemOnlineUrl\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"offerTermsConditions\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"alertType\", type: \"COVID_19\", required: false, notes: \"For `topicType: ALERT`.\" },\n ],\n example: {\n GOOGLE_BUSINESS: { text: \"Now open Saturdays!\", topicType: \"STANDARD\", callToActionType: \"LEARN_MORE\", callToActionUrl: \"https://example.com\" },\n },\n },\n PINTEREST: {\n dataKey: \"data.PINTEREST\",\n summary: \"Create a Pin on a board.\",\n fields: [\n { name: \"boardName\", type: \"string\", required: true, notes: \"The board to pin to.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"One image (or video).\" },\n { name: \"text\", type: \"string\", required: false, notes: \"The Pin title.\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Pin description.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Where the Pin links to.\" },\n { name: \"altText\", type: \"string\", required: false, notes: \"Image alt text.\" },\n { name: \"note\", type: \"string\", required: false, notes: \"Private note (not public).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image.\" },\n { name: \"dominantColor\", type: \"string\", required: false, notes: \"Hex color used as a placeholder before the image loads.\" },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Adds Pinterest's AI disclosure label.\" },\n ],\n example: { PINTEREST: { boardName: \"Inspiration\", text: \"New idea\", uploadIds: [\"<id>\"], link: \"https://bundle.social\" } },\n },\n SNAPCHAT: {\n dataKey: \"data.SNAPCHAT\",\n summary: \"Post a Story or a Spotlight to a Snapchat Public Profile.\",\n fields: [\n { name: \"type\", type: \"STORY | SPOTLIGHT\", required: false, notes: \"Default STORY.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"One image or video. Video: 5–180s, ≥540×960, up to 100 MB. Images are Story-only.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Alias for `description` (Spotlight). ≤160 chars.\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Spotlight description. ≤160 chars.\" },\n { name: \"locale\", type: \"string\", required: false, notes: \"Spotlight locale in `en_US` form. Default en_US.\" },\n { name: \"skipSaveToProfile\", type: \"boolean\", required: false, notes: \"Spotlight only — don't save the post to the profile.\" },\n ],\n example: { SNAPCHAT: { type: \"SPOTLIGHT\", description: \"Launch day\", locale: \"en_US\" } },\n },\n};\n\nconst ALIASES_BY_PLATFORM: Record<Platform, string[]> = {\n TWITTER: [\"x\", \"twitter\"],\n BLUESKY: [\"bluesky\", \"bsky\"],\n MASTODON: [\"mastodon\", \"masto\"],\n THREADS: [\"threads\"],\n LINKEDIN: [\"linkedin\", \"li\"],\n FACEBOOK: [\"facebook\", \"fb\"],\n INSTAGRAM: [\"instagram\", \"ig\", \"insta\"],\n TIKTOK: [\"tiktok\", \"tt\"],\n YOUTUBE: [\"youtube\", \"yt\"],\n REDDIT: [\"reddit\"],\n DISCORD: [\"discord\"],\n SLACK: [\"slack\"],\n GOOGLE_BUSINESS: [\"gbp\", \"google-business\", \"google_business\", \"gmb\"],\n PINTEREST: [\"pinterest\", \"pin\"],\n SNAPCHAT: [\"snapchat\", \"snap\"],\n};\n\nconst LABELS: Record<Platform, string> = {\n TWITTER: \"X / Twitter\",\n BLUESKY: \"Bluesky\",\n MASTODON: \"Mastodon\",\n THREADS: \"Threads\",\n LINKEDIN: \"LinkedIn\",\n FACEBOOK: \"Facebook (Page)\",\n INSTAGRAM: \"Instagram\",\n TIKTOK: \"TikTok\",\n YOUTUBE: \"YouTube\",\n REDDIT: \"Reddit\",\n DISCORD: \"Discord\",\n SLACK: \"Slack\",\n GOOGLE_BUSINESS: \"Google Business Profile\",\n PINTEREST: \"Pinterest\",\n SNAPCHAT: \"Snapchat (Public Profile)\",\n};\n\nconst NOTES: Partial<Record<Platform, string[]>> = {\n TWITTER: [\n \"For an X thread, post the first tweet, then add the rest as replies — note the API does not expose comments for X, so chain them as separate posts.\",\n \"No analytics surface for X.\",\n ],\n LINKEDIN: ['Discover mention URNs with trigger_integration_tool method \"linkedin:mentions\" and put them in `text`.'],\n REDDIT: [\n 'Before posting, run trigger_integration_tool method \"reddit:requirements\" to learn title length limits, allowed post types and whether a flair is required.',\n ],\n YOUTUBE: [\n 'There is no `categoryId` in the post `data`; fetch categories with trigger_integration_tool method \"youtube:categories\".',\n ],\n INSTAGRAM: [\n \"Account types are connected via Facebook or directly via Instagram (instagramConnectionMethod on the integration).\",\n \"brandedContentSponsors and business discovery only work for accounts connected through Facebook Login.\",\n ],\n GOOGLE_BUSINESS: [\"Set the location up in the dashboard first; details/categories/hours are managed via integration helper tools.\"],\n SNAPCHAT: [\n \"Requires a Snapchat Public Profile. Stories take an image or a video; Spotlights are video-only.\",\n \"No comments API surface for Snapchat.\",\n ],\n THREADS: [\"Polls, GIFs and link attachments are mutually exclusive with media — Threads only allows them on text-only posts.\"],\n};\n\n/** General media guidance that applies to every platform's `uploadIds`. */\nexport const MEDIA_NOTES: string[] = [\n \"Images: JPG / PNG / WEBP / GIF. Video: MP4 / MOV / WEBM, up to 5 GB via the large-upload flow.\",\n \"Upload media first (upload_media → id), or let create_post's `media` arg do it; then put ids in `uploadIds` (and carouselItems[].uploadId / mediaItems[].uploadId).\",\n \"Large videos can take a while to process server-side after upload — a newly created post may sit in PROCESSING before going POSTED. Use get_post to check status; retry_post for a transient platform failure.\",\n];\n\n/** The full per-platform reference, one entry per supported platform. */\nexport const PLATFORM_REFERENCE: Record<Platform, PlatformReferenceEntry> = Object.fromEntries(\n PLATFORMS.map((platform) => {\n const supportsComments = (COMMENT_PLATFORMS as readonly string[]).includes(platform);\n const entry: PlatformReferenceEntry = {\n platform,\n label: LABELS[platform],\n aliases: ALIASES_BY_PLATFORM[platform],\n capabilities: {\n posting: true,\n comments: supportsComments,\n analytics: ANALYTICS.includes(platform),\n commentImports: COMMENT_IMPORT_PLATFORMS.includes(platform),\n },\n post: POST[platform],\n ...(supportsComments ? { comment: commentOperation(platform) } : {}),\n notes: NOTES[platform] ?? [],\n };\n return [platform, entry];\n }),\n) as Record<Platform, PlatformReferenceEntry>;\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { registerIntegrationTools } from \"./integrations\";\nimport { registerPostTools } from \"./posts\";\nimport { registerCommentTools } from \"./comments\";\nimport { registerMediaTools } from \"./media\";\nimport { registerAnalyticsTools } from \"./analytics\";\nimport { registerIntegrationToolHelpers } from \"./integration-tools\";\nimport { registerTeamTools } from \"./teams\";\nimport { registerOrganizationTools } from \"./organization\";\nimport { registerPostImportTools } from \"./post-imports\";\nimport { registerPostCsvTools } from \"./post-csv\";\nimport { registerDiagnosticsTools } from \"./diagnostics\";\nimport { registerPlatformReferenceTools } from \"./platform-reference\";\n\nexport function registerAllTools(server: McpServer, ctx: ServerContext): void {\n registerOrganizationTools(server, ctx);\n registerTeamTools(server, ctx);\n registerIntegrationTools(server, ctx);\n registerPlatformReferenceTools(server, ctx);\n registerPostTools(server, ctx);\n registerCommentTools(server, ctx);\n registerMediaTools(server, ctx);\n registerAnalyticsTools(server, ctx);\n registerPostImportTools(server, ctx);\n registerPostCsvTools(server, ctx);\n registerIntegrationToolHelpers(server, ctx);\n registerDiagnosticsTools(server, ctx);\n}\n"],"mappings":";AACA,OAAS,wBAAAA,OAA4B,4CCDrC,OAAS,aAAAC,OAAiB,0CCA1B,IAAAC,EAAA,CACE,KAAQ,mBACR,QAAW,QACX,QAAW,0CACX,YAAe,+IACf,SAAY,CACV,gBACA,eACA,MACA,yBACA,eACA,MACA,SACA,SACA,QACF,EACA,OAAU,gBACV,QAAW,MACX,SAAY,0DACZ,KAAQ,CACN,IAAO,yDACT,EACA,WAAc,CACZ,KAAQ,MACR,IAAO,0DACT,EACA,KAAQ,SACR,IAAO,CACL,mBAAoB,iBACtB,EACA,MAAS,CACP,UACA,cACA,YACA,eACA,SACF,EACA,QAAW,CACT,KAAQ,MACV,EACA,QAAW,CACT,MAAS,OACT,IAAO,eACP,UAAa,eACb,MAAS,qBACT,KAAQ,aACR,aAAc,SACd,eAAkB,eACpB,EACA,aAAgB,CACd,4BAA6B,UAC7B,aAAgB,UAChB,IAAO,SACT,EACA,gBAAmB,CACjB,8BAA+B,SAC/B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M,QAAQ,KAAK,CAAC,CAAC,CACnD,EACA,QAAQ,GAAG,SAAUI,CAAQ,EAC7B,QAAQ,GAAG,UAAWA,CAAQ,CAChC,CAEAR,GAAK,EAAE,MAAOS,GAAU,CACtBX,GAAI,UAAWW,GAAiB,OAASA,CAAK,EAAE,EAChD,QAAQ,KAAK,CAAC,CAChB,CAAC","names":["StdioServerTransport","McpServer","package_default","Bundlesocial","OpenAPI","ApiError","McpToolError","code","message","details","normalizeError","error","body","errorSummary","jsonResult","data","errorResult","DEFAULT_API_URL","DASHBOARD_API_KEYS_URL","DASHBOARD_SOCIAL_ACCOUNTS_URL","TEAM_PAGE_SIZE","TEAM_MAX_PAGES","listAllTeams","client","teams","page","items","total","createClient","apiKey","apiUrl","Bundlesocial","OpenAPI","resolveTeamId","ctx","teamIdArg","McpToolError","team","z","PLATFORMS","ANALYTICS_PLATFORMS","ALIASES","tryNormalizePlatform","input","normalizePlatform","platform","McpToolError","isAnalyticsPlatform","COMMENT_PLATFORMS","isCommentPlatform","normalizeAnalyticsPlatform","registerTool","server","name","config","handler","args","error","errorResult","teamIdSchema","z","platformSchema","mapAccounts","accounts","account","channel","registerIntegrationTools","server","ctx","registerTool","teamId","id","team","jsonResult","teams","listAllTeams","organization","perTeam","summary","platform","redirectUrl","serverUrl","options","resolveTeamId","requestBody","normalizePlatform","channelId","platforms","expiresInMinutes","p","fromTeamId","toTeamId","resetChannel","page","pageSize","z","fs","path","MIME_BY_EXT","isUrl","value","LARGE_UPLOAD_THRESHOLD_BYTES","LARGE_UPLOAD_MIME_BY_EXT","uploadMediaRef","client","teamId","ref","absolutePath","path","buffer","fs","McpToolError","uploadLargeMedia","mime","file","ext","mimeType","init","put","uploadMediaRefs","refs","ids","upload","asPlainObject","value","label","McpToolError","resolveTargetPlatforms","client","teamId","rawTargets","resolved","accountIds","raw","platform","tryNormalizePlatform","accounts","id","account","candidate","a","isPlatformKeyedObject","keys","key","PLATFORMS","expandPlatformSettings","settings","platforms","result","p","buildPostData","input","perPlatform","data","platformsFromData","normalizePlatform","deriveTitle","content","fallback","firstLine","line","toIsoDate","date","buildFirstComment","firstComment","targets","commentable","isCommentPlatform","McpToolError","COMMENT_PLATFORMS","perPlatform","platform","result","key","value","normalizePlatform","referenceKeySchema","z","firstCommentSchema","teamIdSchema","platformsSchema","mediaSchema","platformSettingsSchema","dataSchema","titleSchema","composePost","ctx","args","teamId","resolveTeamId","resolveTargetPlatforms","platformsFromData","mediaUploadIds","uploadMediaRefs","data","buildPostData","deriveTitle","registerPostTools","server","registerTool","content","platforms","media","platformSettings","title","referenceKey","draft","composed","requestBody","resolvedFirstComment","jsonResult","date","postDate","toIsoDate","limit","offset","status","from","to","query","order","orderBy","id","normalizedPlatforms","params","resolvedTeamId","wantsDataChange","existing","commentTargets","postIds","z","commentImportStatusSchema","z","teamIdSchema","assertCommentPlatforms","platforms","bad","platform","isCommentPlatform","McpToolError","COMMENT_PLATFORMS","toIso","value","date","registerCommentTools","server","ctx","registerTool","postId","importedPostId","fetchedParentCommentId","content","delayMinutes","draft","teamId","id","resolveTeamId","resolved","resolveTargetPlatforms","post","status","baseDate","created","parentCommentId","index","text","postDate","perPlatform","comment","jsonResult","limit","offset","query","order","orderBy","normalized","normalizePlatform","params","title","data","wantsDataChange","requestBody","parsed","importId","socialAccountId","commentId","action","reason","banAuthor","z","teamIdSchema","z","registerMediaTools","server","ctx","registerTool","teamId","source","id","resolveTeamId","jsonResult","uploadMediaRef","type","status","ids","fileName","mimeType","path","z","teamIdSchema","z","withinRange","value","from","to","time","registerAnalyticsTools","server","ctx","registerTool","id","platform","raw","platformType","normalizeAnalyticsPlatform","response","jsonResult","teamId","resolveTeamId","postIds","page","limit","postId","importedPostId","McpToolError","organization","team","postsUsage","commentsUsage","uploadsUsage","accounts","integrations","account","base","isAnalyticsPlatform","items","item","error","errorSummary","z","INTEGRATION_TOOLS","client","teamId","p","listIntegrationTools","tool","runIntegrationTool","method","params","candidate","McpToolError","t","missing","key","teamIdSchema","z","registerIntegrationToolHelpers","server","ctx","registerTool","jsonResult","listIntegrationTools","method","params","teamId","id","resolveTeamId","runIntegrationTool","z","registerTeamTools","server","ctx","registerTool","z","limit","offset","search","jsonResult","id","name","avatarUrl","requestBody","McpToolError","z","teamIdSchema","z","registerOrganizationTools","server","ctx","registerTool","jsonResult","teamId","platform","socialAccountId","page","pageSize","resolvedTeamId","resolveTeamId","posts","comments","uploads","imports","error","errorSummary","normalizePlatform","date","z","platformSchema","z","registerPostImportTools","server","ctx","registerTool","platform","count","withAnalytics","importCarousels","surface","mediaType","teamId","id","resolveTeamId","jsonResult","normalizePlatform","importId","limit","offset","postIds","fs","path","z","isUrl","value","readCsvFile","source","response","McpToolError","buffer","name","path","absolutePath","fs","registerPostCsvTools","server","ctx","registerTool","z","file","jsonResult","limit","offset","importId","status","VERSION","package_default","registerDiagnosticsTools","server","ctx","registerTool","checks","add","name","status","message","extra","finish","jsonResult","check","health","error","errorSummary","teams","organizationApiAccess","organization","listAllTeams","team","teamId","accounts","account","DASHBOARD_SOCIAL_ACCOUNTS_URL","usage","z","COMMENT_IMPORT_PLATFORMS","ANALYTICS","commentOperation","platform","POST","ALIASES_BY_PLATFORM","LABELS","NOTES","MEDIA_NOTES","PLATFORM_REFERENCE","PLATFORMS","supportsComments","COMMENT_PLATFORMS","entry","projectEntry","entry","operation","base","registerPlatformReferenceTools","server","ctx","registerTool","z","platform","normalized","tryNormalizePlatform","jsonResult","PLATFORM_REFERENCE","MEDIA_NOTES","PLATFORMS","name","registerAllTools","server","ctx","registerOrganizationTools","registerTeamTools","registerIntegrationTools","registerPlatformReferenceTools","registerPostTools","registerCommentTools","registerMediaTools","registerAnalyticsTools","registerPostImportTools","registerPostCsvTools","registerIntegrationToolHelpers","registerDiagnosticsTools","VERSION","package_default","createServer","options","server","McpServer","ctx","createClient","DEFAULT_API_URL","registerAllTools","readFlag","name","index","inline","arg","log","message","main","VERSION","DASHBOARD_API_KEYS_URL","apiKey","server","createServer","transport","StdioServerTransport","shutdown","error"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/server.ts","../package.json","../src/client.ts","../src/errors.ts","../src/tools/integrations.ts","../src/platforms.ts","../src/register-tool.ts","../src/tools/posts.ts","../src/media.ts","../src/post-data.ts","../src/tools/comments.ts","../src/tools/media.ts","../src/tools/analytics.ts","../src/tools/integration-tools.ts","../src/integration-tools.ts","../src/tools/teams.ts","../src/tools/organization.ts","../src/tools/post-imports.ts","../src/tools/post-csv.ts","../src/tools/diagnostics.ts","../src/tools/platform-reference.ts","../src/platform-reference.ts","../src/tools/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createServer, VERSION } from \"./server\";\nimport { DASHBOARD_API_KEYS_URL } from \"./client\";\n\n/** Read a `--flag value` pair from argv (CLI overrides for the env vars). */\nfunction readFlag(name: string): string | undefined {\n const index = process.argv.indexOf(`--${name}`);\n if (index !== -1 && index + 1 < process.argv.length) return process.argv[index + 1];\n const inline = process.argv.find((arg) => arg.startsWith(`--${name}=`));\n return inline ? inline.slice(`--${name}=`.length) : undefined;\n}\n\nfunction log(message: string): void {\n // stdio transport owns stdout — all logging must go to stderr.\n process.stderr.write(`bundlesocial-mcp: ${message}\\n`);\n}\n\nasync function main(): Promise<void> {\n if (process.argv.includes(\"--version\") || process.argv.includes(\"-v\")) {\n process.stdout.write(`${VERSION}\\n`);\n return;\n }\n if (process.argv.includes(\"--help\") || process.argv.includes(\"-h\")) {\n process.stdout.write(\n `bundlesocial-mcp ${VERSION} — Model Context Protocol server for the bundle.social API.\\n\\n` +\n `Usage: bundlesocial-mcp [--api-key <key>] [--api-url <url>] [--team-id <id>]\\n\\n` +\n `Reads BUNDLESOCIAL_API_KEY (required), BUNDLESOCIAL_API_URL and BUNDLESOCIAL_TEAM_ID from the environment;\\n` +\n `the flags above override them. Communicates over stdio (MCP). Create an API key at ${DASHBOARD_API_KEYS_URL}\\n`,\n );\n return;\n }\n\n const apiKey = readFlag(\"api-key\") ?? process.env.BUNDLESOCIAL_API_KEY;\n if (!apiKey) {\n log(`missing API key. Set BUNDLESOCIAL_API_KEY (or pass --api-key). Create one at ${DASHBOARD_API_KEYS_URL}`);\n process.exit(1);\n }\n\n const server = createServer({\n apiKey,\n apiUrl: readFlag(\"api-url\") ?? process.env.BUNDLESOCIAL_API_URL,\n defaultTeamId: readFlag(\"team-id\") ?? process.env.BUNDLESOCIAL_TEAM_ID,\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n log(\"running on stdio\");\n\n const shutdown = () => {\n void server.close().finally(() => process.exit(0));\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((error) => {\n log(`fatal: ${(error as Error)?.stack ?? error}`);\n process.exit(1);\n});\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport pkg from \"../package.json\";\nimport { type ServerContext, DEFAULT_API_URL, createClient } from \"./client\";\nimport { registerAllTools } from \"./tools\";\n\nexport const VERSION: string = pkg.version;\n\nexport interface CreateServerOptions {\n apiKey: string;\n apiUrl?: string;\n /** Default team id (from BUNDLESOCIAL_TEAM_ID / --team-id). */\n defaultTeamId?: string;\n}\n\n/** Build an MCP server exposing the bundle.social tools. Transport-agnostic. */\nexport function createServer(options: CreateServerOptions): McpServer {\n const server = new McpServer(\n { name: \"bundlesocial\", version: VERSION },\n {\n capabilities: { tools: {} },\n instructions:\n \"Tools for the bundle.social API: posting/scheduling to 14+ social platforms, comments, media uploads, analytics, team & integration management, and bulk/history imports (post-history, comment, CSV). Run check_setup first to verify the API key, org access and team. Use list_integrations to see connected accounts and their ids. create_post / schedule_post target platforms by name (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, gbp) or by integration id; put platform-required fields (Reddit `sr`, Pinterest `boardName`, TikTok `privacy`, YouTube `madeForKids`/`privacyStatus`) under `platformSettings` keyed by platform. Call describe_platform to get the exact per-platform `data.<PLATFORM>` field schema (for posts and comments) before building a `data` / `platformSettings` object; the same fields are documented at https://docs.bundle.social/api-reference/platform-parameters. Team-scoped tools take an optional `teamId` (resolved automatically when the org has one team or BUNDLESOCIAL_TEAM_ID is set). Errors come back as { error: { code, message, details } } with isError: true.\",\n },\n );\n\n const ctx: ServerContext = {\n client: createClient(options.apiKey, options.apiUrl ?? DEFAULT_API_URL),\n defaultTeamId: options.defaultTeamId,\n };\n registerAllTools(server, ctx);\n return server;\n}\n","{\n \"name\": \"bundlesocial-mcp\",\n \"version\": \"1.2.3\",\n \"mcpName\": \"io.github.bundleglobal/bundlesocial-mcp\",\n \"description\": \"Model Context Protocol server for the bundle.social social-media API — post to 14+ platforms from Claude, Cursor and other MCP clients.\",\n \"keywords\": [\n \"bundle.social\",\n \"bundlesocial\",\n \"mcp\",\n \"model context protocol\",\n \"social media\",\n \"api\",\n \"agents\",\n \"claude\",\n \"cursor\"\n ],\n \"author\": \"bundle.global\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/bundleglobal/bundlesocial-mcp#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/bundleglobal/bundlesocial-mcp/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/bundleglobal/bundlesocial-mcp.git\"\n },\n \"type\": \"module\",\n \"bin\": {\n \"bundlesocial-mcp\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist/**\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"start\": \"node dist/index.js\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.12.0\",\n \"bundlesocial\": \"^2.70.0\",\n \"zod\": \"^3.23.8\"\n },\n \"devDependencies\": {\n \"@semantic-release/changelog\": \"^6.0.3\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@types/node\": \"^20.14.0\",\n \"semantic-release\": \"^25.0.2\",\n \"tsup\": \"^8.2.4\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.0.5\"\n }\n}\n","import { Bundlesocial, OpenAPI, type TeamGetListResponse } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\nexport const DEFAULT_API_URL = \"https://api.bundle.social\";\nexport const DASHBOARD_API_KEYS_URL = \"https://bundle.social/dashboard/organization/api-keys\";\nexport const DASHBOARD_SOCIAL_ACCOUNTS_URL = \"https://bundle.social/dashboard/general/social-accounts\";\n\nexport interface ServerContext {\n client: Bundlesocial;\n /** Team id from BUNDLESOCIAL_TEAM_ID / --team-id, if configured. */\n defaultTeamId?: string;\n}\n\nexport type TeamListItem = TeamGetListResponse[\"items\"][number];\n\n/** Page size used when walking the team list (the `list_teams` tool caps at the same value). */\nexport const TEAM_PAGE_SIZE = 100;\n/** Safety cap so a misbehaving `total` can't loop forever (100 pages x 100 = 10k teams). */\nexport const TEAM_MAX_PAGES = 100;\n\n/**\n * Fetch every team in the organization via the paginated team list. Replaces\n * the deprecated `organization.teams` array (removed from the API on 2026-11-15).\n */\nexport async function listAllTeams(client: Bundlesocial): Promise<TeamListItem[]> {\n const teams: TeamListItem[] = [];\n for (let page = 0; page < TEAM_MAX_PAGES; page++) {\n const { items, total } = await client.team.teamGetList({ offset: teams.length, limit: TEAM_PAGE_SIZE });\n teams.push(...(items ?? []));\n if (!items?.length || teams.length >= total) return teams;\n }\n // stdio transport owns stdout, so warnings go to stderr.\n process.stderr.write(`bundlesocial-mcp: team list truncated at ${teams.length} teams (page cap ${TEAM_MAX_PAGES} reached)\\n`);\n return teams;\n}\n\nexport function createClient(apiKey: string, apiUrl: string = DEFAULT_API_URL): Bundlesocial {\n return new Bundlesocial(apiKey, { ...OpenAPI, BASE: apiUrl });\n}\n\n/**\n * Resolve the team to operate on: explicit `teamId` argument > server's\n * configured default > the organization's only team. Throws when ambiguous.\n */\nexport async function resolveTeamId(ctx: ServerContext, teamIdArg?: string): Promise<string> {\n if (teamIdArg) return teamIdArg;\n if (ctx.defaultTeamId) return ctx.defaultTeamId;\n const teams = await listAllTeams(ctx.client);\n if (teams.length === 1) return teams[0].id;\n if (teams.length === 0) {\n throw new McpToolError(\"NO_TEAMS\", \"This organization has no teams yet. Create one in the bundle.social dashboard first.\");\n }\n throw new McpToolError(\n \"TEAM_ID_REQUIRED\",\n `This organization has ${teams.length} teams. Pass a \"teamId\" argument (or set BUNDLESOCIAL_TEAM_ID when starting the server).`,\n { teams: teams.map((team) => ({ id: team.id, name: team.name })) },\n );\n}\n","import { ApiError } from \"bundlesocial\";\n\n/** An error with a stable machine-readable `code`, surfaced in the tool error result. */\nexport class McpToolError extends Error {\n readonly code: string;\n readonly details?: unknown;\n\n constructor(code: string, message: string, details?: unknown) {\n super(message);\n this.name = \"McpToolError\";\n this.code = code;\n this.details = details;\n }\n}\n\nexport interface NormalizedError {\n code: string;\n message: string;\n details?: unknown;\n}\n\nexport function normalizeError(error: unknown): NormalizedError {\n if (error instanceof McpToolError) {\n return { code: error.code, message: error.message, details: error.details };\n }\n if (error instanceof ApiError) {\n const body = error.body as Record<string, unknown> | string | undefined;\n const message =\n (typeof body === \"object\" && body && typeof body.message === \"string\" && body.message) ||\n (typeof body === \"object\" && body && typeof body.error === \"string\" && body.error) ||\n error.statusText ||\n error.message ||\n `HTTP ${error.status}`;\n return { code: `HTTP_${error.status}`, message, details: { status: error.status, url: error.url, body: error.body } };\n }\n if (error instanceof Error) {\n return {\n code: \"UNEXPECTED_ERROR\",\n message: error.message || \"Unexpected error\",\n details: process.env.BUNDLESOCIAL_DEBUG ? { stack: error.stack } : undefined,\n };\n }\n return { code: \"UNEXPECTED_ERROR\", message: String(error) };\n}\n\nexport function errorSummary(error: unknown): string {\n if (error instanceof ApiError) return `HTTP ${error.status}${error.statusText ? ` ${error.statusText}` : \"\"}`;\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\ntype TextContent = { type: \"text\"; text: string };\nexport interface ToolResult {\n content: TextContent[];\n isError?: boolean;\n}\n\n/** Wrap a value as a successful tool result (pretty JSON in a text block). */\nexport function jsonResult(data: unknown): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify(data, null, 2) }] };\n}\n\n/** Wrap an error as a tool error result with the `{ error: { code, message, details? } }` envelope. */\nexport function errorResult(error: unknown): ToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify({ error: normalizeError(error) }, null, 2) }], isError: true };\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n SocialAccountConnectData,\n SocialAccountCreatePortalLinkData,\n} from \"bundlesocial\";\nimport { type ServerContext, listAllTeams, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { normalizePlatform, type Platform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nconst platformSchema = z\n .string()\n .min(1)\n .describe('Platform name/alias (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, gbp).');\n\ntype ConnectBody = NonNullable<SocialAccountConnectData[\"requestBody\"]>;\ntype PortalLinkBody = NonNullable<SocialAccountCreatePortalLinkData[\"requestBody\"]>;\n\ntype SocialAccount = {\n id: string;\n type: string;\n username?: string | null;\n displayName?: string | null;\n avatarUrl?: string | null;\n channels?: Array<{ id: string; name?: string | null; username?: string | null; address?: string | null }> | null;\n};\n\nfunction mapAccounts(accounts: SocialAccount[] | undefined) {\n return (accounts ?? []).map((account) => ({\n id: account.id,\n type: account.type,\n username: account.username ?? null,\n displayName: account.displayName ?? null,\n avatarUrl: account.avatarUrl ?? null,\n channels: (account.channels ?? []).map((channel) => ({\n id: channel.id,\n name: channel.name ?? null,\n username: channel.username ?? null,\n address: channel.address ?? null,\n })),\n }));\n}\n\nexport function registerIntegrationTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_integrations\",\n {\n title: \"List connected integrations\",\n description:\n \"List the social-media integrations (accounts) connected to a bundle.social team — each with its `id`, `type` (platform), `username` and channels. Use this to discover which platforms are available and to get integration ids. Without a team id it lists every team in the organization.\",\n inputSchema: { teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId }) => {\n if (teamId ?? ctx.defaultTeamId) {\n const id = (teamId ?? ctx.defaultTeamId) as string;\n const team = await ctx.client.team.teamGetTeam({ id });\n return jsonResult({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n const teams = await listAllTeams(ctx.client);\n if (teams.length === 1) {\n const team = await ctx.client.team.teamGetTeam({ id: teams[0].id });\n return jsonResult({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n const organization = await ctx.client.organization.organizationGetOrganization();\n const perTeam = [];\n for (const summary of teams) {\n const team = await ctx.client.team.teamGetTeam({ id: summary.id });\n perTeam.push({ teamId: team.id, teamName: team.name, integrations: mapAccounts(team.socialAccounts) });\n }\n return jsonResult({ organizationId: organization.id, organizationName: organization.name ?? null, teams: perTeam });\n },\n );\n\n registerTool(\n server,\n \"connect_integration\",\n {\n title: \"Connect a social account\",\n description:\n \"Start connecting a social account to a team. Returns an OAuth `url` — open it in a browser to authorize the account; bundle.social redirects back to `redirectUrl` afterwards. For Mastodon/Bluesky pass `serverUrl`.\",\n inputSchema: {\n platform: platformSchema,\n redirectUrl: z.string().min(1).describe(\"URL bundle.social redirects to after the user finishes (or cancels) the OAuth flow.\"),\n serverUrl: z.string().optional().describe(\"Mastodon/Bluesky instance URL (required for those platforms).\"),\n teamId: teamIdSchema,\n options: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Advanced provider flags, e.g. {\\\"instagramConnectionMethod\\\":\\\"INSTAGRAM\\\",\\\"withBusinessScope\\\":true,\\\"disableAutoLogin\\\":true,\\\"forceBrowserOAuth\\\":true,\\\"tiktokForceLogin\\\":true}. `withBusinessScope` also unlocks YouTube monetization analytics; `tiktokForceLogin` (experimental) forces TikTok's account picker when it keeps reusing the wrong active account.\",\n ),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platform, redirectUrl, serverUrl, teamId, options }) => {\n const id = await resolveTeamId(ctx, teamId);\n const requestBody = {\n type: normalizePlatform(platform) as ConnectBody[\"type\"],\n teamId: id,\n redirectUrl,\n ...(serverUrl ? { serverUrl } : {}),\n ...(options ?? {}),\n } as ConnectBody;\n return jsonResult(await ctx.client.socialAccount.socialAccountConnect({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"disconnect_integration\",\n {\n title: \"Disconnect a social account\",\n description: \"Disconnect a social account of the given platform from a team. Destructive — also removes it from scheduled posts.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountDisconnect({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"set_integration_channel\",\n {\n title: \"Set a social account's channel/page\",\n description: \"Select the page/channel for a connected account (needed for FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, GOOGLE_BUSINESS). Get channel ids from list_integrations / refresh_integration_channels.\",\n inputSchema: { platform: platformSchema, channelId: z.string().min(1).describe(\"Channel/page id to select.\"), teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, channelId, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountSetChannel({ requestBody: { type: normalizePlatform(platform) as never, teamId: id, channelId } }));\n },\n );\n\n registerTool(\n server,\n \"unset_integration_channel\",\n {\n title: \"Clear a social account's channel/page\",\n description: \"Clear the selected page/channel for a connected account (FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, GOOGLE_BUSINESS) while keeping the authorization.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountUnsetChannel({ requestBody: { type: normalizePlatform(platform) as never, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"refresh_integration_channels\",\n {\n title: \"Refresh a social account's channels\",\n description: \"Re-fetch the available channels for a connected account (needed for REDDIT, DISCORD, SLACK, PINTEREST and the page-based platforms).\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountRefreshChannels({ requestBody: { type: normalizePlatform(platform) as never, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"create_integration_portal_link\",\n {\n title: \"Create a connect-portal link\",\n description:\n \"Create a hosted bundle.social portal link a user can open to connect/manage social accounts without you implementing the OAuth flow. Returns a `url`.\",\n inputSchema: {\n platforms: z.array(z.string().min(1)).min(1).describe(\"Platforms the portal should offer to connect (names/aliases).\"),\n redirectUrl: z.string().optional().describe(\"URL to redirect to when the user finishes.\"),\n teamId: teamIdSchema,\n expiresInMinutes: z.number().int().min(5).max(2880).optional().describe(\"Link lifetime in minutes (5 min – 48 h).\"),\n options: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Advanced portal options — branding (logoUrl, userLogoUrl, userName, goBackButtonText, hidePoweredBy, hideGoBackButton, hideUserLogo, hideUserName, hideLanguageSwitcher, showModalOnConnectSuccess, language, maxSocialAccountsConnected) and the same OAuth flags as connect_integration (serverUrl, instagramConnectionMethod, withBusinessScope, disableAutoLogin, forceBrowserOAuth, tiktokForceLogin).\",\n ),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platforms, redirectUrl, teamId, expiresInMinutes, options }) => {\n const id = await resolveTeamId(ctx, teamId);\n const requestBody = {\n teamId: id,\n socialAccountTypes: platforms.map((p) => normalizePlatform(p)) as PortalLinkBody[\"socialAccountTypes\"],\n ...(redirectUrl ? { redirectUrl } : {}),\n ...(expiresInMinutes ? { expiresIn: expiresInMinutes } : {}),\n ...(options ?? {}),\n } as PortalLinkBody;\n return jsonResult(await ctx.client.socialAccount.socialAccountCreatePortalLink({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"check_integration_connection\",\n {\n title: \"Check a social account's connection\",\n description: \"Run an on-demand connection/disconnect health check for a connected account of the given platform.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountConnectionCheck({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"refresh_integration_profile\",\n {\n title: \"Refresh a social account's profile\",\n description: \"Re-fetch the profile info (username, display name, avatar) for a connected account of the given platform.\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountProfileRefresh({ requestBody: { type: normalizePlatform(platform) as Platform, teamId: id } }));\n },\n );\n\n registerTool(\n server,\n \"get_integration_by_type\",\n {\n title: \"Get a social account by platform\",\n description: \"Fetch the connected social account of a given platform for a team (including its channels).\",\n inputSchema: { platform: platformSchema, teamId: teamIdSchema },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.socialAccount.socialAccountGetByType({ teamId: id, type: normalizePlatform(platform) as Platform }));\n },\n );\n\n registerTool(\n server,\n \"copy_integration\",\n {\n title: \"Copy social accounts between teams\",\n description: \"Copy connected social accounts of the given platforms from one team to another. Set `resetChannel` to require re-picking the page (Facebook/Instagram/LinkedIn/YouTube).\",\n inputSchema: {\n fromTeamId: z.string().min(1).describe(\"Source team id.\"),\n toTeamId: z.string().min(1).describe(\"Destination team id.\"),\n platforms: z.array(z.string().min(1)).min(1).describe(\"Platforms to copy (names/aliases).\"),\n resetChannel: z.boolean().optional().describe(\"If true, the destination must re-select the page/channel.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ fromTeamId, toTeamId, platforms, resetChannel }) =>\n jsonResult(\n await ctx.client.socialAccount.socialAccountCopy({\n requestBody: {\n fromTeamId,\n toTeamId,\n ...(resetChannel !== undefined ? { resetChannel } : {}),\n socialAccountTypes: platforms.map((p) => normalizePlatform(p)) as Platform[],\n },\n }),\n ),\n );\n\n registerTool(\n server,\n \"list_integrations_to_delete\",\n {\n title: \"List social accounts pending deletion\",\n description: \"List social accounts scheduled to be deleted (paginated) across the organization.\",\n inputSchema: {\n page: z.number().int().positive().optional().describe(\"Page (1-based).\"),\n pageSize: z.number().int().positive().max(100).optional().describe(\"Page size.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ page, pageSize }) => jsonResult(await ctx.client.socialAccount.socialAccountGetAccountsToDelete({ page, pageSize })),\n );\n}\n","import { McpToolError } from \"./errors\";\n\n/** Every platform bundle.social can post to. Mirrors the API's `socialAccountTypes` enum. */\nexport const PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"TWITTER\",\n \"THREADS\",\n \"LINKEDIN\",\n \"PINTEREST\",\n \"REDDIT\",\n \"MASTODON\",\n \"DISCORD\",\n \"SLACK\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n] as const;\n\nexport type Platform = (typeof PLATFORMS)[number];\n\n/** Platforms for which the API exposes analytics (X/Twitter, Discord and Slack are absent). */\nexport const ANALYTICS_PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"REDDIT\",\n \"PINTEREST\",\n \"MASTODON\",\n \"LINKEDIN\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n] as const;\n\nexport type AnalyticsPlatform = (typeof ANALYTICS_PLATFORMS)[number];\n\nconst ALIASES: Record<string, Platform> = {\n X: \"TWITTER\",\n TWITTER: \"TWITTER\",\n TIKTOK: \"TIKTOK\",\n TT: \"TIKTOK\",\n YOUTUBE: \"YOUTUBE\",\n YT: \"YOUTUBE\",\n INSTAGRAM: \"INSTAGRAM\",\n IG: \"INSTAGRAM\",\n INSTA: \"INSTAGRAM\",\n FACEBOOK: \"FACEBOOK\",\n FB: \"FACEBOOK\",\n THREADS: \"THREADS\",\n LINKEDIN: \"LINKEDIN\",\n LI: \"LINKEDIN\",\n PINTEREST: \"PINTEREST\",\n PIN: \"PINTEREST\",\n REDDIT: \"REDDIT\",\n MASTODON: \"MASTODON\",\n MASTO: \"MASTODON\",\n DISCORD: \"DISCORD\",\n SLACK: \"SLACK\",\n BLUESKY: \"BLUESKY\",\n BSKY: \"BLUESKY\",\n GOOGLE_BUSINESS: \"GOOGLE_BUSINESS\",\n \"GOOGLE-BUSINESS\": \"GOOGLE_BUSINESS\",\n GBP: \"GOOGLE_BUSINESS\",\n GOOGLEBUSINESS: \"GOOGLE_BUSINESS\",\n GMB: \"GOOGLE_BUSINESS\",\n SNAPCHAT: \"SNAPCHAT\",\n SNAP: \"SNAPCHAT\",\n};\n\nexport function tryNormalizePlatform(input: string): Platform | undefined {\n return ALIASES[input.trim().toUpperCase().replace(/\\s+/g, \"_\")];\n}\n\nexport function normalizePlatform(input: string): Platform {\n const platform = tryNormalizePlatform(input);\n if (!platform) {\n throw new McpToolError(\n \"UNKNOWN_PLATFORM\",\n `Unknown platform \"${input}\". Supported: ${PLATFORMS.join(\", \")} (aliases like \"x\" and \"gbp\" are accepted too).`,\n );\n }\n return platform;\n}\n\nexport function isAnalyticsPlatform(platform: string): platform is AnalyticsPlatform {\n return (ANALYTICS_PLATFORMS as readonly string[]).includes(platform);\n}\n\n/**\n * Platforms on which the API can post comments. TWITTER/X, PINTEREST and\n * GOOGLE_BUSINESS are intentionally absent.\n */\nexport const COMMENT_PLATFORMS = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"LINKEDIN\",\n \"REDDIT\",\n \"MASTODON\",\n \"DISCORD\",\n \"SLACK\",\n \"BLUESKY\",\n] as const;\n\nexport type CommentPlatform = (typeof COMMENT_PLATFORMS)[number];\n\nexport function isCommentPlatform(platform: string): platform is CommentPlatform {\n return (COMMENT_PLATFORMS as readonly string[]).includes(platform);\n}\n\nexport function normalizeAnalyticsPlatform(input: string): AnalyticsPlatform {\n const platform = normalizePlatform(input);\n if (!isAnalyticsPlatform(platform)) {\n throw new McpToolError(\n \"ANALYTICS_NOT_SUPPORTED\",\n `Analytics are not available for ${platform}. Supported: ${ANALYTICS_PLATFORMS.join(\", \")}.`,\n );\n }\n return platform;\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { z, ZodRawShape } from \"zod\";\nimport { errorResult, type ToolResult } from \"./errors\";\n\ntype InferShape<Shape extends ZodRawShape> = { [K in keyof Shape]: z.infer<Shape[K]> };\n\nexport interface ToolConfig<Shape extends ZodRawShape> {\n title?: string;\n description: string;\n inputSchema?: Shape;\n annotations?: {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n };\n}\n\n/**\n * Register a tool whose handler always returns a structured result — thrown\n * errors (incl. SDK `ApiError`s and `McpToolError`s) become the standard\n * `{ error: { code, message, details? } }` envelope with `isError: true`.\n */\nexport function registerTool<Shape extends ZodRawShape>(\n server: McpServer,\n name: string,\n config: ToolConfig<Shape>,\n handler: (args: InferShape<Shape>) => Promise<ToolResult>,\n): void {\n // The MCP SDK's overloads can't statically tie our handler's arg type to the\n // zod shape here, so the cast is confined to this single boundary.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n server.registerTool(name, config as any, (async (args: any) => {\n try {\n return await handler(args ?? {});\n } catch (error) {\n return errorResult(error);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any);\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n PostCreateData,\n PostGetListData,\n PostGetReconnectSocialAccountCandidatesData,\n PostReconnectSocialAccountData,\n PostUpdateData,\n} from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { COMMENT_PLATFORMS, isCommentPlatform, normalizePlatform, type Platform } from \"../platforms\";\nimport { uploadMediaRefs } from \"../media\";\nimport { buildPostData, deriveTitle, platformsFromData, resolveTargetPlatforms, toIsoDate } from \"../post-data\";\nimport { registerTool } from \"../register-tool\";\n\ntype PostCreateBody = NonNullable<PostCreateData[\"requestBody\"]>;\ntype PostData = PostCreateBody[\"data\"];\ntype PostUpdateBody = NonNullable<PostUpdateData[\"requestBody\"]>;\ntype ReconnectPlatform = NonNullable<PostReconnectSocialAccountData[\"requestBody\"]>[\"type\"];\ntype PostFirstComment = NonNullable<NonNullable<PostCreateBody[\"firstComment\"]>>;\n\n/**\n * Normalize the `firstComment` argument into the per-platform object the API\n * expects: either a platform-keyed map, or one string applied to every\n * comment-capable platform the post targets.\n */\nfunction buildFirstComment(\n firstComment: string | Record<string, string> | undefined,\n targets: Platform[],\n): PostFirstComment | undefined {\n if (firstComment === undefined) return undefined;\n if (typeof firstComment === \"string\") {\n const commentable = targets.filter(isCommentPlatform);\n if (commentable.length === 0) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `None of the targeted platforms support comments, so firstComment has no effect. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n const perPlatform: PostFirstComment = {};\n for (const platform of commentable) perPlatform[platform] = firstComment;\n return perPlatform;\n }\n const result: PostFirstComment = {};\n for (const [key, value] of Object.entries(firstComment)) {\n const platform = normalizePlatform(key);\n if (!isCommentPlatform(platform)) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `A first comment is not supported on ${platform}. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n result[platform] = value;\n }\n return result;\n}\n\nconst referenceKeySchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"Your own identifier for this post. Look the post up later with get_post_by_reference_key.\");\n\nconst firstCommentSchema = z\n .union([z.string().min(1), z.record(z.string(), z.string())])\n .optional()\n .describe(\n 'Comment published as soon as the post itself goes live. A string applies to every comment-capable target; a platform-keyed object targets specific platforms, e.g. {\"INSTAGRAM\":\"more below 👇\"}. Supported on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, LINKEDIN, REDDIT, MASTODON, DISCORD, SLACK, BLUESKY.',\n );\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nconst platformsSchema = z\n .array(z.string().min(1))\n .optional()\n .describe(\n 'Target platforms — names/aliases (x, tiktok, instagram, youtube, facebook, threads, linkedin, pinterest, reddit, mastodon, discord, slack, bluesky, gbp, snapchat) and/or connected integration ids from list_integrations. Required unless \"data\" is provided with platform keys.',\n );\n\nconst mediaSchema = z\n .array(z.string().min(1))\n .optional()\n .describe(\n \"Media to attach: public https:// URLs (or local file paths when this server runs in stdio mode). Uploaded automatically and attached to every targeted platform. For per-platform media, use upload_media + the `data` argument instead.\",\n );\n\nconst platformSettingsSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Per-platform options. Either keyed by platform name, e.g. {\"TIKTOK\":{\"privacy\":\"PUBLIC_TO_EVERYONE\"},\"YOUTUBE\":{\"type\":\"SHORT\",\"privacyStatus\":\"PUBLIC\",\"madeForKids\":false}}, or a flat object applied to every targeted platform. Use this for platform-required fields (Reddit `sr`, Pinterest `boardName`, TikTok `privacy`, YouTube `madeForKids`/`privacyStatus`, Instagram/Facebook `type`).',\n );\n\nconst dataSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Advanced: the full post `data` object keyed by platform, e.g. {\"REDDIT\":{\"sr\":\"r/test\",\"text\":\"hello\",\"uploadIds\":[\"<uploadId>\"]}}. Overrides content/media/platformSettings. Targeted platforms are inferred from its keys unless `platforms` is also given.',\n );\n\nconst titleSchema = z.string().min(1).optional().describe(\"Post title. Defaults to the first line of `content`. Also used as the YouTube video title.\");\n\ninterface ComposeArgs {\n teamId?: string;\n content?: string;\n platforms?: string[];\n media?: string[];\n platformSettings?: Record<string, unknown>;\n data?: Record<string, unknown>;\n title?: string;\n}\n\nasync function composePost(ctx: ServerContext, args: ComposeArgs) {\n const teamId = await resolveTeamId(ctx, args.teamId);\n\n let targets: Platform[];\n if (args.platforms && args.platforms.length > 0) {\n targets = await resolveTargetPlatforms(ctx.client, teamId, args.platforms);\n } else if (args.data) {\n targets = platformsFromData(args.data);\n } else {\n throw new McpToolError(\n \"NO_TARGET\",\n 'Provide \"platforms\" (platform names or integration ids), or a \"data\" object keyed by platform.',\n );\n }\n if (targets.length === 0) throw new McpToolError(\"NO_TARGET\", \"Could not determine any target platform for this post.\");\n\n const mediaUploadIds = await uploadMediaRefs(ctx.client, teamId, args.media ?? []);\n const data = buildPostData(targets, {\n content: args.content,\n mediaUploadIds,\n platformSettings: args.platformSettings,\n data: args.data,\n }) as unknown as PostData;\n\n return {\n teamId,\n socialAccountTypes: targets,\n data,\n title: args.title ?? deriveTitle(args.content, \"Untitled post\"),\n };\n}\n\nexport function registerPostTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post\",\n {\n title: \"Create a post (publish now)\",\n description:\n \"Publish a post immediately to one or more connected social-media integrations. Returns the created post (with its id and status). Set `draft: true` to save it as a draft instead of publishing. For a future-dated post use schedule_post.\",\n inputSchema: {\n teamId: teamIdSchema,\n content: z.string().optional().describe(\"Post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n title: titleSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n draft: z.boolean().optional().default(false).describe(\"If true, save as a DRAFT instead of publishing now.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, content, platforms, media, platformSettings, data, title, referenceKey, firstComment, draft }) => {\n const composed = await composePost(ctx, { teamId, content, platforms, media, platformSettings, data, title });\n const requestBody: PostCreateBody = {\n teamId: composed.teamId,\n title: composed.title,\n postDate: new Date().toISOString(),\n status: draft ? \"DRAFT\" : \"SCHEDULED\",\n socialAccountTypes: composed.socialAccountTypes,\n data: composed.data,\n };\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n const resolvedFirstComment = buildFirstComment(firstComment, composed.socialAccountTypes);\n if (resolvedFirstComment) requestBody.firstComment = resolvedFirstComment;\n return jsonResult(await ctx.client.post.postCreate({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"schedule_post\",\n {\n title: \"Schedule a post for later\",\n description:\n \"Schedule a post to be published at a specific date/time on one or more connected integrations. Same inputs as create_post plus a required ISO-8601 `date`. Returns the scheduled post.\",\n inputSchema: {\n teamId: teamIdSchema,\n date: z.string().min(1).describe(\"When to publish — ISO 8601, e.g. 2026-06-01T09:00:00Z.\"),\n content: z.string().optional().describe(\"Post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n title: titleSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, date, content, platforms, media, platformSettings, data, title, referenceKey, firstComment }) => {\n const postDate = toIsoDate(date, \"date\");\n const composed = await composePost(ctx, { teamId, content, platforms, media, platformSettings, data, title });\n const requestBody: PostCreateBody = {\n teamId: composed.teamId,\n title: composed.title,\n postDate,\n status: \"SCHEDULED\",\n socialAccountTypes: composed.socialAccountTypes,\n data: composed.data,\n };\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n const resolvedFirstComment = buildFirstComment(firstComment, composed.socialAccountTypes);\n if (resolvedFirstComment) requestBody.firstComment = resolvedFirstComment;\n return jsonResult(await ctx.client.post.postCreate({ requestBody }));\n },\n );\n\n registerTool(\n server,\n \"list_posts\",\n {\n title: \"List recent posts\",\n description: \"List recent posts for a team, newest first, with optional filters by status, platform, date range and free-text query.\",\n inputSchema: {\n teamId: teamIdSchema,\n limit: z.number().int().positive().max(100).optional().default(20).describe(\"Max number of posts to return (default 20, max 100).\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of posts to skip (for pagination).\"),\n status: z\n .enum([\"DRAFT\", \"SCHEDULED\", \"POSTED\", \"ERROR\", \"DELETED\", \"PROCESSING\", \"REVIEW\", \"RETRYING\"])\n .optional()\n .describe(\"Filter by post status.\"),\n platforms: z.array(z.string().min(1)).optional().describe(\"Filter by platform name/alias.\"),\n from: z.string().optional().describe(\"Only posts with postDate on/after this ISO-8601 date.\"),\n to: z.string().optional().describe(\"Only posts with postDate on/before this ISO-8601 date.\"),\n query: z.string().optional().describe(\"Free-text search over post titles/content.\"),\n order: z.enum([\"ASC\", \"DESC\"]).optional().describe(\"Sort direction (default DESC).\"),\n orderBy: z.enum([\"createdAt\", \"updatedAt\", \"postDate\", \"postedDate\", \"deletedAt\"]).optional().describe(\"Sort field (default postDate).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, limit, offset, status, platforms, from, to, query, order, orderBy }) => {\n const id = await resolveTeamId(ctx, teamId);\n const normalizedPlatforms = (platforms ?? []).map(normalizePlatform);\n const params: PostGetListData = {\n teamId: id,\n limit,\n offset,\n status: status ?? undefined,\n platforms: normalizedPlatforms.length > 0 ? (normalizedPlatforms as PostGetListData[\"platforms\"]) : undefined,\n postDateFrom: from ? toIsoDate(from, \"from\") : undefined,\n postDateTo: to ? toIsoDate(to, \"to\") : undefined,\n q: query,\n order: order ?? undefined,\n orderBy: orderBy ?? undefined,\n };\n return jsonResult(await ctx.client.post.postGetList(params));\n },\n );\n\n registerTool(\n server,\n \"get_post\",\n {\n title: \"Get a post by id\",\n description: \"Fetch a single post by its bundle.social id, including its per-platform data and status.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_post\",\n {\n title: \"Delete a post\",\n description: \"Delete a post by its bundle.social id. This is destructive and cannot be undone.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postDelete({ id })),\n );\n\n registerTool(\n server,\n \"update_post\",\n {\n title: \"Update a post\",\n description:\n \"Update an existing post by id — change its title, publish date, status (DRAFT/SCHEDULED), targeted platforms and/or per-platform content. Only the fields you pass are changed. If you change content/media without `platforms`, the post's current platforms are reused.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Post id.\"),\n title: z.string().optional().describe(\"New post title.\"),\n date: z.string().optional().describe(\"New publish date, ISO 8601.\"),\n status: z.enum([\"DRAFT\", \"SCHEDULED\"]).optional().describe(\"New status.\"),\n content: z.string().optional().describe(\"New post text, applied to every targeted platform.\"),\n platforms: platformsSchema,\n media: mediaSchema,\n platformSettings: platformSettingsSchema,\n data: dataSchema,\n referenceKey: referenceKeySchema,\n firstComment: firstCommentSchema,\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, title, date, status, content, platforms, media, platformSettings, data, referenceKey, firstComment, teamId }) => {\n const resolvedTeamId = await resolveTeamId(ctx, teamId);\n const wantsDataChange =\n content !== undefined || (media?.length ?? 0) > 0 || platformSettings !== undefined || data !== undefined;\n\n let targets: Platform[] | undefined;\n if (platforms && platforms.length > 0) {\n targets = await resolveTargetPlatforms(ctx.client, resolvedTeamId, platforms);\n } else if (data) {\n targets = platformsFromData(data);\n } else if (wantsDataChange) {\n const existing = await ctx.client.post.postGet({ id });\n targets = Object.keys(existing.data ?? {}) as Platform[];\n if (targets.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Could not determine the post's platforms — pass `platforms`.\");\n }\n }\n\n const requestBody: PostUpdateBody = {};\n if (title !== undefined) requestBody.title = title;\n if (referenceKey !== undefined) requestBody.referenceKey = referenceKey;\n if (firstComment !== undefined) {\n const commentTargets = targets ?? (Object.keys((await ctx.client.post.postGet({ id })).data ?? {}) as Platform[]);\n requestBody.firstComment = buildFirstComment(firstComment, commentTargets);\n }\n if (date) requestBody.postDate = toIsoDate(date, \"date\");\n if (status) requestBody.status = status;\n if (targets && targets.length > 0) requestBody.socialAccountTypes = targets as PostUpdateBody[\"socialAccountTypes\"];\n if (wantsDataChange && targets && targets.length > 0) {\n const mediaUploadIds = await uploadMediaRefs(ctx.client, resolvedTeamId, media ?? []);\n requestBody.data = buildPostData(targets, {\n content,\n mediaUploadIds,\n platformSettings,\n data,\n }) as unknown as PostUpdateBody[\"data\"];\n }\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\n \"NOTHING_TO_UPDATE\",\n \"Nothing to update — pass at least one of title, date, status, content, media, platformSettings, data, referenceKey, firstComment, platforms.\",\n );\n }\n return jsonResult(await ctx.client.post.postUpdate({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"retry_post\",\n {\n title: \"Retry a failed post\",\n description: \"Retry publishing a post that ended in the ERROR state.\",\n inputSchema: { id: z.string().min(1).describe(\"Post id.\") },\n annotations: { openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.post.postRetry({ id })),\n );\n\n registerTool(\n server,\n \"get_post_by_reference_key\",\n {\n title: \"Get a post by reference key\",\n description:\n \"Fetch a single post by the `referenceKey` set when it was created, instead of by bundle.social post id. Use this when you track posts under your own identifiers.\",\n inputSchema: { referenceKey: z.string().min(1).describe(\"The reference key you set on the post.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ referenceKey }) => jsonResult(await ctx.client.post.postGetByReferenceKey({ referenceKey })),\n );\n\n registerTool(\n server,\n \"list_reconnect_candidates\",\n {\n title: \"List posts waiting for a reconnected account\",\n description:\n \"List draft/scheduled posts that lost their link to a social account after a disconnect and can be reattached to a newly connected account of the same platform. Pair with reconnect_posts.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().min(1).describe(\"Platform of the reconnected account (name or alias).\"),\n limit: z.number().int().positive().max(100).optional().describe(\"Max number of posts to return.\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of posts to skip.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n const params: PostGetReconnectSocialAccountCandidatesData = {\n teamId: id,\n type: normalizePlatform(platform) as PostGetReconnectSocialAccountCandidatesData[\"type\"],\n limit,\n offset,\n };\n return jsonResult(await ctx.client.post.postGetReconnectSocialAccountCandidates(params));\n },\n );\n\n registerTool(\n server,\n \"reconnect_posts\",\n {\n title: \"Reattach posts to a reconnected account\",\n description:\n \"Attach a newly connected social account to posts that lost their link to the previous account of that platform. Without `postIds`, every candidate is reattached.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().min(1).describe(\"Platform of the reconnected account (name or alias).\"),\n postIds: z.array(z.string().min(1)).optional().describe(\"Only reattach these post ids. Defaults to every candidate.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, platform, postIds }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.post.postReconnectSocialAccount({\n requestBody: {\n teamId: id,\n type: normalizePlatform(platform) as ReconnectPlatform,\n ...(postIds && postIds.length > 0 ? { postIds } : {}),\n },\n }),\n );\n },\n );\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\nconst MIME_BY_EXT: Record<string, string> = {\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".bmp\": \"image/bmp\",\n \".tif\": \"image/tiff\",\n \".tiff\": \"image/tiff\",\n \".heic\": \"image/heic\",\n \".heif\": \"image/heif\",\n \".mp4\": \"video/mp4\",\n \".m4v\": \"video/x-m4v\",\n \".mov\": \"video/quicktime\",\n \".webm\": \"video/webm\",\n \".avi\": \"video/x-msvideo\",\n \".mkv\": \"video/x-matroska\",\n \".pdf\": \"application/pdf\",\n \".mp3\": \"audio/mpeg\",\n \".m4a\": \"audio/mp4\",\n \".wav\": \"audio/wav\",\n};\n\nfunction isUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value.trim());\n}\n\n/** Files larger than this must use the chunked/large-upload flow (init + signed PUT + finalize). */\nexport const LARGE_UPLOAD_THRESHOLD_BYTES = 90 * 1024 * 1024;\n\n/** MIME types accepted by the large-upload (init) endpoint. */\nconst LARGE_UPLOAD_MIME_BY_EXT: Record<string, \"image/jpg\" | \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"video/mp4\" | \"application/pdf\"> = {\n \".jpg\": \"image/jpg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".mp4\": \"video/mp4\",\n \".pdf\": \"application/pdf\",\n};\n\n/**\n * Upload one media reference (a public URL, or — in stdio mode — a local file\n * path) and return the resulting upload object. Local files larger than ~90 MB\n * are uploaded via the large-upload flow automatically.\n */\nexport async function uploadMediaRef(client: Bundlesocial, teamId: string, ref: string) {\n if (isUrl(ref)) {\n return client.upload.uploadCreateFromUrl({ requestBody: { teamId, url: ref.trim() } });\n }\n const absolutePath = path.resolve(ref);\n let buffer: Buffer;\n try {\n buffer = await fs.readFile(absolutePath);\n } catch {\n throw new McpToolError(\n \"MEDIA_NOT_FOUND\",\n `Could not read media \"${ref}\". Provide a public https:// URL, or a local file path that exists on the machine running this MCP server (stdio mode only).`,\n { path: absolutePath },\n );\n }\n if (buffer.byteLength > LARGE_UPLOAD_THRESHOLD_BYTES) {\n return uploadLargeMedia(client, teamId, absolutePath, buffer);\n }\n const mime = MIME_BY_EXT[path.extname(absolutePath).toLowerCase()] ?? \"application/octet-stream\";\n const file = new File([buffer], path.basename(absolutePath), { type: mime });\n return client.upload.uploadCreate({ formData: { teamId, file } });\n}\n\n/**\n * Upload a (large) local file via the init → signed PUT → finalize flow.\n * Only `image/jpg|jpeg|png|gif`, `video/mp4` and `application/pdf` are supported.\n */\nasync function uploadLargeMedia(client: Bundlesocial, teamId: string, absolutePath: string, buffer: Buffer) {\n const ext = path.extname(absolutePath).toLowerCase();\n const mimeType = LARGE_UPLOAD_MIME_BY_EXT[ext];\n if (!mimeType) {\n throw new McpToolError(\n \"LARGE_UPLOAD_UNSUPPORTED_TYPE\",\n `Large uploads (>90 MB) only support .jpg, .jpeg, .png, .gif, .mp4 and .pdf — got \"${ext || \"no extension\"}\".`,\n { path: absolutePath },\n );\n }\n const init = await client.upload.uploadInitLargeUpload({ requestBody: { teamId, fileName: path.basename(absolutePath), mimeType } });\n const put = await fetch(init.url, { method: \"PUT\", headers: { \"content-type\": mimeType }, body: new Uint8Array(buffer) });\n if (!put.ok) {\n throw new McpToolError(\"LARGE_UPLOAD_FAILED\", `Uploading the file to storage failed (HTTP ${put.status}).`, { status: put.status });\n }\n return client.upload.uploadFinalizeLargeUpload({ requestBody: { teamId, path: init.path } });\n}\n\nexport async function uploadMediaRefs(client: Bundlesocial, teamId: string, refs: string[]): Promise<string[]> {\n const ids: string[] = [];\n for (const ref of refs) {\n const upload = await uploadMediaRef(client, teamId, ref);\n ids.push(upload.id);\n }\n return ids;\n}\n","import type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\nimport { PLATFORMS, type Platform, normalizePlatform, tryNormalizePlatform } from \"./platforms\";\n\nfunction asPlainObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new McpToolError(\"INVALID_INPUT\", `${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * Resolve `platforms` arguments to a unique platform list. A value is used\n * directly when it is a recognised platform name/alias; otherwise it is treated\n * as a connected social-account id and resolved via the team's integrations.\n */\nexport async function resolveTargetPlatforms(client: Bundlesocial, teamId: string, rawTargets: string[]): Promise<Platform[]> {\n const resolved = new Set<Platform>();\n const accountIds: string[] = [];\n\n for (const raw of rawTargets) {\n const platform = tryNormalizePlatform(raw);\n if (platform) resolved.add(platform);\n else accountIds.push(raw.trim());\n }\n\n if (accountIds.length > 0) {\n const team = await client.team.teamGetTeam({ id: teamId });\n const accounts = team.socialAccounts ?? [];\n for (const id of accountIds) {\n const account = accounts.find((candidate) => candidate.id === id);\n if (!account) {\n throw new McpToolError(\n \"INTEGRATION_NOT_FOUND\",\n `No connected integration with id \"${id}\" in team ${teamId}. Call list_integrations to see ids, or use a platform name like \"x\" or \"tiktok\".`,\n { availableIntegrations: accounts.map((a) => ({ id: a.id, type: a.type, username: a.username })) },\n );\n }\n resolved.add(account.type as Platform);\n }\n }\n\n return [...resolved];\n}\n\nfunction isPlatformKeyedObject(value: Record<string, unknown>): boolean {\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key) => PLATFORMS.includes(key.trim().toUpperCase() as Platform));\n}\n\nfunction expandPlatformSettings(\n settings: Record<string, unknown> | undefined,\n platforms: Platform[],\n): Record<Platform, Record<string, unknown>> {\n const result = Object.fromEntries(platforms.map((p) => [p, {}])) as Record<Platform, Record<string, unknown>>;\n if (!settings) return result;\n if (isPlatformKeyedObject(settings)) {\n for (const [key, value] of Object.entries(settings)) {\n const platform = key.trim().toUpperCase() as Platform;\n if (platform in result) result[platform] = { ...result[platform], ...asPlainObject(value, `platformSettings.${key}`) };\n }\n return result;\n }\n for (const platform of platforms) result[platform] = { ...settings };\n return result;\n}\n\nexport interface BuildPostDataInput {\n content?: string;\n mediaUploadIds: string[];\n platformSettings?: Record<string, unknown>;\n /** Advanced escape hatch: the full `data` object keyed by platform. */\n data?: Record<string, unknown>;\n}\n\n/** Build the API's `data` object, one entry per targeted platform. */\nexport function buildPostData(platforms: Platform[], input: BuildPostDataInput): Record<string, unknown> {\n if (input.data) return input.data;\n const perPlatform = expandPlatformSettings(input.platformSettings, platforms);\n const data: Record<string, unknown> = {};\n for (const platform of platforms) {\n data[platform] = {\n ...(input.content !== undefined ? { text: input.content } : {}),\n ...(input.mediaUploadIds.length > 0 ? { uploadIds: input.mediaUploadIds } : {}),\n ...perPlatform[platform],\n };\n }\n return data;\n}\n\n/** Determine targeted platforms when only `data` is given (use its keys). */\nexport function platformsFromData(data: Record<string, unknown>): Platform[] {\n return Object.keys(data).map((key) => normalizePlatform(key));\n}\n\nexport function deriveTitle(content: string | undefined, fallback: string): string {\n const firstLine = (content ?? \"\").split(\"\\n\").map((line) => line.trim()).find((line) => line.length > 0);\n if (!firstLine) return fallback;\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine;\n}\n\nexport function toIsoDate(value: string, label: string): string {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `${label} is not a valid ISO 8601 date/time: \"${value}\". Example: 2026-06-01T09:00:00Z`);\n }\n return date.toISOString();\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { CommentCreateData, CommentGetListData, CommentImportCreateData, CommentUpdateData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { COMMENT_PLATFORMS, type CommentPlatform, isCommentPlatform, normalizePlatform } from \"../platforms\";\nimport { resolveTargetPlatforms } from \"../post-data\";\nimport { registerTool } from \"../register-tool\";\n\ntype CommentImportPlatform = NonNullable<CommentImportCreateData[\"requestBody\"]>[\"socialAccountType\"];\n\nconst commentImportStatusSchema = z.enum([\"PENDING\", \"FETCHING\", \"RETRYING\", \"COMPLETED\", \"SKIPPED\", \"FAILED\", \"RATE_LIMITED\"]);\n\ntype CommentCreateBody = NonNullable<CommentCreateData[\"requestBody\"]>;\ntype CommentUpdateBody = NonNullable<CommentUpdateData[\"requestBody\"]>;\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nfunction assertCommentPlatforms(platforms: string[]): CommentPlatform[] {\n const bad = platforms.filter((platform) => !isCommentPlatform(platform));\n if (bad.length > 0) {\n throw new McpToolError(\n \"COMMENTS_NOT_SUPPORTED\",\n `Comments are not available for ${bad.join(\", \")}. Supported: ${COMMENT_PLATFORMS.join(\", \")}.`,\n );\n }\n return platforms as CommentPlatform[];\n}\n\nfunction toIso(value: string): string {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `date is not a valid ISO 8601 date/time: \"${value}\". Example: 2026-06-01T09:00:00Z`);\n }\n return date.toISOString();\n}\n\nexport function registerCommentTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_comment\",\n {\n title: \"Comment on a post\",\n description:\n \"Post one or more comments on a post you created (`postId`) or on a post brought in by create_post_import (`importedPostId`). Pass `content` multiple times to create a chain (the first replies to the post, each subsequent one replies to the previous comment) — useful for X-style threads via comments. Use `fetchedParentCommentId` to reply to a comment pulled in by create_comment_import. Comments are supported on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, LINKEDIN, REDDIT, MASTODON, DISCORD, SLACK, BLUESKY. Returns the created comment(s).\",\n inputSchema: {\n postId: z.string().min(1).optional().describe(\"Id of the bundle.social post to comment on. Either this or importedPostId is required.\"),\n importedPostId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Id of an imported (post-history) post to comment on instead of postId. Requires `platforms`.\"),\n fetchedParentCommentId: z\n .string()\n .min(1)\n .optional()\n .describe(\"Reply to a comment fetched by create_comment_import (its imported-comment id) instead of to the post itself.\"),\n content: z.array(z.string().min(1)).min(1).describe(\"Comment text. Pass multiple to create a chain of replies.\"),\n platforms: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Target comment-capable platform names/aliases and/or integration ids. Defaults to the post's platforms (filtered to comment-capable ones).\"),\n date: z.string().optional().describe(\"When to post the (first) comment, ISO 8601. Default: now.\"),\n delayMinutes: z.number().int().nonnegative().optional().default(0).describe(\"For a chain, minutes to wait between each comment.\"),\n draft: z.boolean().optional().default(false).describe(\"If true, create the comment(s) as DRAFT instead of posting.\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, importedPostId, fetchedParentCommentId, content, platforms, date, delayMinutes, draft, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n if (!postId && !importedPostId) {\n throw new McpToolError(\"NO_POST\", \"Pass `postId` (a bundle.social post) or `importedPostId` (a post brought in by create_post_import).\");\n }\n let resolved: CommentPlatform[];\n if (platforms && platforms.length > 0) {\n resolved = assertCommentPlatforms(await resolveTargetPlatforms(ctx.client, id, platforms));\n } else if (postId) {\n // An imported post has no bundle.social `data` to infer platforms from, so targets are explicit there.\n const post = await ctx.client.post.postGet({ id: postId });\n resolved = Object.keys(post.data ?? {}).filter(isCommentPlatform);\n if (resolved.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Could not determine comment platforms from the post — pass `platforms` (comment-capable only).\");\n }\n } else {\n throw new McpToolError(\"NO_TARGET\", \"Pass `platforms` when commenting on an imported post (comment-capable only).\");\n }\n const status: CommentCreateBody[\"status\"] = draft ? \"DRAFT\" : \"SCHEDULED\";\n const baseDate = date ? new Date(toIso(date)) : new Date();\n\n const created = [];\n let parentCommentId: string | undefined;\n for (let index = 0; index < content.length; index += 1) {\n const text = content[index];\n const postDate = new Date(baseDate.getTime() + index * (delayMinutes ?? 0) * 60_000).toISOString();\n const perPlatform = Object.fromEntries(resolved.map((platform) => [platform, { text }]));\n const comment = await ctx.client.comment.commentCreate({\n requestBody: {\n teamId: id,\n ...(postId ? { internalPostId: postId } : { importedPostId: importedPostId as string }),\n ...(parentCommentId ? { internalParentCommentId: parentCommentId } : {}),\n // Only the first comment of a chain replies to the fetched comment; the rest chain off each other.\n ...(!parentCommentId && fetchedParentCommentId ? { fetchedParentCommentId } : {}),\n status,\n postDate,\n socialAccountTypes: resolved as never,\n data: perPlatform as never,\n text,\n },\n });\n created.push(comment);\n parentCommentId = comment.id;\n }\n return jsonResult(created.length === 1 ? created[0] : created);\n },\n );\n\n registerTool(\n server,\n \"list_comments\",\n {\n title: \"List comments\",\n description: \"List comments for a team, optionally filtered by post, status and platform.\",\n inputSchema: {\n postId: z.string().optional().describe(\"Only comments on this post.\"),\n limit: z.number().int().positive().max(100).optional().default(20),\n offset: z.number().int().nonnegative().optional(),\n status: z.enum([\"DRAFT\", \"SCHEDULED\", \"POSTED\", \"ERROR\", \"DELETED\", \"PROCESSING\", \"RETRYING\"]).optional(),\n platforms: z.array(z.string().min(1)).optional().describe(\"Filter by comment-capable platform name/alias.\"),\n query: z.string().optional(),\n order: z.enum([\"ASC\", \"DESC\"]).optional(),\n orderBy: z.enum([\"createdAt\", \"updatedAt\", \"deletedAt\"]).optional(),\n teamId: teamIdSchema,\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postId, limit, offset, status, platforms, query, order, orderBy, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n const normalized = assertCommentPlatforms((platforms ?? []).map(normalizePlatform));\n const params: CommentGetListData = {\n teamId: id,\n postId,\n limit,\n offset,\n status: status ?? undefined,\n platforms: normalized.length > 0 ? (normalized as CommentGetListData[\"platforms\"]) : undefined,\n q: query,\n order: order ?? undefined,\n orderBy: orderBy ?? undefined,\n };\n return jsonResult(await ctx.client.comment.commentGetList(params));\n },\n );\n\n registerTool(\n server,\n \"get_comment\",\n {\n title: \"Get a comment by id\",\n description: \"Fetch a single comment by its bundle.social id.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_comment\",\n {\n title: \"Delete a comment\",\n description: \"Delete a comment by its bundle.social id. Destructive.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentDelete({ id })),\n );\n\n registerTool(\n server,\n \"update_comment\",\n {\n title: \"Update a comment\",\n description:\n \"Update an existing comment by id — change its title, scheduled date, status (DRAFT/SCHEDULED), targeted platforms and/or per-platform text. Only the fields you pass are changed. Use `data` for the full per-platform object, or `content` + `platforms` for a same-text-everywhere change.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Comment id.\"),\n title: z.string().optional().describe(\"New title.\"),\n date: z.string().optional().describe(\"New scheduled date, ISO 8601.\"),\n status: z.enum([\"DRAFT\", \"SCHEDULED\"]).optional().describe(\"New status.\"),\n content: z.string().optional().describe(\"New comment text, applied to every platform in `platforms`.\"),\n platforms: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Comment-capable platform name/alias. Required when changing `content` without supplying `data`.\"),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Advanced: the full comment `data` object keyed by platform, e.g. {\"LINKEDIN\":{\"text\":\"new\"}}.'),\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, title, date, status, content, platforms, data }) => {\n const normalized = assertCommentPlatforms((platforms ?? []).map(normalizePlatform));\n const wantsDataChange = content !== undefined || data !== undefined;\n\n const requestBody: CommentUpdateBody = {};\n if (title !== undefined) requestBody.title = title;\n if (date) {\n const parsed = new Date(date);\n if (Number.isNaN(parsed.getTime())) {\n throw new McpToolError(\"INVALID_DATE\", `date is not a valid ISO 8601 date/time: \"${date}\". Example: 2026-06-01T09:00:00Z`);\n }\n requestBody.postDate = parsed.toISOString();\n }\n if (status) requestBody.status = status;\n if (normalized.length > 0) requestBody.socialAccountTypes = normalized as CommentUpdateBody[\"socialAccountTypes\"];\n if (wantsDataChange) {\n if (data) {\n requestBody.data = data as unknown as CommentUpdateBody[\"data\"];\n } else {\n if (normalized.length === 0) {\n throw new McpToolError(\"NO_TARGET\", \"Pass `platforms` when changing `content` (the per-platform comment text needs to know which platforms to target).\");\n }\n const perPlatform = Object.fromEntries(normalized.map((platform) => [platform, { text: content as string }]));\n requestBody.data = perPlatform as unknown as CommentUpdateBody[\"data\"];\n }\n }\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\n \"NOTHING_TO_UPDATE\",\n \"Nothing to update — pass at least one of title, date, status, content (+ platforms), data.\",\n );\n }\n return jsonResult(await ctx.client.comment.commentUpdate({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"retry_comment\",\n {\n title: \"Retry a failed comment\",\n description: \"Retry publishing a comment that ended in the ERROR state.\",\n inputSchema: { id: z.string().min(1).describe(\"Comment id.\") },\n annotations: { openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.comment.commentRetry({ id })),\n );\n\n // --- comment imports (fetch incoming comments on a published post) ---------\n\n registerTool(\n server,\n \"create_comment_import\",\n {\n title: \"Import comments on a post\",\n description:\n \"Start an async import of the (incoming) comments on a published post for one platform. Comment imports are available on FACEBOOK, INSTAGRAM, LINKEDIN, YOUTUBE, TIKTOK, REDDIT, THREADS, MASTODON, BLUESKY. Poll get_comment_import / list_comment_imports for status and list_imported_comments for the fetched comments.\",\n inputSchema: {\n postId: z.string().min(1).describe(\"Id of the published post to import comments for.\"),\n platform: z.string().min(1).describe(\"Platform name/alias to import comments from.\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, platform, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportCreate({\n requestBody: { teamId: id, postId, socialAccountType: normalizePlatform(platform) as CommentImportPlatform },\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"list_comment_imports\",\n {\n title: \"List comment imports\",\n description: \"List comment-import jobs for a team, optionally filtered by post and status.\",\n inputSchema: {\n teamId: teamIdSchema,\n postId: z.string().optional().describe(\"Only imports for this post.\"),\n status: commentImportStatusSchema.optional().describe(\"Filter by import status.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, postId, status, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.comment.commentImportGetList({ teamId: id, postId, status, limit: limit ?? null, offset: offset ?? null }));\n },\n );\n\n registerTool(\n server,\n \"get_comment_import\",\n {\n title: \"Get a comment import by id\",\n description: \"Fetch a single comment-import job by its id, including its status and the number of comments imported.\",\n inputSchema: { importId: z.string().min(1).describe(\"Comment import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.comment.commentImportGetById({ importId })),\n );\n\n registerTool(\n server,\n \"list_imported_comments\",\n {\n title: \"List imported comments for a post\",\n description: \"List the comments fetched by comment imports for a post, optionally filtered by platform / social account.\",\n inputSchema: {\n postId: z.string().min(1).describe(\"Id of the post whose imported comments to list.\"),\n platform: z.string().optional().describe(\"Filter by platform name/alias.\"),\n socialAccountId: z.string().optional().describe(\"Filter by social-account id.\"),\n teamId: teamIdSchema,\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postId, platform, socialAccountId, teamId, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportGetFetchedComments({\n teamId: id,\n postId,\n platform: platform ? (normalizePlatform(platform) as CommentImportPlatform) : undefined,\n socialAccountId,\n limit: limit ?? null,\n offset: offset ?? null,\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"act_on_imported_comment\",\n {\n title: \"Moderate an imported comment\",\n description:\n \"Act on a comment fetched by a comment import — delete, hide/unhide, like/unlike, or approve/reject it. Supported actions vary by platform; DELETE and HIDE are the widely available ones.\",\n inputSchema: {\n commentId: z.string().min(1).describe(\"Id of the fetched (imported) comment.\"),\n action: z\n .enum([\"DELETE\", \"HIDE\", \"UNHIDE\", \"LIKE\", \"UNLIKE\", \"APPROVE\", \"REJECT\"])\n .describe(\"What to do with the comment.\"),\n reason: z.string().optional().describe(\"Optional reason recorded with the action.\"),\n banAuthor: z.boolean().optional().describe(\"Also ban the comment's author, where the platform supports it.\"),\n teamId: teamIdSchema,\n },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ commentId, action, reason, banAuthor, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.comment.commentImportActionFetchedComment({\n commentId,\n requestBody: {\n teamId: id,\n action,\n ...(reason !== undefined ? { reason } : {}),\n ...(banAuthor ? { banAuthor: true } : {}),\n },\n }),\n );\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { uploadMediaRef } from \"../media\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerMediaTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"upload_media\",\n {\n title: \"Upload media\",\n description:\n \"Upload a media file (image, video or document) to a bundle.social team from a public https:// URL — or, when this server runs in stdio mode, a local file path. Local files larger than ~90 MB are uploaded via the large-upload flow automatically (only .jpg/.jpeg/.png/.gif/.mp4/.pdf are supported above that size). Returns the upload object; pass its `id` to create_post/schedule_post via the `data` argument (e.g. {\\\"TWITTER\\\":{\\\"text\\\":\\\"hi\\\",\\\"uploadIds\\\":[\\\"<id>\\\"]}}).\",\n inputSchema: {\n teamId: teamIdSchema,\n source: z.string().min(1).describe(\"A public https:// URL, or a local file path (stdio mode only).\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, source }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await uploadMediaRef(ctx.client, id, source));\n },\n );\n\n registerTool(\n server,\n \"list_media\",\n {\n title: \"List uploaded media\",\n description: \"List media uploads for a team, optionally filtered by type (image/video/document) and usage status (USED/UNUSED).\",\n inputSchema: {\n teamId: teamIdSchema,\n type: z.enum([\"image\", \"video\", \"document\"]).optional().describe(\"Filter by media type.\"),\n status: z.enum([\"USED\", \"UNUSED\"]).optional().describe(\"Filter by whether the upload is attached to a post.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, type, status }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadGetList({ teamId: id, type: type ?? null, status: status ?? null }));\n },\n );\n\n registerTool(\n server,\n \"get_media\",\n {\n title: \"Get an upload by id\",\n description: \"Fetch a single media upload by its bundle.social id.\",\n inputSchema: { id: z.string().min(1).describe(\"Upload id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.upload.uploadGet({ id })),\n );\n\n registerTool(\n server,\n \"delete_media\",\n {\n title: \"Delete an upload\",\n description: \"Delete a media upload by its bundle.social id. Destructive.\",\n inputSchema: { id: z.string().min(1).describe(\"Upload id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.upload.uploadDelete({ id })),\n );\n\n registerTool(\n server,\n \"delete_media_many\",\n {\n title: \"Delete multiple uploads\",\n description: \"Delete several media uploads at once by their ids. Destructive.\",\n inputSchema: { ids: z.array(z.string().min(1)).min(1).describe(\"Upload ids to delete.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ ids }) => jsonResult(await ctx.client.upload.uploadDeleteMany({ requestBody: { ids } })),\n );\n\n registerTool(\n server,\n \"init_large_upload\",\n {\n title: \"Initialize a large upload\",\n description:\n \"Low-level: start a >90 MB upload. Returns a signed `url` (PUT the file bytes there with the matching content-type) and a `path` to pass to finalize_large_upload. Prefer `upload_media` with a local file path in stdio mode — it does this automatically.\",\n inputSchema: {\n teamId: teamIdSchema,\n fileName: z.string().min(1).describe(\"File name.\"),\n mimeType: z.enum([\"image/jpg\", \"image/jpeg\", \"image/png\", \"image/gif\", \"video/mp4\", \"application/pdf\"]).describe(\"File MIME type.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, fileName, mimeType }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadInitLargeUpload({ requestBody: { teamId: id, fileName, mimeType } }));\n },\n );\n\n registerTool(\n server,\n \"finalize_large_upload\",\n {\n title: \"Finalize a large upload\",\n description: \"Low-level: finalize a >90 MB upload after the bytes have been PUT to the signed URL from init_large_upload. Returns the upload object.\",\n inputSchema: {\n teamId: teamIdSchema,\n path: z.string().min(1).describe(\"The `path` returned by init_large_upload.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ teamId, path }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.upload.uploadFinalizeLargeUpload({ requestBody: { teamId: id, path } }));\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { AnalyticsGetSocialAccountAnalyticsData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { McpToolError, errorSummary, jsonResult } from \"../errors\";\nimport { isAnalyticsPlatform, normalizeAnalyticsPlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype AnalyticsPlatform = AnalyticsGetSocialAccountAnalyticsData[\"platformType\"];\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nfunction withinRange(value: string | null | undefined, from?: string, to?: string): boolean {\n if (!from && !to) return true;\n if (!value) return false;\n const time = new Date(value).getTime();\n if (Number.isNaN(time)) return false;\n if (from && time < new Date(from).getTime()) return false;\n if (to && time > new Date(to).getTime()) return false;\n return true;\n}\n\nexport function registerAnalyticsTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"get_post_analytics\",\n {\n title: \"Get post analytics\",\n description: \"Get engagement metrics (impressions, views, likes, comments, …) for a single post by its bundle.social id. Optionally limit to one platform. Set `raw: true` for the unprocessed provider payload.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Post id.\"),\n platform: z.string().optional().describe(\"Limit to a single platform name/alias (e.g. instagram, tiktok, youtube). Analytics are not available for X/Twitter, Discord or Slack.\"),\n raw: z.boolean().optional().default(false).describe(\"If true, return the raw provider analytics payload instead of the normalized metrics.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id, platform, raw }) => {\n const platformType = platform ? normalizeAnalyticsPlatform(platform) : undefined;\n const response = raw\n ? await ctx.client.analytics.analyticsGetPostAnalyticsRaw({ postId: id, platformType })\n : await ctx.client.analytics.analyticsGetPostAnalytics({ postId: id, platformType });\n return jsonResult(response);\n },\n );\n\n registerTool(\n server,\n \"get_account_analytics\",\n {\n title: \"Get social-account analytics\",\n description:\n \"Get the analytics time-series (followers, impressions, likes, …) for a connected account on the given platform. Analytics are available on TIKTOK, YOUTUBE, INSTAGRAM, FACEBOOK, THREADS, REDDIT, PINTEREST, MASTODON, LINKEDIN, BLUESKY, GOOGLE_BUSINESS. Set `raw: true` for the unprocessed provider payload.\",\n inputSchema: {\n platform: z.string().min(1).describe(\"Platform name/alias.\"),\n teamId: teamIdSchema,\n raw: z.boolean().optional().default(false).describe(\"If true, return the raw provider analytics payload.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId, raw }) => {\n const id = await resolveTeamId(ctx, teamId);\n const platformType = normalizeAnalyticsPlatform(platform);\n const response = raw\n ? await ctx.client.analytics.analyticsGetSocialAccountAnalyticsRaw({ teamId: id, platformType })\n : await ctx.client.analytics.analyticsGetSocialAccountAnalytics({ teamId: id, platformType });\n return jsonResult(response);\n },\n );\n\n registerTool(\n server,\n \"get_bulk_post_analytics\",\n {\n title: \"Get analytics for multiple posts\",\n description: \"Get analytics for up to 60 posts in one request (paginated, 20 per page) for a single platform.\",\n inputSchema: {\n postIds: z.array(z.string().min(1)).min(1).max(60).describe(\"Post ids (max 60).\"),\n platform: z.string().min(1).describe(\"Platform name/alias the posts belong to.\"),\n page: z.number().int().positive().optional().describe(\"Page (1-based).\"),\n limit: z.number().int().positive().max(20).optional().describe(\"Page size (max 20).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ postIds, platform, page, limit }) =>\n jsonResult(\n await ctx.client.analytics.analyticsGetBulkPostAnalytics({\n postIds,\n platformType: normalizeAnalyticsPlatform(platform),\n page,\n limit,\n }),\n ),\n );\n\n registerTool(\n server,\n \"refresh_analytics\",\n {\n title: \"Force-refresh analytics\",\n description:\n \"Force an immediate analytics refresh. Pass `postId` to refresh that post's analytics; otherwise pass `platform` to refresh a connected account's analytics for the team.\",\n inputSchema: {\n postId: z.string().optional().describe(\"Post id to refresh analytics for.\"),\n importedPostId: z.string().optional().describe(\"Imported-post id to refresh analytics for (alternative to postId).\"),\n platform: z.string().optional().describe(\"Platform name/alias to refresh a social-account's analytics for (used when postId/importedPostId are omitted).\"),\n teamId: teamIdSchema,\n },\n annotations: { openWorldHint: true },\n },\n async ({ postId, importedPostId, platform, teamId }) => {\n if (postId || importedPostId) {\n return jsonResult(\n await ctx.client.analytics.analyticsForcePostAnalytics({\n requestBody: {\n postId: postId ?? null,\n importedPostId: importedPostId ?? null,\n platformType: platform ? normalizeAnalyticsPlatform(platform) : null,\n },\n }),\n );\n }\n if (!platform) {\n throw new McpToolError(\"REFRESH_TARGET_REQUIRED\", \"Pass either `postId`/`importedPostId` (to refresh a post) or `platform` (to refresh a social account).\");\n }\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.analytics.analyticsForceSocialAccountAnalytics({ requestBody: { teamId: id, platformType: normalizeAnalyticsPlatform(platform) } }));\n },\n );\n\n registerTool(\n server,\n \"get_analytics_summary\",\n {\n title: \"Get analytics summary\",\n description:\n \"Organization-level analytics summary: posts/comments/uploads usage quotas for the organization, plus the latest analytics snapshot (followers, impressions, likes, …) for each connected integration on the team. Use `from`/`to` to select the snapshot from a date range.\",\n inputSchema: {\n teamId: z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n from: z.string().optional().describe(\"Start of the range used to select analytics snapshots (ISO 8601).\"),\n to: z.string().optional().describe(\"End of the range used to select analytics snapshots (ISO 8601).\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, from, to }) => {\n const id = await resolveTeamId(ctx, teamId);\n const [organization, team, postsUsage, commentsUsage, uploadsUsage] = await Promise.all([\n ctx.client.organization.organizationGetOrganization(),\n ctx.client.team.teamGetTeam({ id }),\n ctx.client.organization.organizationGetPostsUsage().catch(() => null),\n ctx.client.organization.organizationGetCommentsUsage().catch(() => null),\n ctx.client.organization.organizationGetUploadsUsage().catch(() => null),\n ]);\n\n const accounts = team.socialAccounts ?? [];\n const integrations: Array<Record<string, unknown>> = [];\n for (const account of accounts) {\n const base = { id: account.id, type: account.type, username: account.username ?? null };\n if (!isAnalyticsPlatform(account.type)) {\n integrations.push({ ...base, analytics: null, note: \"analytics not available for this platform\" });\n continue;\n }\n try {\n const result = await ctx.client.analytics.analyticsGetSocialAccountAnalytics({\n teamId: id,\n platformType: account.type as AnalyticsPlatform,\n });\n const items = (result.items ?? []).filter((item) => withinRange(item.createdAt, from, to));\n integrations.push({ ...base, latest: items[items.length - 1] ?? null, dataPoints: items.length });\n } catch (error) {\n integrations.push({ ...base, analytics: null, error: errorSummary(error) });\n }\n }\n\n return jsonResult({\n organization: { id: organization.id, name: organization.name ?? null },\n team: { id: team.id, name: team.name },\n range: { from: from ?? null, to: to ?? null },\n usage: { posts: postsUsage, comments: commentsUsage, uploads: uploadsUsage },\n integrations,\n });\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { listIntegrationTools, runIntegrationTool } from \"../integration-tools\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerIntegrationToolHelpers(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_integration_tools\",\n {\n title: \"List integration helper tools\",\n description:\n \"List the read-only platform helper tools callable via trigger_integration_tool — e.g. fetch subreddit flairs, YouTube categories/playlists/regions, LinkedIn mentions, Instagram locations, Google Business categories, TikTok trending music. Each entry has a `method` id and the params it accepts. Use these to discover values the API needs (flair ids, category ids, mention URNs, …).\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => jsonResult({ tools: listIntegrationTools() }),\n );\n\n registerTool(\n server,\n \"trigger_integration_tool\",\n {\n title: \"Call an integration helper tool\",\n description:\n 'Call one of the platform helper tools (see list_integration_tools), e.g. method \"reddit:flairs\" with params {\"subreddit\":\"r/test\"}. Returns the raw result.',\n inputSchema: {\n method: z.string().min(1).describe('Tool method id, e.g. \"reddit:flairs\", \"youtube:categories\", \"linkedin:mentions\" (call list_integration_tools first).'),\n params: z.record(z.string(), z.unknown()).optional().describe(\"Parameters for the tool as a JSON object, e.g. {\\\"subreddit\\\":\\\"r/test\\\"}.\"),\n teamId: teamIdSchema,\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ method, params, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await runIntegrationTool(ctx.client, id, method, params ?? {}));\n },\n );\n}\n","import type { Bundlesocial } from \"bundlesocial\";\nimport { McpToolError } from \"./errors\";\n\n/**\n * Curated, read-only \"what value goes here?\" helpers — the bundle.social\n * equivalent of fetching subreddit flairs, YouTube categories, LinkedIn\n * mentions, Google Business categories, etc. The platform is implied by the\n * method name; all are team-scoped, with extra parameters supplied as a JSON\n * object.\n */\nexport interface IntegrationTool {\n id: string;\n platform: string;\n description: string;\n requiredParams?: string[];\n optionalParams?: string[];\n run: (client: Bundlesocial, teamId: string, params: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport const INTEGRATION_TOOLS: IntegrationTool[] = [\n {\n id: \"reddit:flairs\",\n platform: \"REDDIT\",\n description: \"List the post flairs available in a subreddit (use the returned flair id when creating a Reddit post that requires a flair).\",\n requiredParams: [\"subreddit\"],\n run: (client, teamId, p) => client.misc.miscRedditGetSubredditFlairs({ teamId, subreddit: String(p.subreddit) }),\n },\n {\n id: \"reddit:requirements\",\n platform: \"REDDIT\",\n description: \"Get a subreddit's posting requirements (title length, flair requirement, allowed post types, etc.).\",\n requiredParams: [\"subreddit\"],\n run: (client, teamId, p) => client.misc.miscRedditGetPostRequirements({ teamId, subreddit: String(p.subreddit) }),\n },\n {\n id: \"youtube:categories\",\n platform: \"YOUTUBE\",\n description: \"List YouTube video categories for a region (use the returned category id as `categoryId` when posting a YouTube video).\",\n optionalParams: [\"regionCode\"],\n run: (client, teamId, p) =>\n client.misc.miscYoutubeGetVideoCategories({ teamId, ...(p.regionCode ? { regionCode: String(p.regionCode) } : {}) }),\n },\n {\n id: \"youtube:playlists\",\n platform: \"YOUTUBE\",\n description: \"List the connected YouTube channel's playlists (use a playlist id to add the posted video to it).\",\n optionalParams: [\"maxResults\"],\n run: (client, teamId, p) =>\n client.misc.miscYoutubeGetChannelPlaylist({ teamId, ...(p.maxResults !== undefined ? { maxResults: Number(p.maxResults) } : {}) }),\n },\n {\n id: \"youtube:regions\",\n platform: \"YOUTUBE\",\n description: \"List YouTube content regions (i18n region codes).\",\n run: (client, teamId) => client.misc.miscYoutubeGetRegions({ teamId }),\n },\n {\n id: \"linkedin:mentions\",\n platform: \"LINKEDIN\",\n description: \"Search LinkedIn people/organizations to mention in a post (use the returned URN in the post text).\",\n requiredParams: [\"q\"],\n optionalParams: [\"scope\"],\n run: (client, teamId, p) =>\n client.misc.miscLinkedinGetTags({\n teamId,\n q: String(p.q),\n ...(p.scope ? { scope: String(p.scope) as \"people\" | \"organizations\" | \"all\" } : {}),\n }),\n },\n {\n id: \"instagram:locations\",\n platform: \"INSTAGRAM\",\n description: \"Search Instagram locations (use the returned location id as `locationId` when posting).\",\n requiredParams: [\"q\"],\n optionalParams: [\"limit\"],\n run: (client, teamId, p) =>\n client.misc.miscInstagramSearchLocations({ teamId, q: String(p.q), ...(p.limit !== undefined ? { limit: Number(p.limit) } : {}) }),\n },\n {\n id: \"gbp:location\",\n platform: \"GOOGLE_BUSINESS\",\n description: \"Get the connected Google Business Profile location's details.\",\n optionalParams: [\"fields\"],\n run: (client, teamId, p) =>\n client.misc.miscGoogleBusinessGetLocation({ teamId, ...(Array.isArray(p.fields) ? { fields: p.fields as never } : {}) }),\n },\n {\n id: \"gbp:categories\",\n platform: \"GOOGLE_BUSINESS\",\n description: \"List Google Business Profile categories for a region/language (use a category id when updating the location).\",\n requiredParams: [\"languageCode\", \"regionCode\"],\n optionalParams: [\"filter\", \"pageSize\", \"pageToken\", \"view\"],\n run: (client, teamId, p) =>\n client.misc.miscGoogleBusinessListCategories({\n teamId,\n languageCode: String(p.languageCode),\n regionCode: String(p.regionCode),\n ...(p.filter ? { filter: String(p.filter) } : {}),\n ...(p.pageSize !== undefined ? { pageSize: Number(p.pageSize) } : {}),\n ...(p.pageToken ? { pageToken: String(p.pageToken) } : {}),\n ...(p.view ? { view: String(p.view) as never } : {}),\n }),\n },\n {\n id: \"instagram:audio\",\n platform: \"INSTAGRAM\",\n description:\n \"Search the Instagram audio catalogue (use the returned audio_id as `musicSoundInfo.musicSoundId` when posting a Reel).\",\n requiredParams: [\"audioType\"],\n optionalParams: [\"searchQuery\"],\n run: (client, teamId, p) =>\n client.misc.miscInstagramSearchAudio({\n teamId,\n audioType: String(p.audioType) as \"original_sound\" | \"music\",\n ...(p.searchQuery ? { searchQuery: String(p.searchQuery) } : {}),\n }),\n },\n {\n id: \"instagram:business-discovery\",\n platform: \"INSTAGRAM\",\n description:\n \"Look up a public Instagram Business/Creator profile by username (followers, media count, recent public media). Requires an account connected via Facebook Login.\",\n requiredParams: [\"username\"],\n run: (client, teamId, p) => client.misc.miscInstagramBusinessDiscovery({ teamId, username: String(p.username) }),\n },\n {\n id: \"tiktok:trending-music\",\n platform: \"TIKTOK\",\n description: \"List trending tracks from TikTok's commercial music library (use a track id in the TikTok post settings).\",\n optionalParams: [\"dateRange\", \"genre\"],\n run: (client, teamId, p) =>\n client.misc.miscTiktokGetCommercialMusicTrendingList({\n teamId,\n ...(p.dateRange ? { dateRange: String(p.dateRange) as \"1DAY\" | \"7DAY\" | \"30DAY\" } : {}),\n ...(p.genre ? { genre: String(p.genre) as never } : {}),\n }),\n },\n];\n\nexport function listIntegrationTools() {\n return INTEGRATION_TOOLS.map((tool) => ({\n method: tool.id,\n platform: tool.platform,\n description: tool.description,\n requiredParams: tool.requiredParams ?? [],\n optionalParams: tool.optionalParams ?? [],\n }));\n}\n\nexport async function runIntegrationTool(\n client: Bundlesocial,\n teamId: string,\n method: string,\n params: Record<string, unknown>,\n): Promise<unknown> {\n const tool = INTEGRATION_TOOLS.find((candidate) => candidate.id === method.trim().toLowerCase());\n if (!tool) {\n throw new McpToolError(\n \"UNKNOWN_INTEGRATION_TOOL\",\n `Unknown integration tool \"${method}\". Available: ${INTEGRATION_TOOLS.map((t) => t.id).join(\", \")}.`,\n { available: INTEGRATION_TOOLS.map((t) => t.id) },\n );\n }\n const missing = (tool.requiredParams ?? []).filter((key) => params[key] === undefined || params[key] === null || params[key] === \"\");\n if (missing.length > 0) {\n throw new McpToolError(\n \"MISSING_PARAMS\",\n `Integration tool \"${tool.id}\" requires: ${missing.join(\", \")}. Provide them in the params object.`,\n { method: tool.id, requiredParams: tool.requiredParams },\n );\n }\n return tool.run(client, teamId, params);\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { TeamUpdateTeamData } from \"bundlesocial\";\nimport type { ServerContext } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\ntype TeamUpdateBody = NonNullable<TeamUpdateTeamData[\"requestBody\"]>;\n\nexport function registerTeamTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"list_teams\",\n {\n title: \"List teams\",\n description: \"List the teams in the organization (paginated). Use this to discover team ids for the optional `teamId` argument on other tools.\",\n inputSchema: {\n limit: z.number().int().positive().max(100).optional().describe(\"Max number of teams to return.\"),\n offset: z.number().int().nonnegative().optional().describe(\"Number of teams to skip (for pagination).\"),\n search: z.string().optional().describe(\"Free-text search over team names.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ limit, offset, search }) =>\n jsonResult(await ctx.client.team.teamGetList({ limit: limit ?? null, offset: offset ?? null, search: search ?? null })),\n );\n\n registerTool(\n server,\n \"get_team\",\n {\n title: \"Get a team by id\",\n description: \"Fetch a single team by id, including its connected social accounts/integrations.\",\n inputSchema: { id: z.string().min(1).describe(\"Team id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.team.teamGetTeam({ id })),\n );\n\n registerTool(\n server,\n \"create_team\",\n {\n title: \"Create a team\",\n description: \"Create a new team in the organization.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Team name.\"),\n avatarUrl: z.string().optional().describe(\"Optional avatar image URL.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ name, avatarUrl }) =>\n jsonResult(\n await ctx.client.team.teamCreateTeam({\n requestBody: { name, avatarUrl: avatarUrl ?? null },\n }),\n ),\n );\n\n registerTool(\n server,\n \"update_team\",\n {\n title: \"Update a team\",\n description: \"Update a team's name and/or avatar. Only the fields you pass are changed.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Team id.\"),\n name: z.string().optional().describe(\"New team name.\"),\n avatarUrl: z.string().nullable().optional().describe(\"New avatar image URL, or null to clear it.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ id, name, avatarUrl }) => {\n const requestBody: TeamUpdateBody = {};\n if (name !== undefined) requestBody.name = name;\n if (avatarUrl !== undefined) requestBody.avatarUrl = avatarUrl;\n if (Object.keys(requestBody).length === 0) {\n throw new McpToolError(\"NOTHING_TO_UPDATE\", \"Nothing to update — pass at least one of name, avatarUrl.\");\n }\n return jsonResult(await ctx.client.team.teamUpdateTeam({ id, requestBody }));\n },\n );\n\n registerTool(\n server,\n \"delete_team\",\n {\n title: \"Delete a team\",\n description: \"Delete a team by id. This is destructive and cannot be undone — it removes the team and its scheduled content.\",\n inputSchema: { id: z.string().min(1).describe(\"Team id.\") },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ id }) => jsonResult(await ctx.client.team.teamDeleteTeam({ id })),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { errorSummary, jsonResult } from \"../errors\";\nimport { normalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\nconst teamIdSchema = z\n .string()\n .min(1)\n .optional()\n .describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\");\n\nexport function registerOrganizationTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"get_organization\",\n {\n title: \"Get the organization\",\n description: \"Fetch the current organization — its id, name, API-access flag and plan limits. Its `teams` array is deprecated (removed 2026-11-15); use `list_teams` to enumerate teams.\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => jsonResult(await ctx.client.organization.organizationGetOrganization()),\n );\n\n registerTool(\n server,\n \"get_usage\",\n {\n title: \"Get usage quotas\",\n description:\n \"Organization usage quotas: posts, comments and uploads (used/limit/remaining), plus a paginated per-social-account breakdown of post-history import usage. Use the pagination/filter args for the imports breakdown.\",\n inputSchema: {\n teamId: teamIdSchema,\n platform: z.string().optional().describe(\"Filter the imports breakdown to one platform name/alias (e.g. instagram, tiktok).\"),\n socialAccountId: z.string().optional().describe(\"Filter the imports breakdown to one social-account id.\"),\n page: z.number().int().positive().optional().describe(\"Page of the imports breakdown (1-based).\"),\n pageSize: z.number().int().positive().max(100).optional().describe(\"Page size of the imports breakdown.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform, socialAccountId, page, pageSize }) => {\n const id = teamId ?? ctx.defaultTeamId;\n const resolvedTeamId = id ?? (await resolveTeamId(ctx, teamId).catch(() => undefined));\n const [posts, comments, uploads, imports] = await Promise.all([\n ctx.client.organization.organizationGetPostsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization.organizationGetCommentsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization.organizationGetUploadsUsage().catch((error) => ({ error: errorSummary(error) })),\n ctx.client.organization\n .organizationGetImportsUsage({\n page,\n pageSize,\n teamId: resolvedTeamId,\n socialAccountType: platform ? normalizePlatform(platform) : undefined,\n socialAccountId,\n })\n .catch((error) => ({ error: errorSummary(error) })),\n ]);\n return jsonResult({ posts, comments, uploads, imports });\n },\n );\n\n registerTool(\n server,\n \"get_daily_limits_usage\",\n {\n title: \"Get a connected account's daily limits\",\n description:\n \"How much of one connected account's daily post and comment allowance has been used on a given day (defaults to today, UTC). Use it before bulk-scheduling to avoid hitting a per-account daily cap.\",\n inputSchema: {\n socialAccountId: z.string().min(1).describe(\"Connected social account id (see list_integrations).\"),\n date: z.string().optional().describe(\"Day to report on, YYYY-MM-DD. Defaults to today.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ socialAccountId, date }) =>\n jsonResult(\n await ctx.client.organization.organizationGetDailyLimitsUsage({\n socialAccountId,\n ...(date ? { date } : {}),\n }),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { PostImportCreateData } from \"bundlesocial\";\nimport { type ServerContext, resolveTeamId } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport { normalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype PostImportPlatform = NonNullable<PostImportCreateData[\"requestBody\"]>[\"socialAccountType\"];\n\nconst platformSchema = z.string().min(1).describe(\"Platform name/alias. Post-history import is available on FACEBOOK, INSTAGRAM, THREADS, TIKTOK, YOUTUBE, LINKEDIN, PINTEREST, REDDIT, MASTODON, BLUESKY.\");\n\nexport function registerPostImportTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post_import\",\n {\n title: \"Import post history\",\n description:\n \"Start an async import of a connected account's recent posts (optionally with analytics) for one platform. Poll list_post_imports / get_post_import for status and list_imported_posts for the imported posts.\",\n inputSchema: {\n platform: platformSchema,\n count: z.number().int().positive().describe(\"How many recent posts to import.\"),\n withAnalytics: z.boolean().optional().describe(\"Also fetch analytics for the imported posts.\"),\n importCarousels: z.boolean().optional().describe(\"Include carousel/album posts (Instagram).\"),\n surface: z.enum([\"PROFILE_GRID\", \"NON_GRID\", \"STORY\", \"ALL\"]).optional().describe(\"Which surface to import from (Instagram).\"),\n mediaType: z.enum([\"VIDEO\", \"IMAGE\"]).optional().describe(\"Restrict to one media type.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ platform, count, withAnalytics, importCarousels, surface, mediaType, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(\n await ctx.client.postImport.postImportCreate({\n requestBody: {\n teamId: id,\n socialAccountType: normalizePlatform(platform) as PostImportPlatform,\n count,\n ...(withAnalytics !== undefined ? { withAnalytics } : {}),\n ...(importCarousels !== undefined ? { importCarousels } : {}),\n ...(surface ? { surface } : {}),\n ...(mediaType ? { mediaType } : {}),\n },\n }),\n );\n },\n );\n\n registerTool(\n server,\n \"list_post_imports\",\n {\n title: \"List post-history imports\",\n description: \"List post-history import jobs for a team, optionally filtered by platform.\",\n inputSchema: {\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n platform: z.string().optional().describe(\"Filter by platform name/alias.\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ teamId, platform }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportGetStatus({ teamId: id, socialAccountType: platform ? (normalizePlatform(platform) as PostImportPlatform) : undefined }));\n },\n );\n\n registerTool(\n server,\n \"get_post_import\",\n {\n title: \"Get a post-history import by id\",\n description: \"Fetch a single post-history import job by its id, including its status and counts.\",\n inputSchema: { importId: z.string().min(1).describe(\"Post import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postImport.postImportGetById({ importId })),\n );\n\n registerTool(\n server,\n \"list_imported_posts\",\n {\n title: \"List imported posts for a platform\",\n description: \"List the posts imported (with analytics, when available) for a connected account on the given platform.\",\n inputSchema: {\n platform: platformSchema,\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ platform, teamId, limit, offset }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportGetImportedPosts({ teamId: id, socialAccountType: normalizePlatform(platform) as PostImportPlatform, limit, offset: offset ?? null }));\n },\n );\n\n registerTool(\n server,\n \"delete_imported_posts\",\n {\n title: \"Delete imported posts\",\n description: \"Bulk-delete imported posts (and their analytics) by id. Destructive.\",\n inputSchema: {\n postIds: z.array(z.string().min(1)).min(1).describe(\"Imported-post ids to delete.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { destructiveHint: true, openWorldHint: true },\n },\n async ({ postIds, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportDeleteImportedPosts({ requestBody: { teamId: id, postIds } }));\n },\n );\n\n registerTool(\n server,\n \"retry_post_import\",\n {\n title: \"Retry a post-history import\",\n description: \"Retry a post-history import job that ended in FAILED / RATE_LIMITED.\",\n inputSchema: {\n importId: z.string().min(1).describe(\"Post import id.\"),\n teamId: z.string().min(1).optional().describe(\"bundle.social team id. Optional when the organization has a single team or BUNDLESOCIAL_TEAM_ID is configured.\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ importId, teamId }) => {\n const id = await resolveTeamId(ctx, teamId);\n return jsonResult(await ctx.client.postImport.postImportRetryImport({ importId, requestBody: { teamId: id } }));\n },\n );\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { McpToolError, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\nfunction isUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value.trim());\n}\n\nasync function readCsvFile(source: string): Promise<File> {\n if (isUrl(source)) {\n const response = await fetch(source.trim());\n if (!response.ok) {\n throw new McpToolError(\"CSV_FETCH_FAILED\", `Could not download the CSV from \"${source}\" (HTTP ${response.status}).`, { status: response.status });\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n const name = path.basename(new URL(source).pathname) || \"import.csv\";\n return new File([buffer], name, { type: \"text/csv\" });\n }\n const absolutePath = path.resolve(source);\n let buffer: Buffer;\n try {\n buffer = await fs.readFile(absolutePath);\n } catch {\n throw new McpToolError(\n \"CSV_NOT_FOUND\",\n `Could not read CSV \"${source}\". Provide a public https:// URL, or a local file path that exists on the machine running this MCP server (stdio mode only).`,\n { path: absolutePath },\n );\n }\n return new File([buffer], path.basename(absolutePath), { type: \"text/csv\" });\n}\n\nexport function registerPostCsvTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"create_post_csv_import\",\n {\n title: \"Bulk-import posts from a CSV\",\n description:\n \"Upload a CSV for async bulk post import. Accepts a public https:// URL to the CSV, or a local file path when this server runs in stdio mode. Poll get_post_csv_import_status / get_post_csv_import_rows for progress and per-row results.\",\n inputSchema: {\n source: z.string().min(1).describe(\"Public https:// URL of the CSV, or a local file path (stdio mode only).\"),\n },\n annotations: { openWorldHint: true },\n },\n async ({ source }) => {\n const file = await readCsvFile(source);\n return jsonResult(await ctx.client.postCsv.postCsvCreate({ formData: { file } }));\n },\n );\n\n registerTool(\n server,\n \"list_post_csv_imports\",\n {\n title: \"List CSV imports\",\n description: \"List the post-CSV import history (paginated).\",\n inputSchema: {\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ limit, offset }) => jsonResult(await ctx.client.postCsv.postCsvGetList({ limit: limit ?? null, offset: offset ?? null })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import\",\n {\n title: \"Get a CSV import by id\",\n description: \"Fetch a single post-CSV import by its id, including counts and status.\",\n inputSchema: { importId: z.string().min(1).describe(\"CSV import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postCsv.postCsvGetById({ importId })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import_status\",\n {\n title: \"Get a CSV import's processing status\",\n description: \"Fetch the processing status of a post-CSV import (rows processed/succeeded/failed).\",\n inputSchema: { importId: z.string().min(1).describe(\"CSV import id.\") },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId }) => jsonResult(await ctx.client.postCsv.postCsvGetStatus({ importId })),\n );\n\n registerTool(\n server,\n \"get_post_csv_import_rows\",\n {\n title: \"Get a CSV import's row results\",\n description: \"List per-row results of a post-CSV import (the raw row, normalized payload, created post id or error), optionally filtered by SUCCESS/FAILED.\",\n inputSchema: {\n importId: z.string().min(1).describe(\"CSV import id.\"),\n status: z.enum([\"SUCCESS\", \"FAILED\"]).optional().describe(\"Filter rows by outcome.\"),\n limit: z.number().int().positive().max(100).optional(),\n offset: z.number().int().nonnegative().optional(),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ importId, status, limit, offset }) =>\n jsonResult(await ctx.client.postCsv.postCsvGetRows({ importId, status, limit: limit ?? null, offset: offset ?? null })),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport pkg from \"../../package.json\";\nimport { type ServerContext, DASHBOARD_SOCIAL_ACCOUNTS_URL, listAllTeams } from \"../client\";\nimport { errorSummary, jsonResult } from \"../errors\";\nimport { registerTool } from \"../register-tool\";\n\nconst VERSION: string = pkg.version;\n\ntype CheckStatus = \"ok\" | \"warn\" | \"fail\";\ninterface Check {\n name: string;\n status: CheckStatus;\n message: string;\n [key: string]: unknown;\n}\n\nexport function registerDiagnosticsTools(server: McpServer, ctx: ServerContext): void {\n registerTool(\n server,\n \"check_setup\",\n {\n title: \"Check the bundle.social setup\",\n description:\n \"Diagnose this MCP server's setup: API key present, API reachable, API key valid, organization API access, team resolution, connected integrations and posts quota. Always returns a structured diagnostic object ({ ok, checks: [...] }).\",\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async () => {\n const checks: Check[] = [];\n const add = (name: string, status: CheckStatus, message: string, extra: Record<string, unknown> = {}) =>\n checks.push({ name, status, message, ...extra });\n const finish = () => jsonResult({ ok: checks.every((check) => check.status !== \"fail\"), mcpVersion: VERSION, node: process.version, checks });\n\n // The server is only constructed with a non-empty API key, so by the time\n // a tool runs the key is always present — record it for completeness.\n add(\"api_key\", \"ok\", \"API key configured\");\n\n try {\n const health = await ctx.client.app.appGetHealth();\n add(\"api_reachable\", \"ok\", \"API reachable\", { health });\n } catch (error) {\n add(\"api_reachable\", \"fail\", \"Could not reach the bundle.social API\", { error: errorSummary(error) });\n return finish();\n }\n\n let teams: Array<{ id: string; name: string }> = [];\n let organizationApiAccess: boolean | undefined;\n try {\n const organization = await ctx.client.organization.organizationGetOrganization();\n organizationApiAccess = organization.apiAccess;\n add(\"authentication\", \"ok\", \"API key is valid\", { organizationId: organization.id, organizationName: organization.name ?? null });\n } catch (error) {\n add(\"authentication\", \"fail\", \"API key was rejected by the API\", { error: errorSummary(error) });\n return finish();\n }\n if (!ctx.defaultTeamId) {\n try {\n teams = (await listAllTeams(ctx.client)).map((team) => ({ id: team.id, name: team.name }));\n } catch (error) {\n add(\"team\", \"fail\", \"Could not list the organization's teams\", { error: errorSummary(error) });\n return finish();\n }\n }\n add(\n \"api_access\",\n organizationApiAccess ? \"ok\" : \"fail\",\n organizationApiAccess\n ? \"Organization has API access enabled\"\n : \"Organization does not have API access enabled — upgrade your plan or contact bundle.social support\",\n );\n\n let teamId: string | undefined;\n if (ctx.defaultTeamId) {\n teamId = ctx.defaultTeamId;\n add(\"team\", \"ok\", \"Using team from BUNDLESOCIAL_TEAM_ID / --team-id\", { teamId });\n } else if (teams.length === 1) {\n teamId = teams[0].id;\n add(\"team\", \"ok\", \"Using the organization's only team\", { teamId, teamName: teams[0].name });\n } else if (teams.length === 0) {\n add(\"team\", \"fail\", \"Organization has no teams — create one in the dashboard\");\n } else {\n add(\"team\", \"warn\", `Organization has ${teams.length} teams; tools need a teamId argument (or set BUNDLESOCIAL_TEAM_ID)`, { teams });\n }\n\n if (teamId) {\n try {\n const team = await ctx.client.team.teamGetTeam({ id: teamId });\n const accounts = team.socialAccounts ?? [];\n add(\n \"integrations\",\n accounts.length > 0 ? \"ok\" : \"warn\",\n accounts.length > 0 ? `${accounts.length} connected integration(s)` : \"No integrations connected — connect one in the dashboard before posting\",\n { count: accounts.length, platforms: accounts.map((account) => account.type), connectUrl: DASHBOARD_SOCIAL_ACCOUNTS_URL },\n );\n } catch (error) {\n add(\"integrations\", \"fail\", \"Could not load the team's integrations\", { teamId, error: errorSummary(error) });\n }\n }\n\n try {\n const usage = await ctx.client.organization.organizationGetPostsUsage();\n add(\"posts_quota\", usage.remaining > 0 ? \"ok\" : \"warn\", `Posts quota: ${usage.used}/${usage.limit} used, ${usage.remaining} remaining`, {\n used: usage.used,\n limit: usage.limit,\n remaining: usage.remaining,\n });\n } catch (error) {\n add(\"posts_quota\", \"warn\", \"Could not read posts quota\", { error: errorSummary(error) });\n }\n\n return finish();\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { jsonResult } from \"../errors\";\nimport {\n MEDIA_NOTES,\n PLATFORM_REFERENCE,\n type PlatformReferenceEntry,\n} from \"../platform-reference\";\nimport { PLATFORMS, tryNormalizePlatform } from \"../platforms\";\nimport { registerTool } from \"../register-tool\";\n\ntype Operation = \"post\" | \"comment\";\n\n/** Narrow an entry to a single operation, or return it whole. */\nfunction projectEntry(entry: PlatformReferenceEntry, operation?: Operation): Record<string, unknown> {\n const base = {\n platform: entry.platform,\n label: entry.label,\n aliases: entry.aliases,\n capabilities: entry.capabilities,\n notes: entry.notes,\n };\n if (operation === \"post\") {\n return { ...base, post: entry.post };\n }\n if (operation === \"comment\") {\n return {\n ...base,\n comment: entry.comment ?? {\n supported: false,\n message: `Comments are not available on ${entry.label} via the bundle.social API.`,\n },\n };\n }\n return { ...base, post: entry.post, ...(entry.comment ? { comment: entry.comment } : {}) };\n}\n\nexport function registerPlatformReferenceTools(server: McpServer, ctx: ServerContext): void {\n // ctx is unused — this tool serves a static reference, but the signature is\n // kept uniform with the other register* functions.\n void ctx;\n\n registerTool(\n server,\n \"describe_platform\",\n {\n title: \"Describe a platform's field schema\",\n description:\n \"Look up the exact per-platform `data.<PLATFORM>` fields the bundle.social API accepts — for posting AND commenting — so you can build a correct `data` / `platformSettings` object instead of guessing. \" +\n \"Pass `platform` (name or alias, e.g. \\\"reddit\\\", \\\"x\\\", \\\"gbp\\\") for one platform, or omit it to get every platform. \" +\n \"Pass `operation` (\\\"post\\\" or \\\"comment\\\") to narrow the response. \" +\n \"Each field lists its name, type, whether it is required, and notes; each platform also reports its capabilities (posting / comments / analytics / comment imports) and a ready-to-use example. \" +\n \"Call this before create_post / schedule_post / update_post / create_comment / update_comment whenever you are unsure which fields a platform needs.\",\n inputSchema: {\n platform: z\n .string()\n .min(1)\n .optional()\n .describe('Platform name or alias (e.g. \"reddit\", \"x\", \"tiktok\", \"gbp\"). Omit to describe every platform.'),\n operation: z\n .enum([\"post\", \"comment\"])\n .optional()\n .describe('Which operation to describe. \"post\" = create/schedule/update a post; \"comment\" = create/update a comment. Omit for both.'),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ platform, operation }) => {\n if (platform) {\n const normalized = tryNormalizePlatform(platform);\n if (!normalized) {\n return jsonResult({\n error: {\n code: \"UNKNOWN_PLATFORM\",\n message: `Unknown platform \"${platform}\". Supported: ${PLATFORMS.join(\", \")} (aliases like \"x\" and \"gbp\" are accepted too).`,\n supportedPlatforms: PLATFORMS,\n },\n });\n }\n return jsonResult({\n platform: projectEntry(PLATFORM_REFERENCE[normalized], operation),\n mediaNotes: MEDIA_NOTES,\n });\n }\n\n return jsonResult({\n platforms: PLATFORMS.map((name) => projectEntry(PLATFORM_REFERENCE[name], operation)),\n mediaNotes: MEDIA_NOTES,\n hint: 'Pass `platform` (e.g. \"reddit\") to focus on one platform, or `operation` (\"post\" | \"comment\") to narrow the response.',\n });\n },\n );\n}\n","import { COMMENT_PLATFORMS, type Platform, PLATFORMS } from \"./platforms\";\n\n/**\n * Structured per-platform field reference for the `data.<PLATFORM>` objects the\n * bundle.social API accepts. Exposed to MCP clients via the `describe_platform`\n * tool so an agent can look up exactly which fields a platform needs without\n * guessing or relying on stale training data.\n *\n * SYNC: the field tables here mirror bundlesocial-cli/PROVIDER_SETTINGS.md and\n * https://docs.bundle.social/api-reference/platform-parameters — when the API\n * gains/removes/changes a `data.<PLATFORM>` field, update all three.\n */\n\nexport interface ReferenceField {\n /** Field name as it appears under `data.<PLATFORM>`. */\n name: string;\n /** Human-readable type, e.g. `string`, `string[]`, an enum union, or an object shape. */\n type: string;\n /** Whether the platform requires this field for a post/comment to succeed. */\n required: boolean;\n /** What the field does and any limits/caveats. */\n notes: string;\n}\n\nexport interface OperationReference {\n /** Where the object lives in the request body, e.g. `data.REDDIT`. */\n dataKey: string;\n /** One-line description of the operation for this platform. */\n summary: string;\n /** Every field the operation accepts for this platform. */\n fields: ReferenceField[];\n /** A minimal, valid example object for this platform. */\n example: Record<string, unknown>;\n}\n\nexport interface PlatformReferenceEntry {\n platform: Platform;\n /** Display name, e.g. `X / Twitter`. */\n label: string;\n /** Accepted names/aliases (lower-cased) for this platform. */\n aliases: string[];\n capabilities: {\n /** Can create/schedule posts. */\n posting: boolean;\n /** Can create comments/replies on a post. */\n comments: boolean;\n /** Exposes post & account analytics. */\n analytics: boolean;\n /** Supports importing the (incoming) comments on a published post. */\n commentImports: boolean;\n };\n /** The `data.<PLATFORM>` schema used by create_post / schedule_post / update_post. */\n post: OperationReference;\n /** The `data.<PLATFORM>` schema used by create_comment / update_comment (omitted when unsupported). */\n comment?: OperationReference;\n /** Extra platform-specific guidance. */\n notes: string[];\n}\n\nconst COMMENT_IMPORT_PLATFORMS: Platform[] = [\n \"FACEBOOK\",\n \"INSTAGRAM\",\n \"LINKEDIN\",\n \"YOUTUBE\",\n \"TIKTOK\",\n \"REDDIT\",\n \"THREADS\",\n \"MASTODON\",\n \"BLUESKY\",\n];\n\nconst ANALYTICS: Platform[] = [\n \"TIKTOK\",\n \"YOUTUBE\",\n \"INSTAGRAM\",\n \"FACEBOOK\",\n \"THREADS\",\n \"REDDIT\",\n \"PINTEREST\",\n \"MASTODON\",\n \"LINKEDIN\",\n \"BLUESKY\",\n \"GOOGLE_BUSINESS\",\n \"SNAPCHAT\",\n];\n\n/** A comment's `data.<PLATFORM>` only ever carries the comment body text. */\nfunction commentOperation(platform: Platform): OperationReference {\n return {\n dataKey: `data.${platform}`,\n summary: `Comment/reply on a post. The per-platform comment object only carries the comment body.`,\n fields: [{ name: \"text\", type: \"string\", required: true, notes: \"The comment body.\" }],\n example: { [platform]: { text: \"Great write-up — thanks for sharing!\" } },\n };\n}\n\n/** Per-platform post-field tables. Keyed by platform; comment data is added below. */\nconst POST: Record<Platform, OperationReference> = {\n TWITTER: {\n dataKey: \"data.TWITTER\",\n summary: \"Post a tweet. For a thread, post the first tweet then add replies via create_comment.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"Post text. ~280 chars (longer if the connected account is X Premium).\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images OR 1 video/GIF.\" },\n {\n name: \"replySettings\",\n type: \"EVERYONE | FOLLOWING | MENTIONED_USERS | SUBSCRIBERS | VERIFIED\",\n required: false,\n notes: \"Who can reply to the tweet.\",\n },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: 'Adds X\\'s \"made with AI\" label to a post with AI-generated media.' },\n ],\n example: { TWITTER: { text: \"Shipping day 🚀\", replySettings: \"EVERYONE\" } },\n },\n BLUESKY: {\n dataKey: \"data.BLUESKY\",\n summary: \"Post to Bluesky.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"~300 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images, or 1 video (set videoAlt).\" },\n { name: \"tags\", type: \"string[]\", required: false, notes: \"Extra hashtags (without `#`), up to 8.\" },\n {\n name: \"labels\",\n type: \"(!no-unauthenticated | porn | sexual | nudity | graphic-media)[]\",\n required: false,\n notes: \"Self-labels / content warnings.\",\n },\n { name: \"quoteUri\", type: \"string\", required: false, notes: \"AT-URI of a post to quote (at://…/app.bsky.feed.post/<rkey>).\" },\n { name: \"externalUrl\", type: \"string (URL)\", required: false, notes: \"External link card URL.\" },\n { name: \"externalTitle\", type: \"string\", required: false, notes: \"External link card title.\" },\n { name: \"externalDescription\", type: \"string\", required: false, notes: \"External link card description.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Image for the external link card (a public bundle.social upload URL).\" },\n { name: \"videoAlt\", type: \"string\", required: false, notes: \"Alt text for a video embed.\" },\n ],\n example: { BLUESKY: { text: \"New post\", tags: [\"launch\", \"indie\"], externalUrl: \"https://bundle.social\" } },\n },\n MASTODON: {\n dataKey: \"data.MASTODON\",\n summary: \"Post a status to Mastodon.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"Length depends on the connected instance (commonly ~500).\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to 4 images OR 1 video.\" },\n { name: \"privacy\", type: \"PUBLIC | UNLISTED | PRIVATE | DIRECT\", required: false, notes: \"Visibility.\" },\n { name: \"spoiler\", type: \"string\", required: false, notes: \"Content-warning text (collapses the post behind it).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image for a video.\" },\n ],\n example: { MASTODON: { text: \"Hello fediverse\", privacy: \"PUBLIC\", spoiler: \"long read\" } },\n },\n THREADS: {\n dataKey: \"data.THREADS\",\n summary: \"Post to Threads.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"~500 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Up to ~10 images, or 1 video.\" },\n {\n name: \"mediaItems\",\n type: \"{ uploadId: string, altText?: string }[]\",\n required: false,\n notes: \"Per-image alt text (alternative to uploadIds).\",\n },\n {\n name: \"topicTag\",\n type: \"string\",\n required: false,\n notes: \"One topic tag shown in the post header. 1–50 chars, no periods (.) or ampersands (&).\",\n },\n {\n name: \"replyControl\",\n type: \"everyone | accounts_you_follow | mentioned_only | parent_post_author_only | followers_only\",\n required: false,\n notes: \"Who can reply. Threads defaults to everyone.\",\n },\n {\n name: \"linkAttachment\",\n type: \"string (URL)\",\n required: false,\n notes: \"Link preview card. Text-only posts (no uploadIds).\",\n },\n {\n name: \"poll\",\n type: \"{ optionA: string, optionB: string, optionC?: string, optionD?: string }\",\n required: false,\n notes: \"2–4 options, 1–25 chars each. Text-only posts, and not together with `gif`.\",\n },\n {\n name: \"gif\",\n type: '{ gifId: string, provider?: \"GIPHY\" }',\n required: false,\n notes: \"GIF attachment (GIPHY is the only provider). Text-only posts, and not together with `poll`.\",\n },\n {\n name: \"allowlistedCountryCodes\",\n type: \"string[]\",\n required: false,\n notes: \"Restrict visibility to these ISO 3166-1 alpha-2 codes. Requires Meta account eligibility.\",\n },\n {\n name: \"crosspostToInstagramStory\",\n type: \"boolean\",\n required: false,\n notes: \"Also share the post to the linked Instagram account as a Story.\",\n },\n {\n name: \"crosspostToInstagramStoryDarkMode\",\n type: \"boolean\",\n required: false,\n notes: \"Cross-post the Instagram Story in dark mode.\",\n },\n ],\n example: { THREADS: { text: \"Quick thought\", topicTag: \"shipping\", replyControl: \"everyone\" } },\n },\n LINKEDIN: {\n dataKey: \"data.LINKEDIN\",\n summary: \"Post to a LinkedIn personal profile or company page (depends on the connected account).\",\n fields: [\n { name: \"text\", type: \"string\", required: true, notes: \"Required. ~3000 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images, a single video, or a document/PDF.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"For an article-preview post.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (a public bundle.social upload URL).\" },\n { name: \"mediaTitle\", type: \"string\", required: false, notes: \"Title for a video or document post.\" },\n { name: \"privacy\", type: \"CONNECTIONS | PUBLIC | LOGGED_IN | CONTAINER\", required: false, notes: \"Visibility.\" },\n { name: \"hideFromFeed\", type: \"boolean\", required: false, notes: \"Don't show in the main feed.\" },\n { name: \"disableReshare\", type: \"boolean\", required: false, notes: \"Disallow resharing.\" },\n ],\n example: { LINKEDIN: { text: \"We just shipped X.\", privacy: \"PUBLIC\", mediaTitle: \"Demo\" } },\n },\n FACEBOOK: {\n dataKey: \"data.FACEBOOK\",\n summary: \"Post to a Facebook Page.\",\n fields: [\n { name: \"type\", type: \"POST | REEL | STORY\", required: false, notes: \"Default POST.\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption / message.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images, or a single video.\" },\n { name: \"mediaItems\", type: \"{ uploadId: string, altText?: string }[]\", required: false, notes: \"Per-image alt text.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Link attachment — `type: POST` only.\" },\n { name: \"mediaTitle\", type: \"string\", required: false, notes: \"Video title — `type: POST` with a video only (not REEL/STORY).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Video cover image.\" },\n {\n name: \"nativeScheduleTime\",\n type: \"string (ISO 8601, local)\",\n required: false,\n notes: \"Schedule directly in Meta's scheduler instead of publishing now; max 30 days ahead.\",\n },\n ],\n example: { FACEBOOK: { type: \"POST\", text: \"Look at this\", link: \"https://bundle.social\" } },\n },\n INSTAGRAM: {\n dataKey: \"data.INSTAGRAM\",\n summary: \"Post to Instagram (feed post, carousel, Reel or Story).\",\n fields: [\n {\n name: \"type\",\n type: \"POST | REEL | STORY\",\n required: false,\n notes: \"POST = single image, carousel (carouselItems) or feed video; REEL = single video; STORY = image or short video.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"Single image/video for POST/REEL/STORY. Square ≥1080×1080 or portrait 4:5; Reels 9:16, up to 90s.\",\n },\n { name: \"altText\", type: \"string\", required: false, notes: \"Alt text for a single-image post.\" },\n {\n name: \"carouselItems\",\n type: \"{ uploadId: string, altText?: string, tagged?: { username, x, y }[] }[]\",\n required: false,\n notes: \"Carousel slides (for `type: POST`).\",\n },\n { name: \"thumbnailOffset\", type: \"number (ms)\", required: false, notes: \"Frame to use as the published video's cover.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (alternative to thumbnailOffset).\" },\n { name: \"shareToFeed\", type: \"boolean\", required: false, notes: \"Reels only — also show in the Feed tab.\" },\n { name: \"collaborators\", type: \"string[]\", required: false, notes: \"Usernames to invite as collaborators.\" },\n { name: \"tagged\", type: \"{ username: string, x?: number, y?: number }[]\", required: false, notes: \"People tags for a single-image post.\" },\n {\n name: \"locationId\",\n type: \"string\",\n required: false,\n notes: 'A location id — discover with trigger_integration_tool method \"instagram:locations\".',\n },\n { name: \"autoFitImage\", type: \"boolean\", required: false, notes: \"Let bundle.social fit the image to a valid aspect ratio.\" },\n { name: \"autoCropImage\", type: \"boolean\", required: false, notes: \"Let bundle.social crop the image to a valid aspect ratio.\" },\n {\n name: \"trialParams\",\n type: '{ graduationStrategy: \"MANUAL\" | \"SS_PERFORMANCE\" }',\n required: false,\n notes: \"Reels only — trial reels are shown to non-followers first.\",\n },\n {\n name: \"isPaidPartnership\",\n type: \"boolean\",\n required: false,\n notes: 'Adds the native \"Paid partnership\" label. Implied by brandedContentSponsors; use alone for a label without a named sponsor.',\n },\n {\n name: \"brandedContentSponsors\",\n type: \"string[]\",\n required: false,\n notes: \"Up to 2 Instagram usernames to tag as paid-partnership sponsors. Accounts connected via Facebook Login only.\",\n },\n {\n name: \"musicSoundInfo\",\n type: \"{ musicSoundId, musicSoundVolume?, videoOriginalSoundVolume? }\",\n required: false,\n notes: 'Reels only — get an audio_id from trigger_integration_tool method \"instagram:audio\". Volumes 0–100.',\n },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Adds Instagram's AI content label.\" },\n ],\n example: { INSTAGRAM: { type: \"REEL\", text: \"BTS\", shareToFeed: true, thumbnailOffset: 1500 } },\n },\n TIKTOK: {\n dataKey: \"data.TIKTOK\",\n summary: \"Post a video or photo carousel to TikTok.\",\n fields: [\n { name: \"type\", type: \"VIDEO | IMAGE\", required: false, notes: \"VIDEO = 1 video; IMAGE = photo carousel.\" },\n {\n name: \"privacy\",\n type: \"PUBLIC_TO_EVERYONE | MUTUAL_FOLLOW_FRIENDS | FOLLOWER_OF_CREATOR | SELF_ONLY\",\n required: true,\n notes: \"Effectively required by TikTok.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Caption.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"The video, or the photos for `type: IMAGE`. Video: MP4/MOV/WEBM, ≥540p, portrait 9:16 recommended, up to ~10 min.\",\n },\n { name: \"photoCoverIndex\", type: \"number\", required: false, notes: \"Which photo is the cover (for `type: IMAGE`).\" },\n { name: \"thumbnailOffset\", type: \"number (ms)\", required: false, notes: \"Frame to use as the video cover.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image (alternative to thumbnailOffset).\" },\n { name: \"isBrandContent\", type: \"boolean\", required: false, notes: \"Disclosure: paid third-party partnership.\" },\n { name: \"isOrganicBrandContent\", type: \"boolean\", required: false, notes: \"Disclosure: promoting your own business.\" },\n { name: \"disableComments\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"disableDuet\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"disableStitch\", type: \"boolean\", required: false, notes: \"Interaction restriction.\" },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Mark the video as AI-generated.\" },\n { name: \"autoAddMusic\", type: \"boolean\", required: false, notes: \"Let TikTok add music to photos.\" },\n { name: \"autoScale\", type: \"boolean\", required: false, notes: \"Auto-scale the video.\" },\n { name: \"uploadToDraft\", type: \"boolean\", required: false, notes: \"Upload as a TikTok draft instead of publishing.\" },\n {\n name: \"musicSoundInfo\",\n type: \"{ musicSoundId, musicSoundVolume?, musicSoundStart?, musicSoundEnd?, videoOriginalSoundVolume? }\",\n required: false,\n notes:\n 'Commercial music — get a song_clip_id from trigger_integration_tool method \"tiktok:trending-music\". Volumes 0–100; start/end in ms.',\n },\n ],\n example: { TIKTOK: { type: \"VIDEO\", text: \"Launch BTS\", privacy: \"PUBLIC_TO_EVERYONE\", disableStitch: true } },\n },\n YOUTUBE: {\n dataKey: \"data.YOUTUBE\",\n summary: \"Upload a video or Short to YouTube.\",\n fields: [\n { name: \"type\", type: \"VIDEO | SHORT\", required: false, notes: \"SHORT = vertical ≤60s; VIDEO = full upload.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"One video.\" },\n { name: \"text\", type: \"string\", required: false, notes: \"The video TITLE (the post `title` field also maps here).\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Video description.\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Custom thumbnail (`type: VIDEO`).\" },\n { name: \"privacy\", type: \"PUBLIC | UNLISTED | PRIVATE\", required: false, notes: \"Visibility.\" },\n {\n name: \"defaultLanguage\",\n type: \"string (BCP-47)\",\n required: false,\n notes: 'Language of the title and description, e.g. \"en\" or \"pl\".',\n },\n {\n name: \"defaultAudioLanguage\",\n type: \"string (BCP-47)\",\n required: false,\n notes: 'Language of the video\\'s default audio track, e.g. \"en\" or \"pl\".',\n },\n { name: \"madeForKids\", type: \"boolean\", required: true, notes: \"Required-ish — YouTube needs you to declare this.\" },\n { name: \"containsSyntheticMedia\", type: \"boolean\", required: false, notes: \"Mark AI-generated content.\" },\n { name: \"hasPaidProductPlacement\", type: \"boolean\", required: false, notes: \"Declare paid placements.\" },\n ],\n example: { YOUTUBE: { type: \"SHORT\", text: \"Launch BTS\", description: \"Behind the scenes…\", privacy: \"PUBLIC\", madeForKids: false } },\n },\n REDDIT: {\n dataKey: \"data.REDDIT\",\n summary: \"Submit a post to a subreddit (or your profile).\",\n fields: [\n { name: \"sr\", type: \"string\", required: true, notes: \"Subreddit (`r/subredditName`) or `u/username`.\" },\n { name: \"text\", type: \"string\", required: true, notes: \"The post title for link/text posts (Reddit's \\\"title\\\").\" },\n { name: \"description\", type: \"string\", required: false, notes: \"The body for a self post.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"An image or video.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Link post target.\" },\n { name: \"nsfw\", type: \"boolean\", required: false, notes: \"Mark NSFW.\" },\n {\n name: \"flairId\",\n type: \"string\",\n required: false,\n notes: 'Required if the subreddit requires a flair — get options with trigger_integration_tool method \"reddit:flairs\".',\n },\n ],\n example: { REDDIT: { sr: \"r/dataisbeautiful\", text: \"Our 2026 growth, visualized\", uploadIds: [\"<id>\"], flairId: \"<flair-id>\" } },\n },\n DISCORD: {\n dataKey: \"data.DISCORD\",\n summary: \"Post a message to a connected Discord channel.\",\n fields: [\n { name: \"channelId\", type: \"string\", required: true, notes: \"The connected server channel (an integration \\\"channel\\\" id — see list_integrations).\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Message content. ≤2000 chars.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Attachments.\" },\n { name: \"username\", type: \"string\", required: false, notes: \"Override the author name shown (webhook).\" },\n { name: \"avatarUrl\", type: \"string (URL)\", required: false, notes: \"Override the author avatar (webhook).\" },\n ],\n example: { DISCORD: { channelId: \"<channel-id>\", text: \"New release 🎉\" } },\n },\n SLACK: {\n dataKey: \"data.SLACK\",\n summary: \"Post a message to a connected Slack channel.\",\n fields: [\n { name: \"channelId\", type: \"string\", required: true, notes: \"The connected workspace channel (an integration \\\"channel\\\" id — see list_integrations).\" },\n { name: \"text\", type: \"string\", required: false, notes: \"Message text.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Attachments.\" },\n { name: \"username\", type: \"string\", required: false, notes: \"Override the author name shown.\" },\n { name: \"avatarUrl\", type: \"string (URL)\", required: false, notes: \"Override the author avatar.\" },\n ],\n example: { SLACK: { channelId: \"<channel-id>\", text: \"Standup notes…\" } },\n },\n GOOGLE_BUSINESS: {\n dataKey: \"data.GOOGLE_BUSINESS\",\n summary: \"Publish an update to a Google Business Profile location.\",\n fields: [\n { name: \"text\", type: \"string\", required: false, notes: \"The update body.\" },\n { name: \"uploadIds\", type: \"string[]\", required: false, notes: \"Images/videos.\" },\n { name: \"topicType\", type: \"STANDARD | EVENT | OFFER | ALERT\", required: false, notes: \"Post kind.\" },\n { name: \"languageCode\", type: \"string\", required: false, notes: \"Language tag like `en` / `en-US`.\" },\n {\n name: \"callToActionType\",\n type: \"BOOK | ORDER | SHOP | LEARN_MORE | SIGN_UP | CALL\",\n required: false,\n notes: \"CTA button.\",\n },\n { name: \"callToActionUrl\", type: \"string (URL)\", required: false, notes: \"CTA target.\" },\n { name: \"eventTitle\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"eventStartDate\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"eventEndDate\", type: \"string\", required: false, notes: \"For `topicType: EVENT`.\" },\n { name: \"offerCouponCode\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"offerRedeemOnlineUrl\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"offerTermsConditions\", type: \"string\", required: false, notes: \"For `topicType: OFFER`.\" },\n { name: \"alertType\", type: \"COVID_19\", required: false, notes: \"For `topicType: ALERT`.\" },\n ],\n example: {\n GOOGLE_BUSINESS: { text: \"Now open Saturdays!\", topicType: \"STANDARD\", callToActionType: \"LEARN_MORE\", callToActionUrl: \"https://example.com\" },\n },\n },\n PINTEREST: {\n dataKey: \"data.PINTEREST\",\n summary: \"Create a Pin (image, video or 2-5 image carousel) on a board.\",\n fields: [\n { name: \"boardName\", type: \"string\", required: true, notes: \"The board to pin to.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"One image or video, or 2-5 images (same aspect ratio, no video) for a carousel Pin. Order = slide order.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"The Pin title.\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Pin description.\" },\n { name: \"link\", type: \"string (URL)\", required: false, notes: \"Where the Pin links to.\" },\n {\n name: \"carouselItems\",\n type: \"{ uploadId: string, title?: string, description?: string, link?: string }[]\",\n required: false,\n notes: \"Per-slide overrides for a carousel Pin, matched by uploadId. Missing fields use the Pin values.\",\n },\n { name: \"altText\", type: \"string\", required: false, notes: \"Image alt text.\" },\n { name: \"note\", type: \"string\", required: false, notes: \"Private note (not public).\" },\n { name: \"thumbnail\", type: \"string (URL)\", required: false, notes: \"Cover image.\" },\n { name: \"dominantColor\", type: \"string\", required: false, notes: \"Hex color used as a placeholder before the image loads.\" },\n { name: \"isAiGenerated\", type: \"boolean\", required: false, notes: \"Adds Pinterest's AI disclosure label.\" },\n ],\n example: { PINTEREST: { boardName: \"Inspiration\", text: \"New idea\", uploadIds: [\"<id>\"], link: \"https://bundle.social\" } },\n },\n SNAPCHAT: {\n dataKey: \"data.SNAPCHAT\",\n summary: \"Post a Story or a Spotlight to a Snapchat Public Profile.\",\n fields: [\n { name: \"type\", type: \"STORY | SPOTLIGHT\", required: false, notes: \"Default STORY.\" },\n {\n name: \"uploadIds\",\n type: \"string[]\",\n required: false,\n notes: \"One image or video. Video: 5–180s, ≥540×960, up to 100 MB. Images are Story-only.\",\n },\n { name: \"text\", type: \"string\", required: false, notes: \"Alias for `description` (Spotlight). ≤160 chars.\" },\n { name: \"description\", type: \"string\", required: false, notes: \"Spotlight description. ≤160 chars.\" },\n { name: \"locale\", type: \"string\", required: false, notes: \"Spotlight locale in `en_US` form. Default en_US.\" },\n { name: \"skipSaveToProfile\", type: \"boolean\", required: false, notes: \"Spotlight only — don't save the post to the profile.\" },\n ],\n example: { SNAPCHAT: { type: \"SPOTLIGHT\", description: \"Launch day\", locale: \"en_US\" } },\n },\n};\n\nconst ALIASES_BY_PLATFORM: Record<Platform, string[]> = {\n TWITTER: [\"x\", \"twitter\"],\n BLUESKY: [\"bluesky\", \"bsky\"],\n MASTODON: [\"mastodon\", \"masto\"],\n THREADS: [\"threads\"],\n LINKEDIN: [\"linkedin\", \"li\"],\n FACEBOOK: [\"facebook\", \"fb\"],\n INSTAGRAM: [\"instagram\", \"ig\", \"insta\"],\n TIKTOK: [\"tiktok\", \"tt\"],\n YOUTUBE: [\"youtube\", \"yt\"],\n REDDIT: [\"reddit\"],\n DISCORD: [\"discord\"],\n SLACK: [\"slack\"],\n GOOGLE_BUSINESS: [\"gbp\", \"google-business\", \"google_business\", \"gmb\"],\n PINTEREST: [\"pinterest\", \"pin\"],\n SNAPCHAT: [\"snapchat\", \"snap\"],\n};\n\nconst LABELS: Record<Platform, string> = {\n TWITTER: \"X / Twitter\",\n BLUESKY: \"Bluesky\",\n MASTODON: \"Mastodon\",\n THREADS: \"Threads\",\n LINKEDIN: \"LinkedIn\",\n FACEBOOK: \"Facebook (Page)\",\n INSTAGRAM: \"Instagram\",\n TIKTOK: \"TikTok\",\n YOUTUBE: \"YouTube\",\n REDDIT: \"Reddit\",\n DISCORD: \"Discord\",\n SLACK: \"Slack\",\n GOOGLE_BUSINESS: \"Google Business Profile\",\n PINTEREST: \"Pinterest\",\n SNAPCHAT: \"Snapchat (Public Profile)\",\n};\n\nconst NOTES: Partial<Record<Platform, string[]>> = {\n TWITTER: [\n \"For an X thread, post the first tweet, then add the rest as replies — note the API does not expose comments for X, so chain them as separate posts.\",\n \"No analytics surface for X.\",\n ],\n LINKEDIN: ['Discover mention URNs with trigger_integration_tool method \"linkedin:mentions\" and put them in `text`.'],\n REDDIT: [\n 'Before posting, run trigger_integration_tool method \"reddit:requirements\" to learn title length limits, allowed post types and whether a flair is required.',\n ],\n YOUTUBE: [\n 'There is no `categoryId` in the post `data`; fetch categories with trigger_integration_tool method \"youtube:categories\".',\n ],\n INSTAGRAM: [\n \"Account types are connected via Facebook or directly via Instagram (instagramConnectionMethod on the integration).\",\n \"brandedContentSponsors and business discovery only work for accounts connected through Facebook Login.\",\n ],\n GOOGLE_BUSINESS: [\"Set the location up in the dashboard first; details/categories/hours are managed via integration helper tools.\"],\n SNAPCHAT: [\n \"Requires a Snapchat Public Profile. Stories take an image or a video; Spotlights are video-only.\",\n \"No comments API surface for Snapchat.\",\n ],\n THREADS: [\"Polls, GIFs and link attachments are mutually exclusive with media — Threads only allows them on text-only posts.\"],\n};\n\n/** General media guidance that applies to every platform's `uploadIds`. */\nexport const MEDIA_NOTES: string[] = [\n \"Images: JPG / PNG / WEBP / GIF. Video: MP4 / MOV / WEBM, up to 5 GB via the large-upload flow.\",\n \"Upload media first (upload_media → id), or let create_post's `media` arg do it; then put ids in `uploadIds` (and carouselItems[].uploadId / mediaItems[].uploadId).\",\n \"Large videos can take a while to process server-side after upload — a newly created post may sit in PROCESSING before going POSTED. Use get_post to check status; retry_post for a transient platform failure.\",\n];\n\n/** The full per-platform reference, one entry per supported platform. */\nexport const PLATFORM_REFERENCE: Record<Platform, PlatformReferenceEntry> = Object.fromEntries(\n PLATFORMS.map((platform) => {\n const supportsComments = (COMMENT_PLATFORMS as readonly string[]).includes(platform);\n const entry: PlatformReferenceEntry = {\n platform,\n label: LABELS[platform],\n aliases: ALIASES_BY_PLATFORM[platform],\n capabilities: {\n posting: true,\n comments: supportsComments,\n analytics: ANALYTICS.includes(platform),\n commentImports: COMMENT_IMPORT_PLATFORMS.includes(platform),\n },\n post: POST[platform],\n ...(supportsComments ? { comment: commentOperation(platform) } : {}),\n notes: NOTES[platform] ?? [],\n };\n return [platform, entry];\n }),\n) as Record<Platform, PlatformReferenceEntry>;\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ServerContext } from \"../client\";\nimport { registerIntegrationTools } from \"./integrations\";\nimport { registerPostTools } from \"./posts\";\nimport { registerCommentTools } from \"./comments\";\nimport { registerMediaTools } from \"./media\";\nimport { registerAnalyticsTools } from \"./analytics\";\nimport { registerIntegrationToolHelpers } from \"./integration-tools\";\nimport { registerTeamTools } from \"./teams\";\nimport { registerOrganizationTools } from \"./organization\";\nimport { registerPostImportTools } from \"./post-imports\";\nimport { registerPostCsvTools } from \"./post-csv\";\nimport { registerDiagnosticsTools } from \"./diagnostics\";\nimport { registerPlatformReferenceTools } from \"./platform-reference\";\n\nexport function registerAllTools(server: McpServer, ctx: ServerContext): void {\n registerOrganizationTools(server, ctx);\n registerTeamTools(server, ctx);\n registerIntegrationTools(server, ctx);\n registerPlatformReferenceTools(server, ctx);\n registerPostTools(server, ctx);\n registerCommentTools(server, ctx);\n registerMediaTools(server, ctx);\n registerAnalyticsTools(server, ctx);\n registerPostImportTools(server, ctx);\n registerPostCsvTools(server, ctx);\n registerIntegrationToolHelpers(server, ctx);\n registerDiagnosticsTools(server, ctx);\n}\n"],"mappings":";AACA,OAAS,wBAAAA,OAA4B,4CCDrC,OAAS,aAAAC,OAAiB,0CCA1B,IAAAC,EAAA,CACE,KAAQ,mBACR,QAAW,QACX,QAAW,0CACX,YAAe,+IACf,SAAY,CACV,gBACA,eACA,MACA,yBACA,eACA,MACA,SACA,SACA,QACF,EACA,OAAU,gBACV,QAAW,MACX,SAAY,0DACZ,KAAQ,CACN,IAAO,yDACT,EACA,WAAc,CACZ,KAAQ,MACR,IAAO,0DACT,EACA,KAAQ,SACR,IAAO,CACL,mBAAoB,iBACtB,EACA,MAAS,CACP,UACA,cACA,YACA,eACA,SACF,EACA,QAAW,CACT,KAAQ,MACV,EACA,QAAW,CACT,MAAS,OACT,IAAO,eACP,UAAa,eACb,MAAS,qBACT,KAAQ,aACR,aAAc,SACd,eAAkB,eACpB,EACA,aAAgB,CACd,4BAA6B,UAC7B,aAAgB,UAChB,IAAO,SACT,EACA,gBAAmB,CACjB,8BAA+B,SAC/B,wBAAyB,UACzB,cAAe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AAO,MAAM,EAAE,QAAQ,IAAM,QAAQ,KAAK,CAAC,CAAC,CACnD,EACA,QAAQ,GAAG,SAAUI,CAAQ,EAC7B,QAAQ,GAAG,UAAWA,CAAQ,CAChC,CAEAR,GAAK,EAAE,MAAOS,GAAU,CACtBX,GAAI,UAAWW,GAAiB,OAASA,CAAK,EAAE,EAChD,QAAQ,KAAK,CAAC,CAChB,CAAC","names":["StdioServerTransport","McpServer","package_default","Bundlesocial","OpenAPI","ApiError","McpToolError","code","message","details","normalizeError","error","body","errorSummary","jsonResult","data","errorResult","DEFAULT_API_URL","DASHBOARD_API_KEYS_URL","DASHBOARD_SOCIAL_ACCOUNTS_URL","TEAM_PAGE_SIZE","TEAM_MAX_PAGES","listAllTeams","client","teams","page","items","total","createClient","apiKey","apiUrl","Bundlesocial","OpenAPI","resolveTeamId","ctx","teamIdArg","McpToolError","team","z","PLATFORMS","ANALYTICS_PLATFORMS","ALIASES","tryNormalizePlatform","input","normalizePlatform","platform","McpToolError","isAnalyticsPlatform","COMMENT_PLATFORMS","isCommentPlatform","normalizeAnalyticsPlatform","registerTool","server","name","config","handler","args","error","errorResult","teamIdSchema","z","platformSchema","mapAccounts","accounts","account","channel","registerIntegrationTools","server","ctx","registerTool","teamId","id","team","jsonResult","teams","listAllTeams","organization","perTeam","summary","platform","redirectUrl","serverUrl","options","resolveTeamId","requestBody","normalizePlatform","channelId","platforms","expiresInMinutes","p","fromTeamId","toTeamId","resetChannel","page","pageSize","z","fs","path","MIME_BY_EXT","isUrl","value","LARGE_UPLOAD_THRESHOLD_BYTES","LARGE_UPLOAD_MIME_BY_EXT","uploadMediaRef","client","teamId","ref","absolutePath","path","buffer","fs","McpToolError","uploadLargeMedia","mime","file","ext","mimeType","init","put","uploadMediaRefs","refs","ids","upload","asPlainObject","value","label","McpToolError","resolveTargetPlatforms","client","teamId","rawTargets","resolved","accountIds","raw","platform","tryNormalizePlatform","accounts","id","account","candidate","a","isPlatformKeyedObject","keys","key","PLATFORMS","expandPlatformSettings","settings","platforms","result","p","buildPostData","input","perPlatform","data","platformsFromData","normalizePlatform","deriveTitle","content","fallback","firstLine","line","toIsoDate","date","buildFirstComment","firstComment","targets","commentable","isCommentPlatform","McpToolError","COMMENT_PLATFORMS","perPlatform","platform","result","key","value","normalizePlatform","referenceKeySchema","z","firstCommentSchema","teamIdSchema","platformsSchema","mediaSchema","platformSettingsSchema","dataSchema","titleSchema","composePost","ctx","args","teamId","resolveTeamId","resolveTargetPlatforms","platformsFromData","mediaUploadIds","uploadMediaRefs","data","buildPostData","deriveTitle","registerPostTools","server","registerTool","content","platforms","media","platformSettings","title","referenceKey","draft","composed","requestBody","resolvedFirstComment","jsonResult","date","postDate","toIsoDate","limit","offset","status","from","to","query","order","orderBy","id","normalizedPlatforms","params","resolvedTeamId","wantsDataChange","existing","commentTargets","postIds","z","commentImportStatusSchema","z","teamIdSchema","assertCommentPlatforms","platforms","bad","platform","isCommentPlatform","McpToolError","COMMENT_PLATFORMS","toIso","value","date","registerCommentTools","server","ctx","registerTool","postId","importedPostId","fetchedParentCommentId","content","delayMinutes","draft","teamId","id","resolveTeamId","resolved","resolveTargetPlatforms","post","status","baseDate","created","parentCommentId","index","text","postDate","perPlatform","comment","jsonResult","limit","offset","query","order","orderBy","normalized","normalizePlatform","params","title","data","wantsDataChange","requestBody","parsed","importId","socialAccountId","commentId","action","reason","banAuthor","z","teamIdSchema","z","registerMediaTools","server","ctx","registerTool","teamId","source","id","resolveTeamId","jsonResult","uploadMediaRef","type","status","ids","fileName","mimeType","path","z","teamIdSchema","z","withinRange","value","from","to","time","registerAnalyticsTools","server","ctx","registerTool","id","platform","raw","platformType","normalizeAnalyticsPlatform","response","jsonResult","teamId","resolveTeamId","postIds","page","limit","postId","importedPostId","McpToolError","organization","team","postsUsage","commentsUsage","uploadsUsage","accounts","integrations","account","base","isAnalyticsPlatform","items","item","error","errorSummary","z","INTEGRATION_TOOLS","client","teamId","p","listIntegrationTools","tool","runIntegrationTool","method","params","candidate","McpToolError","t","missing","key","teamIdSchema","z","registerIntegrationToolHelpers","server","ctx","registerTool","jsonResult","listIntegrationTools","method","params","teamId","id","resolveTeamId","runIntegrationTool","z","registerTeamTools","server","ctx","registerTool","z","limit","offset","search","jsonResult","id","name","avatarUrl","requestBody","McpToolError","z","teamIdSchema","z","registerOrganizationTools","server","ctx","registerTool","jsonResult","teamId","platform","socialAccountId","page","pageSize","resolvedTeamId","resolveTeamId","posts","comments","uploads","imports","error","errorSummary","normalizePlatform","date","z","platformSchema","z","registerPostImportTools","server","ctx","registerTool","platform","count","withAnalytics","importCarousels","surface","mediaType","teamId","id","resolveTeamId","jsonResult","normalizePlatform","importId","limit","offset","postIds","fs","path","z","isUrl","value","readCsvFile","source","response","McpToolError","buffer","name","path","absolutePath","fs","registerPostCsvTools","server","ctx","registerTool","z","file","jsonResult","limit","offset","importId","status","VERSION","package_default","registerDiagnosticsTools","server","ctx","registerTool","checks","add","name","status","message","extra","finish","jsonResult","check","health","error","errorSummary","teams","organizationApiAccess","organization","listAllTeams","team","teamId","accounts","account","DASHBOARD_SOCIAL_ACCOUNTS_URL","usage","z","COMMENT_IMPORT_PLATFORMS","ANALYTICS","commentOperation","platform","POST","ALIASES_BY_PLATFORM","LABELS","NOTES","MEDIA_NOTES","PLATFORM_REFERENCE","PLATFORMS","supportsComments","COMMENT_PLATFORMS","entry","projectEntry","entry","operation","base","registerPlatformReferenceTools","server","ctx","registerTool","z","platform","normalized","tryNormalizePlatform","jsonResult","PLATFORM_REFERENCE","MEDIA_NOTES","PLATFORMS","name","registerAllTools","server","ctx","registerOrganizationTools","registerTeamTools","registerIntegrationTools","registerPlatformReferenceTools","registerPostTools","registerCommentTools","registerMediaTools","registerAnalyticsTools","registerPostImportTools","registerPostCsvTools","registerIntegrationToolHelpers","registerDiagnosticsTools","VERSION","package_default","createServer","options","server","McpServer","ctx","createClient","DEFAULT_API_URL","registerAllTools","readFlag","name","index","inline","arg","log","message","main","VERSION","DASHBOARD_API_KEYS_URL","apiKey","server","createServer","transport","StdioServerTransport","shutdown","error"]}
|