iflow-mcp_lns2905-nano-banana-mcp 0.1.0
MCP server for Nano Banana image generation using Gemini Web API
Requires Python: >=3.10

# Nano Banana MCP

MCP Server for image generation using Gemini Web API (reverse-engineered).

> ⚠️ **Disclaimer**: This project uses unofficial API access via browser cookies. Use at your own risk.

## Features

- 🎨 **Text-to-Image Generation**: Create images from text prompts
- ✏️ **Image Editing**: Modify existing images with natural language
- 💬 **Chat**: Interact with Gemini for text and image generation
- 🎯 **App Icon Generation**: Generate professional app icons with:
  - Automatic background removal (rembg/RMBG 2.0)
  - Platform presets (iOS, Android, macOS, Web)
  - Multiple sizes generation
  - Shape masks (squircle, rounded, circle)
- 🔲 **Pattern Generation**: Create seamless patterns and textures
- 📊 **Diagram Generation**: Generate technical diagrams and flowcharts
- 🖼️ **Banner/Thumbnail Generation**: Social media and YouTube ready

## Architecture

```
┌─────────────────┐     MCP Protocol     ┌──────────────────┐
│   AI Client     │◄───────────────────►│  nano-banana-mcp │
│ (Claude, etc.)  │                      │     (Python)     │
└─────────────────┘                      └────────┬─────────┘
                                                  │
                                                  │ gemini_webapi
                                                  ▼
                                         ┌──────────────────┐
                                         │  Gemini Web UI   │
                                         │  (Google Server) │
                                         └──────────────────┘
```

## Prerequisites

- Python 3.10+
- Google account with Gemini access
- Browser cookies from gemini.google.com

## Installation

```bash
# Clone the repository
git clone <your-repo-url>
cd nano-banana-mcp

# Install with pip (basic)
pip install -e .

# Or with uv
uv pip install -e .
```

### Optional Dependencies

#### Background Removal (for App Icons)

Choose one of the following options:

```bash
# Option 1: rembg (Recommended - lightweight, CPU-only)
pip install rembg[cpu]

# Option 2: rembg with GPU acceleration
pip install rembg[gpu]

# Option 3: RMBG 2.0 (Best quality - requires more resources)
pip install transformers torch torchvision
```

**Background Removal Engines Comparison:**

| Engine | Quality | Speed | Size | GPU Required |
|--------|---------|-------|------|--------------|
| `rmbg2` (BRIA RMBG 2.0) | **Best (90%)** | Medium | ~500MB | Optional (faster with CUDA) |
| `rembg` + `isnet-general-use` | Excellent | Medium | 170MB | No |
| `rembg` + `isnet-anime` | Excellent | Medium | 170MB | No (best for icons) |
| `rembg` + `silueta` | Good | **Fastest** | 43MB | No |
| `rembg` + `u2netp` | Good | Fast | 4.7MB | No |

**Environment Variables for Background Removal:**

```bash
# Choose engine: 'rembg' (default) or 'rmbg2' (best quality)
BG_REMOVAL_ENGINE=rembg

# Choose rembg model (if using rembg engine)
REMBG_MODEL=isnet-general-use  # Options: u2netp, isnet-general-use, isnet-anime, silueta, birefnet-general
```

## Configuration

### 1. Get Your Cookies (Important!)

> ⚠️ **Cookie Expiration**: The `__Secure-1PSIDTS` cookie expires frequently (sometimes in minutes). Follow these **community-tested tips** to maximize cookie lifespan:

#### Best Practices for Long-Lasting Cookies:

1. **Use Incognito Mode** (Highly Recommended)
   - Open an incognito/private browser window
   - Log in to [gemini.google.com](https://gemini.google.com)
   - Get your cookies from there
   - Cookies obtained in incognito can last weeks/months

2. **Close Gemini Immediately After Getting Cookies**
   - After copying cookies, **close the Gemini tab immediately**
   - Keeping Gemini open in browser causes cookies to expire faster
   - Don't visit gemini.google.com while using this tool

3. **Use a Dedicated Google Account**
   - Cookies expire faster when the account is used actively elsewhere
   - Consider creating a separate account just for API access

4. **When Cookies Expire**
   - Usually only `__Secure-1PSIDTS` expires first
   - Try updating just PSIDTS using the `set_cookie` tool
   - If that fails, get fresh `__Secure-1PSID` as well

#### Steps to Get Cookies:

1. Open **Incognito window** (Ctrl+Shift+N / Cmd+Shift+N)
2. Go to [gemini.google.com](https://gemini.google.com) and log in
3. Open DevTools (F12) → Application → Cookies
4. Copy the value of `__Secure-1PSID` (required)
5. Copy `__Secure-1PSIDTS` if available (some accounts don't have it)
6. **Close the Gemini tab immediately**

### 2. Set Environment Variables

Create a `.env` file:

```bash
# Required
GEMINI_SECURE_1PSID=your_cookie_value_here

# Optional
GEMINI_SECURE_1PSIDTS=your_cookie_value_here
NANOBANANA_OUTPUT_DIR=./nanobanana-output
NANOBANANA_MODEL=gemini-2.0-flash-exp
NANOBANANA_TIMEOUT=60
```

### 3. Configure MCP Client

Add to your MCP client config (e.g., Claude Desktop):

```json
{
  "mcpServers": {
    "nano-banana": {
      "command": "nano-banana-mcp",
      "env": {
        "GEMINI_SECURE_1PSID": "your_cookie_value"
      }
    }
  }
}
```

Or with Python directly:

```json
{
  "mcpServers": {
    "nano-banana": {
      "command": "python",
      "args": ["-m", "nano_banana_mcp.server"],
      "cwd": "/path/to/nano-banana-mcp",
      "env": {
        "GEMINI_SECURE_1PSID": "your_cookie_value"
      }
    }
  }
}
```

## Usage

### Generate Image

```
Generate an image of a sunset over mountains
```

### Edit Image

```
Edit my_photo.png: add sunglasses to the person
```

### Generate Icon

```
Create an app icon for a music player app
```

**Advanced icon generation:**
```
Generate app icon for a fitness app with platform=ios, style=gradient, shape=squircle
```

Available options:
- `platform`: `ios`, `android`, `web`, `macos`, `all`
- `style`: `flat-design`, `modern`, `minimalist`, `3d-render`, `isometric`, `gradient`, `glassmorphism`
- `shape`: `squircle` (iOS style), `rounded`, `circle`, `square`
- `remove_background`: `true`/`false`
- `background_color`: hex color like `#FF5733` or named color

### Generate Pattern

```
Create a seamless geometric pattern in blue tones
```

### Generate Diagram

```
Create a flowchart for user authentication
```

## Available Tools

| Tool | Description |
|------|-------------|
| `generate_image` | Generate images from text prompts with style/mood options |
| `edit_image` | Edit existing images with natural language |
| `chat` | General chat with image support |
| `generate_app_icon` | Generate app icons with background removal & platform presets |
| `generate_banner` | Generate banners (16:9, 21:9 aspect ratios) |
| `generate_thumbnail` | Generate YouTube/video thumbnails |
| `generate_logo` | Generate logo designs |
| `generate_pattern` | Generate seamless patterns and textures |
| `generate_diagram` | Generate technical diagrams and flowcharts |
| `generate_illustration` | Generate artistic illustrations |
| `generate_social_post` | Generate social media images |
| `generate_product_photo` | Generate product photography |
| `set_cookie` | Update expired cookies |

## Output

Generated images are saved to `./nanobanana-output/` by default.

## Troubleshooting

### "SECURE_1PSIDTS could get expired frequently"
This is the most common error. Solutions in order of priority:

1. **Get cookies from incognito mode** and close Gemini tab immediately
2. **Use `set_cookie` tool** to update just the PSIDTS value
3. **Update PSID as well** - sometimes PSID itself expires (per community feedback)
4. **Use a dedicated Google account** that isn't used elsewhere

### "Missing GEMINI_SECURE_1PSID"
- Ensure you copied the correct cookie value
- Cookie value should start with `g.a...`

### "Image generation failed"
- Check if your Google account has Gemini access
- Try a simpler prompt
- Cookies may have expired - check the error message

### Rate Limiting
- Wait between requests if you encounter errors
- Avoid rapid successive requests

## Keep-Alive Feature

This MCP server includes an automatic **keep-alive mechanism** that helps extend cookie lifespan:

- Sends background pings every 30 minutes
- Automatically refreshes `__Secure-1PSIDTS` when possible
- **Requirement**: The MCP server process must stay running continuously

The keep-alive works best with cookies obtained from incognito mode on a dedicated account.

## Limitations

- ⚠️ Cookies can expire (use incognito + dedicated account to minimize)
- ⚠️ May be rate-limited by Google
- ⚠️ API can change without notice
- ⚠️ Not suitable for production use

## License

MIT

## Disclaimer

This project is for educational purposes only. It uses unofficial API access and may violate Google's Terms of Service. Use responsibly and at your own risk.