# MCP Server & Tools

> OpenGen serves two stateless Streamable HTTP MCP endpoints. The /mcp endpoint exposes all 15 read and write tools behind OAuth 2.1 or API key auth, while /mcp/readonly exposes 9 read-only tools including 4 zero-auth public discovery tools (find_models, get_model, estimate_cost, search_docs). Both publish RFC 9728 metadata, CORS headers, and standard Accept compatibility.

## Agent Prompt

```text
Connect to OpenGen over Streamable HTTP MCP using https://opengen.dev/docs/mcp:
1. For zero-auth discovery, send JSON-RPC POST requests to https://opengen.dev/mcp/readonly and call find_models, get_model, estimate_cost, or search_docs (or read opengen://skill and opengen://pricing).
2. For private workspace reads and paid generations, connect to https://opengen.dev/mcp with OAuth 2.1 DCR+PKCE (discovered at https://opengen.dev/.well-known/oauth-protected-resource/mcp) or an OpenGen Bearer token.
3. Always call get_model, estimate_cost, and balance before generate. Confirm the exact model, route, and maxCostMicros spend cap with the user, persist an idempotencyKey, and never call generate a second time to recover a timed-out job — use job_get({ idempotencyKey }) instead.
4. When job_get or generate returns private delivery URLs, include clickable Open/Download links alongside expiresAt and the job ID in your response.
```

## Two Streamable HTTP MCP endpoints

OpenGen provides two stateless Streamable HTTP MCP endpoints (`POST` only; `GET` returns `405` with `Allow: POST, OPTIONS`):

| Endpoint                  | Tools                                                         | Authentication                                                                                                                                                                               | RFC 9728 Protected Resource Metadata                           |
| ------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `https://opengen.dev/mcp`          | **15 tools** (9 read-only + 6 write/billable)                 | OAuth 2.1 DCR + PKCE or OpenGen Bearer token (`read`, `generate`)                                                                                                                            | `https://opengen.dev/.well-known/oauth-protected-resource/mcp`          |
| `https://opengen.dev/mcp/readonly` | **9 read-only tools** (4 zero-auth public + 5 workspace-read) | **Zero auth** for `initialize`, `tools/list`, `resources/*`, `prompts/*`, `find_models`, `get_model`, `estimate_cost`, `search_docs`; `read` OAuth/Bearer token required for workspace tools | `https://opengen.dev/.well-known/oauth-protected-resource/mcp/readonly` |

### Edge ergonomics: CORS, `Accept`, and SSE progress

- **Zero-friction `Accept` handling**: Missing `Accept`, `*/*`, or `application/json` headers are normalized cleanly so plain `curl` and browser `fetch` JSON-RPC calls receive `200 OK` with `application/json` (never spurious `406 Not Acceptable`). Explicitly refusing JSON (such as `Accept: application/json;q=0, text/event-stream`) returns `406`.
- **Opt-in SSE progress**: Sending `Accept: application/json, text/event-stream` together with `_meta.progressToken` on `generate` (with `waitMs > 0`) or `job_get` (with `waitMs > 0` or `afterRevision`) streams live `notifications/progress` frames over `text/event-stream` (`Cache-Control: private, no-store, no-transform`, `X-Accel-Buffering: no`).
- **Browser & remote CORS**: Both `/mcp` and `/mcp/readonly` return `Access-Control-Allow-Origin: *` (never `Access-Control-Allow-Credentials: true`), `Cache-Control: no-store`, `Vary: Authorization`, and `204` `OPTIONS` preflight responses.

## Zero-auth test against `/mcp/readonly`

Any agent, IDE, or HTTP client can inspect OpenGen's catalog, schemas, regional privacy disclosures, published pricing, and docs over `/mcp/readonly` with zero credentials:

```bash tab="cURL"
# 1. List all 9 read-only MCP tools with zero auth and plain default Accept
curl --fail-with-body -X POST "https://opengen.dev/mcp/readonly" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'

# 2. Run a zero-auth dry-run cost estimate over MCP
curl --fail-with-body -X POST "https://opengen.dev/mcp/readonly" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "estimate_cost",
      "arguments": {
        "modelId": "openai/gpt-image-2",
        "operation": "text-to-image",
        "input": { "prompt": "Studio portrait of a ceramic vase", "resolution": "1K", "quality": "low" }
      }
    }
  }'
```

```ts tab="TypeScript"
const res = await fetch('https://opengen.dev/mcp/readonly', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'tools/call',
    params: {
      name: 'find_models',
      arguments: { modality: 'video', operation: 'image-to-video', inputRole: 'firstFrame' },
    },
  }),
});

const rpc = await res.json();
console.log(rpc.result.structuredContent.models.length);
```

```python tab="Python"
import httpx

response = httpx.post(
    "https://opengen.dev/mcp/readonly",
    json={
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "search_docs",
            "arguments": {"query": "ed25519 webhook signature", "topic": "webhooks"},
        },
    },
    timeout=20.0,
)
response.raise_for_status()
print(response.json()["result"]["structuredContent"]["docs"][0]["url"])
```

```json tab="MCP"
{
  "tool": "find_models",
  "arguments": {
    "collection": "image-to-video"
  }
}
```

```bash tab="CLI"
# Equivalent portable CLI discovery (zero auth required for public catalog & pricing)
opengen catalog search --modality video --operation image-to-video --input-role firstFrame
opengen collections
```

## Complete MCP tool reference (15 tools)

### Public zero-auth discovery tools (4 — `/mcp/readonly` & `/mcp`)

| Tool            | Required Auth           | Key Arguments                                                                                                               | Purpose                                                                                                                                                                       |
| --------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `find_models`   | None on `/mcp/readonly` | `query?`, `listCollections?`, `collection?`, `modality?`, `providerId?`, `region?`, `familyId?`, `operation?`, `inputRole?` | Search exact catalog variants or list/inspect the 9 curated factual collections                                                                                               |
| `get_model`     | None on `/mcp/readonly` | `id`, `operation?`                                                                                                          | Single-call inspection of an exact model, alias, series, or route: returns `generationProfiles`, regional routes with `privacyDisclosure`, deployments, and published pricing |
| `estimate_cost` | None on `/mcp/readonly` | `modelId`, `operation`, `input`, `billing?`, `routeId?`, `routing?`, `maxCostMicros?`                                       | Stateless dry-run cost estimator (`estimatedCostMicros`, `recommendedMaxCostMicros`, route candidates, plus `workspaceEligibility` when authenticated)                        |
| `search_docs`   | None on `/mcp/readonly` | `query`, `topic?`, `limit?` (`1–10`)                                                                                        | Search OpenGen documentation chunks across `quickstart`, `models`, `generation`, `pricing`, `assets`, `webhooks`, `recovery`, `analytics`, `privacy`, and `mcp-cli`           |

### Workspace read-only tools (5 — `/mcp/readonly` & `/mcp`)

| Tool          | Required Scope | Key Arguments                                                                                                                                         | Purpose                                                                                                                                                   |
| ------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `balance`     | `read`         | `{}`                                                                                                                                                  | Read `availableMicros`, `reservedMicros`, `currency`, `workspaceId`, plus `billingUrl` and `minTopUpUsd` (`5`) when hosted top-ups are active             |
| `analytics`   | `read`         | `since?`, `until?`, `modelId?`, `providerId?`, `deploymentId?`, `endpointRegion?`, `operation?`, `keyId?`, `status?`, `project?`                      | Bounded (max 31-day) workspace usage, spend (`settledMicros`, `heldMicros`, `byKey`, `byTag`), and per-route latency/reliability `cohorts`                |
| `job_get`     | `read`         | `id?` **or** `idempotencyKey?`, plus optional `waitMs` (`0–25000`), `afterRevision`                                                                   | Read, long-poll with live progress, recover a lost submission by `idempotencyKey`, refresh signed output URLs, and attach the inline MCP App preview card |
| `jobs_list`   | `read`         | `status?`, `modelId?`, `providerId?`, `deploymentId?`, `endpointRegion?`, `operation?`, `keyId?`, `project?`, `since?`, `until?`, `limit?`, `cursor?` | List private workspace generation jobs newest-first with `{ data, nextCursor }` pagination                                                                |
| `assets_list` | `read`         | `state?` (default `ready`), `mediaTypePrefix?`, `limit?` (`1–100`), `cursor?`                                                                         | List private workspace-owned uploaded/imported input assets with cursor pagination                                                                        |

### Workspace write & billable tools (6 — `/mcp` only)

| Tool                | Required Scope | Key Arguments                                                                                                                                                                | Purpose                                                                                                                                            |
| ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `generate`          | `generate`     | `modelId`, `operation`, `input`, `idempotencyKey`, `billing?`, `routeId?`, `routing?`, `maxCostMicros?`, `metadata?`, `webhookUrl?`, `webhookEvents?`, `waitMs?` (`0–25000`) | Submit one generation once with a persisted `idempotencyKey`; optionally wait up to 25s for fast results + inline MCP App preview                  |
| `job_cancel`        | `generate`     | `id`                                                                                                                                                                         | Cancel a queued job immediately (releasing its hold) or request upstream cancellation on a running job (refund not guaranteed until confirmed)     |
| `upload_asset`      | `generate`     | `source` (`url` \| `job_output` \| `presign_prepare` \| `presign_complete` \| `base64`), plus source-specific fields                                                         | Ingest private workspace input media and obtain a reusable `assetKey` (inline `base64` strictly capped at `64 KiB`; presigned PUT up to `100 MiB`) |
| `upload_attachment` | `generate`     | `file` (`download_url`, `file_id`, `mime_type?`, `file_name?`), `type` (`image` \| `video` \| `audio`), `idempotencyKey`                                                     | Hosted-chat attachment ingestion (`_meta['openai/fileParams']`) via SSRF-safe public HTTPS import without passing file bytes through LLM tokens    |
| `delete_asset`      | `generate`     | `key`                                                                                                                                                                        | Tombstone and delete a workspace-owned input asset key (blocks new admissions while preserving in-flight job pins)                                 |
| `purge_job_outputs` | `generate`     | `id`                                                                                                                                                                         | Permanently delete archived output media bytes for a terminal settled job while preserving metadata and accounting history                         |

## MCP resources, prompts, and interactive preview apps

Both `/mcp` and `/mcp/readonly` register five MCP Resources and three guided Prompts:

- **Resources**:
  - `ui://opengen/job-result` (`text/html;profile=mcp-app`) — sandboxed interactive MCP App preview card attached to `generate` and `job_get` responses, displaying first-party signed images, videos, and audio with explicit CSP `resourceDomains`.
  - `opengen://skill` (`text/markdown`) — safe discovery, estimation, upload, submit, and recovery workflow instructions.
  - `opengen://llms` (`text/plain`) — compact endpoint and discovery index.
  - `opengen://pricing` (`application/json`) — full single-source published route pricing table from `@media-router/catalog`.
  - `opengen://models/{provider}/{model}` (`application/json`) — resource template listing all 54 exact models with schemas, regional routes, privacy disclosures, and pricing.
- **Prompts**: `generate-image`, `image-to-video`, and `troubleshoot-job`.

> [!TIP]
> Not every MCP host renders interactive MCP App cards. Always surface clickable Open/Download URLs alongside `expiresAt` and the job UUID directly in chat text whenever `deliveryStatus` is `"available"` or `"partial"`.

## Supported clients and verification status

Client-specific setup guides live under [Agent Clients](/docs/clients). OpenGen distinguishes live-verified integrations from documentation-only configurations:

- **Live generation verified** (`openai/gpt-image-2` `1K` `low` + first-party `/media` delivery, reviewed `2026-11-30`): [ChatGPT](/docs/clients/chatgpt) (web), [Claude](/docs/clients/claude) (web), [Grok Bot](/docs/clients/grok-bot) (web), [Codex](/docs/clients/codex) (`codex-cli 0.155.1`), and [OpenGen CLI](/docs/clients/cli) (`@opengen-dev/cli` on [npm](https://www.npmjs.com/package/@opengen-dev/cli)).
- **Live OAuth connection verified** (tool/generation turns separately pending): [Claude Code](/docs/clients/claude-code), [Hermes Agent](/docs/clients/hermes), and [Muse Code](/docs/clients/muse).
- **Documentation-based (unverified end-to-end)**: [Cursor](/docs/clients/cursor), [OpenClaw](/docs/clients/openclaw), [OpenCode](/docs/clients/opencode), and [pi](/docs/clients/pi).

Desktop and mobile apps for hosted assistants remain separately unverified. For raw HTTP integrations outside MCP, see [Quickstart](/docs/quickstart) and [API Reference](/docs/api).
