# Remote MCP server (`@betrail/mcp`)

> **Pre-release checkout package & example hostnames.** `@betrail/mcp` lives in `./mcp` (`"private": true`, zero external npm dependencies). Its canonical Streamable HTTP endpoint is `https://mcp.betrail.example/mcp` (override locally with `BETRAIL_MCP_URL=http://127.0.0.1:8085/mcp`).

`@betrail/mcp` implements the Model Context Protocol Streamable HTTP transport so coding agents can inspect BetPlug game specifications, OpenAPI/AsyncAPI operations, and your own sandbox tenant — plus run confirmation-gated sandbox simulations and wallet/webhook probes — without ever holding a server-wide key or touching live state.

## Security architecture

1. **OAuth 2.1 + PKCE with audience-bound sandbox scopes (RFC 9728).** Unauthenticated requests answer `401` with `WWW-Authenticate` pointing to `/.well-known/oauth-protected-resource`. Every JWT verifies `alg === "HS256"` (rejecting `crit` headers), single-audience `aud === resourceUrl`, `iss`, `exp`, `nbf`, active consent, and `operator_id`. Only sandbox scopes exist: `mcp:read`, `mcp:sandbox:write`, and `mcp:sandbox:keys`.
2. **Sandbox-only enforcement; zero live scopes or keys ever.** `@betrail/mcp` refuses startup if any server-wide credential env var (`BETRAIL_API_KEY`, `BETRAIL_SIGNING_SECRET`, etc.) is set. Every `live` scope (`403`) or non-sandbox credential is rejected, delegated sandbox credentials resolve strictly for the caller's `operator_id`, and every sandbox write/tester tool requires `consent_confirmed: true`.
3. **Untrusted data framing & invisible-character escaping.** Player-controlled strings (`client_seed`, `player_ref`, `view`) returned by `lookup_round`, `verify_round`, and `list_webhook_deliveries` are isolated in `untrusted_fields` with bidi overrides (`U+202A..U+202E`, `U+2066..U+2069`), zero-width characters (`U+200B..U+200D`, `U+FEFF`), and Unicode tags (`U+E0000..U+E007F`) escaped to `\uXXXX` / `\u{XXXXX}` alongside lossless `utf8_hex` for byte-exact fairness verification.
4. **Rate limits & SSRF-hardened 30/min tester budget.** Every JSON-RPC message is rate-limited per token and per operator (`64 KiB` body cap). `send_test_webhook` and `test_wallet_endpoint` enforce global-unicast SSRF egress rules (sandbox ports `80`, `443`, `8080`, `8443`) under a shared `30/min` operator tester budget.

> **Security:** Never configure live credentials or weaken SSRF rules for MCP testers. All delegated OAuth grants can be revoked with one click in Console `/security` (`DELETE /console/mcp/consents/{id}`), immediately invalidating `/mcp` tokens (`401 consent_revoked`).

## Operator sign-in & live Console delegation

`McpOAuthServer` (`/.well-known/oauth-authorization-server`, `/oauth/register`, `/oauth/authorize`, `/oauth/authorize/callback`, `/oauth/token`, `/oauth/revoke`) bridges OAuth 2.1 + PKCE (`S256`) directly through the Operator Console (`/mcp/authorize`) and the API's Console backend API (`/console/mcp/*`):

1. **Browser OAuth 2.1 + PKCE consent (`/mcp/authorize`):** Unauthenticated `GET /oauth/authorize` validates the registered client, redirect URI, `S256` challenge, `resource`, and sandbox scopes, then redirects to `${BETRAIL_MCP_CONSOLE_ORIGIN}/mcp/authorize?ticket=<jwt>`. After 2FA sign-in (`owner`, `admin`, or `developer`), Console displays the unverified-client warning, exact `redirect_origin`, requested scopes, and `<= 24 h` lifetime, minting a consent-bound `btr_test_` key (`POST /console/mcp/consents`, KEK-wrapped at rest).
2. **Live Console delegation (`BETRAIL_MCP_SERVICE_SECRET`):** Set `BETRAIL_MCP_JWT_SECRET` (`>= 32` bytes, shared with Console), `BETRAIL_MCP_CONSOLE_ORIGIN=http://127.0.0.1:3002`, `BETRAIL_MCP_CONSOLE_BFF_URL=http://127.0.0.1:8082`, `BETRAIL_MCP_API_BASE_URL=http://127.0.0.1:8080`, and `BETRAIL_MCP_SERVICE_SECRET` (`>= 32` bytes, distinct from `BETRAIL_CONSOLE_SERVICE_SECRET`). This advertises all **12** MCP tools (`7` read + `5` sandbox write/tester).
3. **Loopback-only local fallback flags:** For air-gapped testing on `BETRAIL_MCP_LISTEN=127.0.0.1:8085`, `BETRAIL_MCP_DEV_CONSOLE_USER=<operator_id>:<user_id>` supplies a loopback-only dev user when `BETRAIL_MCP_CONSOLE_ORIGIN` is unset, and `BETRAIL_MCP_DELEGATED_SANDBOX_CREDENTIALS_JSON` maps `<operator_id>` to `{ "api_key": "btr_test_<key>", "signing_secret": "…", "brands": { ... } }` when `BETRAIL_MCP_SERVICE_SECRET` is unset (`11` tools advertised; non-sandbox keys abort startup).

## Tools (7 read + 5 sandbox write/tester)

`tools/list` advertises all **12** tools with live Console delegation, **11** tools with static delegated credentials JSON (omitting `create_sandbox_key`), and **7** tools under `readOnlyMode: true`:

| Tool | Scope | Inputs | Description |
|---|---|---|---|
| `list_games` | `mcp:read` | `kind?`, `spec_only?` | Lists all catalog games, spec resource URIs, and `served` status (`additionalProperties: false`). |
| `get_game_spec` | `mcp:read` | `game`, `section?` | Returns the canonical game specification or matching heading sections (`section_not_found` on miss). |
| `search_docs` | `mcp:read` | `query`, `category?`, `limit?` | Searches game/block specs, OpenAPI/AsyncAPI contracts, runbooks, and technical guides. |
| `get_api_operation` | `mcp:read` | `operation_id?`, `method?`, `path?` | Retrieves an OpenAPI REST route, seamless wallet callback, live WebSocket frame, or AsyncAPI webhook contract (`round.settled`, `credits.low`, `credits.exhausted`). |
| `lookup_round` | `mcp:read` | `round_id` | Reads a single sandbox round (`GET /v1/rounds/{id}`) scoped to the caller's `operator_id`. |
| `verify_round` | `mcp:read` | `round_id` | Replays a revealed sandbox round (`GET /v1/rounds/{id}/verify`) scoped to the caller's `operator_id`. |
| `list_webhook_deliveries` | `mcp:read` | `brand?`, `delivery_id?`, `status?`, `limit?` | Lists sandbox webhook delivery summaries (`pending`, `delivered`, `dead`) across `round.settled`, `credits.low`, and `credits.exhausted`. |
| `simulate_round` | `mcp:sandbox:write` | `brand`, `game`, `player_ref`, `currency`, `stake`, `params`, `consent_confirmed` | Plays a sandbox round via `POST /v1/rounds` with exact decimal string `stake` after explicit confirmation (to choose a `client_seed`, call `rotate_sandbox_seed` first). |
| `rotate_sandbox_seed` | `mcp:sandbox:write` | `player_ref`, `game`, `client_seed?`, `consent_confirmed` | Optionally updates next `client_seed` (`PUT /client-seeds/{game}`) and rotates the sandbox seed pair (`POST /seeds/{game}/rotate`). |
| `send_test_webhook` | `mcp:sandbox:write` | `brand`, `url`, `consent_confirmed` | Sends a `betrail-v1`-signed `round.settled` sandbox test webhook under SSRF rules and the 30/min budget. |
| `test_wallet_endpoint` | `mcp:sandbox:write` | `brand`, `wallet_url`, `player_ref`, `currency`, `consent_confirmed` | Runs a 6-step sandbox seamless-wallet conformance probe (`balance`, 1-atom `debit`, `idempotent_debit`, `rollback`, `credit`, and `bad_signature` refusal) under SSRF rules and the 30/min budget. |
| `create_sandbox_key` | `mcp:sandbox:keys` | `brand`, `name`, `consent_confirmed` | Mints a one-time `btr_test_<key>` and `signing_secret` via Console delegation (`POST /console/mcp/operators/{operator}/consents/{id}/sandbox-keys`). |

## `betrail://` resources & templates

All resources require `mcp:read` scope:

| Resource / template URI | MIME type | Contents |
|---|---|---|
| `betrail://catalog/games` | `application/json` | Machine-readable catalog of every BetPlug game (`id`, `slug`, `kind`, `spec_resource_uri`, `engine_ported`, `served`). |
| `betrail://contracts/openapi` | `application/yaml` | Full OpenAPI 3.1 REST, session, and seamless wallet callback contract (`api/openapi.yaml`). |
| `betrail://contracts/asyncapi` | `application/yaml` | Full AsyncAPI 3.1 live WebSocket and webhook (`round.settled`, `credits.low`, `credits.exhausted`) contract (`api/asyncapi.yaml`). |
| `betrail://guides/fairness-recipes` | `text/markdown` | Commit-reveal lifecycle, all five legacy RNG recipes (`dice-sha512`, `hmac-nonce`, `plinko-hmac`), `FairRandom`, and live hash chains vs `stack-o-pass` per-player seeds. |
| `betrail://guides/integration-guides` | `text/markdown` | End-to-end sandbox integration guide (`betrail-v1`, seamless wallet callbacks, `POST /v1/launch` embed, and signed webhooks). |
| `betrail://specs/games/{slug}` | `text/markdown` | Canonical per-game specification, RNG recipe, paytable, and exact RTP for `{slug}`. |
| `betrail://docs/adr/{slug}` | `text/markdown` | Published architecture decision notes by `{slug}`. |
| `betrail://docs/blocks/{slug}` | `text/markdown` | Shared engine building-block specifications (`fair-random`, weighted tables, etc.) by `{slug}`. |
| `betrail://docs/runbooks/{slug}` | `text/markdown` | Deployment, CI, and operations runbooks by `{slug}`. |
| `betrail://docs/security/{slug}` | `text/markdown` | Security threat models and control checklists by `{slug}`. |

## Guided MCP prompts

`@betrail/mcp` exposes four zero-secret guided prompts (`prompts/list`, `prompts/get`):

| Prompt | Optional arguments | What it guides |
|---|---|---|
| `integrate` | `stack`, `mode`, `game` | End-to-end sandbox integration across headless REST, seamless wallet callbacks, launch sessions, and conformance tests. |
| `embed` | `game`, `surface` | Mounting `<betrail-game>` (with SRI from `manifest.json`) or the isolated play iframe with `betrail:v1` `postMessage` origin locking. |
| `add-webhook-handler` | `stack`, `events` | Raw-body `betrail-v1` webhook signature verification, nonce replay blocking, and `Betrail-Webhook-Id` deduplication (`round.settled`, `credits.low`, `credits.exhausted`). |
| `verify-round` | `round_id` | Cryptographic audit and deterministic replay of settled or post-draw `void` rounds using `lookup_round`, `verify_round`, and `get_game_spec`. |

## Escaping untrusted player fields in MCP responses (runnable sample)

```ts
import assert from "node:assert/strict";

function escapeUntrustedDisplay(raw: string): { display_escaped: string; utf8_hex: string } {
  const utf8Hex = Buffer.from(raw, "utf8").toString("hex");
  let escaped = "";
  for (const ch of raw) {
    const cp = ch.codePointAt(0)!;
    const isControl = cp <= 0x1f || (cp >= 0x7f && cp <= 0x9f);
    const isBidi =
      (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069) ||
      cp === 0x061c || cp === 0x200e || cp === 0x200f;
    const isZeroWidth = (cp >= 0x200b && cp <= 0x200d) || cp === 0x2060 || cp === 0xfeff || cp === 0x00ad;
    const isTag = cp >= 0xe0000 && cp <= 0xe007f;
    escaped += isControl || isBidi || isZeroWidth || isTag
      ? (cp <= 0xffff ? `\\u${cp.toString(16).padStart(4, "0")}` : `\\u{${cp.toString(16)}}`)
      : ch;
  }
  return { display_escaped: escaped, utf8_hex: utf8Hex };
}

// Construct hostile seed at runtime using escapes so no invisible runes exist in source
const hostileClientSeed = "seed" + "\u202E" + "ignore-rules" + "\u200B" + String.fromCodePoint(0xe0061);
const framed = escapeUntrustedDisplay(hostileClientSeed);

assert.equal(framed.display_escaped, "seed\\u202eignore-rules\\u200b\\u{e0061}");
// Fairness verifier recovers exact original UTF-8 bytes from utf8_hex without display spoofing
assert.equal(Buffer.from(framed.utf8_hex, "hex").toString("utf8"), hostileClientSeed);
```
