# Replicate FLUX.1 Kontext [Max] MCP Server
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
[](https://modelcontextprotocol.io/)
[](https://replicate.com/)
A Model Context Protocol (MCP) server that provides access to FLUX.1 Kontext [Max] - the frontier image generation model through the Replicate API. This server enables high-quality image generation with advanced text rendering capabilities and superior contextual understanding.
**š Repository**: [https://github.com/PierrunoYT/replicate-flux-kontext-max-mcp-server](https://github.com/PierrunoYT/replicate-flux-kontext-max-mcp-server)
> **š Ready to use!** Pre-built executable included - no compilation required.
>
> **ā
Enhanced Reliability**: Server handles missing API tokens gracefully without crashes and includes robust error handling.
## Features
- **Frontier Image Generation**: Uses FLUX.1 Kontext [Max] - the latest frontier model via Replicate API
- **Advanced Text Rendering**: Superior text integration and rendering capabilities
- **Contextual Understanding**: Enhanced understanding of complex prompts and context
- **Image Editing Support**: Both text-to-image and image editing capabilities
- **Automatic Image Download**: Generated images are automatically saved to local `images` directory
- **Multiple Aspect Ratios**: Support for 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 4:5, 5:4, 21:9, 9:21, 2:1, 1:2
- **Reproducible Results**: Optional seed parameter for consistent outputs
- **Prediction Management**: Track, monitor, and cancel running predictions
- **Flexible Output Formats**: Support for JPEG and PNG formats
- **Safety Controls**: Configurable safety tolerance levels (0-6)
- **Detailed Responses**: Returns both local file paths and original URLs with metadata
- **Robust Error Handling**: Graceful handling of missing API tokens without server crashes
- **Universal Portability**: Works anywhere with npx - no local installation required
- **Enhanced Reliability**: Graceful shutdown handlers and comprehensive error reporting
## Prerequisites
- Node.js 18 or higher
- Replicate API token
## Installation
### 1. Get your Replicate API Token
- Visit [Replicate](https://replicate.com/)
- Sign up for an account
- Navigate to your account settings
- Generate an API token (starts with `r8_`)
### 2. Clone or Download
```bash
git clone https://github.com/PierrunoYT/replicate-flux-kontext-max-mcp-server.git
cd replicate-flux-kontext-max-mcp-server
```
### 3. Install Dependencies (Optional)
The server is pre-built, but if you want to modify it:
```bash
npm install
npm run build
```
## Configuration
### š Recommended: Universal npx Configuration (Works Everywhere)
**Best option for portability** - works on any machine with Node.js:
```json
{
"mcpServers": {
"replicate-flux-kontext-max": {
"command": "npx",
"args": [
"-y",
"https://github.com/PierrunoYT/replicate-flux-kontext-max-mcp-server.git"
],
"env": {
"REPLICATE_API_TOKEN": "r8_your-replicate-api-token-here"
}
}
}
}
```
**Benefits:**
- ā
**Universal Access**: Works on any machine with Node.js
- ā
**No Local Installation**: npx downloads and runs automatically
- ā
**Always Latest Version**: Pulls from GitHub repository
- ā
**Cross-Platform**: Windows, macOS, Linux compatible
- ā
**Settings Sync**: Works everywhere you use your MCP client
### Alternative: Local Installation
If you prefer to install locally, use the path helper:
```bash
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):
```json
{
"mcpServers": {
"replicate-flux-kontext-max": {
"command": "node",
"args": ["path/to/replicate-flux-kontext-max-mcp-server/build/index.js"],
"env": {
"REPLICATE_API_TOKEN": "r8_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`
```json
{
"mcpServers": {
"replicate-flux-kontext-max": {
"command": "node",
"args": ["path/to/replicate-flux-kontext-max-mcp-server/build/index.js"],
"env": {
"REPLICATE_API_TOKEN": "r8_your-replicate-api-token-here"
},
"disabled": false,
"alwaysAllow": []
}
}
}
```
## Available Tools
### `flux_kontext_max_generate`
Generate images using FLUX.1 Kontext [Max] with real-time processing via Replicate.
**Parameters:**
- `prompt` (required): Text description of the image to generate, or instruction on how to edit the given image
- `input_image` (optional): Image to use as reference. Must be jpeg, png, gif, or webp. Can be a URL or base64 data URI
- `seed` (optional): Random seed for reproducible generation
- `aspect_ratio` (optional): "match_input_image", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "4:5", "5:4", "21:9", "9:21", "2:1", "1:2" (default: "match_input_image")
- `output_format` (optional): "jpg" or "png" (default: "jpg")
- `safety_tolerance` (optional): Safety level 0-6 (default: 2)
**Response includes:**
- Image URLs for immediate access
- Generation metadata (seed, prediction details)
- File information (content type, dimensions)
- Local file paths for downloaded images
### `flux_kontext_max_generate_async`
Generate images using FLUX.1 Kontext [Max] with async prediction tracking for monitoring progress.
**Parameters:** Same as `flux_kontext_max_generate`
**Use this tool when:**
- You want to monitor generation progress
- Working with complex prompts that might take longer
- Need detailed prediction tracking and logging
**Features:**
- Prediction-based processing with status polling
- 5-minute timeout with progress updates
- Detailed logging of generation progress
- Prediction ID returned for tracking
### `flux_kontext_max_cancel_prediction`
Cancel a running prediction by its ID.
**Parameters:**
- `prediction_id` (required): The ID of the prediction to cancel
**Use this tool when:**
- You need to stop a long-running generation
- Want to free up resources
- Made a mistake in the prompt and want to start over
### `flux_kontext_max_get_prediction`
Get the status and details of a prediction by its ID.
**Parameters:**
- `prediction_id` (required): The ID of the prediction to check
**Response includes:**
- Current prediction status
- Creation and completion timestamps
- Input parameters used
- Output results (if completed)
- Error details (if failed)
- Generation logs
## š„ **How Image Download Works**
The Replicate FLUX.1 Kontext [Max] MCP server automatically downloads generated images to your local machine. Here's the complete process:
### **1. Image Generation Flow**
1. **API Call**: Server calls Replicate's FLUX.1 Kontext [Max] API
2. **Response**: Replicate returns URLs for generated images
3. **Auto-Download**: Server immediately downloads images to local storage
4. **Response**: Returns both local paths and original URLs
### **2. Download Implementation**
#### **Download Function** ([`downloadImage`](src/index.ts:42-81)):
```typescript
async function downloadImage(url: string, filename: string): Promise<string> {
// 1. Parse the URL and determine HTTP/HTTPS client
const parsedUrl = new URL(url);
const client = parsedUrl.protocol === 'https:' ? https : http;
// 2. Create 'images' directory if it doesn't exist
const imagesDir = path.join(process.cwd(), 'images');
if (!fs.existsSync(imagesDir)) {
fs.mkdirSync(imagesDir, { recursive: true });
}
// 3. Create file write stream
const filePath = path.join(imagesDir, filename);
const file = fs.createWriteStream(filePath);
// 4. Download and pipe to file
client.get(url, (response) => {
response.pipe(file);
// Handle completion and errors
});
}
```
#### **Filename Generation** ([`generateImageFilename`](src/index.ts:84-93)):
```typescript
function generateImageFilename(prompt: string, index: number, seed?: number): string {
// Creates safe filename: flux_kontext_max_prompt_seed_index_timestamp.jpg
const safePrompt = prompt
.toLowerCase()
.replace(/[^a-z0-9\s]/g, '') // Remove special characters
.replace(/\s+/g, '_') // Replace spaces with underscores
.substring(0, 50); // Limit length
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const seedStr = seed ? `_${seed}` : '';
return `flux_kontext_max_${safePrompt}${seedStr}_${index}_${timestamp}.jpg`;
}
```
### **3. File Storage Details**
#### **Directory Structure:**
```
your-project/
āāā images/ # Auto-created directory
ā āāā flux_kontext_max_mountain_landscape_123456_1_2025-06-24T18-30-45-123Z.jpg
ā āāā flux_kontext_max_cute_robot_789012_1_2025-06-24T18-31-20-456Z.jpg
ā āāā ...
```
#### **Filename Format:**
- **Prefix**: `flux_kontext_max_`
- **Prompt**: First 50 chars, sanitized (alphanumeric + underscores)
- **Seed**: Random seed used for generation (if provided)
- **Index**: Image number (for multiple images)
- **Timestamp**: ISO timestamp for uniqueness
- **Extension**: `.jpg` or `.png` based on output_format
### **4. Response Format**
The server returns both local and remote information:
```
Successfully generated 1 image(s) using FLUX.1 Kontext [Max] via Replicate:
Prompt: "a serene mountain landscape with text 'FLUX' painted in white"
Aspect Ratio: 1:1
Output Format: jpg
Safety Tolerance: 2
Seed: 1234567890
Generated Images:
Image 1:
Local Path: /path/to/project/images/flux_kontext_max_a_serene_mountain_landscape_1234567890_1_2025-06-24T18-30-45-123Z.jpg
Original URL: https://replicate.delivery/pbxt/...
Filename: flux_kontext_max_a_serene_mountain_landscape_1234567890_1_2025-06-24T18-30-45-123Z.jpg
Images have been downloaded to the local 'images' directory.
```
## Example Usage
### Basic Image Generation
```
Generate a photorealistic image of a golden retriever playing in a field of sunflowers with the text "HAPPY DOG" written in bold letters
```
### With Specific Parameters
```
Generate an image with:
- Prompt: "A minimalist logo design for a tech startup, clean lines, with 'STARTUP' text"
- Aspect ratio: 16:9
- Output format: png
- Seed: 12345
```
### Advanced Usage with Text Rendering
```
Generate an image of "A futuristic cityscape at night with neon lights and flying cars, large billboard displaying 'FUTURE CITY 2025'"
with aspect ratio 21:9 and seed 12345 for reproducible results
```
### Text-Heavy Prompts (Kontext [Max] Specialty)
```
Create an image of a vintage bookstore with multiple book spines showing titles like "The Art of Code", "Digital Dreams", and "Future Stories" clearly readable
```
### Image Editing Examples
#### Basic Image Editing
```
Edit this image to add a rainbow in the sky
Input image: https://example.com/landscape.jpg
```
#### Complex Image Editing
```
Edit the image with:
- Prompt: "Add a donut next to the flour on the counter"
- Input image: https://replicate.delivery/pbxt/example.png
- Output format: png
```
#### Text Addition to Images
```
Add the text "SALE 50% OFF" in bold red letters to this storefront image
Input image: https://example.com/storefront.jpg
```
### Prediction Management
#### Track Generation Progress
```
Use flux_kontext_max_generate_async to start generation, then use flux_kontext_max_get_prediction with the returned prediction ID to monitor progress
```
#### Cancel Long-Running Generation
```
Use flux_kontext_max_cancel_prediction with the prediction ID if you need to stop generation
```
## 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**: `black-forest-labs/flux-kontext-max` on Replicate
- **Method**: Both direct `run()` and prediction-based `predictions.create()`
### Error Handling
- **Graceful API token handling**: Server continues running even without REPLICATE_API_TOKEN set
- **No crash failures**: Removed `process.exit()` calls that caused connection drops
- **Null safety checks**: All tools validate API client availability before execution
- **Graceful shutdown**: Proper SIGINT and SIGTERM signal handling
- **API error catching**: Comprehensive error reporting with detailed context
- **Timeout handling**: Robust async request management with progress updates
- **User-friendly messages**: Clear error descriptions instead of technical crashes
## 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 JavaScript
- `npm run dev` - Watch mode for development
- `npm run start` - Start the server directly
- `npm run test` - Test server startup and basic functionality
- `npm run get-path` - Get configuration path for your system
### Making Changes
1. Edit files in the `src/` directory
2. Run `npm run build` to compile
3. Restart your MCP client to use the updated server
### Testing
```bash
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](https://replicate.com/pricing) for current rates.
**Typical costs** (as of 2024):
- FLUX.1 Kontext [Max]: ~$0.05-0.15 per image
- Costs vary by resolution and complexity
## Troubleshooting
### Server not appearing in MCP client
1. **Recommended**: Use the npx configuration for universal compatibility
2. If using local installation, verify the path to `build/index.js` is correct and absolute
3. Ensure Node.js 18+ is installed: `node --version`
4. Test server startup: `npm run test`
5. Restart your MCP client (Claude Desktop, Kilo Code, etc.)
6. **Note**: Server will start successfully even without REPLICATE_API_TOKEN - check tool responses for API token errors
### Image generation failing
1. Verify your Replicate API token is valid and has sufficient credits
2. Check that your prompt follows Replicate's content policy
3. Try simplifying the prompt or adjusting parameters
4. Use the async tool for complex requests
5. Check the server logs for detailed error messages
6. Ensure the FLUX.1 Kontext [Max] model is available in your region
### Build issues
If you need to rebuild the server:
```bash
npm install
npm run build
```
### Configuration issues
Use the helper script to get the correct path:
```bash
npm run get-path
```
## Support
For issues with:
- **This MCP server**: Create an issue in this repository
- **Replicate API**: Check [Replicate documentation](https://replicate.com/docs)
- **MCP Protocol**: See [MCP documentation](https://modelcontextprotocol.io/)
## License
MIT License - see [LICENSE](LICENSE) file for details.
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test with `npm run test`
5. Submit a pull request
## Changelog
### v1.2.0 (Latest)
- **š API Migration**: Migrated from FAL AI to Replicate API
- **š New Tools**: Added `flux_kontext_max_cancel_prediction` and `flux_kontext_max_get_prediction`
- **š Prediction Management**: Full prediction lifecycle management with tracking
- **š§ Enhanced Async**: Improved async generation with detailed progress monitoring
- **š”ļø Better Error Handling**: Enhanced error reporting and graceful degradation
- **š Updated Documentation**: Comprehensive documentation for Replicate integration
- **ā” Performance**: Optimized image download and processing pipeline
### v1.1.0 (Previous)
- **⨠NEW: Image Editing**: Added FLUX.1 Kontext [Max] image editing capabilities
- **š§ New Tools**: `flux_kontext_max_edit` and `flux_kontext_max_edit_async` for image editing
- **š¼ļø Image Input Support**: Accept image URLs and base64 data URIs for editing
- **šØ Advanced Editing**: Complex image modifications with contextual understanding
- **š Text Addition**: Add text overlays and modifications to existing images
- **š Dual Editing Methods**: Both real-time and async queue-based image editing
- **š„ Auto-download**: Edited images automatically saved with descriptive filenames
### v1.0.0 (Initial)
- **šØ Image Generation**: Basic FLUX.1 Kontext [Max] text-to-image generation
- **š„ Auto-download**: Automatic local image saving
- **š§ MCP Integration**: Full Model Context Protocol support
- **āļø Configuration**: Easy setup with environment variables