Skip to content
BetPlugDocs
DocsAPI & tools
View .md twin

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:

ToolScopeInputsDescription
list_gamesmcp:readkind?, spec_only?Lists all catalog games, spec resource URIs, and served status (additionalProperties: false).
get_game_specmcp:readgame, section?Returns the canonical game specification or matching heading sections (section_not_found on miss).
search_docsmcp:readquery, category?, limit?Searches game/block specs, OpenAPI/AsyncAPI contracts, runbooks, and technical guides.
get_api_operationmcp:readoperation_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_roundmcp:readround_idReads a single sandbox round (GET /v1/rounds/{id}) scoped to the caller's operator_id.
verify_roundmcp:readround_idReplays a revealed sandbox round (GET /v1/rounds/{id}/verify) scoped to the caller's operator_id.
list_webhook_deliveriesmcp:readbrand?, delivery_id?, status?, limit?Lists sandbox webhook delivery summaries (pending, delivered, dead) across round.settled, credits.low, and credits.exhausted.
simulate_roundmcp:sandbox:writebrand, game, player_ref, currency, stake, params, consent_confirmedPlays 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_seedmcp:sandbox:writeplayer_ref, game, client_seed?, consent_confirmedOptionally updates next client_seed (PUT /client-seeds/{game}) and rotates the sandbox seed pair (POST /seeds/{game}/rotate).
send_test_webhookmcp:sandbox:writebrand, url, consent_confirmedSends a betrail-v1-signed round.settled sandbox test webhook under SSRF rules and the 30/min budget.
test_wallet_endpointmcp:sandbox:writebrand, wallet_url, player_ref, currency, consent_confirmedRuns 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_keymcp:sandbox:keysbrand, name, consent_confirmedMints 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 URIMIME typeContents
betrail://catalog/gamesapplication/jsonMachine-readable catalog of every BetPlug game (id, slug, kind, spec_resource_uri, engine_ported, served).
betrail://contracts/openapiapplication/yamlFull OpenAPI 3.1 REST, session, and seamless wallet callback contract (api/openapi.yaml).
betrail://contracts/asyncapiapplication/yamlFull AsyncAPI 3.1 live WebSocket and webhook (round.settled, credits.low, credits.exhausted) contract (api/asyncapi.yaml).
betrail://guides/fairness-recipestext/markdownCommit-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-guidestext/markdownEnd-to-end sandbox integration guide (betrail-v1, seamless wallet callbacks, POST /v1/launch embed, and signed webhooks).
betrail://specs/games/{slug}text/markdownCanonical per-game specification, RNG recipe, paytable, and exact RTP for {slug}.
betrail://docs/adr/{slug}text/markdownPublished architecture decision notes by {slug}.
betrail://docs/blocks/{slug}text/markdownShared engine building-block specifications (fair-random, weighted tables, etc.) by {slug}.
betrail://docs/runbooks/{slug}text/markdownDeployment, CI, and operations runbooks by {slug}.
betrail://docs/security/{slug}text/markdownSecurity threat models and control checklists by {slug}.

Guided MCP prompts#

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

PromptOptional argumentsWhat it guides
integratestack, mode, gameEnd-to-end sandbox integration across headless REST, seamless wallet callbacks, launch sessions, and conformance tests.
embedgame, surfaceMounting <betrail-game> (with SRI from manifest.json) or the isolated play iframe with betrail:v1 postMessage origin locking.
add-webhook-handlerstack, eventsRaw-body betrail-v1 webhook signature verification, nonce replay blocking, and Betrail-Webhook-Id deduplication (round.settled, credits.low, credits.exhausted).
verify-roundround_idCryptographic 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)#

TypeScript
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);
Enter to openEsc to close