Back to Blog

MCP Server Image Generation Example: A Complete Walkthrough

Andrew Adams

Andrew Adams

·10 min read
MCP Server Image Generation Example: A Complete Walkthrough

Looking for a working MCP server image generation example? This guide walks through the full pattern: defining an MCP tool, wiring it to a real image model backend, and registering it in Claude Desktop so an AI agent can generate images on command. We use Wireflow as the generation backend because it exposes published workflows as plain REST endpoints, which keeps the MCP server itself to under a hundred lines of code.

What an MCP Image Generation Server Actually Is

The Model Context Protocol (MCP) is a standard that lets AI assistants like Claude call external tools. An MCP server is a small program that advertises one or more tools (each with a name, a description, and a JSON schema for inputs) and executes them when the assistant asks. For image generation, that means the server accepts a text prompt from the model, forwards it to an image API, and returns the resulting image URL. If you have compared orchestration options before, the trade-offs resemble the ones covered in n8n vs MCP for video automation: MCP is conversational and agent-driven, while traditional automation is trigger-driven.

Most open-source examples follow the same three-part shape. There is a tool definition (what the assistant sees), a handler (the code that runs), and a backend call (the API that does the actual generation). The backend is the part that varies: some servers call Replicate, some call Together AI, some call OpenAI's image endpoint directly. The pattern in this walkthrough uses a published workflow as the backend, the same approach described on the Replicate MCP feature page, which is the companion page for this article and shows the finished setup in action.

The Example Architecture

Here is the flow we are building, end to end. Claude Desktop (or any MCP client) connects to a local MCP server over stdio. The server exposes one tool, generate_image, that takes a prompt string. When called, the handler POSTs the prompt to a workflow execution endpoint, polls until the run completes, and returns the output image URL back to the assistant. This is the same execute-and-poll pattern used in chaining multiple AI models in one API call, just wrapped in an MCP tool.

The reason to put a workflow behind the tool, rather than a raw model API, is flexibility. A workflow can start as a single text-to-image node and later grow an upscale step or a background removal step without changing a line of MCP server code. The tool contract stays prompt in, image URL out while the pipeline behind it evolves. Teams that outgrow single-model calls usually end up here anyway, as the chain AI models API page explains.

MCP server architecture connecting an AI assistant to an image generation backend

Step 1: Define the MCP Tool

Every MCP server starts with a tool definition. Using the official TypeScript SDK, the skeleton looks like this:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "image-gen", version: "1.0.0" });

server.tool(
  "generate_image",
  "Generate an image from a text prompt. Returns a hosted image URL.",
  { prompt: z.string().describe("What the image should show") },
  async ({ prompt }) => {
    const url = await runImageWorkflow(prompt);
    return { content: [{ type: "text", text: url }] };
  }
);

await server.connect(new StdioServerTransport());

The description strings matter more than they look. The assistant decides when to call your tool based on them, so be specific: "Generate an image from a text prompt" gets called for image requests, while a vague "run workflow" often gets ignored. Keep input schemas small; a single prompt field covers most use cases, and you can add optional size or style fields later. For inspiration on what a production-grade node catalog looks like behind such a tool, browse the node-based image generation tools roundup.

Step 2: Wire the Handler to a Generation Backend

Now the runImageWorkflow function. Wireflow's API uses an async execute-and-poll pattern: you start a run, get an execution id back, and poll until the state flips to COMPLETED. Authentication is a Bearer key generated from the dashboard (Settings > API Keys, keys start with sk-). The full endpoint reference lives at wireflow.ai/docs/api/workflows.

const BASE = "https://www.wireflow.ai/api/v1";
const KEY = process.env.WIREFLOW_API_KEY;

async function runImageWorkflow(prompt) {
  // 1. Start the run
  const exec = await fetch(`${BASE}/workflows/${process.env.WORKFLOW_ID}/execute`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": crypto.randomUUID(),
    },
    body: JSON.stringify({ triggerData: { prompt } }),
  }).then(r => r.json());

  // 2. Poll with exponential backoff (start 1s, x1.5, cap 10s)
  let wait = 1000;
  while (true) {
    await new Promise(r => setTimeout(r, wait));
    const run = await fetch(`${BASE}/workflows/executions/${exec.executionId}/poll`, {
      headers: { Authorization: `Bearer ${KEY}` },
    }).then(r => r.json());
    if (run.status === "COMPLETED") return extractImageUrl(run);
    if (run.status === "FAILED") throw new Error(run.error);
    wait = Math.min(wait * 1.5, 10000);
  }
}

Two details are worth copying even if you use a different backend. First, the Idempotency-Key header: if your MCP client retries a request, identical keys within 24 hours replay the original response instead of generating (and billing) a duplicate image. Second, the backoff curve: polling every 500ms hammers the API for a generation that takes 15 to 30 seconds anyway. Rate limits are per plan (10 requests per minute on Free, 60 on Pro), and every response carries X-RateLimit-Remaining so your handler can slow down before hitting a 429. If you plan to fan out many generations at once, the batch image generation API page covers the higher-throughput pattern.

Execute and poll request cycle between an MCP handler and a workflow API

Step 3: Register the Server in Claude Desktop

With the server built, register it in the MCP client. For Claude Desktop, add an entry to claude_desktop_config.json:

{
  "mcpServers": {
    "image-gen": {
      "command": "node",
      "args": ["/path/to/image-gen-server/index.js"],
      "env": {
        "WIREFLOW_API_KEY": "sk-your-api-key",
        "WORKFLOW_ID": "your-workflow-id"
      }
    }
  }
}

Restart the client and ask for an image: "generate an image of a lighthouse at dusk." The assistant recognizes the request matches your tool description, calls generate_image, and posts back the hosted URL. The same server works in Cursor, Cline, and any other MCP-compatible client with equivalent config. If your agent work centers on video rather than stills, the connect Claude to video editing guide applies the identical pattern to a video pipeline.

Alternative: Skip the API Key With a Webhook Trigger

There is a lighter variant worth knowing. Published workflows can also be triggered through a webhook endpoint that requires no API key on the trigger call: POST /api/v1/workflow/{webhookId}/trigger returns a 202 with an execution id, and you poll the result with your key afterward. This is useful when the MCP server runs somewhere you would rather not store credentials for the trigger step, or when a form or CI job shares the same pipeline. The webhook pattern is documented at wireflow.ai/docs/api/webhooks, and the MCP server for video editing page shows it applied to a heavier media pipeline.

Which Integration Pattern Fits Your Setup

Pattern Auth on trigger Best for Latency handling
MCP tool + execute endpoint Bearer key Agent-driven, conversational generation Poll with backoff
Webhook trigger None (poll needs key) Forms, CI, Zapier-style automation Poll or fire-and-forget
Direct model API Provider key One-off scripts, single model Usually synchronous
Self-hosted stack Your infra Full control, custom models You build the queue

If the self-hosted row tempts you, read the honest cost breakdown in the self-hosted image generation API guide first; GPU idle time usually costs more than metered API calls until volume gets serious.

Comparison of MCP, webhook, and direct API integration patterns for image generation

Common Mistakes in MCP Image Generation Servers

A few failure modes show up repeatedly in community MCP servers. Returning base64 image blobs instead of URLs bloats the assistant's context window and often breaks rendering; return a hosted URL and let the client fetch it. Skipping error handling on the poll loop leaves the assistant hanging when a run fails; surface the FAILED state with the error message so the agent can retell the user or retry with a fixed prompt. Hardcoding one model into the tool means every model upgrade is a code change; pointing the tool at a workflow id moves that decision into a visual editor. And ignoring the 402 insufficient-credits response (which includes a per-node credit breakdown) turns a billing issue into a mystery timeout. Model choice itself matters less than the plumbing; current options are compared in the Midjourney alternatives for AI image generation roundup.

Checklist of common failure modes when building an MCP image generation tool

Try it yourself: the exact backend used in this example is live as a published workflow. Open the MCP Prompt to Image workflow to see the nodes, run it, and grab its workflow id for the WORKFLOW_ID variable in Step 2.

FAQ

What is an MCP server for image generation?

It is a small program implementing the Model Context Protocol that exposes an image generation tool to AI assistants. The assistant sends a text prompt, the server calls an image API or workflow, and returns the generated image URL.

Do I need to write my own MCP server, or do prebuilt ones exist?

Prebuilt open-source servers exist for Replicate, Together AI, and OpenAI backends. Writing your own is worth it when you want the backend to be a multi-step pipeline (generate, then upscale, then remove background) rather than a single model call.

Which language should I build an MCP server in?

TypeScript and Python have official SDKs and the most examples. The protocol itself is transport-agnostic JSON-RPC, so anything that can speak stdio or HTTP works.

How does the MCP server authenticate with the image backend?

With a standard Bearer API key stored in the server's environment variables, never in the client config committed to a repo. Wireflow keys are created in the dashboard, start with sk-, and are shown only once.

How long does image generation take through an MCP tool?

Typically 10 to 40 seconds depending on the model and pipeline depth. That is why the execute-and-poll pattern matters: the tool starts the run, polls asynchronously, and only responds when the output is ready.

Can one MCP tool trigger a multi-model pipeline?

Yes. If the tool points at a workflow id instead of a raw model endpoint, the workflow can chain several models (generation, editing, upscaling) while the tool contract stays a single prompt in and a URL out.

What happens if the assistant calls the tool twice with the same prompt?

Without protection, you pay for two generations. Sending an Idempotency-Key header on the execute call makes identical requests within 24 hours replay the original response instead of running again.

Is there a rate limit I should design around?

Yes. Execution starts are capped at 10 per minute across all plans, and request limits range from 10 per minute on Free to 200 on Enterprise. Read the X-RateLimit-Remaining header and back off before you hit a 429.

Conclusion

An MCP server image generation example does not need to be complicated: one tool definition, one execute call, one poll loop, and a config entry. The design decision that pays off most is putting a workflow behind the tool instead of a raw model endpoint, because the pipeline can grow without touching the MCP layer. Wireflow makes that backend a visual canvas with 157 nodes across image, video, and audio, so the same tool you built today can be producing upscaled, background-removed product shots next month with zero server changes. Start with the workflow linked above, drop its id into the Step 2 code, and your assistant can generate images by the end of the afternoon.