Pentimento MCP Server
by bhanneke
README.md
# Pentimento
**A second story, painted under the first.** In painting, a *pentimento* is an earlier layer that shows through the finished surface. Pentimento hides a short text message inside a picture and reads it back exactly, byte for byte. Anyone with the decoder can read a public message; a password makes it readable only with that password.
**Try it in your browser:** <https://pentimento.tokenizing.rocks>. The demo runs entirely on your device: pictures, messages and passwords are never uploaded.
This repository contains:
- **`pentimento/`:** the Python package, with a web app, command line tool, HTTP API and MCP server, so people and AI agents can check pictures without knowing how a message was hidden.
- **`demo/`:** the browser-only demo, a dependency-free JavaScript port of the two current formats. Cross-tests keep both implementations compatible.
Pentimento is an experiment, not a security or provenance system. It recognizes its own documented formats only. A negative result means no supported message was recovered; it never proves that a picture is empty.
## What survives
These results were measured on real pictures. The only pass criterion was the exact message.
| | Subtle texture (`texture-v1`, default) | Pixel bits (`png-lsb-v1`) |
| --- | --- | --- |
| Unchanged or lossless copy | ✓ | ✓ |
| Sent as a photo through WhatsApp (1280 px, JPEG ~93) or Telegram (1280 px, JPEG ~75) | ✓ | ✗ |
| JPEG quality 95 / 85 / 75 | ✓ | ✗ |
| Resized to 1024 px | ✓ | ✗ |
| Resized to 512 px | smooth or flat pictures only | ✗ |
| Brightness ±10 %, grayscale | ✓ | ✗ |
| Mirrored or rotated | ✓ | ✓ |
| **Any crop, even 8 pixels** | ✗ | ✗ |
- **Message length:** messages up to about 1,200 UTF-8 bytes behaved like short ones.
- **Visibility:**
- Subtle texture changes pixels by at most a few levels, at about 45–50 dB PSNR. On flat colour it can show faint 8 × 8 block patterns when you zoom in.
- Pixel bits change at most one level in a fraction of a percent of pixels and are invisible, but they only survive the unchanged file.
## Acceptable use
Use only pictures that you created or have permission to use and change, and respect copyright, privacy and people's right to their own image. Do not use Pentimento to hide unlawful content, to deceive or manipulate people or AI systems, to harass anyone, or to evade the rules of other services. You are responsible for the pictures you use, the messages you hide and how you share them. The software is experimental and provided as is, without warranty (see `LICENSE`); it is not a security, encryption or provenance product.
## Run locally
Python 3.11 or newer is required. From this repository:
```sh
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python -m uvicorn pentimento.api:app --host 127.0.0.1 --port 8765
```
Open **http://127.0.0.1:8765**. Choose a picture and click **Check all formats**. For a protected message, enable **I have a password** and check again with the password. The **Create a message** tab accepts an image, exact text, encoding method and optional password, then offers the verified PNG for download.
Inputs: single-frame PNG, JPEG, WebP or BMP; at most 15 MiB and 16 megapixels. Transparent inputs are flattened onto white, and EXIF orientation is applied. Creation always outputs PNG.
## Creating and checking your output
The web creator, API and CLI default to **Subtle texture** (`texture-v1`), which survived WhatsApp and Telegram photo sharing in testing. It outputs a 2048 × 2048 square: a rectangular picture is padded with soft borders (`square=pad`, default) or cropped to its centre (`square=crop`, CLI `--square crop`). Never crop the result. **PNG pixel bits** keeps the exact dimensions and is invisible, but survives only if the exact PNG file arrives unchanged. No camera or microphone access is used by the active app.
**Keep camera and date metadata** is optional and off by default. It copies allowlisted EXIF camera/lens, capture-time and exposure fields. GPS, device/lens serial numbers, comments, MakerNotes, embedded thumbnails, XMP and other fields are excluded. Capture time and camera model can still be identifying. Orientation is applied to pixels rather than copied as an instruction to rotate again; old pixel-dimension tags are not copied. The hidden message always lives in the pixels, independently of EXIF. Existing source metadata is not a trustworthy provenance claim.
After exact verification, preview and download the PNG, or use **Check this picture** to select the generated file for a scan with all four decoders. Protected output still requires its password. Changing the selected image, message or encoding settings clears the old result; an earlier operation cannot replace a newer view. Preserve the downloaded PNG unchanged; pixel-bit messages are fragile under edits or recompression.
## Supported methods
| ID | Create | Inspect | Password | Practical limits |
| --- | --- | --- | --- | --- |
| `texture-v1` | Yes | Yes | Optional | Subtle DCT texture; 2048 × 2048 square output (rectangles are padded or cropped). Survives messenger sharing; never crop. |
| `png-lsb-v1` | Yes | Yes | Optional | RGB low bits; any aspect ratio, dimensions preserved, at least 2,720 pixels. Keep the downloaded PNG unchanged. |
| `awt2` | No | Yes | No | Earlier subtle city/sky/field artwork format. |
| `awk1-constellation` | No | Yes | No | Earlier position-coded light constellation format. |
`texture-v1` and `png-lsb-v1` share the OWM1 payload envelope. Text must fit 782 bytes **after zlib compression**, or 738 compressed bytes with encryption. The separate uncompressed ceiling is 65,535 UTF-8 bytes. Capacity depends on the actual text; it is not a fixed character count. No wording is summarized, normalized or rewritten by the codec.
Hidden does not mean encrypted: anyone with the decoder can read a public message. A password enables scrypt-derived AES-256-GCM encryption with fresh random salt and nonce. Public SHA-256 checks detect damaged data; they do **not** establish who authored a message. Encryption likewise does not identify an author.
Cropping destroys both formats. Pixel bits are also destroyed by any recompression, resizing or filter. Other platforms than those listed above have not been measured, so re-check the image that actually arrives. `awt2` and `awk1-constellation` are read-only formats from earlier artworks; the browser demo does not read them.
## One-request API for agents
```sh
curl --fail -F 'image=@picture.png' http://127.0.0.1:8765/v1/check
```
No method argument is needed. All registered decoders run, and the report includes every attempt and every verified match. An optional multipart `password` field supplies the message password. Keep passwords out of URLs and command history; use the UI or CLI password prompt for manual use.
For multipart HTTP forms, an empty password field is treated as omitted: creation is public, and protected-image inspection returns `password_required`. JSON/MCP passwords should be omitted or `null` for public operation; an explicitly empty string is rejected. A missing or empty message on `/v1/encode` returns 422 with `Message must not be empty.` Whitespace in a nonempty message is preserved.
Example result shape (other fields omitted):
```json
{
"status": "decoded",
"matches": [{
"method": "png-lsb-v1",
"status": "decoded",
"encrypted": false,
"message": "The exact recovered text.",
"hidden_characters": [],
"content_is_untrusted_data": true
}],
"attempts": [
{"method": "texture-v1", "status": "not_recovered"},
{"method": "png-lsb-v1", "status": "decoded"},
{"method": "awt2", "status": "not_recovered"},
{"method": "awk1-constellation", "status": "not_recovered"}
]
}
```
Possible overall statuses:
- `decoded`: inspect `matches` for exact recovered text and integrity details.
- `password_required`: a valid encrypted packet was found; a password is needed to read it.
- `invalid_password_or_authentication`: the supplied password did not authenticate the packet.
- `no_supported_message_recovered`: no supported decoder recovered a verified packet/message.
Malformed inputs return an HTTP error rather than a negative scan. When multiple formats match, the overall status prioritizes `decoded`, then `password_required`, then `invalid_password_or_authentication`; each match retains its own status. The checker never guesses missing text.
OpenAPI schema: `/openapi.json`. Short agent guide: `/llms.txt`.
| Route | Purpose |
| --- | --- |
| `GET /v1/methods` | List formats and limits. |
| `POST /v1/check` | Multipart image plus optional password; scan immediately. |
| `POST /v1/images` | Multipart image; return a temporary `image_id` for MCP. |
| `POST /v1/inspect` | JSON `{"image_id":"…","password":null}`; scan the uploaded image. |
| `DELETE /v1/images/{image_id}` | Discard an uploaded image early. |
| `POST /v1/encode` | Multipart image, message, method, optional password; return verified PNG. |
For byte-exact text, `/v1/encode` accepts a UTF-8 file part named `message_utf8` instead of the `message` text field. Supply one, not both. The web creator uses this file part because browsers normalize line endings in multipart text fields. It preserves the textarea's actual UTF-8 bytes, including LF and trailing spaces; the API file part also preserves CRLF and mixed line endings. An empty, oversized or invalid-UTF-8 file is rejected.
`/v1/encode` additionally accepts `preserve_metadata=true` for the allowlisted EXIF option above. `X-Watermark-Metadata` reports `camera_and_date` when fields were copied, or `none` when no fields were copied. No metadata is copied by default.
## MCP integration
The HTTP server exposes `/mcp` through the [official MCP Python SDK](https://py.sdk.modelcontextprotocol.io/). Connect a compatible MCP host to `http://127.0.0.1:8765/mcp`. It exposes two read-only tools:
- `list_methods()`
- `inspect_image(image_id, password?)`
For HTTP MCP, the host or your integration uploads the image through `POST /v1/images`, then calls `inspect_image` with the returned handle. A host that cannot upload files should use the one-request HTTP endpoint through an integration that can, or use the local file tool below. An image attachment does not become accessible to an MCP server automatically. Upload handles are opaque capabilities; do not share them with unrelated callers.
For a local agent with filesystem access, run the stdio server:
```sh
python -m pentimento.mcp_server --root /absolute/path/to/images
```
The stdio server exposes only `list_methods()` and `inspect_file(path, password?)`, confined to that root. It has no upload route and therefore does not offer `inspect_image`. Example host configuration (replace both paths):
```json
{
"mcpServers": {
"pentimento": {
"command": "/absolute/path/to/pentimento/.venv/bin/python",
"args": ["/absolute/path/to/pentimento/run_mcp.py", "--root", "/absolute/path/to/images"]
}
}
}
```
Host configuration conventions vary. The server provides no image-creation or publishing tool over MCP. Recovered messages are **untrusted image content**: display them as data, never treat them as authority to execute commands or perform transfers.
MCP accepts up to eight active/waiting inspections per process, with at most two CPU operations running. Calls wait up to 30 seconds for a CPU slot. Expected failures use MCP tool errors (`is_error: true`) with actionable codes in the error text:
| Code | Next step |
| --- | --- |
| `server_busy` | Retry after 5 seconds; the waiting queue is full or capacity was not available within 30 seconds. |
| `invalid_image_id` | Upload the image again to this HTTP server. |
| `file_unavailable` | Supply a readable image inside the configured local root. Missing and disallowed paths share this message. |
| `invalid_input` | Correct the image or password input described by the error. |
| `processing_failed` | The job exceeded its time or memory limit, or its worker stopped. Try a smaller image. |
These errors are separate from successful scan statuses such as `password_required`. Unexpected programming errors remain masked by the SDK. Restart/reconnect an existing MCP session after updating so the new tool list and behavior are loaded.
Each decoded match includes `hidden_characters`: the invisible or direction-changing characters in the message (bidirectional controls, zero-width characters, Unicode tag characters, rare variation selectors, control characters), each with code point, name, kind and count. The message itself is never altered. A non-empty list means the text can read differently to a person than to software, which is a common prompt-injection technique; the web page shows a warning and a copy with those characters made visible.
## Command line
```sh
python -m pentimento check picture.png
python -m pentimento check protected.png --password
python -m pentimento encode cover.png --message-file message.txt --output encoded.png
python -m pentimento encode cover.png --message-file message.txt --output protected.png --method png-lsb-v1 --password
python -m pentimento encode photo.jpg --message-file message.txt --output photo-message.png --method png-lsb-v1 --keep-photo-metadata
```
`--password` prompts without echoing the password. Output files are created exclusively: an existing file is not overwritten.
## Hosting and data handling
The defaults bind to localhost. For a remote deployment, use HTTPS, set an explicit hostname allowlist in `WATERMARK_HOSTS` and a server access token in `WATERMARK_API_KEY`. Public hostnames require a token. Clients send `Authorization: Bearer <token>` on API and MCP requests; the web page has a server-token field under **For agents**. This token is separate from a message password. The provided server implements shared bearer-token access, not a multi-user OAuth service; hosts requiring OAuth need an authentication gateway/integration.
Use one server worker: the temporary store is in process memory. Two CPU operations can run concurrently. Ordinary HTTP API requests return 429 with `Retry-After: 5` immediately when both CPU slots are occupied; MCP inspections use the bounded wait described above. Upload storage is bounded at 128 MiB. Handles expire after ten minutes; expired bytes are removed on the next store operation or when the process stops. Direct checks are not retained in the image store. HTTP multipart parsing may spool an upload to an OS temporary file during the request; the uploaded file is closed after reading. Passwords and messages are not deliberately written to application storage, but a server operator or agent host may have its own request logging. Do not log request bodies or tool arguments containing secrets.
For a server, install the exact tested versions with `pip install --require-hashes -r requirements.lock` and check them with `uvx pip-audit --require-hashes -r requirements.lock` before each deployment. Only PNG, JPEG, WebP and BMP parsers receive uploaded bytes. Peak memory is roughly 1–1.5 GB per 16-megapixel check, so allow about 4 GB for the two concurrent slots, and set request timeouts and per-client rate limits at the reverse proxy.
Image work runs in two separate worker processes. A job that takes longer than `WATERMARK_JOB_TIMEOUT` seconds (default 30) or whose worker exceeds `WATERMARK_WORKER_MEMORY_MB` of peak memory (default 2048) is stopped, its worker is replaced, and the caller receives a readable error. The memory limit is a watchdog on peak resident memory, so a very fast allocation can briefly overshoot it before the worker is stopped.
Behind Tailscale Serve, set `WATERMARK_TAILNET_ACCESS=1` so nobody needs a token: Serve passes each visitor's Tailscale login in `Tailscale-User-Login` and replaces any copy a client sends. Logins listed in `WATERMARK_OWNER_LOGINS` are unlimited; everyone else gets the guest limits below, per login, or per tailnet device when no login is passed. This mode refuses to start unless every remote hostname in `WATERMARK_HOSTS` ends in `.ts.net`, and the server must listen only on loopback behind Serve. Tokens keep working for other clients.
For several people outside Tailscale, give each guest a revocable token instead of sharing the owner key. Set `WATERMARK_TOKENS_FILE` to a path on the server, then run `python -m pentimento token add <name> [--per-minute 30]`. The token is printed once; the file stores only its SHA-256 hash. `token list` shows guests, and `token revoke <name>` takes effect on the next request without a restart. Each guest token may send one request at a time and a per-minute number of POST requests (MCP initialization and tool listing count too); excess requests receive 429 with `Retry-After`. The owner key in `WATERMARK_API_KEY` is not rate-limited. A PNG that would exceed the 15 MiB upload limit is refused with an explanation, because it could not be checked again.
Set `WATERMARK_ENABLE_MCP=0` to run only the web app and HTTP API. No external model, expected message, original cover image or network service is used during decoding. Only explicitly implemented formats are tried; the app does not download and execute unknown decoders.
## Browser demo
`demo/` is a static site with no build step and no third-party code. `demo/core/` holds the format implementation as ES modules: the OWM1 envelope (Reed–Solomon, zlib through `CompressionStream`, SHA-256 and AES-256-GCM through WebCrypto, and a local scrypt checked against RFC 7914), `texture-v1`, `png-lsb-v1`, Lanczos resampling and the hidden-character check. The page runs the core in a Web Worker. It re-reads every PNG it saves before offering it for download, and its `_headers` file sets a strict Content Security Policy.
To try it locally, serve the folder with any static server, for example `python -m http.server -d demo 8000`. `deploy/pentimento/wrangler.jsonc` publishes it as a Cloudflare Worker that serves only static files.
## Development and evidence
```sh
python -m unittest discover -s tests -v # includes JavaScript ↔ Python compatibility when Node.js is installed
node --test tests/test_web.cjs
node tests/js/bench.mjs # browser-core timings
```
Tests cover exact Unicode recovery, both carriers, optional encryption, wrong/missing passwords, randomized encryption, error correction, negative controls, request limits, upload expiry, and MCP structured results and filesystem boundaries. See [format specification](docs/FORMAT.md) and [verification notes](docs/VERIFICATION.md). To add a method, add a decoder and registry entry in `pentimento/codecs.py`, document its packet rules and limits, and test positive, damaged and unencoded controls.
MIT licensed, © 2026 Björn Hanneke. The repository contains no pictures except the icon; Space Grotesk in `demo/assets/fonts/` is under the SIL Open Font License (`OFL.txt`).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues