# MooseCP Image Server

A Model Context Protocol (MCP) server designed to provide LLMs with efficient, token-optimized visual access to image directories and AI generation capabilities. Instead of dumping full-resolution images (which waste tokens and cause context overflow), MooseCP provides a hierarchical workflow: **List $\rightarrow$ Scan $\rightarrow$ Preview $\rightarrow$ Inspect**.

## ⚠️ AI SLOP DISCLAIMER
This entire project was vibe-coded by an AI. It is 100% slop code. Use it at your own risk.

## 🚨 SECURITY WARNING
**This server is designed to be run on `localhost` ONLY.** 
It contains tools (such as `read_image` and `list_directory`) that allow the LLM to read arbitrary files from your filesystem. If you expose this server to the network or a public IP, any user or compromised AI could potentially read sensitive system files (e.g., SSH keys, `/etc/passwd`). 
**NEVER run this server on a public-facing IP without implementing strict path validation.**

## Tools Overview

### 📁 `list_directory`
Provides a simplified file-browser view of a directory.
*   **Best for**: Getting a sense of the files present and their basic metadata (size, date).
*   **Features**: Pagination and sorting by name, size, or modification date.

### 🖼️ `contact_sheet`
Generates a high-density grid of thumbnails.
*   **Best for**: Quickly scanning hundreds of images to find a specific one or get a general "vibe" of a folder.
*   **Note**: This tool is paginated. You must iterate through pages to see all images in a folder.
*   **Workflow**: Use the indices shown on the contact sheet to call `preview_image`.

### 🔍 `preview_image`
Provides medium-detail previews optimized for the model's token budget.
*   **Best for**: Comparing a few candidates, inspecting specific details, or selecting a "favorite" image.
*   **Efficiency**: Automatically calculates dimensions to fit the model's patch size (e.g., 48px patches for Gemma 4), ensuring maximum detail without wasting tokens on padding.
*   **Workflow**: Pass indices from the `contact_sheet` or a direct file path.

### 📖 `read_png_metadata`
Extracts AI generation parameters from PNG files.
*   **Best for**: Retrieving prompts, seeds, and model hashes from AI-generated images.

### 📸 `read_image`
Returns the full-resolution image.
*   **Best for**: Final confirmation or deep visual analysis where every pixel counts.

### 🎨 `generate_image`
Triggers an image generation on a local Stable Diffusion WebUI Forge instance.
*   **Workflow**: Always call `get_model_info` first to determine the correct prompting style (e.g., tag-based vs. natural language).
*   **Features**: Supports model-specific presets, resolution presets, and standard parameter overrides.
*   **Output**: Returns a Base64 image for AI analysis and a proxy URL for direct embedding in the chat.

### ℹ️ `get_model_info`
Provides the "manual" for available generation models.
*   **Best for**: Learning the prompting style, recommended settings, and available resolution presets for a specific model.
*   **Workflow**: Call without arguments to see the catalog; call with `model_name` for the detailed guide.

### 🏷️ `search_tags`
Searches the Danbooru tag database for recognized tags and aliases.
*   **Best for**: Finding the correct booru-style tags, checking tag popularity, and resolving aliases (e.g., 'lesbian' → 'yuri').
*   **Workflow**: Provide a query string to get a list of the most popular matching tags.

### 🌐 `browse_wikipedia`
Allows the model to browse Wikipedia using its API.
*   **Best for**: Quickly retrieving summaries, structural maps (ToC), or specific section content from Wikipedia without dumping the entire page.
*   **Workflow**: Use `mode='summary'` (default) to get an overview and a Table of Contents. Use `mode='section'` with a linear index from the ToC to dive into specific details.
*   **Features**: Returns raw Wikitext to save tokens, handles redirects, and automatically falls back to a search result list if a page is not found.

---

## Installation & Requirements

### Dependencies
This server requires Python 3.10+ and the following packages:
*   `uvicorn`: ASGI server for the SSE transport.
*   `starlette`: Lightweight ASGI framework.
*   `Pillow`: Image processing and thumbnail generation.
*   `requests`: For communicating with the Stable Diffusion API.
*   `httpx`: For asynchronous API requests (e.g., Wikipedia).

```bash
pip install -r requirements.txt
```

### Setup
1.  Clone this repository to your server.
2.  (Optional) Edit `config.py` to adjust the server port, log level, or token budgets if you are using a model other than Gemma 4.
3.  Run the server:
    ```bash
    python main.py
    ```

## Configuration (`config.py`)

Tuning the server's behavior is done via `config.py`.

### 🌐 Server & Logging
| Parameter | Description | Default |
| :--- | :--- | :--- |
| `HOST` | The network address the server binds to. | `"127.0.0.1"` |
| `PORT` | The port the server listens on. | `8000` |
| `LOG_LEVEL` | Logging verbosity (`DEBUG`, `INFO`, `WARNING`, `ERROR`). | `"WARNING"` |
| `LOG_FILE` | Absolute path to the server log file. | `ROOT_DIR / "debug.log"` |
| `USER_AGENT` | User-Agent string for API requests (e.g., Wikipedia). | Browser-like string |

### 🎨 Stable Diffusion Integration
| Parameter | Description | Default |
| :--- | :--- | :--- |
| `SD_URL` | Base URL of the SD WebUI/Forge instance. | `"http://127.0.0.1:7860"` |
| `MODEL_PRESETS_PATH` | Path to the `model_presets.toml` file. | `ROOT_DIR / "model_presets.toml"` |
| `RES_PRESETS_PATH` | Path to the `resolution_presets.toml` file. | `ROOT_DIR / "resolution_presets.toml"` |
| `TAG_DATABASE_PATH` | Path to the Danbooru `tags.csv` file. | (Path to extension folder) |
| `TAG_SEARCH_LIMIT` | Number of results returned by `search_tags` (direct or similar). | `20` |

### 🧠 Model & Token Tuning (Optimized for Gemma 4)
| Parameter | Description | Default |
| :--- | :--- | :--- |
| `PATCH_SIZE` | Model's vision patch size in pixels. | `48` |
| `PREVIEW_TOKEN_BUDGET` | Target token count for `preview_image` thumbnails. | `70` |
| `CONTACT_SHEET_COLS` | Number of columns in the contact sheet grid. | `10` |
| `CONTACT_SHEET_ROWS` | Number of rows in the contact sheet grid. | `7` |
| `CONTACT_SHEET_THUMB_SIZE` | Pixel size of thumbnails in the contact sheet. | `192` |

### 🖼️ Image & Font Settings
| Parameter | Description | Default |
| :--- | :--- | :--- |
| `IMAGE_QUALITY` | JPEG compression quality (1-100). | `95` |
| `SYSTEM_FONT_NAMES` | List of font names for Pillow to try in system paths. | Arial, DejaVu, etc. |
| `FALLBACK_FONT_PATHS` | List of absolute paths to `.ttf` files. | Linux-specific paths |
