@codingmantra/mcp-server 0.1.4 → 0.2.2

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
@@ -1,73 +1,186 @@
1
1
  # @codingmantra/mcp-server
2
2
 
3
- A **Model Context Protocol (MCP)** server that connects AI agents (like Claude Desktop, Cursor, and Cline) to CodingMantra's AI generation tools.
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
- ## Features
5
+ ## What's New in v0.2.2
6
+ - **Current API coverage:** Story Teller, HeyGen Talking Avatar IV, and Jewellery Rate Poster tools.
7
+ - **Video contract alignment:** Required prompt/model/duration/resolution/aspect ratio, character descriptions, seed, guidance, and local reference-image resolution.
8
+ - **Terminal job handling:** Polling stops for completed, failed, or cancelled jobs.
6
9
 
7
- - **Product Photography** — Generate AI studio product photos with custom scenes, templates, and dynamic logo/text overlays. Supports advanced options including `model`, `resolution` (1K, 2K, 4K), and `aspectRatio`.
8
- - **Logo Creator** — Generate AI brand logos with style, references, and color customization. Supports advanced options including `modelId`, `resolution` (1K, 2K), and `aspectRatio`.
9
- - **QR Code Generator** — Create custom QR codes (URL, text, WiFi, vCard, UPI, email) with branding and colors.
10
- - **Video Generation** — Asynchronously generate high-quality AI videos. Supports:
11
- - Product Videography
12
- - Apparel Try-On Videos
13
- - Festival & Event Videos
14
- - Jewelry Showcase Videos
15
- - Logo Animation
16
- - **Asynchronous Job Polling** — Tools support a polling mechanism (`check_video_job_status`) to track long-running video generation tasks.
10
+ - 🖼️ **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
+ - 📁 **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.
13
+ - 🎯 **Advanced Model & Resolution Parameters**: Direct support for `model`, `modelId`, `promptId`, custom reference images, and server-side credit synchronization.
14
+ - 🛡️ **Graceful Error Handling & 120s Timeout**: Informative error diagnostics when API keys are missing or requests time out, with clean stdio protocol execution.
17
15
 
18
- ## Setup
16
+ ---
19
17
 
20
- ### 1. Get an API Key
18
+ ## Features & Tool Suite
21
19
 
20
+ The server exposes **28 specialized generative and utility tools** over standard I/O (`stdio`):
21
+
22
+ ### 1. Synchronous Image Generation (Immediate Inline Image Output)
23
+ - **`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.
24
+ - **`generate_logo`** — Generates bespoke vector-style or 3D brand logos with customizable typography, colors, industries, and reference images.
25
+ - **`try_on_jewelry`** — Virtual luxury jewelry try-on with model styling, metal & gemstone preservation, Fresnel light dispersion, and anatomical contact shadows.
26
+ - **`try_on_apparel`** — Virtual fashion apparel try-on with natural gravitational folds, realistic fabric tension, and ground contact shadows.
27
+ - **`try_on_product`** — Universal commercial product staging and virtual try-on across footwear, accessories, cosmetics, eyewear, and furniture with 3-point studio lighting.
28
+ - **`generate_festival_post`** — High-conversion festival marketing graphics, holiday greetings (Diwali, Eid, Christmas, New Year), and promotional banners with product and logo integration.
29
+ - **`build_human`** — Creates photorealistic AI human models tailored for brand photography, fashion, and marketing with complete demographic, facial, hair, and body customization, plus multi-view character sheets (2×2 grid).
30
+ - **`generate_youtube_thumbnail`** — High-CTR YouTube thumbnails with rule-of-thirds composition, emotional human expressions, vibrant contrast separation, and legible bold text overlays.
31
+ - **`generate_passport_photo`** — Converts any portrait into an official, compliant passport or visa identity photo with pixel-level facial identity preservation.
32
+ - **`sketch_to_real`** — Transforms hand-drawn sketches, line drawings, or product drafts into photorealistic commercial images while preserving ground-truth silhouettes.
33
+ - **`edit_professional_photo`** — Transforms and grades portraits and personal photos into magazine-grade studio or editorial photography with natural dermal micro-pores and optical depth of field.
34
+ - **`edit_nano_banana`** — Creative multi-reference image editor and compositor combining multiple subjects, backgrounds, and artistic styles (figurines, chibi, anime, retro, 3D renders).
35
+ - **`generate_blog_image`** — Generates high-impact, editorial blog hero images, article thumbnails, and banners with clean composition, visual hierarchy, intentional negative space, and exact text overlays.
36
+ - **`generate_baby_milestone`** — Creates magical baby milestone keepsake portraits with pristine subject preservation, seamless background cutout, and organic milestone text integration.
37
+ - **`upscale_image`** — Restores a reference image with Pro AI at 4K (60 credits), checks output size and proportions, and returns the image synchronously. Fine details can change; review the result.
38
+
39
+ - **`generate_jewellery_rate_poster`** — Branded gold and silver rate posters using caller-supplied rates, business details, and optional product/logo images.
40
+
41
+ ### 2. QR Code Tools
42
+ - **`generate_qr_code`** — Full-featured custom QR code generator supporting URLs, plain text, Wi-Fi credentials, vCards, emails, and UPI payment strings with custom styling, colors, and error correction.
43
+ - **`generate_qr_code_simple`** — Lightweight single-parameter QR code generation from text or URL.
44
+
45
+ ### 3. Account & Discovery Utilities
46
+ - **`get_user_credits`** — Checks your current CodingMantra AI wallet credit balance in real time.
47
+ - **`list_image_models`** — Queries all available CodingMantra AI image generation models (Gemini Flash, Pro, Grok Imagine 2.0, GPT Image 2.5 Flare), supported resolutions, aspect ratios, and credit costs.
48
+
49
+ ### 4. Asynchronous Video Tools (with Job Polling)
50
+ - **`generate_product_video`** — Commercial product videography (Google Veo 3.1 & OpenRouter Wan 3.0).
51
+ - **`generate_apparel_video`** — Model runway and apparel try-on video showcase.
52
+ - **`generate_festival_video`** — Festive event greetings and celebratory motion graphics.
53
+ - **`generate_jewelry_video`** — High-end luxury jewelry videography with realistic optical brilliance dispersion.
54
+ - **`generate_logo_video`** — 3D logo reveal and motion graphic intros.
55
+ - **`generate_story_video`** — Cinematic stories with character descriptions, sound effects, and visual atmosphere.
56
+ - **`generate_talking_avatar`** — HeyGen Avatar IV portrait animation with a script, HeyGen voice ID, and performance controls.
57
+ - **`check_video_job_status`** — Real-time polling tool to track background video rendering status (`pending` → `processing` → `completed` / `failed` / `cancelled`).
58
+
59
+ All generations automatically deduct credits from your CodingMantra wallet and persist outputs directly to your online media gallery at [https://codingmantra.com/my-gallery](https://codingmantra.com/my-gallery).
60
+
61
+ ---
62
+
63
+ ## Video parameters
64
+
65
+ 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.
66
+
67
+ Talking Avatar requires `image` (local PNG/JPEG/WebP path or data URI, not a public URL), `script`, and a HeyGen `voiceId`. Optional controls include targetDuration (5–120 seconds, default 15), speed (0.5–1.5), performancePreset, expressiveness, motionPrompt, backgroundMode/backgroundColor, captions, title, resolution (720p or 1080p, default 1080p), and aspectRatio (9:16, 1:1, or 16:9, default 9:16). Scripts must fit the duration budget; credits are calculated by the backend. Poll every 15–30 seconds until completed, failed, or cancelled.
68
+
69
+ ---
70
+
71
+ ## Quick Setup
72
+
73
+ ### 1. Obtain Your API Key
22
74
  Generate an API key from your [CodingMantra Dashboard → My API Keys](https://codingmantra.com/my-api).
23
75
 
24
- ### 2. Configure Claude Desktop
76
+ ### 2. Configure Your AI Client
25
77
 
26
- Add the following to your `claude_desktop_config.json`:
78
+ #### A. Claude Desktop
79
+ Add to your `claude_desktop_config.json`:
80
+ - **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
81
+ - **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
27
82
 
28
83
  ```json
29
84
  {
30
85
  "mcpServers": {
31
86
  "codingmantra": {
32
87
  "command": "npx",
33
- "args": ["-y", "@codingmantra/mcp-server"],
88
+ "args": ["-y", "@codingmantra/mcp-server@latest"],
34
89
  "env": {
35
- "CODINGMANTRA_API_KEY": "YOUR_API_KEY"
90
+ "CODINGMANTRA_API_KEY": "YOUR_CODINGMANTRA_API_KEY"
36
91
  }
37
92
  }
38
93
  }
39
94
  }
40
95
  ```
41
96
 
42
- ### 3. Restart Claude Desktop
43
-
44
- After saving the config, restart Claude Desktop. You can now ask Claude to:
97
+ #### B. Cursor
98
+ Add to `.cursor/mcp.json` in your project or global settings:
45
99
 
46
- - *"Generate a product photo of this watch on a marble surface"*
47
- - *"Create a minimalist logo for my company TechFlow"*
48
- - *"Generate a QR code for https://codingmantra.com"*
49
- - *"Generate a 4-second jewelry video showcasing this ring with a cinematic camera spin, and then check its status until it completes."*
100
+ ```json
101
+ {
102
+ "mcpServers": {
103
+ "codingmantra": {
104
+ "command": "npx",
105
+ "args": ["-y", "@codingmantra/mcp-server@latest"],
106
+ "env": {
107
+ "CODINGMANTRA_API_KEY": "YOUR_CODINGMANTRA_API_KEY"
108
+ }
109
+ }
110
+ }
111
+ }
112
+ ```
50
113
 
51
- ## Development
114
+ #### C. Cline (VS Code Extension)
115
+ In Cline Settings → MCP Servers, add:
52
116
 
53
- ```bash
54
- # Install dependencies
55
- npm install
117
+ ```json
118
+ {
119
+ "codingmantra": {
120
+ "command": "npx",
121
+ "args": ["-y", "@codingmantra/mcp-server@latest"],
122
+ "env": {
123
+ "CODINGMANTRA_API_KEY": "YOUR_CODINGMANTRA_API_KEY"
124
+ }
125
+ }
126
+ }
127
+ ```
56
128
 
57
- # Build
58
- npm run build
129
+ #### D. Antigravity / Agentic Workspace
130
+ Add to `.agents/mcp_config.json`:
59
131
 
60
- # Run locally
61
- CODINGMANTRA_API_KEY=your_key npm start
132
+ ```json
133
+ {
134
+ "mcpServers": {
135
+ "codingmantra": {
136
+ "command": "npx",
137
+ "args": ["-y", "@codingmantra/mcp-server@latest"],
138
+ "env": {
139
+ "CODINGMANTRA_API_KEY": "YOUR_CODINGMANTRA_API_KEY"
140
+ }
141
+ }
142
+ }
143
+ }
62
144
  ```
63
145
 
146
+ ---
147
+
148
+ ## Example Natural Language Prompts
149
+
150
+ Once configured, restart your AI assistant and try prompts like:
151
+
152
+ - *"How many credits do I have left in my CodingMantra account?"*
153
+ - *"Generate a luxury product photo of this perfume bottle on a dark reflective obsidian pedestal with subtle mist."*
154
+ - *"Virtually try on this diamond necklace on an elegant editorial model wearing a black velvet evening gown."*
155
+ - *"Create a YouTube thumbnail for my video 'Top 10 AI Tools of 2026' with bold text and high contrast."*
156
+ - *"Create a modern minimalist geometric logo for a fintech company called 'Acuity'."*
157
+ - *"Generate a UPI payment QR code for merchant@upi with an amount of 500."*
158
+ - *"Create a 4-second jewelry video showing this diamond ring rotating on a black velvet pedestal with cinematic sunbeam flares, and check its progress until it's finished."*
159
+
160
+ ---
161
+
64
162
  ## Environment Variables
65
163
 
66
- | Variable | Required | Description |
67
- |---|---|---|
68
- | `CODINGMANTRA_API_KEY` | ✅ | Your CodingMantra developer API key |
69
- | `CODINGMANTRA_API_URL` | ❌ | Custom API base URL (default: `https://codingmantra.com/api`) |
164
+ | Variable | Required | Description | Default |
165
+ |---|---|---|---|
166
+ | `CODINGMANTRA_API_KEY` | ✅ | Your CodingMantra developer API key (`cm_...`) | None |
167
+ | `CODINGMANTRA_API_URL` | ❌ | Custom API base URL | `https://codingmantra.com/api` |
168
+
169
+ ---
170
+
171
+ ## Local Development
172
+
173
+ ```bash
174
+ # Build TypeScript
175
+ npm run build
176
+
177
+ # Verify stdio contracts with a mock API (no credits spent)
178
+ npm test
179
+
180
+ # Start server directly on stdio
181
+ CODINGMANTRA_API_KEY=your_key node build/index.js
182
+ ```
70
183
 
71
184
  ## License
72
185
 
73
- Private — Part of the CodingMantra Web Portal.
186
+ Private & Proprietary — Part of the CodingMantra Web Portal © 2026. All rights reserved.
@@ -1,33 +1,63 @@
1
1
  import dotenv from 'dotenv';
2
- dotenv.config();
3
- const API_KEY = process.env.CODINGMANTRA_API_KEY;
4
- const API_BASE_URL = process.env.CODINGMANTRA_API_URL || 'https://codingmantra.com/api';
5
- if (!API_KEY) {
6
- console.error('CRITICAL: CODINGMANTRA_API_KEY environment variable is missing.');
7
- console.error('Please set it in your environment or .env file before running this server.');
8
- process.exit(1);
2
+ dotenv.config({ quiet: true });
3
+ const DEFAULT_TIMEOUT_MS = 120_000; // 2 minutes for heavy generation tasks
4
+ export function getApiKey() {
5
+ return process.env.CODINGMANTRA_API_KEY;
6
+ }
7
+ export function getApiBaseUrl() {
8
+ return process.env.CODINGMANTRA_API_URL || 'https://codingmantra.com/api';
9
+ }
10
+ if (!getApiKey()) {
11
+ console.error('[CodingMantra MCP] WARNING: CODINGMANTRA_API_KEY environment variable is not set.');
12
+ console.error('[CodingMantra MCP] Please configure your API key in your MCP client settings or .env file.');
13
+ console.error('[CodingMantra MCP] Generate an API key from https://codingmantra.com/my-api');
9
14
  }
10
15
  /**
11
16
  * Helper to make authenticated requests to the CodingMantra API.
12
17
  */
13
18
  export async function apiClient(endpoint, options = {}) {
14
- const url = `${API_BASE_URL}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;
19
+ const apiKey = getApiKey();
20
+ if (!apiKey) {
21
+ throw new Error('CODINGMANTRA_API_KEY environment variable is missing. ' +
22
+ 'Please set your API key in your MCP server configuration. ' +
23
+ 'You can generate an API key at https://codingmantra.com/my-api');
24
+ }
25
+ const baseUrl = getApiBaseUrl();
26
+ const url = `${baseUrl}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;
15
27
  const headers = new Headers(options.headers || {});
16
- headers.set('Authorization', `Bearer ${API_KEY}`);
28
+ headers.set('Authorization', `Bearer ${apiKey}`);
17
29
  if (!(options.body instanceof FormData)) {
18
30
  headers.set('Content-Type', 'application/json');
19
31
  }
20
- const response = await fetch(url, {
21
- ...options,
22
- headers,
23
- });
32
+ // Set timeout if no external abort signal provided
33
+ const signal = options.signal || AbortSignal.timeout(DEFAULT_TIMEOUT_MS);
34
+ let response;
35
+ try {
36
+ response = await fetch(url, {
37
+ ...options,
38
+ headers,
39
+ signal,
40
+ });
41
+ }
42
+ 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}`);
45
+ }
46
+ throw new Error(`Failed to connect to CodingMantra API at ${url}: ${fetchError?.message || fetchError}`);
47
+ }
24
48
  if (!response.ok) {
25
- let errorMsg = `API request failed with status ${response.status} ${response.statusText}`;
49
+ let errorMsg = `API request failed (${response.status} ${response.statusText})`;
26
50
  try {
27
51
  const errorData = await response.json();
28
- if (errorData?.error?.message) {
52
+ if (typeof errorData?.error === 'string') {
53
+ errorMsg += `: ${errorData.error}`;
54
+ }
55
+ else if (errorData?.error?.message) {
29
56
  errorMsg += `: ${errorData.error.message}`;
30
57
  }
58
+ else if (errorData?.message) {
59
+ errorMsg += `: ${errorData.message}`;
60
+ }
31
61
  else {
32
62
  errorMsg += `: ${JSON.stringify(errorData)}`;
33
63
  }
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * Extracts raw base64 data and MIME type from a data URI.
5
+ */
6
+ export function parseDataUri(dataUri) {
7
+ if (!dataUri || typeof dataUri !== 'string')
8
+ return null;
9
+ const match = dataUri.match(/^data:([^;]+);base64,(.+)$/);
10
+ if (match && match[1] && match[2]) {
11
+ return {
12
+ mimeType: match[1],
13
+ data: match[2],
14
+ };
15
+ }
16
+ return null;
17
+ }
18
+ /**
19
+ * Detects MIME type from a file path extension.
20
+ */
21
+ function getMimeTypeFromExt(filePath) {
22
+ const ext = path.extname(filePath).toLowerCase().replace('.', '');
23
+ switch (ext) {
24
+ case 'png':
25
+ return 'image/png';
26
+ case 'jpg':
27
+ case 'jpeg':
28
+ return 'image/jpeg';
29
+ case 'webp':
30
+ return 'image/webp';
31
+ case 'svg':
32
+ return 'image/svg+xml';
33
+ case 'gif':
34
+ return 'image/gif';
35
+ default:
36
+ return 'image/png';
37
+ }
38
+ }
39
+ /**
40
+ * Resolves an image input string. If it's a local file path on disk,
41
+ * reads it and converts to a base64 data URI.
42
+ * If already a URL or data URI, returns as is.
43
+ */
44
+ export function resolveImageInput(input) {
45
+ if (!input || typeof input !== 'string')
46
+ return '';
47
+ const trimmed = input.trim();
48
+ // Already a remote URL or data URI
49
+ if (trimmed.startsWith('data:') || trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
50
+ return trimmed;
51
+ }
52
+ // Check if it's a local file path
53
+ try {
54
+ const resolvedPath = path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
55
+ if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
56
+ const buffer = fs.readFileSync(resolvedPath);
57
+ const mimeType = getMimeTypeFromExt(resolvedPath);
58
+ return `data:${mimeType};base64,${buffer.toString('base64')}`;
59
+ }
60
+ }
61
+ catch {
62
+ // If any filesystem read error, fall through
63
+ }
64
+ return trimmed;
65
+ }
66
+ /**
67
+ * Helper to resolve an array of images or single image inputs.
68
+ */
69
+ export function resolveImagesArray(images) {
70
+ if (!images || !Array.isArray(images))
71
+ return [];
72
+ return images.map(item => {
73
+ const rawSrc = item.dataUrl || item.path || item.url || '';
74
+ const resolved = resolveImageInput(rawSrc);
75
+ if (resolved.startsWith('data:')) {
76
+ return { ...item, dataUrl: resolved };
77
+ }
78
+ return { ...item, url: resolved };
79
+ });
80
+ }
81
+ /**
82
+ * Standardizes synchronous image generation responses into MCP content.
83
+ * Returns both native ImageContent (for visual render in Claude/Cursor)
84
+ * and rich Markdown text.
85
+ */
86
+ export function formatImageToolResult(result, successTitle) {
87
+ const content = [];
88
+ const rawData = result?.data || result;
89
+ // Extract all potential image data URIs
90
+ const dataUris = [];
91
+ if (rawData?.photoDataUri)
92
+ dataUris.push(rawData.photoDataUri);
93
+ if (Array.isArray(rawData?.photoDataUris)) {
94
+ for (const uri of rawData.photoDataUris) {
95
+ if (uri && !dataUris.includes(uri))
96
+ dataUris.push(uri);
97
+ }
98
+ }
99
+ if (rawData?.qrCodeDataUrl)
100
+ dataUris.push(rawData.qrCodeDataUrl);
101
+ if (rawData?.upscaledImage)
102
+ dataUris.push(rawData.upscaledImage);
103
+ if (rawData?.output && typeof rawData.output === 'string' && rawData.output.startsWith('data:')) {
104
+ dataUris.push(rawData.output);
105
+ }
106
+ // Add native ImageContent blocks for each generated image
107
+ for (const uri of dataUris) {
108
+ const parsed = parseDataUri(uri);
109
+ if (parsed) {
110
+ content.push({
111
+ type: 'image',
112
+ data: parsed.data,
113
+ mimeType: parsed.mimeType,
114
+ });
115
+ }
116
+ }
117
+ // Build Markdown text summary
118
+ let text = `### ✅ ${successTitle}\n\n`;
119
+ const publicUrls = [];
120
+ if (rawData?.imageUrl)
121
+ publicUrls.push(rawData.imageUrl);
122
+ if (Array.isArray(rawData?.imageUrls)) {
123
+ for (const u of rawData.imageUrls) {
124
+ if (u && !publicUrls.includes(u))
125
+ publicUrls.push(u);
126
+ }
127
+ }
128
+ if (publicUrls.length > 0) {
129
+ if (publicUrls.length === 1) {
130
+ text += `**Public Image URL:** [View Full Resolution](${publicUrls[0]})\n\n`;
131
+ }
132
+ else {
133
+ text += `**Public Image URLs:**\n` + publicUrls.map((u, i) => `- [Image ${i + 1}](${u})`).join('\n') + `\n\n`;
134
+ }
135
+ }
136
+ if (dataUris.length > 0) {
137
+ text += `🖼️ **Inline Media:** Generated ${dataUris.length} image(s) rendered directly above.\n`;
138
+ }
139
+ text += `\n📁 **Gallery:** Output saved to your [CodingMantra Media Gallery](https://codingmantra.com/my-gallery).\n`;
140
+ content.push({
141
+ type: 'text',
142
+ text: text.trim(),
143
+ });
144
+ return { content };
145
+ }