Remote MCP server (@betrail/mcp)
Pre-release checkout package & example hostnames.
@betrail/mcplives in./mcp("private": true, zero external npm dependencies). Its canonical Streamable HTTP endpoint ishttps://mcp.(override locally withbetrail. example/ mcp 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#
- OAuth 2.1 + PKCE with audience-bound sandbox scopes (RFC 9728). Unauthenticated requests answer
401withWWW-Authenticatepointing to/.well-known/. Every JWT verifiesoauth-protected-resource alg === "HS256"(rejectingcritheaders), single-audienceaud === resourceUrl,iss,exp,nbf, active consent, andoperator_id. Only sandbox scopes exist:mcp:read,mcp:sandbox:write, andmcp:sandbox:keys. - Sandbox-only enforcement; zero live scopes or keys ever.
@betrail/mcprefuses startup if any server-wide credential env var (BETRAIL_API_KEY,BETRAIL_SIGNING_SECRET, etc.) is set. Everylivescope (403) or non-sandbox credential is rejected, delegated sandbox credentials resolve strictly for the caller'soperator_id, and every sandbox write/tester tool requiresconsent_confirmed: true. - Untrusted data framing & invisible-character escaping. Player-controlled strings (
client_seed,player_ref,view) returned bylookup_round,verify_round, andlist_webhook_deliveriesare isolated inuntrusted_fieldswith 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 losslessutf8_hexfor byte-exact fairness verification. - Rate limits & SSRF-hardened 30/min tester budget. Every JSON-RPC message is rate-limited per token and per operator (
64 KiBbody cap).send_test_webhookandtest_wallet_endpointenforce global-unicast SSRF egress rules (sandbox ports80,443,8080,8443) under a shared30/minoperator 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/), immediately invalidatingmcp/ consents/ {id} /mcptokens (401 consent_revoked).
Operator sign-in & live Console delegation#
McpOAuthServer (/.well-known/, /oauth/register, /oauth/authorize, /oauth/, /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/*):
- Browser OAuth 2.1 + PKCE consent (
/mcp/authorize): UnauthenticatedGET /oauth/authorizevalidates the registered client, redirect URI,S256challenge,resource, and sandbox scopes, then redirects to${BETRAIL_MCP_CONSOLE_ORIGIN}/. After 2FA sign-in (mcp/ authorize?ticket= <jwt> owner,admin, ordeveloper), Console displays the unverified-client warning, exactredirect_origin, requested scopes, and<= 24 hlifetime, minting a consent-boundbtr_test_key (POST /console/, KEK-wrapped at rest).mcp/ consents - Live Console delegation (
BETRAIL_): SetMCP_ SERVICE_ SECRET BETRAIL_MCP_JWT_SECRET(>= 32bytes, 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=, andhttp://127.0.0.1: 8080 BETRAIL_(MCP_ SERVICE_ SECRET >= 32bytes, distinct fromBETRAIL_). This advertises all 12 MCP tools (CONSOLE_ SERVICE_ SECRET 7read +5sandbox write/tester). - Loopback-only local fallback flags: For air-gapped testing on
BETRAIL_,MCP_ LISTEN= 127.0.0.1: 8085 BETRAIL_supplies a loopback-only dev user whenMCP_ DEV_ CONSOLE_ USER= <operator_ id>:<user_ id> BETRAIL_is unset, andMCP_ CONSOLE_ ORIGIN BETRAIL_mapsMCP_ DELEGATED_ SANDBOX_ CREDENTIALS_ JSON <operator_id>to{ "api_key": "btr_test_<key>", "signing_secret": "…", "brands": { ... } }whenBETRAIL_is unset (MCP_ SERVICE_ SECRET 11tools 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/) 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/) and rotates the sandbox seed pair (POST /seeds/). |
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/). |
betrail:// resources & templates#
All resources require mcp:read scope:
| Resource / template URI | MIME type | Contents |
|---|---|---|
betrail://catalog/ | application/json | Machine-readable catalog of every BetPlug game (id, slug, kind, spec_resource_uri, engine_ported, served). |
betrail://contracts/ | application/yaml | Full OpenAPI 3.1 REST, session, and seamless wallet callback contract (api/openapi.yaml). |
betrail://contracts/ | application/yaml | Full AsyncAPI 3.1 live WebSocket and webhook (round.settled, credits.low, credits.exhausted) contract (api/asyncapi.yaml). |
betrail://guides/ | 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/ | text/markdown | End-to-end sandbox integration guide (betrail-v1, seamless wallet callbacks, POST /v1/launch embed, and signed webhooks). |
betrail://specs/ | text/markdown | Canonical per-game specification, RNG recipe, paytable, and exact RTP for {slug}. |
betrail://docs/ | text/markdown | Published architecture decision notes by {slug}. |
betrail://docs/ | text/markdown | Shared engine building-block specifications (fair-random, weighted tables, etc.) by {slug}. |
betrail://docs/ | text/markdown | Deployment, CI, and operations runbooks by {slug}. |
betrail://docs/ | 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)#
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);