docs: add README, session, architecture, deployment and update guides

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-07 17:09:51 +02:00
1 parent 981dc3b941
commit d751acfe63
7 files changed
+278

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
# CLAUDE.md
MCP server (TypeScript, ESM, Express 5, `@modelcontextprotocol/sdk`) that generates images by driving chatgpt.com with Playwright. Mirrors the MCP contract of ZenvairoMediaGenerator-MCP (submit + poll, signed public URLs).
## Commands
- `npm run dev`: run with tsx
- `npm run build` / `npm start`: compile to `dist/` and run
- `npm run typecheck`
- `npm test`: unit tests plus fixture-based browser tests. The browser tests skip if Playwright Chromium is missing. When the default cache is read-only, set `PLAYWRIGHT_BROWSERS_PATH`.
- `npm run login` (`-- --check`): manual chatgpt.com login with the persistent profile. The server must be stopped first.
## Layout
- `src/index.ts`: HTTP app, auth, media routes, update routes
- `src/tools.ts`: MCP tools
- `src/jobs.ts`: serial queue, pacing, circuit breaker
- `src/chatgpt/`: `selectors.ts` (the only DOM knowledge), `client.ts` (page operations), `provider.ts` (one image per new chat), `browser.ts` (persistent context), `prompts.ts`
- `src/media.ts`, `src/public-media.ts`: disk storage, manifests, HMAC URLs
- `src/update.ts`, `scripts/update.sh`: authenticated self-update
- `test/fixtures/`: reduced chatgpt.com DOM used by `test/client.test.ts`
## Conventions
- When chatgpt.com changes, edit only `src/chatgpt/selectors.ts`, putting new selectors first, and update the fixtures.
- Never log prompts, reference images, tokens or profile contents.
- Never commit `profiles/`, `diagnostics/`, `media/` or `.env`.
- Read `LESSONS.md` before changing the browser automation.
+12
View File
@@ -0,0 +1,12 @@
# Lessons
Recurring mistakes and how to avoid them. Several of these come from ZenvairoProspect's earlier chatgpt.com automation.
- **The composer is not a login signal.** chatgpt.com shows `#prompt-textarea` to logged-out guests too. Detect a login with profile and history markers, and detect logged-out state with login buttons.
- **Don't scan the whole page for limit or error texts.** The user's prompt is on the page. Check only error banners and the assistant reply.
- **The first image is not the final one.** ChatGPT renders blurred partial previews. Wait until the `src` is stable and no "creating image" text remains.
- **Uploaded references are images too.** Exclude images inside the user message, and anything present before sending.
- **Download through the browser.** CDN image URLs need the session cookies, so use `page.request.get`, not Node `fetch`.
- **One process per profile.** Chromium locks the profile directory. Stop the service before `npm run login`.
- **Don't force contradictory format rules.** Prospect rejected good images because a prompt rule and a QA aspect-ratio rule disagreed. Aspect ratio is a best-effort hint here and is not validated.
- **zsh and `git show rev:path`.** Quote the argument (`git show 'abc^:path'`), or zsh modifiers such as `:r` mangle it.
+47
View File
@@ -0,0 +1,47 @@
# ChatGPT Image MCP (unofficial)
Remote, stateless Streamable HTTP MCP server that generates images with **ChatGPT in the cloud**. It drives the chatgpt.com web UI with Playwright and a persistent, logged-in Chromium profile. Images come from the account's own ChatGPT image quota; no OpenAI API key is involved.
It uses the same submit + poll contract as ZenvairoMediaGenerator-MCP: `generate_image` returns a `generationId` immediately and `query_tasks` returns the result, including an expiring signed `publicUrl`.
## Tools
| Tool | Purpose |
|---|---|
| `who_am_i` | Model, accepted arguments, delivery options, queue/session state |
| `generate_image` | Queue a generation (`model: "chatgpt-web"`, `arguments: [{name, value}]`) |
| `query_tasks` | Poll status; `COMPLETED` returns `outputs[]` with `publicUrl`, `downloadUrl`, optional `base64` |
| `check_session` | Verify that the browser profile is logged in |
| `get_usage` | Counters, queue length, circuit-breaker state |
Arguments for `generate_image`: `prompt` (required), `aspect_ratio` (`auto`, `1:1`, `16:9`, `9:16`, ...), `image_count` (1-4), and `reference_images`, an array of `{generation_id, index?}` or `{base64, mime_type}`.
```json
{
"model": "chatgpt-web",
"arguments": [
{ "name": "prompt", "value": "A cozy bakery storefront in Seville at dawn, photorealistic" },
{ "name": "aspect_ratio", "value": "4:5" }
]
}
```
## Quick start (development)
```bash
npm ci
npx playwright install chromium
cp .env.example .env # set MCP_SERVER_TOKEN and PUBLIC_MEDIA_SIGNING_SECRET
npm run login # log in to chatgpt.com once in the opened window
npm run dev # http://127.0.0.1:8088/mcp
npm test
```
## Docs
- [docs/chatgpt-session.md](docs/chatgpt-session.md): logging in, expired sessions, usage limits, UI changes
- [docs/architecture.md](docs/architecture.md): generation flow and lineage
- [docs/deployment.md](docs/deployment.md): install on Debian/Ubuntu with systemd
- [docs/update.md](docs/update.md): update script and authenticated update endpoint
> This automates a consumer web UI. It is unofficial, can break whenever chatgpt.com changes, and must comply with OpenAI's terms for the account used.
+32
View File
@@ -0,0 +1,32 @@
# Architecture
```
MCP client ──POST /mcp──▶ tools.ts ──▶ JobManager (serial queue, pacing, circuit breaker)
│
▼
ChatGptImageProvider ──▶ BrowserSession (persistent Chromium profile)
│ │
▼ ▼
media.ts (disk + manifests) chatgpt.com
```
## Generation flow (one image)
1. Open `CHATGPT_URL` (a new empty chat). Fail with `SESSION_NOT_READY` if login markers are visible.
2. Record the image `src`s already on the page (baseline).
3. Upload reference images through the hidden file input and wait for the upload to finish.
4. Type the wrapped prompt (`src/chatgpt/prompts.ts`) into the composer and send it.
5. Wait for the turn: the stop button appears and then stays gone for two polls.
6. Wait for a new image outside the user message, at least 256 px per side, fully loaded, with a `src` that stays the same for 3 polls and no "creating image" text. ChatGPT shows blurred partial previews first, so the first image seen is not the final one.
7. Download it through the browser request context (it carries the session cookies), validate size and format, store it as `<generationId>-<index>.<ext>`.
`image_count > 1` repeats this in a new chat per image. Every job runs alone because the profile can only be used by one browser.
## Lineage
Ported from ZenvairoProspect's `imagegen` package (Python, branch `legacy/whatsapp-mockup`): selectors as ordered fallback lists, the persistent profile with a manual login, turn detection through the stop button, usage-limit detection by text, downloads through `page.request`, HTML diagnostics and random pacing. The MCP surface, media storage and signed URLs follow ZenvairoMediaGenerator-MCP so clients can switch backends.
Changes from Prospect:
- Limit and error texts are matched only against error banners and the assistant reply, never against the whole page. The user's prompt is on the page too.
- The final image is detected by `src` stability, and uploaded references are excluded.
- A circuit breaker rejects new jobs right away, instead of the queue sleeping for an hour.
+46
View File
@@ -0,0 +1,46 @@
# ChatGPT session
The server drives chatgpt.com with a persistent Chromium profile (`CHATGPT_PROFILE_DIR`). That profile must be logged in once by a human; the server never handles passwords.
Chromium locks the profile directory, so **stop the service before** running any of the commands below.
## Log in on a machine with a display
```bash
npm run login # dev (tsx)
npm run login:prod # after npm run build
```
A visible browser opens chatgpt.com. Log in by hand (2FA included). The window closes by itself once the session is detected (up to 10 minutes).
Check the profile without opening a window:
```bash
npm run login -- --check
```
## Log in for a headless server
Pick one:
1. **Log in locally, copy the profile.** Run `npm run login` on your desktop with the same Playwright version, then copy the directory to the server (`rsync -a profiles/chatgpt/ server:/opt/chatgpt-imagegen-mcp/profiles/chatgpt/`) and `chown -R mcp:mcp` it. Playwright's Chromium stores cookies with the `basic` password store, so the profile works on another machine.
2. **Log in on the server through X forwarding.** `ssh -X` to the server and run `sudo -u mcp --preserve-env=DISPLAY,XAUTHORITY npm run login:prod`.
Then start the service and confirm with the `check_session` MCP tool or `GET /health` (`session.loggedIn`).
## When the session expires
Jobs fail with `SESSION_NOT_READY` and the circuit breaker rejects new jobs for `CHATGPT_SESSION_RECHECK_MINUTES`. Stop the service, log in again, start it.
## Usage limits
The account's own image quota applies. When chatgpt.com shows a limit notice the job fails with `USAGE_LIMIT_REACHED` (`retryable: true`, `retryAfter`) and new jobs are rejected for `CHATGPT_USAGE_LIMIT_COOLDOWN_MINUTES`. Random pacing between generations (`CHATGPT_MIN/MAX_INTERVAL_SECONDS`) keeps the traffic human-like.
## When chatgpt.com changes its markup
All DOM knowledge lives in `src/chatgpt/selectors.ts`: ordered lists of alternative selectors. On a UI failure the server writes an HTML dump and a screenshot to `DIAGNOSTICS_DIR` (newest `MAX_DIAGNOSTICS` kept). Inspect them, add the new selector **at the front** of the matching list, and update the fixtures in `test/fixtures/`. Diagnostics may contain conversation text: never commit them.
## Notes
- This automates a consumer web UI. It is unofficial, may break without notice, and must comply with OpenAI's terms for the account used.
- Never put the profile directory in git or logs: it holds the session cookies.
+57
View File
@@ -0,0 +1,57 @@
# Deployment
Target: Debian or Ubuntu (one of the last three major releases) in an LXC container or VPS, running under systemd behind nginx. Docker is not used for deployment.
## 1. System packages
```bash
apt update && apt install -y git xvfb curl ca-certificates
# Node.js >= 20 via NodeSource (see https://github.com/nodesource/distributions)
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt install -y nodejs
```
`xvfb` provides the virtual display: Chromium runs headed inside Xvfb by default because ChatGPT/Cloudflare blocks headless Chromium more often.
## 2. User and code
```bash
useradd --system --create-home --home-dir /opt/chatgpt-imagegen-mcp --shell /bin/bash mcp
sudo -u mcp git clone <repo-url> /opt/chatgpt-imagegen-mcp
cd /opt/chatgpt-imagegen-mcp
sudo -u mcp npm ci
npx playwright install-deps chromium # as root: installs Chromium system libraries
sudo -u mcp npx playwright install chromium # as mcp: downloads the browser
sudo -u mcp npm run build
```
## 3. Configuration
```bash
sudo -u mcp cp .env.example .env && chmod 600 .env
```
Edit `.env` (bearer token, `UPDATE_TOKEN`, media/profile paths, ...). Generate secrets with `openssl rand -hex 32`.
## 4. ChatGPT login
The persistent Chromium profile must be logged in to chatgpt.com once. See [chatgpt-session.md](chatgpt-session.md).
## 5. systemd and sudoers
```bash
cp deploy/chatgpt-imagegen-mcp.service /etc/systemd/system/
install -m 0440 deploy/sudoers.chatgpt-imagegen-mcp /etc/sudoers.d/chatgpt-imagegen-mcp
visudo -cf /etc/sudoers.d/chatgpt-imagegen-mcp
systemctl daemon-reload && systemctl enable --now chatgpt-imagegen-mcp.service
journalctl -u chatgpt-imagegen-mcp.service -f
```
The sudoers rule only lets `mcp` restart this one service; the update script needs it. Adjust paths in the unit if you install elsewhere (and add any custom media/profile/log directories to `ReadWritePaths`).
## 6. nginx
Include `deploy/nginx-location.conf` in your TLS `server` block, then `nginx -t && systemctl reload nginx`. The service listens on `127.0.0.1:8088`; the MCP endpoint is `https://<host>/chatgptimagegen/mcp` with bearer auth. Set `TRUST_PROXY=1` in `.env` so rate limiting sees real client IPs.
## 7. Updates
See [update.md](update.md).
+56
View File
@@ -0,0 +1,56 @@
# Updating
## Script
`scripts/update.sh` updates the install it lives in. It is idempotent and logs timestamped lines to stdout.
1. Takes a lock (`flock` on `.update.lock`); fails if another update is running.
2. `git fetch` + `git pull --ff-only`.
3. `npm ci`, then `npx playwright install chromium` (system libraries need `npx playwright install-deps chromium` as root, see [deployment.md](deployment.md)).
4. Backs up `dist/`, runs `npm run build` and `npm test`. On failure the previous `dist/` is restored and the service is not restarted.
5. Prints `UPDATE_SUCCEEDED <iso timestamp>` and restarts the service with `sudo -n systemctl restart $SERVICE_NAME` (default `chatgpt-imagegen-mcp.service`).
On error the last line is `UPDATE_FAILED <iso timestamp> ...` and the exit code is non-zero. There are no database migrations: state is plain files on disk.
Run manually: `sudo -u mcp scripts/update.sh >> logs/update.log 2>&1`.
## Endpoint
Enabled only when `UPDATE_TOKEN` is set to a secret of at least 32 characters (otherwise both routes return `503 {"error":"update_not_configured"}`). Authenticate with `Authorization: Bearer $UPDATE_TOKEN`. These routes are not covered by the MCP bearer token.
```bash
curl -X POST -H "Authorization: Bearer $UPDATE_TOKEN" https://host/chatgptimagegen/admin/update
curl -H "Authorization: Bearer $UPDATE_TOKEN" https://host/chatgptimagegen/admin/update/status
```
| Request | Result |
| --- | --- |
| `POST /admin/update` | `202` update started, `409` already running |
| `GET /admin/update/status` | `{ state, startedAt, finishedAt, exitCode, logTail }` |
| missing/wrong token | `401` |
| token not configured | `503` |
| too many requests | `429` with `Retry-After` |
`state` is `idle`, `running`, `succeeded` or `failed`. `logTail` is the last 50 lines of the log.
The script restarts the service at the end, which kills the server process. After the restart the server reads the last log line: if it holds the `UPDATE_SUCCEEDED` (or `UPDATE_FAILED`) marker, status reports `succeeded` (or `failed`) with that timestamp (`startedAt` is null and `exitCode` is synthetic). Poll the status endpoint until it answers again.
## Rate limiting
In memory, per client IP (`req.ip`), reset on restart. Behind nginx set `TRUST_PROXY=1` (or the number of proxy hops) so the real client IP is used; otherwise every request appears to come from nginx.
- `UPDATE_RATE_LIMIT_MAX` (default 30) requests per window, any outcome.
- Failed authentication attempts are limited to 5 per window (or `UPDATE_RATE_LIMIT_MAX` if lower).
- `UPDATE_RATE_LIMIT_WINDOW_SECONDS` (default 900).
## Configuration
| Variable | Default | Purpose |
| --- | --- | --- |
| `UPDATE_TOKEN` | unset (endpoint disabled) | Bearer secret, min 32 chars |
| `UPDATE_SCRIPT` | `<cwd>/scripts/update.sh` | Script run by the endpoint |
| `UPDATE_LOG_FILE` | `<cwd>/logs/update.log` | Appended stdout/stderr of the script |
| `UPDATE_RATE_LIMIT_MAX` | 30 | Requests per window per IP |
| `UPDATE_RATE_LIMIT_WINDOW_SECONDS` | 900 | Window length |
| `TRUST_PROXY` | unset | Express `trust proxy` value |
| `SERVICE_NAME` | `chatgpt-imagegen-mcp.service` | Service restarted by the script |