@codingmantra/mcp-server 0.2.2 β†’ 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,14 +2,21 @@
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.2.2
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.
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.
12
+
6
13
  - **Current API coverage:** Story Teller, HeyGen Talking Avatar IV, and Jewellery Rate Poster tools.
7
14
  - **Video contract alignment:** Required prompt/model/duration/resolution/aspect ratio, character descriptions, seed, guidance, and local reference-image resolution.
8
15
  - **Terminal job handling:** Polling stops for completed, failed, or cancelled jobs.
9
16
 
10
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.
11
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.
12
- - ⚑ **Expanded Tool Suite (28 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.
13
20
  - 🎯 **Advanced Model & Resolution Parameters**: Direct support for `model`, `modelId`, `promptId`, custom reference images, and server-side credit synchronization.
14
21
  - πŸ›‘οΈ **Graceful Error Handling & 120s Timeout**: Informative error diagnostics when API keys are missing or requests time out, with clean stdio protocol execution.
15
22
 
@@ -17,7 +24,7 @@ The official **Model Context Protocol (MCP)** server connecting AI assistants (C
17
24
 
18
25
  ## Features & Tool Suite
19
26
 
20
- The server exposes **28 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`):
21
28
 
22
29
  ### 1. Synchronous Image Generation (Immediate Inline Image Output)
23
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.
@@ -60,6 +67,65 @@ All generations automatically deduct credits from your CodingMantra wallet and p
60
67
 
61
68
  ---
62
69
 
70
+ ### 5. Social Content & Scheduling
71
+
72
+ - **`get_social_workflow`** β€” Capabilities, workflow, content guidance, and platform limits.
73
+ - **`list_social_accounts`** β€” Connected Facebook Pages and Instagram accounts; no provider tokens.
74
+ - **`generate_social_caption`** β€” Generate or refine a caption and hashtags using images, brandBrief, and saved brand context. Uses credits.
75
+ - **`list_social_drafts`** β€” Paginated saved drafts (20 per page).
76
+ - **`save_social_draft`** β€” Create or fully replace a draft; uploads local images. Does not schedule or publish.
77
+ - **`delete_social_draft`** β€” Remove a saved draft.
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.
82
+ - **`schedule_social_post`** β€” Queue final content for automatic future delivery to selected accounts.
83
+ - **`list_social_posts`** β€” Filter the posting calendar by status, platform, and date range.
84
+ - **`get_social_post`** β€” Inspect overall/per-account status, errors, retries, job IDs, and provider post IDs.
85
+ - **`update_social_post`** β€” Edit or reschedule a queued post; retry a failed post with a new future time.
86
+ - **`cancel_social_post`** β€” Cancel remaining deliveries; retain history and successful account results.
87
+ - **`delete_social_post`** β€” Delete an eligible schedule record; does not delete a live platform post.
88
+ - **`publish_social_post`** β€” Queue immediate delivery to one or multiple connected accounts; poll to confirm publication.
89
+ - **`get_social_analytics`** β€” Recorded reach, engagement, totals, top posts, and posting activity.
90
+
91
+ #### Working with Claude, Codex, Antigravity, and other assistants
92
+
93
+ Connect accounts once in the [Social Media Hub](https://codingmantra.com/tools/digital-marketing/social-media-hub). The same `CODINGMANTRA_API_KEY` used for media generation identifies the owner of all drafts and schedules; browser cookies and Meta access tokens are not needed in your assistant. Account connection/reconnection remains in the browser. Any assistant supporting standard MCP stdio can discover the tools and their schemas. Responses include text plus structured JSON, UTC ISO timestamps, IDs, and pagination fields.
94
+
95
+ Try: β€œCreate three Facebook posts for my bakery’s launch. Use a warm voice and these verified opening hours. Save drafts for review, then schedule the approved posts at 9 AM Asia/Kolkata next week.” Or: β€œShow failed posts, explain their errors, and move this queued post to tomorrow at 6 PM Asia/Kolkata.”
96
+
97
+ Start with `get_social_workflow` and `list_social_accounts`. Use exact returned account IDs. Supply `brandBrief` to isolate a particular brand; otherwise caption generation uses saved brand context. Provide audience, verified facts, tone, offer, and CTA. Combine caption generation with existing image tools, or write captions directly in your assistant without AI credit charges.
98
+
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.
100
+
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.
106
+
107
+ ```json
108
+ {
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"
115
+ }
116
+ ```
117
+
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`.
127
+
128
+
63
129
  ## Video parameters
64
130
 
65
131
  General video tools require `prompt` (10–5000 characters), `model`, `timeDuration`, `resolution`, and `aspectRatio`. Use model-supported settings; Veo requires 8 seconds for 1080p, references, or an end frame. Choose one image mode: main image, frames, or references. Reference images accept URLs, data URIs, or local paths (up to 3 for Veo). Optional settings include characters, seed, guidanceScale, soundEffects, and styleAmbiance.
@@ -184,3 +250,5 @@ CODINGMANTRA_API_KEY=your_key node build/index.js
184
250
  ## License
185
251
 
186
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
@@ -2,12 +2,14 @@
2
2
  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
- import { apiClient } from './api-client.js';
5
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
6
+ import { apiClient, CodingMantraApiError } from './api-client.js';
6
7
  import { formatImageToolResult, resolveImageInput, resolveImagesArray } from './image-utils.js';
7
8
  const server = new Server({
8
9
  name: "codingmantra-mcp",
9
- version: "0.2.2",
10
+ version: "0.4.0",
10
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 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.",
11
13
  capabilities: {
12
14
  tools: {},
13
15
  },
@@ -942,10 +944,246 @@ const CHECK_JOB_STATUS_TOOL = {
942
944
  required: ["jobId"]
943
945
  }
944
946
  };
947
+ // Social tools share the same API key as media generation; social tokens stay on the server.
948
+ const SOCIAL_ACCOUNT_SCHEMA = {
949
+ type: 'object', properties: {
950
+ platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Connected social platform.' },
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
+ accountName: { type: 'string', minLength: 1, description: 'Account display name returned by list_social_accounts.' },
953
+ }, required: ['platform', 'accountId', 'accountName'],
954
+ };
955
+ const SOCIAL_CONTENT_PROPERTIES = {
956
+ caption: { type: 'string', maxLength: 63206, description: 'Post text. Instagram caption plus hashtags must fit 2200 characters.' },
957
+ brandBrief: { type: 'string', maxLength: 4000, description: 'Brand name, audience, voice, offer, facts, and call to action for this post.' },
958
+ hashtags: { type: 'array', maxItems: 30, items: { type: 'string', description: 'Hashtag with or without a leading #.' }, description: 'Relevant hashtags; duplicates already in the caption are omitted during publication.' },
959
+ mediaUrls: { type: 'array', maxItems: 10, items: { type: 'string', description: 'HTTPS image URL, PNG/JPEG/WebP data URI, or local image path.' }, description: 'Images only. Instagram currently requires exactly one image; Facebook accepts up to 10.' },
960
+ };
961
+ const SOCIAL_SCHEDULE_PROPERTIES = {
962
+ draftId: { type: 'string', description: 'Optional saved draft ID. Scheduling consumes it atomically; repeating this request returns the same scheduled post.' },
963
+ socialContentId: { type: 'string', description: 'Optional media library content ID for tracking.' },
964
+ platforms: { type: 'array', minItems: 1, maxItems: 20, items: SOCIAL_ACCOUNT_SCHEMA, description: 'Connected accounts to publish to; select each account once.' },
965
+ content: { type: 'object', properties: SOCIAL_CONTENT_PROPERTIES, required: ['caption'], description: 'Final post caption, hashtags, brand brief, and images.' },
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
+ };
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.' };
989
+ const socialRead = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
990
+ const socialWrite = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
991
+ const socialDelete = { ...socialWrite, destructiveHint: true, idempotentHint: true };
992
+ const SOCIAL_TOOLS = [
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: {} } },
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 } },
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.' } } } },
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.' } } } },
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.' } } } },
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'] } },
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).' } } } },
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'] } },
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: {
1005
+ status: { type: 'string', enum: ['scheduled', 'published', 'failed', 'cancelled'], description: 'Post status filter.' },
1006
+ platform: { type: 'string', enum: ['facebook', 'instagram'], description: 'Platform filter.' },
1007
+ fromDate: { type: 'string', format: 'date-time', description: 'Inclusive start timestamp with offset.' },
1008
+ toDate: { type: 'string', format: 'date-time', description: 'Inclusive end timestamp with offset.' },
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.' },
1011
+ } } },
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'] } },
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'] } },
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'] } },
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'] } },
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'] } },
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.' } } } },
1018
+ ];
1019
+ const socialSchemaValidator = new AjvJsonSchemaValidator();
1020
+ const socialValidators = new Map(SOCIAL_TOOLS.map(tool => [tool.name, socialSchemaValidator.getValidator(tool.inputSchema)]));
1021
+ function normalizeSocialDates(value) {
1022
+ if (Array.isArray(value))
1023
+ return value.map(normalizeSocialDates);
1024
+ if (value && typeof value === 'object') {
1025
+ const object = value;
1026
+ const seconds = object._seconds ?? object.seconds;
1027
+ if (typeof seconds === 'number' && Object.keys(object).every(key => ['_seconds', '_nanoseconds', 'seconds', 'nanoseconds'].includes(key))) {
1028
+ return new Date(seconds * 1000).toISOString();
1029
+ }
1030
+ return Object.fromEntries(Object.entries(object).map(([key, nested]) => [key, normalizeSocialDates(nested)]));
1031
+ }
1032
+ return value;
1033
+ }
1034
+ function socialImage(value) {
1035
+ if (typeof value !== 'string')
1036
+ throw new Error('Each media image must be a URL, data URI, or local file path.');
1037
+ const resolved = resolveImageInput(value);
1038
+ if (/^data:image\/(jpeg|png|webp);base64,/i.test(resolved))
1039
+ return resolved;
1040
+ try {
1041
+ if (new URL(resolved).protocol === 'https:')
1042
+ return resolved;
1043
+ }
1044
+ catch { /* invalid source */ }
1045
+ throw new Error('Use an HTTPS image URL or a local PNG, JPEG, or WebP file.');
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
+ }
1058
+ function socialQuery(args, allowed) {
1059
+ const query = new URLSearchParams();
1060
+ for (const key of allowed)
1061
+ if (args[key] !== undefined)
1062
+ query.set(key, String(args[key]));
1063
+ return query.size ? `?${query}` : '';
1064
+ }
1065
+ function socialId(args) {
1066
+ if (typeof args.id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(args.id))
1067
+ throw new Error('Provide a valid post or draft ID.');
1068
+ return encodeURIComponent(args.id);
1069
+ }
1070
+ async function executeSocialTool(name, rawArgs) {
1071
+ const validated = socialValidators.get(name)(rawArgs);
1072
+ if (!validated.valid)
1073
+ throw new Error(`Invalid ${name} parameters: ${validated.errorMessage}`);
1074
+ const args = { ...rawArgs };
1075
+ if (args.mediaUrls !== undefined) {
1076
+ if (!Array.isArray(args.mediaUrls))
1077
+ throw new Error('mediaUrls must be an array.');
1078
+ args.mediaUrls = args.mediaUrls.map(socialImage);
1079
+ }
1080
+ if (args.content !== undefined) {
1081
+ if (!args.content || typeof args.content !== 'object' || Array.isArray(args.content))
1082
+ throw new Error('content must be a post object.');
1083
+ const content = { ...args.content };
1084
+ if (content.mediaUrls !== undefined) {
1085
+ if (!Array.isArray(content.mediaUrls))
1086
+ throw new Error('content.mediaUrls must be an array.');
1087
+ content.mediaUrls = content.mediaUrls.map(socialImage);
1088
+ }
1089
+ args.content = content;
1090
+ }
1091
+ if (Array.isArray(args.images))
1092
+ args.images = args.images.map(socialApiImage);
1093
+ let result;
1094
+ if (name === 'get_social_workflow') {
1095
+ result = {
1096
+ supportedPlatforms: ['facebook', 'instagram'],
1097
+ connectUrl: 'https://codingmantra.com/tools/digital-marketing/social-media-hub',
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'],
1099
+ limits: { instagram: { images: 1, captionIncludingHashtags: 2200 }, facebook: { maxImages: 10, captionIncludingHashtags: 63206 }, videoPublishing: false },
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.',
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.',
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.',
1108
+ };
1109
+ }
1110
+ else {
1111
+ let endpoint = '';
1112
+ let method = 'GET';
1113
+ let body;
1114
+ const headers = {};
1115
+ if (name === 'list_social_accounts')
1116
+ endpoint = '/v1/social/accounts';
1117
+ if (name === 'generate_social_caption') {
1118
+ endpoint = '/social/caption';
1119
+ method = 'POST';
1120
+ body = { caption: args.caption || '', brandBrief: args.brandBrief || '', mediaUrls: args.mediaUrls || [], platform: args.platform || 'instagram' };
1121
+ }
1122
+ if (name === 'list_social_drafts')
1123
+ endpoint = '/social/drafts' + socialQuery(args, ['offset']);
1124
+ if (name === 'save_social_draft') {
1125
+ endpoint = '/social/drafts';
1126
+ method = 'POST';
1127
+ body = args;
1128
+ }
1129
+ if (name === 'delete_social_draft') {
1130
+ endpoint = `/social/drafts?id=${socialId(args)}`;
1131
+ method = 'DELETE';
1132
+ }
1133
+ if (name === 'list_social_media')
1134
+ endpoint = '/social/gallery' + socialQuery({ ...args, type: 'image' }, ['type', 'page', 'limit']);
1135
+ if (name === 'schedule_social_draft') {
1136
+ endpoint = '/social/schedule';
1137
+ method = 'POST';
1138
+ body = args;
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
+ }
1154
+ if (name === 'list_social_posts')
1155
+ endpoint = '/v1/social/posts' + socialQuery(args, ['status', 'platform', 'fromDate', 'toDate', 'limit', 'offset']);
1156
+ if (['update_social_post', 'delete_social_post'].includes(name)) {
1157
+ endpoint = `/social/schedule/${socialId(args)}`;
1158
+ if (name === 'update_social_post') {
1159
+ method = 'PATCH';
1160
+ const { id: _id, ...updates } = args;
1161
+ body = updates;
1162
+ }
1163
+ if (name === 'delete_social_post')
1164
+ method = 'DELETE';
1165
+ }
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';
1170
+ }
1171
+ if (name === 'get_social_analytics')
1172
+ endpoint = '/social/analytics' + socialQuery(args, ['range', 'platform', 'accountId']);
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 } : {}) });
1178
+ }
1179
+ result = normalizeSocialDates(result);
1180
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: result, ...(result.success === false ? { isError: true } : {}) };
1181
+ }
945
1182
  // ─── Tool Registration ─────────────────────────────────────────────────────────
946
1183
  server.setRequestHandler(ListToolsRequestSchema, async () => {
947
1184
  return {
948
1185
  tools: [
1186
+ ...SOCIAL_TOOLS,
949
1187
  GENERATE_JEWELLERY_RATE_POSTER_TOOL,
950
1188
  GENERATE_PRODUCT_PHOTO_TOOL,
951
1189
  GENERATE_LOGO_TOOL,
@@ -981,6 +1219,8 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
981
1219
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
982
1220
  try {
983
1221
  const { name, arguments: rawArgs } = request.params;
1222
+ if (SOCIAL_TOOLS.some(tool => tool.name === name))
1223
+ return await executeSocialTool(name, rawArgs || {});
984
1224
  const args = rawArgs || {};
985
1225
  if (name === 'generate_jewellery_rate_poster') {
986
1226
  const response = await apiClient('/image/jewellery-rate-poster', {
@@ -1336,17 +1576,21 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1336
1576
  throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
1337
1577
  }
1338
1578
  catch (error) {
1579
+ const message = error instanceof Error ? error.message : String(error);
1339
1580
  return {
1340
- 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}` }],
1341
1583
  isError: true,
1342
1584
  };
1343
1585
  }
1344
1586
  });
1345
1587
  // ─── Server Startup ─────────────────────────────────────────────────────────────
1346
1588
  async function run() {
1347
- 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 });
1348
1592
  await server.connect(transport);
1349
- console.error("[CodingMantra MCP] Server v0.2.2 initialized and running on stdio (28 tools active)");
1593
+ console.error("[CodingMantra MCP] Server v0.4.0 initialized and running on stdio (46 tools active)");
1350
1594
  }
1351
1595
  run().catch((error) => {
1352
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.2.2",
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": {