code2img-mcp 0.0.0-stage → 0.1.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
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # code2img-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Model Context Protocol server for [Code2Img](https://code2img.app) — turn source code into
4
+ shareable images straight from Claude Desktop, Cursor, VS Code, Windsurf or any MCP client.
5
+
6
+ Seven tools: `render_code_image`, `list_themes`, `list_languages`, `list_backgrounds`,
7
+ `create_share_link`, `get_usage`, `get_share_urls`.
8
+
9
+ ## stdio (local install)
10
+
11
+ Not published on npm yet: `npx` installs the tarball served by the Code2Img instance.
12
+
13
+ ```bash
14
+ CODE2IMG_API_KEY=c2i_live_… npx -y --package https://code2img.app/downloads/code2img-mcp.tgz code2img-mcp
15
+ ```
16
+
17
+ Claude Desktop / Cursor / Windsurf (`claude_desktop_config.json`, `~/.cursor/mcp.json`,
18
+ `~/.codeium/windsurf/mcp_config.json`):
19
+
20
+ ```json
21
+ {
22
+ "mcpServers": {
23
+ "code2img": {
24
+ "command": "npx",
25
+ "args": ["-y", "--package", "https://code2img.app/downloads/code2img-mcp.tgz", "code2img-mcp"],
26
+ "env": { "CODE2IMG_API_KEY": "c2i_live_…" }
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ VS Code (`.vscode/mcp.json`) uses `"servers"` instead of `"mcpServers"`.
33
+
34
+ ## Remote (no install)
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "code2img": {
40
+ "type": "http",
41
+ "url": "https://code2img.app/mcp",
42
+ "headers": { "Authorization": "Bearer c2i_live_…" }
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ ```bash
49
+ claude mcp add --transport http code2img https://code2img.app/mcp \
50
+ --header "Authorization: Bearer c2i_live_…"
51
+ ```
52
+
53
+ ## Environment
54
+
55
+ | Variable | Default | Notes |
56
+ |---|---|---|
57
+ | `CODE2IMG_API_KEY` | — (required) | create one at <https://code2img.app/dashboard> |
58
+ | `CODE2IMG_API_URL` | `https://code2img.app/api` | point at a self-hosted instance |
59
+
60
+ ## Behaviour
61
+
62
+ - `render_code_image` returns the image **and** a public URL valid for 30 days.
63
+ - `create_share_link` renders once and returns a public page with an OpenGraph preview
64
+ (expires after 7 days by default; the code itself is never stored).
65
+ - Every call is billed against your API key quota — Free 30/min and 500/day, Pro 300/min
66
+ and 5000/day. Free renders carry a small code2img.app watermark.
67
+ - Errors come back as `isError` with the reason and the next action (bad key, exhausted
68
+ quota, render timeout).
69
+
70
+ License: MIT.
@@ -0,0 +1,26 @@
1
+ export declare const DEFAULT_API_URL = "https://code2img.app/api";
2
+ export interface Problem {
3
+ type?: string;
4
+ title?: string;
5
+ status?: number;
6
+ detail?: string;
7
+ }
8
+ /** Any non-2xx answer, with the next action spelled out for the calling LLM. */
9
+ export declare class ApiFailure extends Error {
10
+ readonly status: number;
11
+ readonly problem: Problem;
12
+ constructor(status: number, problem: Problem);
13
+ get hint(): string;
14
+ }
15
+ export declare class Api {
16
+ private readonly apiKey;
17
+ private readonly fetchImpl;
18
+ private readonly base;
19
+ constructor(apiKey: string, baseUrl?: string, fetchImpl?: typeof fetch);
20
+ private request;
21
+ json<T>(path: string, body?: unknown): Promise<T>;
22
+ bytes(path: string): Promise<{
23
+ data: Uint8Array;
24
+ mime: string;
25
+ }>;
26
+ }
package/dist/client.js ADDED
@@ -0,0 +1,62 @@
1
+ // Thin HTTP client for the Code2Img API. Written here rather than importing @code2img/sdk
2
+ // so the published npm package has no workspace dependency.
3
+ export const DEFAULT_API_URL = "https://code2img.app/api";
4
+ /** Any non-2xx answer, with the next action spelled out for the calling LLM. */
5
+ export class ApiFailure extends Error {
6
+ status;
7
+ problem;
8
+ constructor(status, problem) {
9
+ super(`Code2Img API ${status}: ${problem.title ?? "request failed"}${problem.detail ? ` — ${problem.detail}` : ""}`);
10
+ this.status = status;
11
+ this.problem = problem;
12
+ this.name = "ApiFailure";
13
+ }
14
+ get hint() {
15
+ switch (this.status) {
16
+ case 401:
17
+ return "The API key is missing, revoked or wrong. Create one at https://code2img.app/dashboard and pass it as CODE2IMG_API_KEY (stdio) or Authorization: Bearer <key> (remote).";
18
+ case 403:
19
+ return "This key lacks the scope for that call. Create a key with the write scope.";
20
+ case 429:
21
+ return "Quota exhausted for this minute or day. Wait and retry; upgrade to Pro for higher limits (https://code2img.app/pricing).";
22
+ case 504:
23
+ return "The render service timed out — shorten the snippet or retry once.";
24
+ default:
25
+ return this.problem.detail ? "Fix the arguments and retry." : "Retry once, then report the failure.";
26
+ }
27
+ }
28
+ }
29
+ export class Api {
30
+ apiKey;
31
+ fetchImpl;
32
+ base;
33
+ constructor(apiKey, baseUrl = DEFAULT_API_URL, fetchImpl = fetch) {
34
+ this.apiKey = apiKey;
35
+ this.fetchImpl = fetchImpl;
36
+ this.base = baseUrl.replace(/\/$/, "");
37
+ }
38
+ async request(path, init = {}) {
39
+ const res = await this.fetchImpl(`${this.base}${path}`, {
40
+ ...init,
41
+ headers: {
42
+ authorization: `Bearer ${this.apiKey}`,
43
+ ...(init.body instanceof FormData ? {} : { "content-type": "application/json" }),
44
+ ...init.headers,
45
+ },
46
+ });
47
+ if (!res.ok) {
48
+ const problem = (await res.json().catch(() => ({})));
49
+ throw new ApiFailure(res.status, problem);
50
+ }
51
+ return res;
52
+ }
53
+ json(path, body) {
54
+ return this.request(path, body === undefined ? {} : { method: "POST", body: JSON.stringify(body) }).then((r) => r.json());
55
+ }
56
+ bytes(path) {
57
+ return this.request(path).then(async (r) => ({
58
+ data: new Uint8Array(await r.arrayBuffer()),
59
+ mime: r.headers.get("content-type")?.split(";")[0] ?? "image/png",
60
+ }));
61
+ }
62
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare function serveMcp(req: Request, opts: {
2
+ apiKey: string;
3
+ baseUrl?: string;
4
+ fetch?: typeof fetch;
5
+ }): Promise<Response>;
package/dist/http.js ADDED
@@ -0,0 +1,13 @@
1
+ // Remote transport: Web-standard Streamable HTTP, stateless (one server per request, no
2
+ // session state to keep). Mounted by apps/web at POST/GET/DELETE /mcp.
3
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
4
+ import { createMcpServer } from "./server.js";
5
+ export async function serveMcp(req, opts) {
6
+ const server = createMcpServer(opts);
7
+ // Stateless: no session id, no resumability — every MCP message carries its own auth.
8
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
9
+ await server.connect(transport);
10
+ const res = await transport.handleRequest(req);
11
+ await server.close();
12
+ return res;
13
+ }
@@ -0,0 +1,2 @@
1
+ export { createMcpServer, SERVER_INFO, SERVER_INSTRUCTIONS } from "./server.js";
2
+ export { Api, ApiFailure, DEFAULT_API_URL } from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // Code2Img MCP server: one implementation, two transports — `./http` for the hosted
2
+ // endpoint (apps/web mounts it at /mcp) and the `code2img-mcp` bin for stdio.
3
+ export { createMcpServer, SERVER_INFO, SERVER_INSTRUCTIONS } from "./server.js";
4
+ export { Api, ApiFailure, DEFAULT_API_URL } from "./client.js";
@@ -0,0 +1,11 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ export declare const SERVER_INFO: {
3
+ readonly name: "code2img";
4
+ readonly version: "0.1.0";
5
+ };
6
+ export declare const SERVER_INSTRUCTIONS = "Code2Img turns source code into a shareable image (PNG/JPG).\n\nTypical flow: call render_code_image with the snippet, then send the returned URL or the\nattached image. Use list_themes, list_languages and list_backgrounds to discover valid ids\nbefore rendering \u2014 never invent one. Use create_share_link when the user wants a public,\nexpiring page (image + social preview) instead of raw bytes, and get_share_urls to find\nlinks you created earlier. get_usage reports the remaining quota when a call fails with 429.\n\nRenders are billed against your API key quota: Free 30 requests/min and 500/day, Pro\n300/min and 5000/day. Free renders carry a small code2img.app watermark.";
7
+ export declare function createMcpServer(opts: {
8
+ apiKey: string;
9
+ baseUrl?: string;
10
+ fetch?: typeof fetch;
11
+ }): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,233 @@
1
+ // The Code2Img MCP server: seven tools over the public API. The API is the trust boundary
2
+ // (quotas, entitlements, watermark), so every tool is a thin, honest HTTP call — one
3
+ // implementation shared by the hosted endpoint (/mcp) and the stdio package.
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { z } from "zod";
6
+ import { Api, ApiFailure } from "./client.js";
7
+ export const SERVER_INFO = { name: "code2img", version: "0.1.0" };
8
+ export const SERVER_INSTRUCTIONS = `Code2Img turns source code into a shareable image (PNG/JPG).
9
+
10
+ Typical flow: call render_code_image with the snippet, then send the returned URL or the
11
+ attached image. Use list_themes, list_languages and list_backgrounds to discover valid ids
12
+ before rendering — never invent one. Use create_share_link when the user wants a public,
13
+ expiring page (image + social preview) instead of raw bytes, and get_share_urls to find
14
+ links you created earlier. get_usage reports the remaining quota when a call fails with 429.
15
+
16
+ Renders are billed against your API key quota: Free 30 requests/min and 500/day, Pro
17
+ 300/min and 5000/day. Free renders carry a small code2img.app watermark.`;
18
+ // Every tool failure is one clear sentence plus the next action the model should take.
19
+ const failure = (e) => {
20
+ const message = e instanceof ApiFailure ? `${e.message}\n\nNext step: ${e.hint}` : `Unexpected error: ${e?.message ?? String(e)}`;
21
+ return { isError: true, content: [{ type: "text", text: message }] };
22
+ };
23
+ // Only the fields the caller actually set: the API applies its own defaults.
24
+ function configOf(a) {
25
+ const { background, ...rest } = a;
26
+ const config = { ...rest };
27
+ if (background)
28
+ config.background = { type: "gradient", preset: background };
29
+ return config;
30
+ }
31
+ const CODE = z
32
+ .string()
33
+ .min(1)
34
+ .max(50_000) // keep in sync with MAX_CODE_BYTES in @code2img/shared
35
+ .describe("The source code to render, exactly as it should appear. Keep it under 50 KB; long lines are clipped, not wrapped.");
36
+ const STYLE = {
37
+ language: z
38
+ .string()
39
+ .optional()
40
+ .describe('Shiki language id, e.g. "typescript", "python", "rust". Defaults to "auto" (detected from the code).'),
41
+ theme: z
42
+ .string()
43
+ .optional()
44
+ .describe('Shiki theme id, e.g. "github-dark", "dracula", "catppuccin-mocha". Call list_themes for the full list. Defaults to "github-dark".'),
45
+ font: z
46
+ .string()
47
+ .optional()
48
+ .describe('Monospace font id, e.g. "jetbrains-mono", "fira-code", "ibm-plex-mono". Defaults to "jetbrains-mono".'),
49
+ title: z.string().max(120).optional().describe('Window title shown in the card header, e.g. "app.ts" or "npm install".'),
50
+ fontSize: z.number().int().min(10).max(24).optional().describe("Code font size in px (10–24). Use 14–16 for a long snippet, 20+ for a short one."),
51
+ lineNumbers: z.boolean().optional().describe("Show line numbers in the gutter. Defaults to true."),
52
+ background: z
53
+ .string()
54
+ .optional()
55
+ .describe('Gradient preset id behind the card, e.g. "sunset", "ocean", "midnight". Call list_backgrounds for the full list. Defaults to "sunset".'),
56
+ };
57
+ export function createMcpServer(opts) {
58
+ const api = new Api(opts.apiKey, opts.baseUrl, opts.fetch);
59
+ const server = new McpServer(SERVER_INFO, { instructions: SERVER_INSTRUCTIONS });
60
+ server.registerTool("render_code_image", {
61
+ title: "Render code as an image",
62
+ description: "Use when the user wants a code screenshot, a snippet image for a slide, README or social post. " +
63
+ "Returns the image itself plus a public URL that stays valid for 30 days (safe to embed). " +
64
+ 'Example: code="npm install code2img", language="bash", theme="dracula", background="ocean". ' +
65
+ "Unsupported theme/language ids are still rendered (the API falls back to plain text), so prefer the ids from list_themes/list_languages.",
66
+ inputSchema: {
67
+ code: CODE,
68
+ ...STYLE,
69
+ format: z.enum(["png", "jpg"]).default("png").describe("Image format. png keeps crisp text and transparency, jpg is smaller."),
70
+ scale: z.number().int().min(1).max(4).default(2).describe("Pixel density: 1 = 1x, 2 = retina (default), 4 = Pro only (silently capped on Free)."),
71
+ },
72
+ annotations: { readOnlyHint: false, openWorldHint: false, idempotentHint: false },
73
+ }, async (args) => {
74
+ try {
75
+ const image = await api.json("/v1/images", {
76
+ config: configOf(args),
77
+ format: args.format,
78
+ scale: args.scale,
79
+ response_type: "url",
80
+ });
81
+ const { data, mime } = await api.bytes(`/v1/images/${image.id}`);
82
+ return {
83
+ content: [
84
+ { type: "image", data: Buffer.from(data).toString("base64"), mimeType: mime },
85
+ {
86
+ type: "text",
87
+ text: `Rendered ${args.format.toUpperCase()} (${data.length} bytes).\nURL (valid until ${image.expires_at}, no auth needed): ${image.url}`,
88
+ },
89
+ ],
90
+ };
91
+ }
92
+ catch (e) {
93
+ return failure(e);
94
+ }
95
+ });
96
+ server.registerTool("list_themes", {
97
+ title: "List syntax themes",
98
+ description: "Use before render_code_image when you need a valid theme id, or when the user asks which themes exist. " +
99
+ "Returns every Shiki theme id supported by Code2Img (dark and light).",
100
+ inputSchema: {},
101
+ annotations: { readOnlyHint: true, openWorldHint: false },
102
+ }, async () => {
103
+ try {
104
+ const { themes } = await api.json("/v1/themes");
105
+ return { content: [{ type: "text", text: `${themes.length} themes: ${themes.join(", ")}` }] };
106
+ }
107
+ catch (e) {
108
+ return failure(e);
109
+ }
110
+ });
111
+ server.registerTool("list_languages", {
112
+ title: "List languages",
113
+ description: "Use before render_code_image when unsure of a language id, or when the user asks which languages are supported. " +
114
+ 'Passing "auto" (the default) lets the API detect the language from the code.',
115
+ inputSchema: {},
116
+ annotations: { readOnlyHint: true, openWorldHint: false },
117
+ }, async () => {
118
+ try {
119
+ const { languages } = await api.json("/v1/languages");
120
+ return {
121
+ content: [{ type: "text", text: `"auto" plus ${languages.length} languages: ${languages.join(", ")}` }],
122
+ };
123
+ }
124
+ catch (e) {
125
+ return failure(e);
126
+ }
127
+ });
128
+ server.registerTool("list_backgrounds", {
129
+ title: "List backgrounds",
130
+ description: "Use before render_code_image when you need a valid background id. Returns the gradient presets " +
131
+ "(pass the id as `background`) and the decorative pattern names used by the editor.",
132
+ inputSchema: {},
133
+ annotations: { readOnlyHint: true, openWorldHint: false },
134
+ }, async () => {
135
+ try {
136
+ const { gradients, patterns } = await api.json("/v1/backgrounds");
137
+ return {
138
+ content: [
139
+ {
140
+ type: "text",
141
+ text: `Gradients: ${gradients.map((g) => `${g.id} (${g.name})`).join(", ")}\nPatterns: ${patterns.join(", ")}`,
142
+ },
143
+ ],
144
+ };
145
+ }
146
+ catch (e) {
147
+ return failure(e);
148
+ }
149
+ });
150
+ server.registerTool("create_share_link", {
151
+ title: "Create a public share page",
152
+ description: "Use when the user wants a link to send around rather than an image file: it renders the snippet, stores it " +
153
+ "and returns a public page with an OpenGraph preview (X, LinkedIn, Slack unfurl it). Expires by default after 7 days. " +
154
+ "The code itself is never stored — only the rendered image.",
155
+ inputSchema: {
156
+ code: CODE,
157
+ ...STYLE,
158
+ expiry: z
159
+ .enum(["1d", "7d", "30d", "never"])
160
+ .default("7d")
161
+ .describe('Lifetime of the public page: "1d", "7d" (default), "30d" or "never".'),
162
+ utm_campaign: z.string().max(40).optional().describe("Optional campaign name tagged on shared links opened from the page."),
163
+ },
164
+ annotations: { readOnlyHint: false, openWorldHint: false, idempotentHint: false },
165
+ }, async (args) => {
166
+ try {
167
+ const { utm_campaign, expiry, ...style } = args;
168
+ const share = await api.json("/v1/share", {
169
+ config: configOf(style),
170
+ expiry,
171
+ ...(utm_campaign ? { utm: { campaign: utm_campaign } } : {}),
172
+ });
173
+ return {
174
+ content: [
175
+ {
176
+ type: "text",
177
+ text: `Public page: ${share.url}\nExpires: ${share.expiresAt ?? "never"}\nSlug: ${share.slug}`,
178
+ },
179
+ ],
180
+ };
181
+ }
182
+ catch (e) {
183
+ return failure(e);
184
+ }
185
+ });
186
+ server.registerTool("get_usage", {
187
+ title: "Get API usage",
188
+ description: "Use when a call failed with 429, or when the user asks how much quota is left. Returns the plan, today's " +
189
+ "request and render counters, the per-minute and per-day limits, and the active key prefixes.",
190
+ inputSchema: {},
191
+ annotations: { readOnlyHint: true, openWorldHint: false },
192
+ }, async () => {
193
+ try {
194
+ const u = await api.json("/v1/usage");
195
+ return {
196
+ content: [
197
+ {
198
+ type: "text",
199
+ text: `Plan: ${u.plan} (${u.day})\n` +
200
+ `Today: ${u.api_calls} requests, ${u.renders} renders\n` +
201
+ `Quota: ${u.limits.remaining_minute}/${u.limits.per_minute} left this minute, ` +
202
+ `${u.limits.remaining_day}/${u.limits.per_day} left today`,
203
+ },
204
+ ],
205
+ };
206
+ }
207
+ catch (e) {
208
+ return failure(e);
209
+ }
210
+ });
211
+ server.registerTool("get_share_urls", {
212
+ title: "List my share pages",
213
+ description: "Use when the user asks for links created earlier, or to recover a share URL instead of rendering again. " +
214
+ "Returns the most recent public pages with their state (active, expired, deleted).",
215
+ inputSchema: {
216
+ limit: z.number().int().min(1).max(50).default(10).describe("How many recent pages to return (1–50)."),
217
+ },
218
+ annotations: { readOnlyHint: true, openWorldHint: false },
219
+ }, async (args) => {
220
+ try {
221
+ const { shares } = await api.json("/v1/share");
222
+ if (!shares.length) {
223
+ return { content: [{ type: "text", text: "No share pages yet. Use create_share_link to make one." }] };
224
+ }
225
+ const lines = shares.slice(0, args.limit).map((s) => `${s.url} — ${s.state}, created ${s.created_at}`);
226
+ return { content: [{ type: "text", text: `${shares.length} share page(s), newest first:\n${lines.join("\n")}` }] };
227
+ }
228
+ catch (e) {
229
+ return failure(e);
230
+ }
231
+ });
232
+ return server;
233
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/stdio.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // Stdio entry point: `npx code2img-mcp` from Claude Desktop, Cursor, VS Code, Windsurf.
3
+ // CODE2IMG_API_KEY is required; CODE2IMG_API_URL overrides the API base (self-hosted).
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { DEFAULT_API_URL } from "./client.js";
6
+ import { createMcpServer } from "./server.js";
7
+ const apiKey = process.env.CODE2IMG_API_KEY?.trim();
8
+ if (!apiKey) {
9
+ // stdout is the MCP channel: diagnostics go to stderr only.
10
+ console.error("code2img-mcp: set CODE2IMG_API_KEY (create one at https://code2img.app/dashboard)");
11
+ process.exit(1);
12
+ }
13
+ const server = createMcpServer({ apiKey, baseUrl: process.env.CODE2IMG_API_URL || DEFAULT_API_URL });
14
+ await server.connect(new StdioServerTransport());
15
+ console.error(`code2img-mcp ready (API: ${process.env.CODE2IMG_API_URL || DEFAULT_API_URL})`);
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "code2img-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Model Context Protocol server for Code2Img: render code screenshots from Claude Desktop, Cursor, VS Code or Windsurf (stdio), or call the hosted server at https://code2img.app/mcp.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "code2img-mcp": "./dist/stdio.js"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./http": {
16
+ "types": "./dist/http.d.ts",
17
+ "default": "./dist/http.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.build.json",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest run",
34
+ "prepublishOnly": "pnpm build"
35
+ },
36
+ "dependencies": {
37
+ "@modelcontextprotocol/sdk": "^1.32.2",
38
+ "zod": "^3.24.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.10.0",
42
+ "typescript": "^5.7.2",
43
+ "vitest": "^2.1.8"
44
+ }
6
45
  }