Replicate Imagen 4 MCP Server
Access Google's Imagen 4 Ultra model via the Replicate platform for high-quality image generation.
Replicate Imagen 4 MCP Server
A Model Context Protocol (MCP) server that provides access to Google's Imagen 4 Ultra model through the Replicate platform. This server enables high-quality image generation with enhanced detail, richer lighting, and fewer artifacts.
š Repository: https://github.com/PierrunoYT/replicate-imagen4-mcp-server
š Ready to use! Works everywhere with npx - no local installation required.
Features
- High-Quality Image Generation: Uses Google's Imagen 4 Ultra model via Replicate
- Automatic Image Download: All generated images are automatically downloaded to local storage
- Organized File Management: Images saved to dedicated 'images' directory with smart naming
- Multiple Aspect Ratios: Support for 1:1, 16:9, 9:16, 3:4, and 4:3
- Multiple Output Formats: JPG and PNG support
- Safety Filtering: Configurable content safety levels
- Dual Access: Returns both local file paths and original URLs
- Prediction Tracking: Check status of running predictions
- Portable Installation: Works anywhere with npx + GitHub
- Robust Error Handling: Graceful handling of missing tokens and API errors
- Connection Stability: No more unexpected disconnections or crashes
- Detailed Responses: Returns image URLs, metadata, and generation details
Prerequisites
- Node.js 18 or higher
- Replicate API token
Installation
Option 1: Portable Installation (Recommended)
The easiest way to use this MCP server is with npx, which works anywhere without local installation:
{
"mcpServers": {
"replicate-imagen4": {
"command": "npx",
"args": ["-y", "https://github.com/PierrunoYT/replicate-imagen4-mcp-server.git"],
"env": {
"REPLICATE_API_TOKEN": "your_token_here"
}
}
}
}
Option 2: Local Installation
For local development or if you prefer to clone the repository:
git clone https://github.com/PierrunoYT/replicate-imagen4-mcp-server.git
cd replicate-imagen4-mcp-server
npm install
npm run build
Setup
1. Get your Replicate API Token
- Visit Replicate
- Sign up for an account
- Navigate to your account settings
- Generate an API token
2. Set Environment Variable
Set the REPLICATE_API_TOKEN environment variable:
export REPLICATE_API_TOKEN=r8_NBY**********************************
Or create a .env
file:
REPLICATE_API_TOKEN=r8_NBY**********************************
Automatic Image Download
š„ How It Works
All generated images are automatically downloaded to your local machine for persistent storage and offline access:
1. Image Generation Flow
- API Call: Server calls Replicate's Imagen 4 Ultra API
- Response: Replicate returns an output object with URL method
- Auto-Download: Server immediately downloads images to local storage
- Response: Returns both local paths and original URLs
2. File Organization
Directory Structure:
your-project/
āāā images/ # Auto-created directory
ā āāā imagen4_mountain_landscape_1_2025-06-24T18-30-45-123Z.jpg
ā āāā imagen4_cute_robot_1_2025-06-24T18-31-20-456Z.png
ā āāā ...
Filename Format:
- Prefix:
imagen4_
- Prompt: First 50 chars, sanitized (alphanumeric + underscores)
- Index: Image number (for multiple images)
- Timestamp: ISO timestamp for uniqueness
- Extension:
.jpg
or.png
based on output format
3. Benefits
ā
Persistent Storage: Images saved locally, not just temporary URLs
ā
Offline Access: View images without internet connection
ā
Organized Storage: All images in dedicated images
directory
ā
Unique Naming: No filename conflicts with timestamp system
ā
Fallback Safety: Original URLs provided if download fails
Configuration
Quick Setup Helper
Run the path helper to get the exact configuration for your system:
npm run get-path
This will output the complete MCP configuration with the correct absolute path.
For Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json
(macOS) or %APPDATA%\Claude\claude_desktop_config.json
(Windows):
{
"mcpServers": {
"replicate-imagen4": {
"command": "node",
"args": ["path/to/replicate-imagen4-mcp-server/build/index.js"],
"env": {
"REPLICATE_API_TOKEN": "your-replicate-api-token-here"
}
}
}
}
For Kilo Code MCP Settings
Add to your MCP settings file at:
C:\Users\[username]\AppData\Roaming\Kilo-Code\MCP\settings\mcp_settings.json
{
"mcpServers": {
"replicate-imagen4": {
"command": "node",
"args": ["path/to/replicate-imagen4-mcp-server/build/index.js"],
"env": {
"REPLICATE_API_TOKEN": "your-replicate-api-token-here"
},
"disabled": false,
"alwaysAllow": []
}
}
}
Available Tools
imagen4_generate
Generate images using Imagen 4 Ultra with automatic local download.
Parameters:
prompt
(required): Text prompt for image generationaspect_ratio
(optional): "1:1", "9:16", "16:9", "3:4", or "4:3" (default: "1:1")safety_filter_level
(optional): "block_low_and_above", "block_medium_and_above", or "block_only_high" (default: "block_only_high")output_format
(optional): "jpg" or "png" (default: "jpg")
Features:
- Automatic Download: Images automatically saved to local 'images' directory
- Smart Naming: Generates descriptive filenames based on prompt and timestamp
- Dual Access: Returns both local file paths and original URLs
- Error Resilience: Graceful fallback if download fails
Response includes:
- Local file path for immediate access
- Original image URL as backup
- Generation metadata and settings
- Download status information
imagen4_generate_and_save
Generate images using Imagen 4 Ultra with custom filename support and automatic download.
Parameters:
prompt
(required): Text prompt for image generationfilename
(optional): Custom filename for the image (default: auto-generated)aspect_ratio
(optional): "1:1", "9:16", "16:9", "3:4", or "4:3" (default: "1:1")safety_filter_level
(optional): "block_low_and_above", "block_medium_and_above", or "block_only_high" (default: "block_only_high")output_format
(optional): "jpg" or "png" (default: "jpg")
Features:
- Custom Naming: Use your own filename for the image
- Auto-Download: Images automatically saved to 'images' directory
- Dual Access: Returns both local file paths and original URLs
- Error Resilience: Graceful fallback if download fails
imagen4_get_prediction
Get the status and result of a specific Replicate prediction.
Parameters:
prediction_id
(required): The ID of the prediction to check
Use this tool to:
- Check the status of long-running predictions
- Get detailed logs and error information
- Retrieve results from async operations
Example Usage
Basic Image Generation
Generate a photorealistic image of a golden retriever playing in a field of sunflowers
With Specific Parameters
Generate an image with:
- Prompt: "A minimalist logo design for a tech startup, clean lines"
- Aspect ratio: 16:9
- Output format: png
- Safety filter: block_medium_and_above
Generate and Save to File
Generate and save an image of "A futuristic cityscape at night with neon lights and flying cars"
to "cityscape.jpg" with 16:9 aspect ratio
Using the Replicate API Directly
Here's how to use the Replicate API directly in your own code:
import { writeFile } from "fs/promises";
import Replicate from "replicate";
const replicate = new Replicate();
const input = {
prompt: "The photo: Create a cinematic, photorealistic medium shot capturing the nostalgic warmth of a mid-2000s indie film. The focus is a young woman with a sleek, straight bob haircut in cool platinum white with freckled skin, looking directly and intently into the camera lens with a knowing smirk, her head is looking up slightly. She wears an oversized band t-shirt that says \"Imagen 4 Ultra on Replicate\" in huge stylized text over a long-sleeved striped top and simple silver stud earrings. The lighting is soft, golden hour sunlight creating lens flare and illuminating dust motes in the air. The background shows a blurred outdoor urban setting with graffiti-covered walls (the graffiti says \"ultra\" in stylized graffiti lettering), rendered with a shallow depth of field. Natural film grain, a warm, slightly muted color palette, and sharp focus on her expressive eyes enhance the intimate, authentic feel",
aspect_ratio: "16:9"
};
const output = await replicate.run("google/imagen-4-ultra", { input });
// To access the file URL:
console.log(output.url());
//=> "https://replicate.delivery/.../output.jpg"
// To write the file to disk:
await writeFile("output.jpg", output);
//=> output.jpg written to disk
Technical Details
Architecture
- Language: TypeScript with ES2022 target
- Runtime: Node.js 18+ with ES modules
- Protocol: Model Context Protocol (MCP) SDK v1.0.0
- API Client: Replicate JavaScript client v0.34.1
- Validation: Zod schema validation
API Model Used
- Model:
google/imagen-4-ultra
on Replicate - Capabilities: High-quality image generation with advanced safety filtering
Error Handling
- Environment variable validation
- API error catching and reporting
- Network error handling for file downloads
- Detailed error messages with context
Development
Project Structure
āāā src/
ā āāā index.ts # Main MCP server implementation
āāā build/ # Compiled JavaScript (ready to use)
āāā test-server.js # Server testing utility
āāā get-path.js # Configuration path helper
āāā example-mcp-config.json # Example configuration
āāā package.json # Project metadata and dependencies
āāā tsconfig.json # TypeScript configuration
Scripts
npm run build
- Compile TypeScript to JavaScriptnpm run dev
- Watch mode for developmentnpm run start
- Start the server directlynpm run test
- Test server startup and basic functionalitynpm run get-path
- Get configuration path for your system
Making Changes
- Edit files in the
src/
directory - Run
npm run build
to compile - Restart your MCP client to use the updated server
Testing
npm run test
This runs a basic connectivity test that verifies:
- Server starts correctly
- MCP protocol initialization
- Tool discovery functionality
API Costs
This server uses the Replicate platform, which charges per image generation. Check Replicate pricing for current rates.
Typical costs (as of 2024):
- Imagen 4 Ultra: ~$0.05-0.10 per image
- Costs vary by resolution and complexity
Authentication
The Replicate API uses token-based authentication. Your token should be kept secure and not included in your code. Always use environment variables:
export REPLICATE_API_TOKEN=r8_NBY**********************************
You can test your authentication with:
curl https://api.replicate.com/v1/account -H "Authorization: Bearer $REPLICATE_API_TOKEN"
Troubleshooting
Server not appearing in MCP client
- Verify the path to
build/index.js
is correct and absolute - Check that your REPLICATE_API_TOKEN is set correctly in the environment variables
- Ensure Node.js 18+ is installed:
node --version
- Test server startup:
npm run test
- Restart your MCP client (Claude Desktop, Kilo Code, etc.)
Image generation failing
- Verify your Replicate API token is valid and has sufficient credits
- Check that your prompt follows Replicate's content policy
- Try adjusting the safety filter level
- Check the server logs for detailed error messages
- Use the
imagen4_get_prediction
tool to check prediction status
Build issues
If you need to rebuild the server:
npm install
npm run build
Configuration issues
Use the helper script to get the correct path:
npm run get-path
Support
For issues with:
- This MCP server: Create an issue in this repository
- Replicate API: Check Replicate documentation
- MCP Protocol: See MCP documentation
License
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Test with
npm run test
- Submit a pull request
Related Servers
MCP Forge
Generate MCP servers using Smithery with Cursor IDE integration.
PHP MCP Server
Provides semantic PHP code analysis and refactoring tools, enabling AI assistants to perform safe, intelligent code transformations at the AST level.
Scorecard
Access Scorecard's AI model evaluation and testing tools via a Cloudflare Workers deployment.
eBPF MCP
A secure MCP server for eBPF, designed for AI integration, kernel introspection, and automation.
Blockchain Vulnerability Analyzer
Analyzes blockchain smart contracts for vulnerabilities using Mythril and Slither.
MCP Bridge API
A lightweight, LLM-agnostic RESTful proxy that unifies multiple MCP servers under a single API.
Chrome DevTools MCP
Debug web applications by connecting to Chrome's developer tools via the Chrome DevTools Protocol.
MCP Sandbox
An interactive sandbox to safely execute Python code and install packages in isolated Docker containers.
MCP Bridge
A proxy server that enables existing REST APIs to be used as Model Context Protocol (MCP) servers.
SolTracker
Access real-time and historical token, wallet, and trading data from the Solana ecosystem via the Solana Tracker API.