Call an App from your own server
Call an Oyster App from a Worker or server over MCP. Open a session, send the execute call, read large outputs in slices, retry safely and avoid paying twice.
Another server can call the Apps on your Oyster. It speaks MCP over HTTP to
$OYSTER_URL/mcp. This page covers the parts a client must get right: the
session, the key, the execute call, large outputs, retries and idempotency.
You can use any MCP client library. If you write the calls yourself, follow the steps below. The example at the end is a complete client in one file.
Choose a key
Send the key on every request as Authorization: Bearer <key>. The key is
checked on every request, including notifications.
- The owner key works, but it can do everything on that Oyster. Do not give it to another server.
- A scoped key reaches only the Apps it was granted. Issue one with
POST /api/keys. See Call one App from another server.
A bad or revoked key gets 401.
Open a session
A session has four steps.
- Initialize.
POST /mcpwith a JSON-RPCinitializerequest. SendprotocolVersion2025-11-25. That is the only version Oyster accepts. Send both headersContent-Type: application/jsonandAccept: application/json, text/event-stream. Without thatAccept, the request is refused. - Keep the session id. The reply carries an
mcp-session-idheader. Send it on every later request. - Confirm.
POSTanotifications/initializednotification. It has noid. The answer is202with no body. - Call tools. Send
tools/callrequests with themcp-session-idheader. You may also sendmcp-protocol-version: 2025-11-25. Any other value gets400.
Replies to requests arrive as a server-sent event stream
(content-type: text/event-stream). Each reply is a data: line holding one
JSON-RPC message. Match it to your request by id, and ignore any data: line
that is empty.
To end the session, send DELETE /mcp with the mcp-session-id header.
Reuse the session
Open one session and reuse it for every call. Each key may hold at most 8 open
sessions. A ninth initialize gets 429 with the body
Too many open MCP Sessions. Opening a new session for every call, or for every
chunk of a large output, runs into that limit.
Sessions live in memory on the Oyster. A request with an unknown or closed
session id gets 404. When that happens, initialize a new session and repeat
the call.
Call execute
Oyster serves one tool, execute. It takes one argument, code: a string of
async JavaScript. The code runs in a fresh sandbox on each call. Nothing
survives between calls.
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "execute",
"arguments": {
"code": "return await env.PRINTS.listOutputs({})"
}
}
}
Each App is env.<APP>, such as env.PRINTS. Call a method as
await env.PRINTS.listOutputs({ ... }) and return the value you want. To find
methods, the code can call forage.search({ query }) and
forage.describe({ path }).
The reply’s result.content[0].text is the returned value as JSON text. Parse
it. If result.isError is true, the text is the failure message instead.
A returned value larger than 256 KiB fails with
Sandbox result exceeds 256 KiB. For large data, read it in slices, as below.
Read a large output
openOutput on Prints reads at most 128 KiB of one print per call. The bytes
come back base64-encoded. That size fits inside the 256 KiB result limit.
return await env.PRINTS.openOutput({
printId,
byteOffset: 0,
byteLength: 131072,
});
The result has printId, path, byteOffset, content (base64), encoding
("base64") and truncated.
Page through the file like this:
- Start at
byteOffset0. - Decode
content. Add the decoded byte count tobyteOffset. - Call again with the new offset.
- Stop when
contentis an empty string. That is the final slice.
Do not use truncated to decide when to stop. It is true for any slice that
carries bytes, including the last one. It is false only on the empty slice at
the end of the file.
A call can also return a refusal such as { "error": "not_found" }. Check for
error before you read content. A byteOffset past the end of the file is an
error, not an empty slice.
Retry
Retry only what is safe to repeat.
| Status | Where it comes from | What to do |
|---|---|---|
401 |
Bad or revoked key. | Do not retry. Fix the key. |
404 |
Unknown or closed session. | Initialize a new session, then repeat the call. |
429 |
The open-session limit (Too many open MCP Sessions). |
Close a session you no longer use, or wait, then retry. |
503 |
MCP is unavailable or MCP is closed. |
Wait, then retry. |
Oyster does not send a Retry-After header for these. If a proxy or Cloudflare
adds one, honor it. Otherwise back off, for example 1, 2 and 4 seconds, and stop
after a few tries.
A retried initialize is safe. A retried execute runs your code again. A
5xx on execute does not tell you whether the code ran. Retry it only when
the call is idempotent.
Make calls idempotent
execute is not idempotent. Each call runs the code you send. Oyster never
replays a program for you.
Methods that spend money take a request id. Prints generateImage and
generateVideo take requestId, which is media_request_ followed by 21
random lowercase letters or digits. Make the id before the first call and keep
it. To retry, send the same id with the same input. You get the same generation,
not a second one, and you are not charged twice.
If a call with the same id arrives while the first is still running, it returns
a pending result with retryAfterMs. Wait that long and send the same call
again. The same id with different input returns { "error": "conflict" }.
Reads such as listOutputs and openOutput change nothing. Repeat them freely.
Run a process with Shed
A key limited to one Computer can run and manage processes there through Shed.
Issue it with apps.use on Shed and computer.use on that Computer. The key
acts on that Computer only.
start takes a requestId of your choosing, up to 256 characters. Make it
before the first call and keep it. To retry, send the same id with the same
input and you get the same process, not a second one. The same id with a
different command, directory or port returns a conflict.
const started = await env.SHED.start({
command: "pnpm dev",
cwd: "/workspace/guestbook",
port: 3000,
requestId: "guestbook-dev-1",
});
// started.process.id names the process from here on.
// Read what it printed. Offsets and lengths are bytes, up to 128 KiB a call.
const log = await env.SHED.logs({ id: started.process.id, offset: 0 });
// Stop it and start the same command again as a new process.
const again = await env.SHED.restart({
id: started.process.id,
requestId: "guestbook-dev-2",
});
// again.parentId is started.process.id.
await env.SHED.stop({ id: again.process.id });
A key can read the logs of, restart and stop only the processes it started.
listProcesses shows every process on the Computer, with controllable: true
on the ones you may control. A process started in the Shed window is not
controllable by a key.
restart answers { "kind": "pending", "retryAfterMs": 1000 } while the old
process is still exiting. Send the same call again. A process that was started
before Shed recorded its port cannot be restarted. Start it again with a new
requestId.
observe({ id }) reads any process on the Computer as one run: its state
(running, completed, failed, cancelled when you stopped it, or
unknown), a reason such as computer_slept when the Computer went to sleep
under it, and its times. completed means it exited with code 0, not that its
result was checked. For a process you started, log.cursor says how far along
the log you are: send it back as cursor until log.eof is true, and read the
bytes with logs. cost is null; Shed does not meter a process.
Revoking the key refuses its next call. Processes it already started keep running until you stop them from the Shed window.
Example
This client opens one session, calls execute, retries 429 and 503, and
reads an output in slices. It runs on Node 24 or newer and in a Worker.
const base = process.env.OYSTER_URL!;
const key = process.env.OYSTER_KEY!;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
let sessionId: string | undefined;
let nextId = 1;
async function post(body: object, headers: Record<string, string> = {}) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(`${base}/mcp`, {
method: "POST",
headers: {
authorization: `Bearer ${key}`,
"content-type": "application/json",
accept: "application/json, text/event-stream",
...headers,
},
body: JSON.stringify(body),
});
if ((res.status === 429 || res.status === 503) && attempt < 3) {
const wait = Number(res.headers.get("retry-after")) * 1000;
await sleep(wait || 1000 * 2 ** attempt);
continue;
}
return res;
}
}
async function open() {
const res = await post({
jsonrpc: "2.0",
id: nextId++,
method: "initialize",
params: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "my-server", version: "1" },
},
});
if (!res.ok) throw new Error(`initialize failed: ${res.status}`);
sessionId = res.headers.get("mcp-session-id")!;
await res.text();
await post(
{ jsonrpc: "2.0", method: "notifications/initialized" },
{ "mcp-session-id": sessionId },
);
}
async function reply(res: Response, id: number) {
for (const event of (await res.text()).split("\n\n")) {
const data = event
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).trim())
.join("");
if (data === "") continue;
const message = JSON.parse(data);
if (message.id === id) return message;
}
throw new Error("no reply");
}
async function execute(code: string): Promise<unknown> {
if (sessionId === undefined) await open();
const id = nextId++;
const res = await post(
{
jsonrpc: "2.0",
id,
method: "tools/call",
params: { name: "execute", arguments: { code } },
},
{ "mcp-session-id": sessionId! },
);
if (res.status === 404) {
// The session is gone. Open a new one and run the call again.
sessionId = undefined;
return execute(code);
}
if (!res.ok) throw new Error(`execute failed: ${res.status}`);
const { result, error } = await reply(res, id);
if (error) throw new Error(error.message);
const text = result.content[0].text;
if (result.isError) throw new Error(text);
return JSON.parse(text);
}
export async function readOutput(printId: string): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
let byteOffset = 0;
for (;;) {
const slice = (await execute(
`return await env.PRINTS.openOutput(${JSON.stringify({ printId, byteOffset })})`,
)) as { error?: string; content?: string };
if (slice.error) throw new Error(slice.error);
if (!slice.content) break; // the empty slice is the end
const bytes = Uint8Array.from(atob(slice.content), (c) => c.charCodeAt(0));
chunks.push(bytes);
byteOffset += bytes.length;
}
return new Uint8Array(await new Blob(chunks).arrayBuffer());
}
Call readOutput(printId) with an id from listOutputs. Close the session with
DELETE /mcp when your server shuts down.
Where next
- Call one App from another server issues the scoped key.
- Prints lists the methods that generate and read outputs.
- Oyster docs cover the MCP endpoint.