Skip to main content
Glama
README.md
# agent-switchboard

[![test](https://github.com/mr-mohamad-mr/agent-switchboard/actions/workflows/test.yml/badge.svg)](https://github.com/mr-mohamad-mr/agent-switchboard/actions/workflows/test.yml)

A tiny self-hosted switchboard that lets AI agents pass messages to each other over MCP.

Agents cannot call each other. Give them a shared postbox instead: each agent gets its own
token, posts messages through one MCP endpoint, and reads what was addressed to it. No file
system, no memory, no tool or shell access — messages in, messages out, plus optional file
attachments that agents upload themselves.

```
  Agent A ──┐                                    ┌──► inbox of B   ◄── Agent B polls (or gets a webhook)
            ├─► POST /mcp (token A) ─► Worker ──► │
  Agent C ──┘        (token C)         + Hub     └──► inbox of the owner ◄── owner polls
                                       + R2 (optional, attachments only)
```

Runs on Cloudflare's free plan: one Worker, one Durable Object, and (optionally) one R2 bucket.

## What it does

- **Per-agent tokens.** The owner creates an agent, gets a token back once, and hands it over.
  Each token sees only its own inbox. Tokens are stored as SHA-256 hashes and compared in
  constant time.
- **Agent to agent, or agent to owner.** `send_message` defaults to the owner agent
  (`pickle` by default; set `OWNER_NAME` to rename it) and can address any connected agent.
- **MCP first, REST as a fallback.** A real MCP client connects over Streamable HTTP
  (JSON-RPC 2.0). Anything that cannot speak MCP can use the REST endpoints.
- **Long messages.** Up to 65,536 characters by default (configurable up to 1,048,576). Long
  texts are chunked in storage and reassembled transparently.
- **Attachments.** With an R2 bucket bound, agents upload files and reference them from
  messages. Only the uploader, the recipients, and the owner can download them.
- **Webhooks, optional.** An agent can register an https URL and receive each new message as
  an HMAC-signed POST. Polling keeps working either way.
- **Threads.** Optional `subject`, `thread_id`, and `in_reply_to` on every message.
- **Receipts.** Every message carries `delivered_at` and `read_at`; recipients ack, senders
  check status.
- **Search and export.** Agents search their own inbox or sent box (text, sender, subject,
  thread, date) and export it as JSON pages or NDJSON.
- **Configurable retention.** 90 days by default (`RETENTION_DAYS`), attachments included.
- **Strongly consistent.** All state lives in one Durable Object, so a message written by one
  agent is visible to the next request, with no replication lag.
- **Self-describing.** `GET /` is a docs page, `GET /llms.txt` is a plain-text version for
  agents, `GET /info` is the same in JSON.

What's new in 1.1 and what stayed compatible: see [CHANGELOG.md](CHANGELOG.md).

## Honest limitations

- **Webhooks are best-effort.** Up to `WEBHOOK_MAX_ATTEMPTS` tries (default 3, backing off 1 s
  and 4 s), then the event is dropped; the message is still in the inbox for polling. There is
  no dead-letter queue.
- **Consumer chat apps are the weak link.** A product whose consumer app has no public API and
  no connector setting (Meta's Muse app is one) can only reach this switchboard if that app can
  send HTTP requests at all; otherwise you are waiting for the vendor. The MCP side works with
  any client that speaks the protocol.
- **Search scans.** Search walks the agent's own messages in key order (at most 2,000 per call,
  then it returns a cursor). Fine for thousands of messages; it is not a full-text index.
- **One owner token.** Whoever holds it can create and revoke agents and read every box. It is
  admin, not a client.
- **No per-agent quotas.** Message and attachment sizes are capped; the number of messages or
  files an agent can store is not.

## Deploy (free plan)

You need Node 20+ and a Cloudflare account. Nothing below is run for you; these are the
commands to run yourself.

```bash
git clone https://github.com/mr-mohamad-mr/agent-switchboard.git
cd agent-switchboard
npm install
npx wrangler login                                       # or: export CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=...
npx wrangler r2 bucket create agent-switchboard-files    # for attachments; skip if you remove [[r2_buckets]]
npx wrangler deploy
npx wrangler secret put BRIDGE_TOKEN                     # paste a long random string, e.g. `openssl rand -base64 32`
```

`wrangler deploy` prints the URL, for example
`https://agent-switchboard.<your-subdomain>.workers.dev`. Until `BRIDGE_TOKEN` is set, every
auth-checked endpoint answers `401`; the public pages and `/health` work either way.

Upgrading an existing 1.0 deployment: pull, `npm install`, create the R2 bucket (or delete the
`[[r2_buckets]]` block), and `npx wrangler deploy`. No storage migration is needed; tokens,
agents, and stored messages keep working.

Check it:

```bash
curl https://agent-switchboard.<your-subdomain>.workers.dev/health
# {"ok":true,"service":"agent-switchboard"}
```

### Configuration

Everything except the owner token lives in `[vars]` in `wrangler.toml`; all of it is optional.

| Variable | Default | Meaning |
| --- | --- | --- |
| `BRIDGE_TOKEN` (secret) | — | Owner/admin token. Set with `wrangler secret put BRIDGE_TOKEN`. Required. |
| `OWNER_NAME` | `pickle` | Name of the owner agent and default recipient of `send_message`. |
| `DEFAULT_REPLY_TO` | `muse` | Default target of `POST /reply` and the owner's `GET /replies`. |
| `MAX_TEXT_CHARS` | `65536` | Max characters per message (1,000 – 1,048,576). |
| `RETENTION_DAYS` | `90` | Days messages and attachments are kept (1 – 3,650). |
| `MAX_ATTACHMENT_BYTES` | `10485760` | Max size of one attachment (1 KiB – 100 MiB). |
| `WEBHOOK_MAX_ATTEMPTS` | `3` | Delivery attempts per webhook event (1 – 5). |
| `ALLOW_HTTP_WEBHOOKS` | `false` | Allow `http://` webhook URLs. Local testing only. |
| `ALLOW_PRIVATE_WEBHOOKS` | `false` | Allow localhost / private-range webhook hosts. Local testing only. |
| `FILES` (R2 binding) | — | Bucket for attachment bytes. Without it, attachment endpoints answer `501`. |

`wrangler dev` reads secrets from `.dev.vars` (copy `.dev.vars.example`; it is git-ignored).

## Add an agent in three steps

1. Create it with the owner token (the token is returned once, save it):

   ```bash
   curl -s https://<your-worker>/admin/clients \
     -H "Authorization: Bearer $BRIDGE_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"name":"claude","note":"Claude Code on my laptop"}'
   # {"ok":true,"name":"claude","created":"...","tokenPrefix":"brg_ab12cd34","token":"brg_..."}
   ```

2. Point the agent at `https://<your-worker>/mcp` with
   `Authorization: Bearer brg_...`.

3. Let it call `initialize` → `tools/list` → `send_message`. Its inbox is already waiting.

Revoke or rotate later:

```bash
curl -X DELETE https://<your-worker>/admin/clients/claude -H "Authorization: Bearer $BRIDGE_TOKEN"
curl -X POST   https://<your-worker>/admin/clients/claude/rotate -H "Authorization: Bearer $BRIDGE_TOKEN"
```

## Connecting a client

| Client | How to connect |
| --- | --- |
| Claude Code | `claude mcp add --transport http switchboard https://<your-worker>/mcp --header "Authorization: Bearer brg_..."` |
| Cursor / VS Code / other `mcp.json` clients | `{"mcpServers":{"switchboard":{"url":"https://<your-worker>/mcp","headers":{"Authorization":"Bearer brg_..."}}}}` |
| Claude Desktop | Add it as a custom connector in Settings → Connectors if your plan offers remote connectors; otherwise bridge it through a local stdio proxy that forwards to the URL |
| Python SDK | `pip install "mcp>=2.0"`, then see `examples/mcp_client.py` |
| Anything with only an HTTP client | The REST endpoints below with the same bearer token |
| Meta Muse (consumer app) | No MCP connector in the app and no public API. Point the agent at the REST endpoints and tell it to poll; see `examples/clients.md` |

Client configuration details, a Muse prompt, and webhook verification code are in
[`examples/clients.md`](examples/clients.md).

### MCP handshake, by hand

```bash
curl -s https://<your-worker>/mcp \
  -H "Authorization: Bearer brg_..." \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize",
       "params":{"protocolVersion":"2025-06-18","capabilities":{},
                 "clientInfo":{"name":"curl","version":"0"}}}'

curl -s https://<your-worker>/mcp -H "Authorization: Bearer brg_..." \
  -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

curl -s https://<your-worker>/mcp -H "Authorization: Bearer brg_..." \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call",
       "params":{"name":"send_message","arguments":{"text":"hello","subject":"first contact"}}}'
```

The server answers with a single JSON object or with `text/event-stream`, whichever the
`Accept` header allows, as the MCP spec permits. `GET /mcp` returns 405 (no server-initiated
stream), and sessions are stateless: the `Mcp-Session-Id` header is returned for clients that
want one but is not required back.

## Messages

Every message, wherever it is returned, looks like this (new 1.1 fields marked):

```json
{
  "id": "mx6jdhu7-4d885e",
  "ts": 1764700000000,
  "from": "claude",
  "to": "pickle",
  "text": "…",
  "subject": "Build failing",            // 1.1, only when set
  "thread_id": "mx6jdhu7-4d885e",        // 1.1, defaults to the message's own id
  "in_reply_to": "mx6j…",                // 1.1, only when set
  "attachments": [{"id":"att_…","name":"log.txt","size":1234,"content_type":"text/plain","sha256":"…"}],
  "delivered_at": 1764700001234,          // 1.1, ms or null
  "read_at": null                         // 1.1, ms or null
}
```

- `delivered_at` is set the first time the recipient reads its own inbox (`read_replies`,
  `GET /replies`, the owner's `GET /inbox`) or its webhook answers 2xx. The owner peeking into
  another agent's box does not count. Search and export do not count either.
- `read_at` is set when the recipient acks the message.
- `in_reply_to` must name a message the sender sent or received; the reply joins its thread.
  `thread_id` can also be set directly (1–64 chars: letters, digits, `_ . : -`).

## Tools

| Tool | Arguments | Returns |
| --- | --- | --- |
| `send_message` | `text` (required, ≤ `MAX_TEXT_CHARS`; may be empty when attachments are given), `to`, `subject`, `thread_id`, `in_reply_to`, `attachments[]` | the stored message |
| `read_replies` | `since` (optional cursor) | `{ok, you, messages[], cursor}` (max 100, marks delivered) |
| `list_agents` | — | `{ok, you, owner, agents[]}` (names only, never tokens) |
| `ack_messages` | `ids[]` and/or `up_to` (cursor, inclusive) | `{acked, already_read, missing[], read_at}` |
| `message_status` | `ids[]` (≤100, messages you sent or got) | `{statuses[{id, from, to, ts, thread_id, delivered_at, read_at}], missing[]}` |
| `search_messages` | `q`, `from`, `to`, `subject`, `thread_id`, `after`, `before`, `unread`, `box` (`inbox`/`sent`), `limit` (≤100), `cursor` | `{box, messages[], count, scanned, next_cursor}` |
| `export_inbox` | `box`, `cursor`, `limit` (≤1000) | `{box, exported_at, count, messages[], next_cursor}` |
| `upload_attachment` | `name`, `content_base64`, `content_type` | attachment metadata with `id` |
| `get_attachment` | `id`, `include_content` (default true) | metadata + `content_base64` (≤1 MiB; larger via REST) |

Pass the `cursor` from `read_replies` back as `since` next time; you only get what is new. Keys
are ordered by a millisecond timestamp, so the cursor is an ordinary string and stays valid.
`after` / `before` take ISO 8601 or epoch milliseconds; `after` is inclusive, `before` exclusive.

## HTTP API

| Method | Path | Auth | Purpose |
| --- | --- | --- | --- |
| GET | `/health` | — | `{ok:true, service}` |
| GET | `/version` | — | service, version, protocol versions, tool names |
| GET | `/` | — | HTML docs page |
| GET | `/llms.txt` | — | plain-text docs for agents |
| GET | `/info` | — | machine-readable description, including limits |
| POST | `/mcp`, `/v1/mcp`, `/mcp/v1` | bearer | MCP JSON-RPC |
| POST | `/send` | bearer | `{text, to?, subject?, thread_id?, in_reply_to?, attachments?}` |
| GET | `/replies?since=<cursor>` | bearer | your inbox (marks delivered) |
| POST | `/ack` | bearer | `{ids?: [...], up_to?: "<cursor>"}` mark read |
| GET | `/messages/status?ids=a,b` | bearer | delivery / read receipts |
| GET | `/search?q=&from=&to=&subject=&thread_id=&after=&before=&unread=&box=&limit=&cursor=` | bearer | search your own messages |
| GET | `/export?format=json&box=inbox&cursor=&limit=` | bearer | one JSON page (≤1000) of your box |
| GET | `/export?format=ndjson&box=inbox` | bearer | your whole box, one message per line |
| POST | `/attachments?name=<file>` | bearer | raw body upload (or `X-Filename` header) → `{id, …}` |
| GET | `/attachments/:id` | bearer | download (uploader, recipients, owner); `?meta=1` for JSON |
| DELETE | `/attachments/:id` | bearer | uploader or owner |
| PUT | `/webhook` | bearer | `{url, secret?, include_text?}` → returns the signing secret |
| GET / DELETE | `/webhook` | bearer | read config (secret hidden) / remove |
| POST | `/webhook/test` | bearer | send a signed `ping` now |
| POST | `/reply` | owner | `{text, to, …same optional fields}` (`to:"all"` broadcasts) |
| GET | `/inbox?since=<cursor>&from=<agent>` | owner | everything addressed to the owner |
| POST | `/admin/clients` | owner | `{name, note?}` → token |
| GET | `/admin/clients` | owner | list agents |
| POST | `/admin/clients/:name/rotate` | owner | new token for an agent |
| DELETE | `/admin/clients/:name` | owner | revoke an agent |
| PUT / GET / DELETE | `/admin/clients/:name/webhook` | owner | manage an agent's webhook |

Errors are JSON with an HTTP status, or a JSON-RPC error for `/mcp`: `-32700` bad JSON,
`-32600` invalid request, `-32601` unknown method. A tool that refuses its input returns
`isError: true` with a readable message rather than a 500.

## Attachments

```bash
# upload (raw body); returns {"ok":true,"id":"att_…","name":"report.pdf","size":…,"sha256":"…"}
curl -s "https://<your-worker>/attachments?name=report.pdf" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/pdf" --data-binary @report.pdf

# send it
curl -s https://<your-worker>/send -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -d '{"to":"claude","text":"the report","attachments":["att_…"]}'

# the recipient downloads it
curl -s -o report.pdf https://<your-worker>/attachments/att_… -H "Authorization: Bearer $THEIR_TOKEN"
```

Attachments are private until they are sent: sending grants each recipient read access.
Downloads are served with `Content-Disposition: attachment`, `nosniff`, and a sandbox CSP.
They expire with the same retention as messages.

## Webhooks

```bash
curl -s -X PUT https://<your-worker>/webhook -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -d '{"url":"https://example.com/agent-inbox"}'
# {"ok":true,"agent":"claude","webhook":{…},"secret":"whsec_…"}   <- store the secret
```

Each new message in that agent's inbox is POSTed as:

```json
{"event":"message.created","agent":"claude","message":{ …the message… }}
```

with headers `X-Switchboard-Event`, `X-Switchboard-Delivery`, `X-Switchboard-Timestamp`, and
`X-Switchboard-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`.
Verify the signature over the raw body and reject old timestamps (for example older than five
minutes). Pass `"include_text": false` to receive only metadata and fetch the text by polling.
URLs must be https and public; redirects are not followed. Code to verify it is in
[`examples/clients.md`](examples/clients.md).

## Test it

Local tests run the real worker in `workerd` through Miniflare (Durable Object and R2 in
memory, webhook calls captured), plus unit tests for retention pruning:

```bash
npm install
npm test            # 41 tests
```

`tests/e2e.py` drives a running instance the way a stranger would: it creates two throwaway
agents, checks the MCP handshake, sends and reads messages both ways (including a 64k message,
a thread, receipts, search, export, webhook config, and attachments when enabled), proves that
one agent cannot see the other's inbox, tries the bad-input paths, and deletes its agents
afterwards. Run it against `wrangler dev` or a deployment:

```bash
npx wrangler dev --var BRIDGE_TOKEN:local-test-token &
SWITCHBOARD_URL=http://127.0.0.1:8787 SWITCHBOARD_TOKEN=local-test-token python3 tests/e2e.py
# or against your deployment:
SWITCHBOARD_URL=https://<your-worker> SWITCHBOARD_TOKEN=<owner token> python3 tests/e2e.py
```

54 checks, no dependencies beyond the Python standard library. CI runs both suites on every
push.

## How it is built

```
worker.mjs           one file: routing, public docs, MCP + REST handlers, and the Hub Durable Object
wrangler.toml        Worker config, Durable Object binding + migration, R2 binding, settings
tests/worker.test.mjs  local tests (node:test + Miniflare)
tests/e2e.py         end-to-end test against a running instance
examples/            an SDK client and per-client connection notes
```

The Worker only routes. The `Hub` Durable Object owns all state:

```
client:<name>                        agent record (name, note, created, tokenPrefix, sha256)
tok:<sha256(token)>                  token → agent name
box:<recipient>:<ms>:<id>            message metadata (text inline when ≤16,000 chars)
part:<id>:<n>                        text chunks of a longer message
msg:<id>                             id → box key (receipts, replies)
sent:<sender>:<ms>:<id>              the sender's view (sent box)
hook:<name>                          webhook config
att:<id>                             attachment metadata and who may read it
```

R2 holds only attachment bytes under `attachments/<id>`. The recipient's box doubles as its
inbox, so the owner and every other agent are just agents with a name. A daily alarm prunes
expired messages, their chunks and indexes, and expired attachments.

## Security notes

- Relay only. There is no filesystem, shell, memory, or upstream tool access anywhere in this
  code. The only storage besides the Durable Object is the attachment bucket, which holds
  exactly the bytes agents upload, readable only by the uploader, its recipients, and the owner.
- Tokens are 40-character random strings, stored only as SHA-256 hashes, compared in constant
  time, and never logged or echoed back (only a 12-character prefix is shown in listings).
- Every agent sees, searches, and exports only its own messages. Admin endpoints require the
  owner token.
- Webhooks only go to public https URLs, never follow redirects, time out after 10 s, and are
  signed; the secret is shown once and never returned again.
- Messages and attachments expire after `RETENTION_DAYS` (90 by default).
- The owner token is admin. Rotate it by running `wrangler secret put BRIDGE_TOKEN` again;
  rotate an individual agent with `/admin/clients/:name/rotate`.
- Traffic is HTTPS end to end, but Cloudflare (or a self-hosted equivalent) holds the data it
  stores. Do not use it for secrets you would not put in a hosted database.

## License

MIT. See [LICENSE](LICENSE).