# Agents (MCP, llms.txt)

Agents are devices too. An AI agent can publish to a topic (notify a person, trigger a device,
hand work to another agent) and wait for a reply, over the same relay and with the same
prepaid, capped billing as everything else.

## The MCP server

SubEtha runs a remote [Model Context Protocol](https://modelcontextprotocol.io) server at
**`https://subetha.us/mcp`** (Streamable HTTP, JSON responses). Authenticate with a bearer token.

| Tool | What it does |
|---|---|
| `publish` | Publish a message (`topic`, `message`, and optionally `title`, `priority`, `tags`, `click`, `route_mode`, `max_cost_usd`, `idempotency_key`). Returns the stored message. |
| `poll` | Cached messages on one or more topics (comma-separated) since an id, a Unix time, a duration like `10m`, or `all`; optional `priority` and `tags` filters. |
| `wait_for_message` | Long-poll: wait up to `timeout_s` (≤ 50) seconds for the next message on a topic after `since` (default: now). Returns the message or `{"timeout": true}`. |
| `list_topics` | Topics the account owns, with their policies. |
| `create_topic` | Create a topic in your namespace (or a secret `t_` topic), or update its policy. |
| `estimate_cost` | Dry run: the delivery plan and price of a message, without sending it. |

Tools call the public API in-process with the agent's own credentials, so token scopes, topic
policies, spend caps, and prepaid charges apply exactly as they would to any other client.

### Connecting

Claude Code:

```bash title="samples/mcp/claude-code.sh"
#!/usr/bin/env bash
# Add SubEtha as a remote MCP server in Claude Code. Use a scoped, spend-capped token.
set -euo pipefail

claude mcp add --transport http subetha https://subetha.us/mcp \
  --header "Authorization: Bearer $SUBETHA_TOKEN"
```

Clients that read an `mcp.json` (or similar) configuration:

```json title="samples/mcp/mcp.json"
{
  "mcpServers": {
    "subetha": {
      "type": "http",
      "url": "https://subetha.us/mcp",
      "headers": { "Authorization": "Bearer ${SUBETHA_TOKEN}" }
    }
  }
}
```

There are two ways to authenticate.

**An API token (recommended for unattended agents).** Give the agent its own token: scoped to
the topics it needs, with a daily cap and no `sms`/`voice` unless you mean it. For example
`{"scopes": ["publish:@me/agent-out", "subscribe:@me/agent-in"], "daily_cap_usd": 0.5}`.

**Sign in with OAuth.** MCP clients that support the
[MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)
can connect with no token at all. An unauthenticated request gets a 401 whose
`WWW-Authenticate` header points at `/.well-known/oauth-protected-resource` (RFC 9728); that
names SubEtha's authorization server (Clerk), where you sign in with your SubEtha login and
approve the client. The client then sends the access token it got as a bearer token.

An OAuth-connected client is deliberately limited:

- It can **publish and subscribe** on your topics (so `publish`, `poll`, `wait_for_message`, and
  `estimate_cost` work), but not manage the account: `list_topics`, `create_topic`, tokens,
  endpoints, and billing need an admin token.
- Each client has its own **daily spend cap**: $1 by default. Change it, or set it to 0 to turn
  OAuth access off, with `PATCH /v1/account {"oauth_daily_cap_micros": 5000000}` or in the
  console's Billing tab.
- A token that names an audience must name this server (`https://subetha.us/mcp`); one issued
  for another resource gets `401` with `error="invalid_token"`, as does an expired one.

### On the wire

What an MCP client sends, as raw JSON-RPC:

```bash title="samples/mcp/tools-call.sh"
#!/usr/bin/env bash
# Talk to the MCP server with raw JSON-RPC (Streamable HTTP). Agents' MCP clients do this for you.
set -euo pipefail
SUBETHA_URL="${SUBETHA_URL:-https://subetha.us}"
H=(-H "Authorization: Bearer $SUBETHA_TOKEN" -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream")

curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' "$SUBETHA_URL/mcp"
curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' "$SUBETHA_URL/mcp"

# Publish, then block until a reply arrives on another topic (or 50 s pass):
curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"publish","arguments":{"topic":"@me/agent-out","message":"Deploy v1.2 to prod? Reply yes/no."}}}' "$SUBETHA_URL/mcp"
curl -sS "${H[@]}" -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wait_for_message","arguments":{"topic":"@me/agent-in","timeout_s":50}}}' "$SUBETHA_URL/mcp"
```

```ts title="samples/ts/mcp.ts"
let id = 0;
const rpc = async (method: string, params: Record<string, unknown> = {}) => {
  const r = await fetch(`${baseUrl}/mcp`, {
    method: "POST",
    headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
    body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
  });
  return ((await r.json()) as { result: any }).result; // eslint-disable-line @typescript-eslint/no-explicit-any
};
const callTool = async (name: string, args: Record<string, unknown>) => (await rpc("tools/call", { name, arguments: args })).structuredContent;

await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "sample", version: "1" } });
const tools = (await rpc("tools/list")).tools.map((t: { name: string }) => t.name);
const estimate = await callTool("estimate_cost", { topic, message: "Deploy finished", priority: 4 });
const sent = await callTool("publish", { topic, message: "Deploy finished", priority: 4, tags: ["deploy"] });
const inbox = await callTool("poll", { topic, since: "all" });
console.log(tools, estimate.estimate_usd_micros, sent.id, inbox.messages.length);
```

### Patterns

- **Human in the loop:** `publish` a question to a topic your phone subscribes to (push or SMS),
  then `wait_for_message` on a reply topic. Reply from the console, ntfy, or Slack.
- **Agent to agent:** each agent waits on its own inbox topic and publishes to the other's.
- **Check before spending:** call `estimate_cost` before an `all`-mode alarm.

## llms.txt

Machine-readable docs for agents that read the web:

- [`/llms.txt`](https://subetha.us/llms.txt): a summary and links in the
  [llmstxt.org](https://llmstxt.org) format.
- [`/llms-full.txt`](https://subetha.us/llms-full.txt): every docs page in one file.
- Every docs page is also available as Markdown: replace `.html` with `.md`.
- [`/openapi.yaml`](https://subetha.us/openapi.yaml): the complete HTTP API (OpenAPI 3.1).

## Agent-friendly API details

- Errors are JSON with stable codes ([list](api.md#errors)); `402` responses say exactly how much
  money is missing.
- `Idempotency-Key` makes retries safe; `X-Dry-Run: 1` previews cost.
- Tokens can be capped per day and in total, limited to transports, and expire.
