# Midjourney MCP Server

A Model Context Protocol (MCP) server that provides Midjourney image generation capabilities through the MJ API.

## 🚀 Quick Start

1. **Install and run directly:**
   ```bash
   npx midjourney-mcp
   ```

2. **Add to Claude Desktop** (`claude_desktop_config.json`):
   ```json
   {
     "mcpServers": {
       "midjourney": {
         "command": "npx",
         "args": ["midjourney-mcp"]
       }
     }
   }
   ```

3. **Start creating images:**
   ```
   "Create a cyberpunk cityscape at night with neon lights, 16:9 aspect ratio"
   ```

**That's it!** The server is pre-configured with working API credentials.

## Features

- **Text-to-Image Generation**: Create images using Midjourney with text prompts
- **Task Status Tracking**: Monitor the progress of image generation tasks
- **Flexible Parameters**: Support for aspect ratios, quality settings, and styles
- **Easy Integration**: Works with any MCP-compatible host (Claude Desktop, Zed, etc.)

## Installation

### Using npx (Recommended)

```bash
npx midjourney-mcp
```

### Global Installation

```bash
npm install -g midjourney-mcp
midjourney-mcp
```

### Local Development

```bash
git clone <repository-url>
cd midjourney-mcp
npm install
npm run build
npm run dev
```

## Configuration

Set your MJ API key as an environment variable:

```bash
export MJ_API_KEY="sk-your-api-key-here"
```

### Optional Environment Variables

- `MJ_BASE_URL`: API base URL (default: "https://aiclound.vip")
- `MJ_TIMEOUT`: Request timeout in milliseconds (default: 30000)
- `MJ_MAX_RETRIES`: Maximum retry attempts (default: 3)

## Usage with Claude Desktop

Add the following to your Claude Desktop configuration file:

### macOS
`~/Library/Application Support/Claude/claude_desktop_config.json`

### Windows
`%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "midjourney": {
      "command": "npx",
      "args": ["midjourney-mcp"],
      "env": {
        "MJ_API_KEY": "sk-your-api-key-here"
      }
    }
  }
}
```

## Available Tools

### 🎨 midjourney_imagine
Generate images using text prompts with full parameter support.

**Parameters:**
- `prompt` (required): Text description of the image to generate
- `aspect_ratio` (optional): Image aspect ratio (1:1, 16:9, 9:16, 4:3, 3:4, 2:3, 3:2, 5:4, 4:5)
- `quality` (optional): Image quality (low, medium, high)
- `style` (optional): Style setting (raw, stylize)
- `model` (optional): Midjourney model (midjourney, niji, niji-5, niji-6)
- `chaos` (optional): Chaos level 0-100 (variation amount)
- `stylize` (optional): Stylization level 0-1000 (artistic level)
- `weird` (optional): Weirdness level 0-3000 (unusual results)
- `seed` (optional): Seed for reproducible results
- `no` (optional): Negative prompt (things to avoid)
- `reference_images` (optional): Array of base64 encoded reference images

### 📋 midjourney_get_task
Check the status and results of any Midjourney task.

**Parameters:**
- `task_id` (required): The ID of the task to check

### 📈 midjourney_upscale
Upscale a specific image from a completed generation.

**Parameters:**
- `task_id` (required): The ID of the completed generation task
- `index` (required): Which image to upscale (1-4)

### 🎲 midjourney_variation
Create variations of a specific image.

**Parameters:**
- `task_id` (required): The ID of the completed generation task
- `index` (required): Which image to create variations of (1-4)

### 🔄 midjourney_reroll
Regenerate a task with the same prompt but different results.

**Parameters:**
- `task_id` (required): The ID of the task to reroll

### 🎭 midjourney_blend
Blend 2-5 images together to create a new combined image.

**Parameters:**
- `images` (required): Array of 2-5 base64 encoded images to blend
- `aspect_ratio` (optional): Aspect ratio for the blended image

### 📝 midjourney_describe
Generate text descriptions of images that could be used as prompts.

**Parameters:**
- `image` (required): Base64 encoded image to describe

### ⚡ midjourney_action
Execute button actions on completed tasks (Zoom, Pan, etc.).

**Parameters:**
- `task_id` (required): The ID of the task with available actions
- `action` (required): The action to perform (button label or custom ID)

## Example Usage

Once configured with Claude Desktop, you can use natural language to generate images:

```
"Create a beautiful sunset over mountains with aspect ratio 16:9"
"Generate a portrait of a cat in high quality using niji model"
"Make an abstract art piece with high chaos and stylization"
"Check the status of task 1748519117239161"
"Upscale image 1 from my last generation"
"Create variations of image 2"
```

## ✨ Recent Improvements (v1.1.0)

### Enhanced User Experience
- **🎨 Improved Response Format**: All tools now provide clear, actionable feedback with emojis and structured information
- **⏱️ Real-time Duration Tracking**: See how long tasks have been running with automatic duration calculation
- **🔍 Smart Status Detection**: Automatic detection of stuck tasks (>15 minutes) with helpful troubleshooting suggestions
- **💡 Better Guidance**: Clear next steps and usage tips for every operation, including estimated completion times

### Advanced Task Management
- **📊 Comprehensive Status Reports**: Detailed task information with optional debug mode showing raw API responses
- **🖼️ Direct Image Display**: Generated images are displayed directly in responses using proper image content types
- **🎮 Organized Action Buttons**: Clear categorization of upscale (U1-U4), variation (V1-V4), and reroll options
- **⚠️ Stuck Task Detection**: Automatic warnings for tasks running longer than expected with actionable advice

### Improved Tool Responses
- **Immediate Feedback**: All submission tools now return task IDs immediately with clear status information
- **Estimated Timing**: Realistic time estimates for different operations (30-90s for imagine, 30-60s for upscale, etc.)
- **Usage Examples**: Built-in examples showing how to use follow-up actions
- **Error Handling**: Better error messages with actionable suggestions and troubleshooting tips

## ✅ Test Status

**Last Tested**: 2025-05-29
**Status**: 🎉 All core functions working perfectly

### Successful Test Results
- ✅ Server startup and MCP protocol compliance
- ✅ All 8 tools correctly registered and responding
- ✅ Imagine tool: Successfully submitted and completed task ID `1748526068622289`
- ✅ Task status queries working with enhanced progress reports and image display
- ✅ Parameter validation and comprehensive error handling
- ✅ API authentication and communication
- ✅ Claude Desktop integration ready and tested

### Example Successful Generation
```
Prompt: "画个小猫：一只可爱的小猫，用卡通风格绘制，带有柔和的色彩和梦幻般的背景"
Parameters: 1:1 aspect ratio, medium quality
Result: Task ID 1748526068622289 completed successfully in 3m 20s
Generated Image: Available with U1-U4 upscale and V1-V4 variation options
```

## Development

### Project Structure

```
midjourney-mcp/
├── src/
│   ├── index.ts          # Main server entry point
│   ├── tools/
│   │   └── midjourney.ts # Midjourney tool implementations
│   └── utils/
│       └── config.ts     # Configuration management
├── build/                # Compiled JavaScript
├── package.json
└── tsconfig.json
```

### Scripts

- `npm run build`: Compile TypeScript to JavaScript
- `npm run watch`: Watch for changes and recompile
- `npm run dev`: Build and run the server
- `npm run inspector`: Debug with MCP inspector

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
