> ## Documentation Index
> Fetch the complete documentation index at: https://docs.embededitor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Relay Protocol

> Everything a relay does, to build your own in any stack: its routes, the link's token, the editor's socket, the session's lifetime and the two MCP tools.

Three parties take part. The **editor** runs in the user's tab. The **relay** is your server. The **agent** is an MCP client, like Claude. The editor talks to the relay over HTTP and one WebSocket, the agent talks to the relay over MCP, and the editor and the agent never talk to each other.

## The Flow

```mermaid theme={"dark"}
sequenceDiagram
    participant U as User
    participant E as Editor (the user's tab)
    participant R as Relay
    participant A as Agent (MCP client)
    U->>E: Taps Agent
    E->>R: POST /sessions
    R-->>E: expiresAt, link, token
    E->>R: Opens /socket, subprotocols ee-agent and the token
    E->>R: commands message
    E-->>U: Shows the link, with its copy
    U->>A: Pastes the link with a request
    A->>R: POST /mcp, list_commands with the link
    R->>E: AGENT_CONNECTED
    R-->>A: The guide, then the commands as JSON
    A->>R: POST /mcp, run_command with the link, name and input
    R->>E: CALL with id, name and input
    E-->>R: result with the same id
    R-->>A: The result, as MCP content
    U->>E: Taps Disconnect
    E->>R: POST /sessions/end with the token
    R->>E: ENDED, then close 4000
```

With your backend making the link, only the first request changes: the editor calls your `onAgentLink`, your route asks the relay with your secret, and the rest is the same.

```mermaid theme={"dark"}
sequenceDiagram
    participant E as Editor
    participant B as Your backend
    participant R as Relay
    E->>B: onAgentLink, your own request and sign-in
    B->>R: POST /sessions, Authorization Bearer and the relay's secret
    R-->>B: expiresAt, link, token
    B-->>E: expiresAt, link, token
    E->>R: Opens /socket on agentRelay
```

## The Link's Token

* **What it is**: 32 random bytes from a cryptographic source, as base64url with no padding: 43 characters of `A-Z`, `a-z`, `0-9`, `-` and `_`.
* **The link**: `<origin>/link#<token>`, the origin the `POST /sessions` request came in on (`new URL(req.url).origin`). A browser that opens the link never sends what follows the `#`.
* **Where it travels**: in the answer of `POST /sessions`, in the socket's subprotocol, in the body of `POST /sessions/end`, and in the `link` argument of every MCP call, inside its JSON body. Never in a URL's path or query, and never in a header a server logs.
* **What the relay keeps**: its SHA-256, as 64 lowercase hex characters, which names the session. Ours hashes the token's text (its 43 characters, as UTF-8). The hash never leaves the relay, so your relay only needs to hash the same way everywhere it looks a session up.
* **How a link is read**: the relay takes what follows the last `#` (or the whole text, for a token pasted alone), trimmed, and takes it as a token when it matches `^[A-Za-z0-9_-]{40,128}$`: 40 to 128 characters.

The editor only passes the token along, so another token format works as long as it's 40 to 128 characters, random, and its characters are valid in a WebSocket subprotocol. base64url's are.

**The relay's origin.** The link and the MCP server's instructions name the origin the request came in on, so they name whatever address the request was sent to. That's right when the person's browser and agent reach the relay where it runs (ours on Cloudflare, on its own domain). Behind a proxy, a TLS terminator, or when your backend calls the relay on an internal address, the origin a request arrives with isn't the one the person reaches: set the public one instead (`@embededitor/relay`'s `publicOrigin` setting).

## HTTP Routes

| Method | Path | Called by | Its credential |
| - | - | - | - |
| `POST` | `/sessions` | The editor, or your backend | An `Origin` the relay allows, or `Authorization: Bearer <secret>`, the relay's secret |
| `POST` | `/sessions/end` | The editor | The token, in the body |
| `GET`, upgraded | `/socket` | The editor | The token, in the subprotocol |
| `POST` | `/mcp` | The agent | The link, in each call |
| Any | `/link` and `/` | A browser that opens a link | None |

Any other path answers 404 with `Not found`. A failure inside the relay answers 500 with `Internal error`.

The editor builds every URL from `agentRelay` with an absolute path (`new URL('/sessions', agentRelay)`), so `agentRelay` is an origin: a path in it is dropped.

### POST /sessions

Makes a link. On a relay of your own, the request needs no body. Ours, at `agent.embededitor.com`, asks for the license's public key too: the editor sends it as the body, JSON as text (`{ "publicKey": "ee_pk_…" }`, which asks the browser no CORS preflight). Ours makes the link only for a key of the form `ee_pk_` plus 32 base62 characters (`A-Z`, `a-z`, `0-9`) that belongs to an active license, the page's `Origin` one of the key's domains (none listed: any page), and otherwise answers 403 with why: `PUBLIC_KEY_REQUIRED`, `PUBLIC_KEY_UNKNOWN` (not of that form, none such, or rotated or removed), `PUBLIC_KEY_INACTIVE` (its license isn't active) or `PUBLIC_KEY_DOMAIN`, each with its `message`. While it can't check a key, it answers 503, `UNAVAILABLE`: the registry gave no answer within 5 s, answered something other than the key or its absence, or answered in a form the relay can't read; its rate limiter was unavailable; or the request carried no address it can count (Cloudflare's `cf-connecting-ip`, which its edge always sets). Every new link checks the key again. A page whose address (an IPv6 one counted by its /64) makes more than 600 connection requests or asks about more than 20 unknown keys in a minute gets 429, `RATE_LIMITED`, until the minute is past; the count is the page's own. An existing link continues until it ends, even if the license expires or is revoked meanwhile. The editor tells a 403 apart: its card says "The agent isn't set up for this site yet.", and the console gets the `message`. A 429 and a 503 show "Couldn’t Create the Link", with **Try Again**.

A request passes when one of the relay's allowed origins names its `Origin` header, or when it carries `Authorization: Bearer <secret>` with the relay's secret. Anything else answers 403. An entry names an origin in one of three ways: it is that origin exactly; it is a subdomain pattern, `scheme://*.domain[:port]`, and the origin has that scheme and port on a subdomain of that domain, at any depth (never the domain itself), the subdomain letters, digits, hyphens and dots; or it is `*`, the whole entry, which names every origin (a relay open to any site's editor). A request with no `Origin` passes none of them.

The `Authorization` header matches `^Bearer\s+(\S+)$`, case-insensitive: the scheme in any case (`Bearer`, `bearer`), whitespace, then the secret, which has no whitespace in it. A secret with a space in it never matches, so pick one without (`openssl rand -hex 32` has none). HTTP trims a header value's leading and trailing whitespace before the relay reads it.

| Answer | When |
| - | - |
| 200, JSON | The link was made. |
| 204 | `OPTIONS`, the CORS preflight. |
| 403, JSON | Neither credential passed. |
| 405, `Method not allowed` | Any other method. |

```json 200 theme={"dark"}
{
	"expiresAt": 1794240000000,
	"link": "https://agent.shop.example.com/link#3q2-7wQ9yGJ4bN1xZkP0aV8sLmT5cRd6eHf2uIo3wXy",
	"token": "3q2-7wQ9yGJ4bN1xZkP0aV8sLmT5cRd6eHf2uIo3wXy"
}
```

```json 403 theme={"dark"}
{
	"error": "FORBIDDEN",
	"message": "A link is made by the editor on a page this relay allows (allowedOrigins), or by your server with the relay's secret (Authorization: Bearer <agentSessionSecret>)."
}
```

`expiresAt` is in ms since the epoch, 2 hours after the request. The session starts waiting for its socket at once: one that sees no socket within 2 minutes ends as `TAB_CLOSED`.

**CORS.** Every answer of `/sessions` (200, 204, 403 and 405) carries `vary: origin`. When the request's `Origin` is one the relay allows, it also carries that origin, never `*`, and the two headers a preflight asks for:

```http theme={"dark"}
access-control-allow-headers: content-type
access-control-allow-methods: POST, OPTIONS
access-control-allow-origin: https://shop.example.com
vary: origin
```

Any other origin, or none, gets `vary: origin` alone. Without its origin in the answer, the browser hides the answer from the editor. The editor's request is a POST with no header of its own, its body none or the public key as text, a CORS simple request, so a browser sends no preflight for it. Your backend's request comes from a server, which needs no CORS.

### POST /sessions/end

Ends a link at once, whether its socket is open or not.

```json Disconnect theme={"dark"}
{ "token": "3q2-7wQ9yGJ4bN1xZkP0aV8sLmT5cRd6eHf2uIo3wXy" }
```

```json The tab closing theme={"dark"}
{ "closed": true, "token": "3q2-7wQ9yGJ4bN1xZkP0aV8sLmT5cRd6eHf2uIo3wXy" }
```

`closed: true` ends it as `TAB_CLOSED`. Without it, the end is the user's Disconnect, `DISCONNECTED`.

| Answer | When |
| - | - |
| 204 | A token was read, even one that names no session or one that already ended (nothing changes then). Also `OPTIONS`. |
| 400, `Expected a token` | Any other method, or a body that isn't JSON with a token. |

The editor sends the body as text (`fetch` with a string body, and `navigator.sendBeacon` as the page hides), so its `Content-Type` is `text/plain;charset=UTF-8`: read the body as JSON whatever its type. That makes it a CORS simple request, with no preflight, and the editor never reads the answer, so it works with or without CORS headers. Ours answers it from any page, the token its proof: every answer (204, 400, and the preflight's 204) carries

```http theme={"dark"}
access-control-allow-headers: content-type
access-control-allow-methods: POST, OPTIONS
access-control-allow-origin: *
```

The body is a token and a flag, under 100 bytes. Ours (`@embededitor/relay`, on Node and on Cloudflare alike) reads at most 4 KB of it, and answers a larger one 400, by its `Content-Length` before reading or by the bytes read.

### GET /socket

The editor's WebSocket: `wss://<relay>/socket` (`ws://` for an `http:` relay), opened with the subprotocols `ee-agent` and the token, in that order:

```http theme={"dark"}
GET /socket HTTP/1.1
Upgrade: websocket
Sec-WebSocket-Protocol: ee-agent, 3q2-7wQ9yGJ4bN1xZkP0aV8sLmT5cRd6eHf2uIo3wXy
```

| Answer | When |
| - | - |
| 400, `Expected the editor socket` | Not an upgrade, a first subprotocol other than `ee-agent`, or a second one that isn't a token. |
| 101, `Sec-WebSocket-Protocol: ee-agent` | Anything else. A browser drops a socket whose answer doesn't name one of the subprotocols it offered, so always echo `ee-agent`. |

A socket for a session that ended, or that doesn't exist, is accepted and then closed at once with 4000 and the reason (`EXPIRED` for one that doesn't exist), with no `ENDED` message before it. A browser can't read the status of a refused upgrade, so the close is how the editor learns why.

The relay doesn't check the socket's `Origin`: the token is its credential.

### POST /mcp

The MCP server: Streamable HTTP, stateless. See [MCP](#mcp). It answers no CORS: MCP clients call it from their own process or servers, never from a page.

Only a `POST` carries a call. Any other method (`GET`, which would open a stream nothing writes to, `DELETE`, which would end a session there isn't, `OPTIONS`) answers 405 with `allow: POST` and a JSON-RPC error as JSON:

```json 405 theme={"dark"}
{ "error": { "code": -32000, "message": "Method not allowed: this server takes a POST for each call." }, "id": null, "jsonrpc": "2.0" }
```

### /link

A page for a person who opens the link in a browser, and for an agent without the MCP server that fetches it, served at `/link` and at `/`, for any method: 200, `text/html; charset=utf-8`. Its heading says "This is an Embed Editor agent link" (its `<title>`, "Embed Editor agent link"); it says the agent can't use the link yet, to add the MCP server `<origin>/mcp` to it once and then paste the link again with a request, and that the agent then edits the photo in the editor's tab while the person watches. The address is written in the page's HTML, from the origin the links name (`publicOrigin`, else the one the request came in on), and the page has no script: an agent that fetches the link runs none. The token after the `#` never reaches the server.

## The Editor's Socket

Every frame is text. `ping` and `pong` are the plain words; every other message is JSON, one object per frame.

```ts wire.ts theme={"dark"}
// a command the editor offers: its name in snake case, with the description and JSON Schema commands() gives
type AgentCommand = { description: string; inputSchema: Record<string, unknown>; name: string };
// what a call gave back, as MCP's tools/call result has it
type CallResult = { content: ToolContent[]; isError: boolean };
// the editor's messages
type EditorMessage = { commands: AgentCommand[]; guide?: string; type: 'COMMANDS' } | (CallResult & { id: string; type: 'RESULT' });
// why a session ended
type EndReason = 'DISCONNECTED' | 'EXPIRED' | 'TAB_CLOSED';
// the relay's messages
type SessionMessage = { type: 'AGENT_CONNECTED' } | { id: string; input: unknown; name: string; type: 'CALL' } | { reason: EndReason; type: 'ENDED' };
// one piece of a result, as MCP writes it
type ToolContent = { data: string; mimeType: string; type: 'image' } | { text: string; type: 'text' };
```

### From the Editor

**`commands`**, sent as each socket opens and whenever the available commands or guide change. `commands` is the editor's list of available tools; `guide` is the text that tells the agent how to use them, including the editor's language and the person's mark. The host can replace its parts with [`aiPrompts`](https://docs.embededitor.com/ai/customize-prompts). The list is the editor's own AI's list with Annotate's tools: `retouch_run` takes `MARK`, `ALL` and `BACKGROUND` alone, and answers `INVALID_COMMAND` at `input.area.kind` for `POLYGON` or `RECT`.

The relay keeps the latest list and guide from the session's open socket without interpreting them. A message from a replaced socket or with a non-list `commands` changes nothing; a non-string `guide` counts as none. Until the first message, the list is empty and there is no guide.

```json theme={"dark"}
{
	"commands": [
		{
			"description": "Sets the crop's ratio as a tap on it in the Aspect section does, by its name ('1:1', '1:2', '3:4', '9:16', '16:9', '4:3', '2:1'), or 'ORIGINAL', …",
			"inputSchema": { "properties": { "ratio": "…" }, "type": "object" },
			"name": "crop_set_ratio"
		}
	],
	"guide": "## The base\n\n- Use a tool of the editor whenever one does the job; …\n\n## When you annotate: you are the art director\n\n…",
	"type": "commands"
}
```

The relay keeps the list and the guide together up to 1 MiB (1,048,576 bytes), counted as a Durable Object stores them: two bytes a character (a UTF-16 unit) of the list's JSON and the guide. The Full's are about 83,000 characters, so about 170 KB.  A `commands` message past it is dropped: the relay keeps what it had before.

**`result`**, a call's answer, under the call's `id`:

```json theme={"dark"}
{ "content": [{ "text": "null", "type": "text" }], "id": "0b9c6a52-4f1e-4d8a-9a57-2f7c1d3e8b40", "isError": false, "type": "result" }
```

A screenshot's `result` is the largest message: about 113 KB for the whole photo (an 85 KB JPEG, in base64, inside JSON) and about 41 KB for a zoom, as measured. Size the socket's message limit for it with room to spare: `@embededitor/relay` takes up to 8 MiB a message on Node, and on Cloudflare a Worker's own limit, 32 MiB.

**`ping`**, every 10 s.

### From the Relay

**`AGENT_CONNECTED`**, on an agent's first `list_commands` or `run_command` with the link, and again each time a socket opens on a session an agent already called. The editor shows "Agent Connected" from then on.

```json theme={"dark"}
{ "type": "AGENT_CONNECTED" }
```

**`CALL`**, one `run_command`: a fresh UUID as its `id`, the command's `name` as the agent sent it, and its `input` as the agent sent it (`{}` when it sent none).

```json theme={"dark"}
{ "id": "0b9c6a52-4f1e-4d8a-9a57-2f7c1d3e8b40", "input": { "ratio": "16:9" }, "name": "crop_set_ratio", "type": "CALL" }
```

The editor runs a `CALL` only when its `name` is in the commands it last offered (its latest `commands` message). Any other name, an empty one included, is an unknown command and runs nothing: the editor answers it at once, `isError: true`, with one text part, as the handle rejects a command it doesn't have:

```json theme={"dark"}
{"code":"INVALID_COMMAND","props":["command"]}
```

**`ENDED`**, the session's end, sent to the open socket just before its close with 4000. A socket opened on a session that already ended, or that doesn't exist, gets the close alone.

```json theme={"dark"}
{ "reason": "DISCONNECTED", "type": "ENDED" }
```

**`pong`**, at once, for each `ping`.

Send nothing else. The editor drops a frame that isn't JSON or isn't one of these messages, and a `CALL` with no `id`; a `CALL` whose `name` isn't text is an unknown command. It reads an `ENDED` reason other than `DISCONNECTED` or `EXPIRED` as `TAB_CLOSED`, as it reads a close's. The relay, the same way, drops a frame from the editor that isn't JSON or isn't one of its messages.

Several calls may be on their way at once. The editor runs them in the order they arrive (its command queue) and answers each under its `id`, in any order. A result for an `id` the relay no longer waits for, its 55 s past, is dropped.

**A call belongs to the session, not to the socket it went out on.** The relay keeps the calls on their way by `id`, per session, and takes a `result` from whichever socket the session has now: a call sent on one socket may be answered on a newer one, after the editor reconnected. A socket replaced by a newer one (4001) fails no call on its way. Only the session's socket lost (closed, or found silent) or the session's end answers them early.

Once the user presses Disconnect, or the session ends, the editor runs none of the calls still waiting, stops the AI's work of the one running as its Stop does, and answers none of them: the relay answers each with the end's sentence.

### The Heartbeat

A network lost without a close, or a phone's tab asleep, leaves a socket open and dead. Both ends watch for it.

| | Who | Rule |
| - | - | - |
| Ping | The editor | Sends `ping` every 10 s. |
| Pong | The relay | Answers `pong` at once. Ours answers without waking its Durable Object (`setWebSocketAutoResponse`). |
| A silent relay | The editor | Anything heard counts. When its check, every 10 s, finds nothing heard for 15 s, it closes the socket and opens another. |
| A silent tab | The relay | When a `run_command` arrives and the last `ping` (or the socket's opening, before any ping) is older than 25 s: closes the socket with 4002, starts the 2-minute grace, and answers the call at once that the tab is away. |

Only `run_command` checks the socket's silence. `list_commands` answers the stored list without looking at the socket, even while the tab is away. And only the editor's `ping` moves the relay's clock: a `result` or a `commands` message doesn't. A silent socket that no `run_command` touches stays open, and its session lives on until the link's 2 hours, unless the socket's close arrives first.

### Close Codes

| Code | Reason | The relay closes with it when | The editor |
| - | - | - | - |
| 4000 | The `EndReason` | The session ended (after `ENDED`), or the socket opened on a session that ended or doesn't exist (no `ENDED` first). | Ends the link, shows why, and never reconnects. A reason other than `DISCONNECTED` or `EXPIRED` reads as `TAB_CLOSED`. |
| 4001 | `REPLACED` | A newer socket opened on the same session. The calls on their way keep waiting. | Ignores it when it opened the newer socket itself. Otherwise reconnects, as on a drop. |
| 4002 | `SILENT` | A `run_command` found the socket silent for over 25 s. | Reconnects, as on a drop. |
| Any other | | The network dropped, or the relay restarted. | Reconnects. |

**Reconnecting.** The editor tries again after 0.5, 1, 2, 4, 8 and 15 s, then every 15 s, and at once when the tab becomes visible or the network comes back (`visibilitychange`, `online`). On each socket it sends its commands again. It stops 2 minutes after the drop, the relay's own grace, and shows the link ended ("Connection lost").

**The tab closing.** On `pagehide`, unless the page goes to the back-forward cache, the editor sends `POST /sessions/end` with `closed: true` by `navigator.sendBeacon`, a request that outlives the page.

**Disconnect.** The editor stops the agent's calls at once, sends `POST /sessions/end` with the token, and ends the link whatever the answer.

## The Session

What a relay keeps per session (ours, in its Durable Object's storage):

| Field | What it holds |
| - | - |
| `expiresAt` | When it was made, plus 2 hours. |
| `disconnectedAt` | Since when no socket is open: from the moment it was made until its first socket. `null` while one is open. |
| `socket`, `socketAt` | The open socket's tag, and when it opened. |
| `connected` | An agent called with the link. |
| `commands` | The editor's latest command list, as JSON. |
| `guide` | The text the editor's latest `commands` message carried for the agent, `''` for none. |
| `endedAt`, `endedReason` | When and why it ended. |

| Constant | Value | What it times |
| - | - | - |
| `LINK_LIFETIME` | 2 h | A link's life from when it's made, whatever happens. |
| `RECONNECT_GRACE` | 2 min | How long a session waits for a socket, after it's made, after its socket closed, or after a `run_command` found its socket silent, before it ends as `TAB_CLOSED`. |
| `SOCKET_STALE` | 25 s | A socket with no ping for longer is a tab away, when a `run_command` finds it so. |
| `CALL_TIMEOUT` | 55 s | How long a call waits for the editor's result. Keep it under an MCP client's own timeout (60 s), so the agent always hears why. |
| `ENDED_KEPT` | 1 h | How long an ended session's record stays, so a late call hears why it ended. Then it's deleted. |

### Its Life

1. **Made** by `POST /sessions`: it lives 2 hours and waits for its socket.
2. **Socket open**: a newer socket replaces any open one (4001), and the wait stops. The calls on their way keep waiting, their results welcome on the newer socket. Where an agent already called, the relay sends `AGENT_CONNECTED`.
3. **Agent Connected**, on the first `list_commands` or `run_command` with the link: the relay sends `AGENT_CONNECTED`.
4. **Socket lost**, closed, or found silent by a `run_command`: every call on its way answers that the tab disconnected while it ran, a `run_command` meanwhile answers that the tab is away, and the 2-minute grace starts. A socket that opens again stops it.
5. **Ended**, for one of three reasons: the relay sends `ENDED`, closes the socket with 4000 and the reason, and answers every call on its way with the ended sentence. Its record stays an hour, then it's deleted, and a call with that link answers that it isn't valid.

| Reason | When | The panel says |
| - | - | - |
| `DISCONNECTED` | `POST /sessions/end` without `closed` | "Agent Disconnected" |
| `TAB_CLOSED` | `POST /sessions/end` with `closed: true`, or no socket for 2 minutes | "Connection Lost" |
| `EXPIRED` | 2 hours after it was made | "Link Expired" |

## MCP

**Transport.** Streamable HTTP, MCP's HTTP transport, at `/mcp`, stateless: no `Mcp-Session-Id`, and each request answered as JSON (`application/json`), never as an event stream. Ours makes a fresh `Server` and `WebStandardStreamableHTTPServerTransport` for every request, from `@modelcontextprotocol/sdk` 1.32.2, with `enableJsonResponse: true` and no session id generator. A client sends `POST` with `Accept: application/json, text/event-stream` and `Content-Type: application/json`; the SDK answers 406 or 415 otherwise.

**Server.** Its name is `embed-editor`, its version `0.0.0`, its capability `tools`, and its instructions, which a client reads before any call:

```text instructions theme={"dark"}
This server drives a person's Embed Editor (an image editor open in their browser tab) through the editor's own commands.
The person gives you a link from the editor, like https://agent.shop.example.com/link#… — call list_commands with it first, then run_command for each command, the link in every call.
The commands annotate the photo (arrows, texts, boxes), blur or pixelate areas, adjust, filter, crop, frame, undo and save.
```

The example link names the relay's own origin, the one the MCP request came in on (`new URL(req.url).origin`), as the link `POST /sessions` answers does: here, a relay at `https://agent.shop.example.com`. Behind a proxy, name the public origin instead ([The relay's origin](#the-links-token)).

### The Two Tools

`tools/list` answers these two, always, with or without a link:

```json tools/list theme={"dark"}
[
	{
		"description": "Lists the commands of the person's Embed Editor, open in their browser tab, by the link they copied from it: each command's name, what it does, and its input as JSON Schema. Call it first, then run_command for each command.",
		"inputSchema": {
			"properties": {
				"link": { "description": "The link the person copied from the editor, as they pasted it (like https://agent.shop.example.com/link#…).", "type": "string" }
			},
			"required": ["link"],
			"type": "object"
		},
		"name": "list_commands"
	},
	{
		"description": "Runs one of the editor's commands, as list_commands gives them: its name, and its input as the command's inputSchema says.",
		"inputSchema": {
			"properties": {
				"input": { "description": "The command's input, as its inputSchema in list_commands says ({} for a command that takes none).", "type": "object" },
				"link": { "description": "The link the person copied from the editor, as they pasted it (like https://agent.shop.example.com/link#…).", "type": "string" },
				"name": { "description": "The command's name, as list_commands gives it (like read_screenshot).", "type": "string" }
			},
			"required": ["link", "name", "input"],
			"type": "object"
		},
		"name": "run_command"
	}
]
```

The two link descriptions name the relay's own origin, as the instructions do.

Every `tools/call` is checked in this order, and the first that fails answers ([Errors](#errors)):

1. **The link.** No `link`, or no token in it: the not-a-link sentence, whatever the tool's name.
2. **The tool's name.** Neither `list_commands` nor `run_command`: `No tool <name>`.
3. **`run_command`'s `name`.** Not a string, or absent: the sentence that it takes the command's name. An empty string passes here.
4. **The session**, found by the token's hash: never made, deleted, or ended, it answers why. For `run_command`, then the socket: none open, or silent, answers that the tab is away.
5. **The editor**, for `run_command`: a name it didn't offer, the empty one included, answers `{"code":"INVALID_COMMAND","props":["command"]}`.

### list\_commands

Answers one text part: the guide below, then the editor's text for the agent (the `guide` of its latest `commands` message) where it sent one, then the session's command list as JSON, the array of that message's `commands`, each after a blank line. It answers the stored list without looking at the socket, so it answers even while the tab is away. On an agent's first call it marks the session connected, and the relay sends `AGENT_CONNECTED`.

```text The guide theme={"dark"}
You are connected to the person's Embed Editor, open in their browser tab. They watch every change you make as you make it.
How to work:
1. Call read_size for the image's size, then read_screenshot to see the photo. Every coordinate a command takes is in image px, as read_size gives them; each screenshot comes with a note saying how its px map to image px.
2. After you place something, look again (read_screenshot, with `area` to zoom on the spot) and correct it with the update command of what you placed.
3. Every edit is one undo step: history_undo takes back the last one, yours or the person's.
4. Save (output_save) only when the person asks for it.
Each command in the list at the end runs with run_command: its name, and its input as its inputSchema says.
```

### run\_command

Reads `name` (a string) and `input` (`{}` when absent), marks the session connected, and sends the editor a `CALL` when its socket is open and not silent. It waits up to 55 s for the `result`, and answers its `content` and `isError` as the `tools/call` result, only the fields MCP reads: `content`, a list of text and image pieces, and `isError`, a boolean. A result with anything else in their place, or a piece MCP can't carry, isn't passed on: the agent is answered as failed ("The editor's answer to `<name>` couldn't be read. Take a screenshot to see whether it ran."). `name` is at most 128 characters; a longer one, or one that isn't a string, is answered as failed.

The relay doesn't check the name against the list: the editor does. It runs a name only when it's in the commands it last offered, and answers any other, an empty one included, with `{"code":"INVALID_COMMAND","props":["command"]}`. A name it offered it turns back into its command by looking it up in that list, never by a rule on its letters (`crop_set_ratio` is `crop.setRatio`), and runs it on its own handle, with the command's schema and its errors, in its turn as the user sees the editor's own AI work: nothing it makes is selected, and an Undo or a Redo of its step selects nothing it made.

What the editor answers:

| Command | `content` |
| - | - |
| Most | One text part: the command's value as JSON, `null` for a command that gives nothing back. A file is its name, size and type, `{ "name": "photo.jpg", "size": 482113, "type": "image/jpeg" }`: its bytes stay in the browser. `read_options` waits for Annotate's screens first, as the editor loads them a moment after the photo shows. |
| A name it didn't offer | `isError: true`, one text part: `{"code":"INVALID_COMMAND","props":["command"]}`. Nothing runs. |
| `read_screenshot` | An image part, a JPEG as base64 (`mimeType: 'image/jpeg'`, quality 0.85, at most 1024 px on its longer side), then a text part, its note. Its input is `{ area?: { x, y, width, height }, maxSize?: number }`, `area` in the output's px; `maxSize` can't go past 1024. |
| A refused one | `isError: true`, one text part, as JSON: its `code` and the paths it names (`props`), with the schema's `issues` where the input was off its schema, as `{"code":"INVALID_COMMAND","issues":[…],"props":["input.piece.at"]}`. Any other failure is `{"code":"FAILED","props":[]}`. The editor's own AI reads the same texts. |

A screenshot's note, for example:

```text theme={"dark"}
Screenshot 1024×683 px of the image area x 0–3000, y 0–2000 (image px), the output's x 0–3000, y 0–2000 (read_screenshot's area px). Image px = (0 + sx × 2.9297, 0 + sy × 2.9283).
```

A whole-photo screenshot's `result` measured about 113 KB on the socket (an 85 KB JPEG in base64, inside JSON), a zoom about 41 KB: size your socket's message limit for it ([From the Editor](#from-the-editor)).

### Errors

The relay's own answers, in the order a call is checked (above). Each answers `isError: true` with one text part, a sentence the agent can repeat to the user.

| When | The text |
| - | - |
| No `link`, or no token in it | `That isn't an Embed Editor link. Ask the person to copy the link the editor shows, and pass it whole.` |
| A tool other than the two | `No tool <name>: this server has list_commands and run_command.` |
| `run_command` with no `name`, or one that isn't a string | `run_command takes the command's name, as list_commands gives it.` |
| No session for it: never made, or deleted an hour after its end | `This editor link isn't valid. Ask the person to copy it again from their editor.` |
| Ended, `DISCONNECTED` | `The person disconnected you from their editor. Ask them for a new link if they want you to keep editing.` |
| Ended, `EXPIRED` | `This editor link expired. Ask the person for a new link from their editor.` |
| Ended, `TAB_CLOSED` | `The editor's tab was closed, so this link ended. Ask the person for a new link from their editor.` |
| `run_command`, the tab away or silent | `The editor's tab is not connected right now (it may be in the background, asleep, or offline). Ask the person to bring the tab back, then try again.` |
| `run_command`, no result in 55 s | `The editor didn't answer <name> within 55 s. Take a screenshot to see whether it ran.` |
| `run_command`, the socket lost while the call ran | `The editor's tab disconnected while <name> ran: it may have run or not. Once the tab is back, take a screenshot to see.` |

`<name>` is the name the call gave: the tool's in `No tool`, the command's in the others. A name the editor didn't offer comes back from the editor itself (`{"code":"INVALID_COMMAND","props":["command"]}`, in [run\_command](#run_command)).

## Routing

The link's hash names the session, and everything for a link goes to whatever holds its socket: its record, its timers, and the calls waiting for a result.

* **On Cloudflare** ([`@embededitor/relay/cloudflare`](https://docs.embededitor.com/mcp/relay#on-cloudflare-workers), ours included): the hash names a Durable Object (`idFromName(hash)`), the one place that holds the socket and the record, wherever a request lands. Its alarm runs the lifetime, the grace and the record's deletion.
* **One process** ([`@embededitor/relay`](https://docs.embededitor.com/mcp/relay) on Node): a map from hash to session, each with its socket, its record, its waiting calls and its timer.
* **Several processes**: the record in a store every process reads, with its own expiry. The process that holds a socket listens on its hash's channel (Redis pub/sub, for one), and the process an MCP request lands on publishes the `CALL` there and waits for the `result` on a reply channel, 55 s at most.

The last one is an idea for other stacks, not built or tried.

## Security

* **The token never sits in a URL, a log or storage.** Hash it as it arrives, look the session up by the hash, and log neither.
* **Compare the relay's secret in constant time.** Hash both sides with SHA-256 and compare the digests with no early exit, so the answer's time says nothing of how much matched (ours ORs the XOR of every byte; Node has `crypto.timingSafeEqual`). A missing or empty secret turns the Bearer way off: `Bearer ` with nothing after it never passes. Read the header as [POST /sessions](#post-sessions) says: the scheme in any case, whitespace, a secret with no whitespace.
* **Match the allowed origins as [POST /sessions](#post-sessions) says.** The `Origin` header against each entry: `*` for every origin, an exact origin, or a subdomain pattern that takes only real subdomains (the same scheme, the same port, the suffix after a dot, and a subdomain of letters, digits, hyphens and dots, so `evilshop.example.com` and `shop.example.com.evil.example` never pass `*.shop.example.com`). Never a bare suffix or substring match, and a request with no `Origin` doesn't pass this way. Answer CORS for the matched origin only, never `*`, with `vary: origin` on every answer. The `Origin` check keeps other sites' pages from making links in a browser. A client outside a browser can send any `Origin`, so where that matters, make links from your backend.
* **The link is the whole permission.** Anyone who holds it drives the editor until it ends. Keep its lifetime short, and end it as the tab closes.
* **Limit how many links one user makes**, in a real deploy. Behind your backend, its sign-in tells you who.
* **The socket needs no `Origin` check**: the token in its subprotocol is its credential.

> [card] [MCP](https://docs.embededitor.com/mcp/overview.md)
>
> Add MCP to your editor, and what your users see.

> [card] [Your Own Relay](https://docs.embededitor.com/mcp/relay.md)
>
> Run the MCP relay at your own address, step by step.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.