# GPT-Image-1 MCP Server

A Model Context Protocol (MCP) server that provides image generation, editing, and management capabilities using OpenAI's GPT-Image-1 model.

## Features

- **Image Generation**: Generate high-quality images from text prompts
- **Image Editing**: Edit existing images with new prompts
- **Image Management**: Store, retrieve, and manage generated images
- **History Tracking**: Track all image generations with metadata
- **Comprehensive Logging**: Full logging and error handling
- **TypeScript Support**: Fully typed with TypeScript

## Installation

### Via npm (Recommended)

```bash
npm install -g @graisol/gpt-image-mcp
```

### From Source

1. Clone the repository:
```bash
git clone https://github.com/GRAIsol/gpt-image-mcp.git
cd gpt-image-mcp
```

2. Install dependencies:
```bash
npm install
```

3. Build the project:
```bash
npm run build
```

## Configuration

### Command Line Usage

```bash
# Using npm global installation
gpt-image-mcp --api-key your_openai_api_key_here

# Using npx
npx @graisol/gpt-image-mcp --api-key your_openai_api_key_here

# Show help
gpt-image-mcp --help
```

### Environment Variables (Optional)

You can also use environment variables for configuration:

```env
# Required (if not provided via --api-key)
OPENAI_API_KEY=your_openai_api_key_here

# Optional
OPENAI_ORG_ID=your_org_id_here
DEFAULT_IMAGE_SIZE=1024x1024
DEFAULT_IMAGE_QUALITY=high
DEFAULT_MODERATION=auto
IMAGE_STORAGE_PATH=./mcp-images
MAX_STORED_IMAGES=100
LOG_LEVEL=2
LOG_FILE=./logs/server.log
```

## Usage

### Development Mode
```bash
npm run dev
```

### Production Mode
```bash
npm run build
npm start
```

## MCP Integration

### Claude Code CLI (Recommended)

The Claude Code CLI requires environment variables to be passed using the `--env` flag.

If you installed the package globally via npm:

```bash
claude mcp add gpt-image-mcp gpt-image-mcp --env OPENAI_API_KEY=your_openai_api_key_here
```

Or using npx:

```bash
claude mcp add gpt-image-mcp npx @graisol/gpt-image-mcp --env OPENAI_API_KEY=your_openai_api_key_here
```

If you built from source:

```bash
claude mcp add gpt-image-mcp node /PATH/TO/YOUR/PROJECT/gpt-image-mcp/build/index.js --env OPENAI_API_KEY=your_openai_api_key_here
```

Replace `your_openai_api_key_here` with your actual OpenAI API key.

### Claude Desktop Configuration

For Claude Desktop, add the following to your configuration file:

**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

If you installed via npm:

```json
{
  "mcpServers": {
    "gpt-image-1": {
      "command": "npx",
      "args": ["@graisol/gpt-image-mcp", "--api-key", "your_openai_api_key_here"]
    }
  }
}
```

Or using environment variables:

```json
{
  "mcpServers": {
    "gpt-image-1": {
      "command": "npx",
      "args": ["@graisol/gpt-image-mcp"],
      "env": {
        "OPENAI_API_KEY": "your_openai_api_key_here"
      }
    }
  }
}
```

If you built from source:

```json
{
  "mcpServers": {
    "gpt-image-1": {
      "command": "node",
      "args": ["/path/to/your/gpt-image-mcp/build/index.js"],
      "env": {
        "OPENAI_API_KEY": "your_openai_api_key_here"
      }
    }
  }
}
```

### Cursor IDE

For Cursor IDE, add the following to your `.cursor/mcp.json` configuration file:

```json
{
  "gpt-image-1": {
    "command": "node",
    "args": ["./build/index.js"],
    "cwd": "/path/to/gpt-image-mcp",
    "env": {
      "OPENAI_API_KEY": "your_openai_api_key_here"
    }
  }
}
```

Or using the npm global installation:

```json
{
    "mcpServers": {
      "gpt-image-mcp": {
        "command": "npx",
        "args": ["@graisol/gpt-image-mcp@latest", "--api-key", "your-api-key-here"]
      }
    }
  }
```

### VS Code (with MCP Extensions)

For VS Code with MCP support extensions, add the following to your workspace settings (`.vscode/settings.json`):

```json
{
  "mcp.servers": {
    "gpt-image-1": {
      "command": "node",
      "args": ["/path/to/gpt-image-mcp/build/index.js"],
      "env": {
        "OPENAI_API_KEY": "your_openai_api_key_here"
      }
    }
  }
}
```

Or using the npm global installation:

```json
{
  "mcp.servers": {
    "gpt-image-1": {
      "command": "npx",
      "args": ["@graisol/gpt-image-mcp", "--api-key", "your_openai_api_key_here"]
    }
  }
}
```

### Other IDEs

For other IDEs and editors, refer to their specific MCP integration documentation. Most follow similar JSON configuration patterns with `command`, `args`, and `env` parameters.

## MCP Tools

### `generate_image`
Generate images from text prompts.

**Parameters:**
- `prompt` (required): Text description of the image
- `n` (optional): Number of images to generate (1-10, default: 1)
- `size` (optional): Image size - '1024x1024', '1024x1536', '1536x1024', or 'auto' (default: 1024x1024)
- `quality` (optional): Image quality - 'low', 'medium', or 'high' (default: medium)
- `background` (optional): Background type - 'transparent', 'opaque', or 'auto' (default: auto)
- `output_compression` (optional): Compression level (0-100)
- `moderation` (optional): Moderation level - 'auto' or 'low' (default: auto)
- `output_format` (optional): Output format - 'png', 'jpeg', or 'webp' (default: png)

**Example:**
```json
{
  "prompt": "A futuristic cityscape at sunset with flying cars",
  "n": 2,
  "size": "1536x1024",
  "quality": "high",
  "background": "opaque",
  "output_format": "png"
}
```

### `edit_image`
Edit existing images with new prompts.

**Parameters:**
- `image` (required): Base64 encoded image or image URL
- `prompt` (required): Text description of desired changes
- `mask` (optional): Mask PNG for inpainting edits
- `n` (optional): Number of images to generate (1-10, default: 1)
- `size` (optional): Output image size - '1024x1024', '1024x1536', '1536x1024', or 'auto'
- `quality` (optional): Image quality - 'low', 'medium', or 'high'
- `background` (optional): Background type - 'transparent', 'opaque', or 'auto'
- `output_compression` (optional): Compression level (0-100)
- `moderation` (optional): Moderation level - 'auto' or 'low'
- `output_format` (optional): Output format - 'png', 'jpeg', or 'webp'

**Example:**
```json
{
  "image": "data:image/png;base64,iVBORw0KGgoAAAANS...",
  "prompt": "Add a rainbow in the sky",
  "size": "1024x1024"
}
```

### `get_image_info`
Get detailed information about a generated image.

**Parameters:**
- `image_id` (required): ID of the image

**Example:**
```json
{
  "image_id": "img_1640995200000_abc123def456"
}
```

### `list_generations`
List recent image generations with optional filtering.

**Parameters:**
- `limit` (optional): Maximum number of results (default: 10)
- `offset` (optional): Number of results to skip (default: 0)
- `filter` (optional): Filter by prompt content

**Example:**
```json
{
  "limit": 20,
  "offset": 0,
  "filter": "sunset"
}
```

## API Response Format

All tools return responses in the following format:

```json
{
  "content": [
    {
      "type": "text",
      "text": "JSON-formatted result"
    }
  ]
}
```

## Supported Image Sizes

- `1024x1024` (square format, default)
- `1024x1536` (portrait format)
- `1536x1024` (landscape format)
- `auto` (automatic sizing based on prompt context)

## Error Handling

The server provides comprehensive error handling with detailed error messages:

- **400 Bad Request**: Invalid request parameters
- **401 Unauthorized**: Invalid API key
- **403 Forbidden**: Access denied or organization verification required
- **404 Not Found**: Model or endpoint not found
- **429 Rate Limited**: Too many requests
- **500 Internal Server Error**: OpenAI service temporarily unavailable

## Storage

Generated images and metadata are stored locally in the configured storage directory:

- `./mcp-images/` - Default storage location
- `generation_history.json` - Image generation history
- `{image_id}.json` - Individual image metadata files
- `{image_id}.png` - Base64 images (if stored locally)

## Logging

The server includes comprehensive logging with configurable levels:

- **ERROR (0)**: Error messages only
- **WARN (1)**: Warning and error messages
- **INFO (2)**: Informational, warning, and error messages (default)
- **DEBUG (3)**: All messages including debug information

## Development

### Project Structure
```
gpt-image-mcp/
├── src/
│   ├── types/          # TypeScript type definitions
│   ├── utils/          # Utility functions
│   │   ├── openai-client.ts
│   │   ├── image-manager.ts
│   │   └── logger.ts
│   ├── tools/          # MCP tool implementations
│   │   └── index.ts
│   └── index.ts        # Main server entry point
├── build/              # Compiled JavaScript output
├── mcp-images/         # Image storage directory
├── package.json
├── tsconfig.json
└── README.md
```

### Building
```bash
npm run build
```

### Running Tests
```bash
npm test
```

## License

MIT License

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## Support

For issues and questions, please open an issue on the GitHub repository.
