Skip to main content
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

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.

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

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.
200
403
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:
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.
Disconnect
The tab closing
closed: true ends it as TAB_CLOSED. Without it, the end is the user’s Disconnect, DISCONNECTED. 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
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:
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. 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:
405
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.
wire.ts

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. 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.
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:
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.
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).
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:
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.
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. 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

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):

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.

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:
instructions
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 Two Tools

tools/list answers these two, always, with or without a link:
tools/list
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):
  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.
The guide

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: A screenshot’s note, for example:
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).

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. <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).

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, 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 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 says: the scheme in any case, whitespace, a secret with no whitespace.
  • Match the allowed origins as 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.

MCP

Add MCP to your editor, and what your users see.

Your Own Relay

Run the MCP relay at your own address, step by step.