@codingmantra/mcp-server 0.3.0 β†’ 0.4.0

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/README.md CHANGED
@@ -2,7 +2,12 @@
2
2
 
3
3
  The official **Model Context Protocol (MCP)** server connecting AI assistants (Claude Desktop, Cursor, Cline, and Antigravity) to CodingMantra's generative AI media engines.
4
4
 
5
- ## What's New in v0.3.0
5
+ ## What's New in v0.4.0
6
+
7
+ - Social publishing and scheduling use the versioned developer API, supporting stable platform-prefixed account IDs, multiple targets, and caller-supplied idempotency keys.
8
+ - New `upload_social_image` and `get_social_image` tools support URL, base64, data URI, local files, and reusable media IDs.
9
+ - Per-account polling includes provider post IDs; cancellation retains delivery history. HTTP error codes and Retry-After are exposed in structured MCP errors.
10
+ - **Migration:** publication and scheduling inputs changed from the v0.3 platform/accountId or platforms/content shape to the contract below. Existing drafts, caption generation, analytics, and editing tools remain available.
6
11
  - **Social media workflows:** 15 tools for connected accounts, caption creation, drafts, gallery images, immediate publishing, scheduling, status, cancellation, and analytics. Uses the same CodingMantra API key.
7
12
 
8
13
  - **Current API coverage:** Story Teller, HeyGen Talking Avatar IV, and Jewellery Rate Poster tools.
@@ -11,7 +16,7 @@ The official **Model Context Protocol (MCP)** server connecting AI assistants (C
11
16
 
12
17
  - πŸ–ΌοΈ **Native MCP Image Output**: Generated images (including QR codes, logos, try-on shots, and product photos) return standard MCP `ImageContent` so they render directly in your AI assistant's chat window.
13
18
  - πŸ“ **Local File Path Resolution**: Pass local paths (e.g. `./shoe.png` or `/Users/.../portrait.jpg`) directly in tool argumentsβ€”the server automatically reads and encodes them as base64 data URIs.
14
- - ⚑ **Expanded Tool Suite (43 Tools)**: Expanded image generation support including Passport Photos, Baby Milestones, YouTube Thumbnails, Blog Images, Nano Banana, Professional Photography, Sketch-to-Real, Human Builder, Apparel/Product/Jewelry Try-On, Festival Posts, Upscaling, and Discovery.
19
+ - ⚑ **Expanded Tool Suite (46 Tools)**: Expanded image generation support including Passport Photos, Baby Milestones, YouTube Thumbnails, Blog Images, Nano Banana, Professional Photography, Sketch-to-Real, Human Builder, Apparel/Product/Jewelry Try-On, Festival Posts, Upscaling, and Discovery.
15
20
  - 🎯 **Advanced Model & Resolution Parameters**: Direct support for `model`, `modelId`, `promptId`, custom reference images, and server-side credit synchronization.
16
21
  - πŸ›‘οΈ **Graceful Error Handling & 120s Timeout**: Informative error diagnostics when API keys are missing or requests time out, with clean stdio protocol execution.
17
22
 
@@ -19,7 +24,7 @@ The official **Model Context Protocol (MCP)** server connecting AI assistants (C
19
24
 
20
25
  ## Features & Tool Suite
21
26
 
22
- The server exposes **43 specialized generative and utility tools** over standard I/O (`stdio`):
27
+ The server exposes **46 specialized generative and utility tools** over standard I/O (`stdio`):
23
28
 
24
29
  ### 1. Synchronous Image Generation (Immediate Inline Image Output)
25
30
  - **`generate_product_photo`** β€” Generates studio-grade commercial product photos with custom background scenes, ambient occlusion contact shadows, camera optics, resolutions (1K, 2K, 4K), aspect ratios, and dynamic logo/text overlays.
@@ -71,13 +76,16 @@ All generations automatically deduct credits from your CodingMantra wallet and p
71
76
  - **`save_social_draft`** β€” Create or fully replace a draft; uploads local images. Does not schedule or publish.
72
77
  - **`delete_social_draft`** β€” Remove a saved draft.
73
78
  - **`list_social_media`** β€” Paginate your generated image gallery.
79
+ - **`upload_social_image`** β€” Upload and normalize an image; returns reusable owner-scoped media ID and URL.
80
+ - **`get_social_image`** β€” Read uploaded media metadata.
81
+ - **`schedule_social_draft`** β€” Atomically queue an approved saved draft; reuse draftId safely.
74
82
  - **`schedule_social_post`** β€” Queue final content for automatic future delivery to selected accounts.
75
83
  - **`list_social_posts`** β€” Filter the posting calendar by status, platform, and date range.
76
- - **`get_social_post`** β€” Inspect status, errors, retries, and published job IDs.
84
+ - **`get_social_post`** β€” Inspect overall/per-account status, errors, retries, job IDs, and provider post IDs.
77
85
  - **`update_social_post`** β€” Edit or reschedule a queued post; retry a failed post with a new future time.
78
- - **`cancel_social_post`** β€” Stop a queued post before publication starts.
86
+ - **`cancel_social_post`** β€” Cancel remaining deliveries; retain history and successful account results.
79
87
  - **`delete_social_post`** β€” Delete an eligible schedule record; does not delete a live platform post.
80
- - **`publish_social_post`** β€” Post immediately to one connected account.
88
+ - **`publish_social_post`** β€” Queue immediate delivery to one or multiple connected accounts; poll to confirm publication.
81
89
  - **`get_social_analytics`** β€” Recorded reach, engagement, totals, top posts, and posting activity.
82
90
 
83
91
  #### Working with Claude, Codex, Antigravity, and other assistants
@@ -90,22 +98,32 @@ Start with `get_social_workflow` and `list_social_accounts`. Use exact returned
90
98
 
91
99
  Instagram supports **exactly one image**, with at most **2,200 characters including hashtags**. Facebook supports text and up to 10 images, with 63,206 characters including hashtags. Video/reel publishing and other networks are not implemented. Generated images may use local file paths; the server resolves them and the backend persists them when drafts or schedules are saved.
92
100
 
93
- Scheduling requires `platforms`, `content.caption` (may be empty if there is an image), and a future `scheduledFor` ISO timestamp with an explicit UTC offset. Do not guess an ambiguous timezone. Use `draftId` when queuing a saved draft: the backend atomically consumes it and repeated requests return the same schedule. Immediate publishing has no idempotency guarantee; inspect publication state before retrying a timeout. Successful schedules publish on the backend cron worker even when the assistant is offline.
101
+ Publishing and scheduling accept `accountIds` as one string or up to 20 distinct IDs from `list_social_accounts`, such as `facebook:123456` and `instagram:17890000000000000`. Account names are labels; use `platformAccountId` without its prefix only in existing draft/edit/analytics inputs. Those tools retain their legacy schemas.
102
+
103
+ Each intended post requires a caller-chosen `idempotencyKey` (8–128 letters, digits, dot, underscore, colon, or hyphen). Preserve the exact key and body on a retry. A new key intentionally creates a new post. Conflicting reuse returns 409; removing the original history returns 410. Both publication and scheduling are **asynchronous**: queue acceptance does not prove a live post. Poll `get_social_post` for each account's status, job ID and `providerPostId`. Provider acceptance followed by response loss can still be ambiguous; inspect provider history before rescheduling.
104
+
105
+ Call `schedule_social_post` with a future ISO timestamp containing an explicit UTC offset. Resolve an ambiguous timezone first. `publish_social_post` uses the same shape without `scheduledFor`. Drafts remain separate; copy approved caption/images into the request. Standalone scheduling does not consume a saved draft or accept `draftId`/`socialContentId`. Use `schedule_social_draft` for the existing atomic draft-consumption workflow: provide draftId, complete platforms/content and scheduledFor using the draft’s raw platform account IDs. Reusing draftId returns the original schedule. This tool retains the v0.3 scheduling shape for approved saved drafts.
94
106
 
95
107
  ```json
96
108
  {
97
- "draftId": "returned_draft_id",
98
- "platforms": [{ "platform": "facebook", "accountId": "returned_page_id", "accountName": "My Bakery" }],
99
- "content": {
100
- "caption": "Our opening day is almost here. Join us for fresh bread!",
101
- "hashtags": ["bakery", "freshbread"],
102
- "mediaUrls": ["https://example.com/my-generated-image.png"]
103
- },
104
- "scheduledFor": "2026-10-10T09:00:00+05:30"
109
+ "accountIds": ["facebook:123456", "instagram:17890000000000000"],
110
+ "caption": "Meet our new collection.",
111
+ "hashtags": ["NewCollection"],
112
+ "images": [{"url": "https://example.com/product.jpg"}],
113
+ "idempotencyKey": "brand-launch-2027-001",
114
+ "scheduledFor": "2027-01-15T10:00:00+05:30"
105
115
  }
106
116
  ```
107
117
 
108
- Deployment order: deploy the updated web API, verify the cron worker, then release/use MCP v0.3.0. The backend must support bearer API keys; older browser-session-only endpoints return 401. For REST examples and the route map, see the repository’s `docs/social-mcp-api.md`.
118
+ Each `images` item accepts a URL/base64/data-URI/local-path string or `{url}`, `{base64, mimeType?}`, `{path}`, or `{mediaId}`. `upload_social_image` takes `{ "image": <input> }`, excluding an existing media ID; it returns a `data` envelope with media ID, URL, JPEG MIME type, dimensions, bytes, and creation time. For example, upload `{ "image": { "path": "/path/to/product.png" } }`, then use `{ "mediaId": "returned-uuid" }` in a post. `get_social_image` accepts `{ "id": "returned-uuid" }`. Uploads do not publish or run AI generation.
119
+
120
+ Source images must be static JPEG/PNG/WebP and no more than 10 MB/40 million pixels. JSON bodies are bounded to 20 MB. HTTPS URLs must be public port 443, return directly, and contain no credentials. Redirects/private destinations are rejected. The backend normalizes images to JPEG; Instagram requires a 4:5–1.91:1 aspect ratio. Dedicated API assets remain independent of gallery deletion. Use media IDs for large or repeated images.
121
+
122
+ Versioned social responses retain the REST `{data: ...}` envelope in MCP text and structuredContent. List posts accepts `limit` 1–100 (default 20), `offset` 0–10,000, status/platform and ISO date filters. `cancel_social_post` cancels remaining deliveries and retains history; it does not remove remote posts. Updating or deleting history uses the existing owner-scoped hub API and remains blocked for active/published posts. Editing a keyed post does not free its original key; create an intentional new post with a new key.
123
+
124
+ Limits are shared across keys per user: 300 reads and 60 writes per minute. API failures provide structured `error.code`, `error.status`, and optional `error.retryAfter` alongside text. Wait for Retry-After on 429 or request-in-progress conflicts; no automatic retry is performed by the MCP server.
125
+
126
+ Deployment order: deploy the updated web API and Firestore rules, verify the cron worker, then release/use MCP v0.4.0. The package version here is prepared locally; updating source does not publish npm. See [social API documentation](https://codingmantra.com/api-docs/social-media), [OpenAPI contract](https://codingmantra.com/openapi/social-media.json), and repository `docs/social-mcp-api.md`.
109
127
 
110
128
 
111
129
  ## Video parameters
@@ -232,3 +250,5 @@ CODINGMANTRA_API_KEY=your_key node build/index.js
232
250
  ## License
233
251
 
234
252
  Private & Proprietary β€” Part of the CodingMantra Web Portal Β© 2026. All rights reserved.
253
+
254
+ MCP transport note: the server accepts messages up to 24 MB so base64 images within the 20 MB API JSON limit fit with the MCP envelope. Individual clients may impose smaller message limits; use local paths, direct HTTPS URLs, and reusable media IDs in that case. Larger messages exceed the transport bound and can close the connection.
@@ -1,6 +1,18 @@
1
1
  import dotenv from 'dotenv';
2
2
  dotenv.config({ quiet: true });
3
3
  const DEFAULT_TIMEOUT_MS = 120_000; // 2 minutes for heavy generation tasks
4
+ export class CodingMantraApiError extends Error {
5
+ status;
6
+ code;
7
+ retryAfter;
8
+ constructor(message, status, code, retryAfter) {
9
+ super(message);
10
+ this.status = status;
11
+ this.code = code;
12
+ this.retryAfter = retryAfter;
13
+ this.name = 'CodingMantraApiError';
14
+ }
15
+ }
4
16
  export function getApiKey() {
5
17
  return process.env.CODINGMANTRA_API_KEY;
6
18
  }
@@ -40,15 +52,20 @@ export async function apiClient(endpoint, options = {}) {
40
52
  });
41
53
  }
42
54
  catch (fetchError) {
43
- if (fetchError?.name === 'TimeoutError' || fetchError?.name === 'AbortError') {
44
- throw new Error(`CodingMantra API request timed out after ${DEFAULT_TIMEOUT_MS / 1000}s for ${endpoint}`);
55
+ if (fetchError instanceof Error && (fetchError.name === 'TimeoutError' || fetchError.name === 'AbortError')) {
56
+ const retryAdvice = endpoint === '/v1/social/posts' && options.method === 'POST'
57
+ ? ' Retry the exact body with the same idempotencyKey; do not create a new key.' : '';
58
+ throw new Error(`CodingMantra API request timed out for ${endpoint}.${retryAdvice}`);
45
59
  }
46
- throw new Error(`Failed to connect to CodingMantra API at ${url}: ${fetchError?.message || fetchError}`);
60
+ throw new Error(`Failed to connect to CodingMantra API at ${url}: ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`);
47
61
  }
48
62
  if (!response.ok) {
49
63
  let errorMsg = `API request failed (${response.status} ${response.statusText})`;
64
+ let code;
65
+ const text = await response.text();
50
66
  try {
51
- const errorData = await response.json();
67
+ const errorData = JSON.parse(text);
68
+ code = typeof errorData?.error?.code === 'string' ? errorData.error.code : undefined;
52
69
  if (typeof errorData?.error === 'string') {
53
70
  errorMsg += `: ${errorData.error}`;
54
71
  }
@@ -63,9 +80,9 @@ export async function apiClient(endpoint, options = {}) {
63
80
  }
64
81
  }
65
82
  catch {
66
- errorMsg += `: ${await response.text()}`;
83
+ errorMsg += `: ${text.slice(0, 1000)}`;
67
84
  }
68
- throw new Error(errorMsg);
85
+ throw new CodingMantraApiError(errorMsg, response.status, code, response.headers.get('retry-after') || undefined);
69
86
  }
70
87
  return response.json();
71
88
  }
@@ -41,7 +41,7 @@ function getMimeTypeFromExt(filePath) {
41
41
  * reads it and converts to a base64 data URI.
42
42
  * If already a URL or data URI, returns as is.
43
43
  */
44
- export function resolveImageInput(input) {
44
+ export function resolveImageInput(input, maxBytes) {
45
45
  if (!input || typeof input !== 'string')
46
46
  return '';
47
47
  const trimmed = input.trim();
@@ -53,12 +53,16 @@ export function resolveImageInput(input) {
53
53
  try {
54
54
  const resolvedPath = path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
55
55
  if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
56
+ if (maxBytes && fs.statSync(resolvedPath).size > maxBytes)
57
+ throw new RangeError('Source image exceeds the allowed size (10 MB for social API uploads).');
56
58
  const buffer = fs.readFileSync(resolvedPath);
57
59
  const mimeType = getMimeTypeFromExt(resolvedPath);
58
60
  return `data:${mimeType};base64,${buffer.toString('base64')}`;
59
61
  }
60
62
  }
61
- catch {
63
+ catch (error) {
64
+ if (error instanceof RangeError)
65
+ throw error;
62
66
  // If any filesystem read error, fall through
63
67
  }
64
68
  return trimmed;
package/build/index.js CHANGED
@@ -3,13 +3,13 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
  import { CallToolRequestSchema, ListToolsRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
5
5
  import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
6
- import { apiClient } from './api-client.js';
6
+ import { apiClient, CodingMantraApiError } from './api-client.js';
7
7
  import { formatImageToolResult, resolveImageInput, resolveImagesArray } from './image-utils.js';
8
8
  const server = new Server({
9
9
  name: "codingmantra-mcp",
10
- version: "0.3.0",
10
+ version: "0.4.0",
11
11
  }, {
12
- instructions: "For social media, start with get_social_workflow and list_social_accounts. Create captions and images, save drafts for review, then schedule or publish according to the user’s request. Use exact connected account IDs and explicit timezone offsets. Only Facebook Pages and Instagram image posts are supported. Keep social provider tokens on the backend.",
12
+ instructions: "For social media, start with get_social_workflow and list_social_accounts. Create captions and images, save drafts for review, then schedule or publish according to the user’s request. Use platform-prefixed account IDs, a stable caller-chosen idempotencyKey for each intended post, and explicit timezone offsets. Publication is asynchronous; poll get_social_post and never claim a queued post is live. Only Facebook Pages and Instagram image posts are supported. Keep social provider tokens on the backend.",
13
13
  capabilities: {
14
14
  tools: {},
15
15
  },
@@ -948,7 +948,7 @@ const CHECK_JOB_STATUS_TOOL = {
948
948
  const SOCIAL_ACCOUNT_SCHEMA = {
949
949
  type: 'object', properties: {
950
950
  platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Connected social platform.' },
951
- accountId: { type: 'string', minLength: 1, description: 'Exact account ID returned by list_social_accounts.' },
951
+ accountId: { type: 'string', minLength: 1, description: 'Raw platformAccountId returned by list_social_accounts, without the facebook: or instagram: prefix; used only for draft/edit operations.' },
952
952
  accountName: { type: 'string', minLength: 1, description: 'Account display name returned by list_social_accounts.' },
953
953
  }, required: ['platform', 'accountId', 'accountName'],
954
954
  };
@@ -965,32 +965,55 @@ const SOCIAL_SCHEDULE_PROPERTIES = {
965
965
  content: { type: 'object', properties: SOCIAL_CONTENT_PROPERTIES, required: ['caption'], description: 'Final post caption, hashtags, brand brief, and images.' },
966
966
  scheduledFor: { type: 'string', format: 'date-time', description: 'Future ISO 8601 timestamp with explicit UTC offset, e.g. 2026-10-10T09:00:00+05:30. Resolve the user’s timezone before scheduling.' },
967
967
  };
968
- const SOCIAL_ID = { type: 'string', minLength: 1, pattern: '^[A-Za-z0-9_-]+$', description: 'Exact draft or scheduled post ID returned by a social tool.' };
968
+ const SOCIAL_API_IMAGE = {
969
+ description: 'HTTPS URL, raw base64, data URI, local image path, or explicit image object. Static JPEG/PNG/WebP; 10 MB decoded limit. Uploaded media IDs belong to your API-key owner.',
970
+ oneOf: [
971
+ { type: 'string', minLength: 1, description: 'Public HTTPS URL, raw base64, data URI, or local image file path.' },
972
+ { type: 'object', additionalProperties: false, properties: { url: { type: 'string', minLength: 1, description: 'Direct public HTTPS image URL on port 443; no redirects.' } }, required: ['url'] },
973
+ { type: 'object', additionalProperties: false, properties: { base64: { type: 'string', minLength: 1, description: 'Raw base64 or image data URI.' }, mimeType: { type: 'string', enum: ['image/jpeg', 'image/png', 'image/webp'], description: 'Optional declared type; must match actual bytes.' } }, required: ['base64'] },
974
+ { type: 'object', additionalProperties: false, properties: { path: { type: 'string', minLength: 1, description: 'Local JPEG/PNG/WebP image file to upload.' } }, required: ['path'] },
975
+ { type: 'object', additionalProperties: false, properties: { mediaId: { type: 'string', format: 'uuid', description: 'Reusable UUID returned by upload_social_image.' } }, required: ['mediaId'] },
976
+ ],
977
+ };
978
+ const SOCIAL_POST_PROPERTIES = {
979
+ accountIds: { description: 'One or up to 20 distinct IDs from list_social_accounts: facebook:<Meta Page ID> or instagram:<Meta account ID>.', oneOf: [
980
+ { type: 'string', pattern: '^(facebook|instagram):[0-9]+$', description: 'One platform-prefixed connected account ID.' },
981
+ { type: 'array', minItems: 1, maxItems: 20, uniqueItems: true, items: { type: 'string', pattern: '^(facebook|instagram):[0-9]+$', description: 'Platform-prefixed connected account ID.' } },
982
+ ] },
983
+ caption: SOCIAL_CONTENT_PROPERTIES.caption,
984
+ hashtags: SOCIAL_CONTENT_PROPERTIES.hashtags,
985
+ images: { type: 'array', maxItems: 10, items: SOCIAL_API_IMAGE, description: 'Image inputs; Instagram requires exactly one. Use reusable mediaId for large images.' },
986
+ idempotencyKey: { type: 'string', minLength: 8, maxLength: 128, pattern: '^[A-Za-z0-9._:-]+$', description: 'Caller-chosen key for this intended post. Preserve the exact key and body on retries; a new key means a new post. Never invent a new key after a timeout.' },
987
+ };
988
+ const SOCIAL_ID = { type: 'string', minLength: 1, pattern: '^[A-Za-z0-9_-]+$', description: 'Exact draft, media UUID or post ID returned by a social tool.' };
969
989
  const socialRead = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
970
990
  const socialWrite = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
971
991
  const socialDelete = { ...socialWrite, destructiveHint: true, idempotentHint: true };
972
992
  const SOCIAL_TOOLS = [
973
993
  { name: 'get_social_workflow', description: 'Read the social workflow, capabilities, timezone guidance, and platform restrictions before planning content or posting. Read-only; no API call.', annotations: { ...socialRead, openWorldHint: false }, inputSchema: { type: 'object', properties: {} } },
974
- { name: 'list_social_accounts', description: 'List connected Facebook Pages and Instagram accounts with IDs, names, permissions, and reconnect status. Read-only; OAuth tokens are never returned. Connect accounts in the web hub first.', annotations: socialRead, inputSchema: { type: 'object', properties: {} } },
994
+ { name: 'list_social_accounts', description: 'Read connected Facebook Pages and Instagram accounts with stable platform-prefixed IDs, raw platformAccountId, names, capabilities and reconnect status. No provider tokens. Connect in the web hub first.', annotations: socialRead, inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
975
995
  { name: 'generate_social_caption', description: 'Synchronously create or refine a caption and hashtags from a brief or images. Uses wallet credits and saved brand context unless brandBrief is supplied. Does not publish. Include verified facts, audience, tone, and CTA in the brief; review the result.', annotations: socialWrite, inputSchema: { type: 'object', properties: { ...SOCIAL_CONTENT_PROPERTIES, platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Target platform; defaults to Instagram.' } } } },
976
996
  { name: 'list_social_drafts', description: 'Read saved drafts, including captions, images, account selections, and proposed dates. Returns 20 per page; use offset for pagination.', annotations: socialRead, inputSchema: { type: 'object', properties: { offset: { type: 'integer', minimum: 0, description: 'Number of drafts to skip.' } } } },
977
997
  { name: 'save_social_draft', description: 'Save a new draft or replace an existing draft by id. Does not queue or publish. Send the complete draft when editing; omitted fields use API defaults. Local images are uploaded and persisted.', annotations: socialWrite, inputSchema: { type: 'object', properties: { ...SOCIAL_CONTENT_PROPERTIES, id: SOCIAL_ID, platforms: { type: 'array', items: SOCIAL_ACCOUNT_SCHEMA, description: 'Optional target accounts; drafts may have no accounts yet.' }, scheduledFor: { type: ['string', 'null'], format: 'date-time', description: 'Optional proposed date with explicit offset; saving does not schedule.' }, socialContentId: { type: 'string', description: 'Optional media library content ID.' } } } },
978
998
  { name: 'delete_social_draft', description: 'Delete one saved draft belonging to the API-key owner. Does not delete a scheduled or published post.', annotations: socialDelete, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
979
999
  { name: 'list_social_media', description: 'Read generated images from your gallery for use in posts. Returns public media URLs; use existing image generation tools to create new visuals.', annotations: socialRead, inputSchema: { type: 'object', properties: { page: { type: 'integer', minimum: 1, description: 'Gallery page (default 1).' }, limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Images per page (default 24).' } } } },
980
- { name: 'schedule_social_post', description: 'Queue a final post for automatic future publication to connected accounts. Returns a scheduled post ID. ISO timestamps require a UTC offset; the server scheduler publishes even when this assistant is offline. Use draftId to avoid duplicate draft scheduling.', annotations: socialWrite, inputSchema: { type: 'object', properties: SOCIAL_SCHEDULE_PROPERTIES, required: ['platforms', 'content', 'scheduledFor'] } },
1000
+ { name: 'upload_social_image', description: 'Synchronously upload and normalize an image from HTTPS URL, base64, data URI, or local file. Returns an owner-scoped reusable media ID and JPEG URL; does not publish or generate AI content. Source max 10 MB/40 million pixels; request max 20 MB.', annotations: socialWrite, inputSchema: { type: 'object', additionalProperties: false, properties: { image: { ...SOCIAL_API_IMAGE, oneOf: SOCIAL_API_IMAGE.oneOf.slice(0, 4) } }, required: ['image'] } },
1001
+ { name: 'get_social_image', description: 'Read prepared image metadata by reusable media UUID. Read-only and scoped to your API-key owner.', annotations: socialRead, inputSchema: { type: 'object', additionalProperties: false, properties: { id: { type: 'string', format: 'uuid', description: 'Media UUID returned by upload_social_image.' } }, required: ['id'] } },
1002
+ { name: 'schedule_social_draft', description: 'Asynchronously queue an approved saved hub draft using the existing atomic draft-consumption workflow. Requires draftId and complete final platforms/content/scheduledFor. Reusing draftId returns the original schedule; do not use for new standalone posts. Use raw platformAccountId in platforms.', annotations: { ...socialWrite, idempotentHint: true }, inputSchema: { type: 'object', additionalProperties: false, properties: SOCIAL_SCHEDULE_PROPERTIES, required: ['draftId', 'platforms', 'content', 'scheduledFor'] } },
1003
+ { name: 'schedule_social_post', description: 'Asynchronously queue future delivery to one or multiple owned accounts. Requires a future ISO timestamp with an explicit offset and an idempotencyKey. Acceptance is not publication; poll get_social_post for per-account results. Does not consume a saved draft.', annotations: { ...socialWrite, idempotentHint: true }, inputSchema: { type: 'object', additionalProperties: false, properties: { ...SOCIAL_POST_PROPERTIES, scheduledFor: SOCIAL_SCHEDULE_PROPERTIES.scheduledFor }, required: ['accountIds', 'idempotencyKey', 'scheduledFor'] } },
981
1004
  { name: 'list_social_posts', description: 'Read scheduled, published, failed, or cancelled posts. Filter by platform, status, or date range; use limit/offset for pagination. Dates must include a UTC offset.', annotations: socialRead, inputSchema: { type: 'object', properties: {
982
1005
  status: { type: 'string', enum: ['scheduled', 'published', 'failed', 'cancelled'], description: 'Post status filter.' },
983
1006
  platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Platform filter.' },
984
1007
  fromDate: { type: 'string', format: 'date-time', description: 'Inclusive start timestamp with offset.' },
985
1008
  toDate: { type: 'string', format: 'date-time', description: 'Inclusive end timestamp with offset.' },
986
- limit: { type: 'integer', minimum: 1, maximum: 500, description: 'Page size, default 50.' },
987
- offset: { type: 'integer', minimum: 0, description: 'Number of posts to skip.' },
1009
+ limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Page size, default 20.' },
1010
+ offset: { type: 'integer', minimum: 0, maximum: 10000, description: 'Number of posts to skip.' },
988
1011
  } } },
989
- { name: 'get_social_post', description: 'Read one scheduled post, including status, error, retries, and published job IDs. Check this before retrying a failed or ambiguous publication.', annotations: socialRead, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
1012
+ { name: 'get_social_post', description: 'Read one scheduled post, including overall and per-account delivery status, retries, errors, job IDs and providerPostId receipts. Check this before retrying a failed or ambiguous publication.', annotations: socialRead, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
990
1013
  { name: 'update_social_post', description: 'Edit a pending schedule, content, or target accounts. Provide a new future scheduledFor to reschedule or retry a failed post. The API rejects changes to posts that are publishing or already published.', annotations: { ...socialWrite, idempotentHint: true }, inputSchema: { type: 'object', properties: { id: SOCIAL_ID, content: { type: 'object', properties: SOCIAL_CONTENT_PROPERTIES, description: 'Fields to change; omitted fields retain their existing values.' }, platforms: SOCIAL_SCHEDULE_PROPERTIES.platforms, scheduledFor: SOCIAL_SCHEDULE_PROPERTIES.scheduledFor }, required: ['id'] } },
991
- { name: 'cancel_social_post', description: 'Cancel a queued post so it will not publish. The API rejects cancellation while publishing or after publication. Does not remove an already published platform post.', annotations: socialDelete, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
1014
+ { name: 'cancel_social_post', description: 'Cancel outstanding deliveries and retain the record. Successful targets remain published; pending targets are cancelled. The API rejects cancellation while publishing or after publication. Does not remove an already published platform post.', annotations: socialDelete, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
992
1015
  { name: 'delete_social_post', description: 'Remove a schedule record. The API prevents deletion during publishing or after publication. Does not delete a live Facebook or Instagram post.', annotations: socialDelete, inputSchema: { type: 'object', properties: { id: SOCIAL_ID }, required: ['id'] } },
993
- { name: 'publish_social_post', description: 'Publish immediately to one connected Facebook Page or Instagram account when the user requests posting now. Returns the platform publication result. Images only; Instagram requires exactly one image. Avoid blind retries after timeouts because a post may already be live.', annotations: { ...socialWrite, destructiveHint: true }, inputSchema: { type: 'object', properties: { ...SOCIAL_CONTENT_PROPERTIES, platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Platform to publish to.' }, accountId: { type: 'string', minLength: 1, description: 'Exact connected account ID from list_social_accounts.' }, socialContentId: { type: 'string', description: 'Optional media library content ID for publication tracking.' }, link: { type: 'string', description: 'Optional HTTPS link for a Facebook post.' } }, required: ['platform', 'accountId', 'caption'] } },
1016
+ { name: 'publish_social_post', description: 'Asynchronously queue immediate delivery to one or multiple owned Facebook/Instagram accounts. Requires idempotencyKey; identical retries return the original post. HTTP acceptance does not mean live publication. Poll get_social_post; remote response loss may still be ambiguous.', annotations: { ...socialWrite, destructiveHint: true, idempotentHint: true }, inputSchema: { type: 'object', additionalProperties: false, properties: SOCIAL_POST_PROPERTIES, required: ['accountIds', 'idempotencyKey'] } },
994
1017
  { name: 'get_social_analytics', description: 'Read recorded publishing totals, reach, engagement, top posts, and posting activity. Metrics reflect stored provider data and may be incomplete; these are not guaranteed optimal posting times.', annotations: socialRead, inputSchema: { type: 'object', properties: { range: { type: 'string', enum: ['7d', '30d', '90d'], description: 'Reporting range, default 30d.' }, platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Optional platform filter.' }, accountId: { type: 'string', description: 'Optional connected account filter.' } } } },
995
1018
  ];
996
1019
  const socialSchemaValidator = new AjvJsonSchemaValidator();
@@ -1021,6 +1044,17 @@ function socialImage(value) {
1021
1044
  catch { /* invalid source */ }
1022
1045
  throw new Error('Use an HTTPS image URL or a local PNG, JPEG, or WebP file.');
1023
1046
  }
1047
+ function socialApiImage(value) {
1048
+ if (typeof value === 'string')
1049
+ return resolveImageInput(value, 10 * 1024 * 1024);
1050
+ if (value && typeof value === 'object' && 'path' in value) {
1051
+ const image = socialImage(resolveImageInput(String(value.path), 10 * 1024 * 1024));
1052
+ if (!image.startsWith('data:'))
1053
+ throw new Error('The local image path must point to an existing JPEG, PNG or WebP file.');
1054
+ return image;
1055
+ }
1056
+ return value;
1057
+ }
1024
1058
  function socialQuery(args, allowed) {
1025
1059
  const query = new URLSearchParams();
1026
1060
  for (const key of allowed)
@@ -1054,25 +1088,32 @@ async function executeSocialTool(name, rawArgs) {
1054
1088
  }
1055
1089
  args.content = content;
1056
1090
  }
1091
+ if (Array.isArray(args.images))
1092
+ args.images = args.images.map(socialApiImage);
1057
1093
  let result;
1058
1094
  if (name === 'get_social_workflow') {
1059
1095
  result = {
1060
1096
  supportedPlatforms: ['facebook', 'instagram'],
1061
1097
  connectUrl: 'https://codingmantra.com/tools/digital-marketing/social-media-hub',
1062
- steps: ['list_social_accounts', 'generate_social_caption or write a caption with your assistant', 'generate an image with existing MCP tools or list_social_media', 'save_social_draft for review', 'schedule_social_post or publish_social_post as requested', 'list_social_posts / get_social_post / get_social_analytics'],
1098
+ steps: ['list_social_accounts', 'generate_social_caption or write a caption with your assistant', 'generate an image, list_social_media, or upload_social_image for a reusable mediaId', 'save_social_draft for review', 'schedule_social_post or publish_social_post as requested; schedule_social_draft for an approved saved draft', 'list_social_posts / get_social_post / get_social_analytics'],
1063
1099
  limits: { instagram: { images: 1, captionIncludingHashtags: 2200 }, facebook: { maxImages: 10, captionIncludingHashtags: 63206 }, videoPublishing: false },
1064
1100
  timezone: 'Ask for the user’s intended timezone when ambiguous; convert to an ISO 8601 timestamp with an explicit UTC offset. Dates are returned as ISO 8601 UTC timestamps.',
1065
1101
  contentGuidance: 'Use a clear hook, useful verified facts, the intended audience and brand voice, and one CTA. Supply brandBrief to generate_social_caption for per-brand context. Never invent prices, claims, discounts, or business details. Caption generation uses credits; drafts and schedules do not run AI.',
1066
- scheduling: 'The deployed backend requires its cron scheduler to run. The assistant does not need to remain online. Saved drafts are consumed atomically; reuse draftId to make repeated scheduling requests safe.',
1067
- retries: 'Inspect failed post errors and publishedJobIds before rescheduling. Immediate publication has no idempotency guarantee; do not automatically retry ambiguous timeouts.',
1102
+ accountIds: 'Use accounts[].id for publishing/scheduling (facebook:123 or instagram:456); draft/edit/analytics tools use the raw platformAccountId plus platform.',
1103
+ apiDocsUrl: 'https://codingmantra.com/api-docs/social-media',
1104
+ openApiUrl: 'https://codingmantra.com/openapi/social-media.json',
1105
+ rateLimits: { readsPerMinute: 300, writesPerMinute: 60, scope: 'per user, shared across API keys; respect Retry-After on 429' },
1106
+ scheduling: 'The deployed backend requires its cron scheduler to run. Both immediate and future delivery are asynchronous. Poll get_social_post for per-account receipts. Saving a draft does not publish. schedule_social_post copies standalone content; schedule_social_draft atomically consumes an approved saved draft and reuses draftId for safe retries.',
1107
+ retries: 'Preserve idempotencyKey and the exact request body for retries. Same-key retries return the original record; conflicting content returns 409, removed history returns 410. Do not generate a new key after a timeout. Provider acceptance followed by response loss can still be ambiguous; inspect the hub and provider history before rescheduling.',
1068
1108
  };
1069
1109
  }
1070
1110
  else {
1071
1111
  let endpoint = '';
1072
1112
  let method = 'GET';
1073
1113
  let body;
1114
+ const headers = {};
1074
1115
  if (name === 'list_social_accounts')
1075
- endpoint = '/social/meta/connection';
1116
+ endpoint = '/v1/social/accounts';
1076
1117
  if (name === 'generate_social_caption') {
1077
1118
  endpoint = '/social/caption';
1078
1119
  method = 'POST';
@@ -1091,53 +1132,49 @@ async function executeSocialTool(name, rawArgs) {
1091
1132
  }
1092
1133
  if (name === 'list_social_media')
1093
1134
  endpoint = '/social/gallery' + socialQuery({ ...args, type: 'image' }, ['type', 'page', 'limit']);
1094
- if (name === 'schedule_social_post') {
1135
+ if (name === 'schedule_social_draft') {
1095
1136
  endpoint = '/social/schedule';
1096
1137
  method = 'POST';
1097
1138
  body = args;
1098
1139
  }
1140
+ if (name === 'upload_social_image') {
1141
+ endpoint = '/v1/social/media';
1142
+ method = 'POST';
1143
+ body = socialApiImage(args.image);
1144
+ }
1145
+ if (name === 'get_social_image')
1146
+ endpoint = `/v1/social/media/${socialId(args)}`;
1147
+ if (name === 'schedule_social_post' || name === 'publish_social_post') {
1148
+ endpoint = '/v1/social/posts';
1149
+ method = 'POST';
1150
+ const { idempotencyKey, ...post } = args;
1151
+ headers['Idempotency-Key'] = String(idempotencyKey);
1152
+ body = post;
1153
+ }
1099
1154
  if (name === 'list_social_posts')
1100
- endpoint = '/social/schedule' + socialQuery(args, ['status', 'platform', 'fromDate', 'toDate', 'limit', 'offset']);
1101
- if (['get_social_post', 'update_social_post', 'cancel_social_post', 'delete_social_post'].includes(name)) {
1155
+ endpoint = '/v1/social/posts' + socialQuery(args, ['status', 'platform', 'fromDate', 'toDate', 'limit', 'offset']);
1156
+ if (['update_social_post', 'delete_social_post'].includes(name)) {
1102
1157
  endpoint = `/social/schedule/${socialId(args)}`;
1103
1158
  if (name === 'update_social_post') {
1104
1159
  method = 'PATCH';
1105
1160
  const { id: _id, ...updates } = args;
1106
1161
  body = updates;
1107
1162
  }
1108
- if (name === 'cancel_social_post') {
1109
- method = 'PATCH';
1110
- body = { status: 'cancelled' };
1111
- }
1112
1163
  if (name === 'delete_social_post')
1113
1164
  method = 'DELETE';
1114
1165
  }
1115
- if (name === 'publish_social_post') {
1116
- endpoint = '/social/meta/publish';
1117
- method = 'POST';
1118
- const caption = typeof args.caption === 'string' ? args.caption.trim() : '';
1119
- if (args.hashtags !== undefined && (!Array.isArray(args.hashtags) || args.hashtags.some(tag => typeof tag !== 'string' || !/^#?[\p{L}\p{N}_]+$/u.test(tag))))
1120
- throw new Error('Use valid hashtags containing letters, numbers, or underscores.');
1121
- const existing = new Set((caption.match(/#[\p{L}\p{N}_]+/gu) || []).map(tag => tag.toLowerCase()));
1122
- const tags = (args.hashtags || []).map(tag => `#${tag.replace(/^#/, '')}`).filter(tag => {
1123
- if (existing.has(tag.toLowerCase()))
1124
- return false;
1125
- existing.add(tag.toLowerCase());
1126
- return true;
1127
- });
1128
- const text = [caption, tags.join(' ')].filter(Boolean).join('\n\n');
1129
- const images = args.mediaUrls || [];
1130
- if (!['facebook', 'instagram'].includes(String(args.platform)))
1131
- throw new Error('Choose Facebook or Instagram.');
1132
- if (args.platform === 'instagram' && images.length !== 1)
1133
- throw new Error('Instagram requires exactly one image.');
1134
- body = args.platform === 'instagram'
1135
- ? { platform: 'instagram', instagramId: args.accountId, caption: text, imageDataUrl: images[0]?.startsWith('data:') ? images[0] : undefined, imageUrl: images[0]?.startsWith('https:') ? images[0] : undefined, socialContentId: args.socialContentId }
1136
- : { platform: 'facebook', pageId: args.accountId, message: text, imageUrls: images.length ? images : undefined, link: args.link, socialContentId: args.socialContentId };
1166
+ if (name === 'get_social_post' || name === 'cancel_social_post') {
1167
+ endpoint = `/v1/social/posts/${socialId(args)}`;
1168
+ if (name === 'cancel_social_post')
1169
+ method = 'DELETE';
1137
1170
  }
1138
1171
  if (name === 'get_social_analytics')
1139
1172
  endpoint = '/social/analytics' + socialQuery(args, ['range', 'platform', 'accountId']);
1140
- result = await apiClient(endpoint, { method, ...(body ? { body: JSON.stringify(body) } : {}) });
1173
+ const requestBody = body !== undefined ? JSON.stringify(body) : undefined;
1174
+ if (endpoint.startsWith('/v1/social/') && requestBody && Buffer.byteLength(requestBody, 'utf8') > 20 * 1024 * 1024) {
1175
+ throw new Error('Social API JSON requests must be 20 MB or smaller. Upload images separately and reuse media IDs.');
1176
+ }
1177
+ result = await apiClient(endpoint, { method, headers, signal: AbortSignal.timeout(300_000), ...(requestBody !== undefined ? { body: requestBody } : {}) });
1141
1178
  }
1142
1179
  result = normalizeSocialDates(result);
1143
1180
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: result, ...(result.success === false ? { isError: true } : {}) };
@@ -1539,17 +1576,21 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1539
1576
  throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
1540
1577
  }
1541
1578
  catch (error) {
1579
+ const message = error instanceof Error ? error.message : String(error);
1542
1580
  return {
1543
- content: [{ type: "text", text: `❌ **Error:** ${error.message || error}` }],
1581
+ ...(error instanceof CodingMantraApiError ? { structuredContent: { error: { code: error.code, message, status: error.status, retryAfter: error.retryAfter } } } : {}),
1582
+ content: [{ type: "text", text: `❌ **Error:** ${message}` }],
1544
1583
  isError: true,
1545
1584
  };
1546
1585
  }
1547
1586
  });
1548
1587
  // ─── Server Startup ─────────────────────────────────────────────────────────────
1549
1588
  async function run() {
1550
- const transport = new StdioServerTransport();
1589
+ // A 10 MB source becomes ~13.4 MB in base64. Leave room for the 20 MB
1590
+ // API JSON limit plus the MCP request envelope, while still bounding input.
1591
+ const transport = new StdioServerTransport(process.stdin, process.stdout, { maxBufferSize: 24 * 1024 * 1024 });
1551
1592
  await server.connect(transport);
1552
- console.error("[CodingMantra MCP] Server v0.3.0 initialized and running on stdio (43 tools active)");
1593
+ console.error("[CodingMantra MCP] Server v0.4.0 initialized and running on stdio (46 tools active)");
1553
1594
  }
1554
1595
  run().catch((error) => {
1555
1596
  console.error("Fatal error running CodingMantra MCP server:", error);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codingmantra/mcp-server",
3
- "version": "0.3.0",
4
- "description": "Official Model Context Protocol (MCP) Server for CodingMantra AI Generation Tools",
3
+ "version": "0.4.0",
4
+ "description": "Official MCP server for CodingMantra AI tools and social media publishing and scheduling",
5
5
  "type": "module",
6
6
  "main": "build/index.js",
7
7
  "bin": {