simulate-monte-carlo

io.github.encodiv1.0.0更新於 Sep 30, 2026

Real Monte Carlo simulation of a compound event/conditional probability. Paid via x402.

已驗證Streamable HTTP可網頁執行FinanceData & Analytics

概覽

AI 產生的概覽

實際執行蒙地卡羅模擬,根據宣告的隨機變數與布林事件運算式估算複合或條件機率。

功能
只提供一個工具 simulate_monte_carlo,接收具名隨機變數(uniform、normal、bernoulli、binomial、poisson、exponential、discrete)、由這些變數名稱構成的布林事件運算式,以及選用的 condition 運算式,透過拒絕取樣計算 P(event | condition)。它進行真正的隨機取樣與計數,而不是猜測機率,並回傳可重現的 seed。運算式由小型的分詞器、解析器與 AST 解譯器處理,僅支援算術、比較、布林邏輯、括號以及 min、max、abs。每次呼叫都自成一体,沒有資料庫或持久狀態。
適用情境
當你需要為難以解析求解的複合或條件事件取得數值機率估計時使用,例如骰子點數和、可靠度問題或簡單風險模型。它適合可接受帶信賴區間的模擬結果的快速探索性估算,不適合高風險統計工作。它不是通用計算機或符號數學引擎。
執行需求
遠端 streamable HTTP 端點,不需要安裝套件。未宣告驗證、環境變數或標頭。每次呼叫需透過 x402 以 Base 主網上的 USDC 付款,付款資訊位於 MCP JSON-RPC 的 _meta 欄位中,因此需要已儲值的錢包或可付款的用戶端。若改為在本機執行,則需要 Node.js,並從憑證檔案讀取 CDP 憑證。
安裝前請注意
每次呼叫都按 Base 主網上的真實 USDC 計費,價格為 0.03 美元,助理可能在沒有額外確認的情況下產生費用;未付款的呼叫會回傳付款資訊並要求重試。運算式由呼叫方提供,但說明文件指出它是由受限的解譯器求值,沒有程式碼執行路徑。結果是估計值:95% 信賴區間採用常態近似,在機率接近 0 或 1 時不夠精確。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 simulate-monte-carlo,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "simulate-monte-carlo": {
      "type": "http",
      "url": "https://simulate-monte-carlo.encodari.workers.dev/mcp"
    }
  }
}

README

simulate-monte-carlo

[simulate-monte-carlo MCP server]

Remote MCP server (Cloudflare Workers) with one tool that estimates a compound event or conditional probability by actually running a Monte Carlo simulation:

  • simulate_monte_carlo — declare named random variables (uniform, normal, bernoulli, binomial, poisson, exponential, discrete), an event boolean expression over those names (e.g. "a > 0.5 && b == 1"), and an optional condition expression to get a conditional probability P(event | condition) via rejection sampling. Real random sampling and real counting — not a model guess about what the probability should be.

No database, no persistent state: each call builds a fresh McpServer (see createServer() in src/index.ts) and is self-contained. The PRNG is seedable (mulberry32): pass the seed returned in a previous response to reproduce the exact same result.

Why a hand-written expression interpreter, not eval

event/condition are arbitrary caller-supplied strings. Running them through eval/Function would mean executing untrusted code inside the Worker. Instead, src/tools/monteCarlo.ts includes a small tokenizer + recursive-descent parser + AST interpreter that only understands numbers, declared variable names, arithmetic (+ - * /), comparisons (< <= > >= == !=), boolean logic (&& || !), parentheses, and a three-function whitelist (min, max, abs). There is no code execution path — the interpreter can't do anything beyond evaluate that narrow grammar.

Billing (x402)

Charges per call via x402 — real USDC payment on Base mainnet, against the Coinbase Developer Platform (CDP) facilitator. The payment travels inside the MCP JSON-RPC itself (_meta), not as an HTTP header; see src/payments.ts.

ToolPrice
simulate_monte_carlo$0.03 USDC

An unpaid tools/call returns isError: true with the accepts (network, amount, payTo) the client needs to pay and retry — not an unexplained exception.

Structure

src/  index.ts            # registers the tool in the McpServer and exposes the MCP HTTP handler  payments.ts         # x402 billing on Base mainnet via the CDP facilitator  tools/    monteCarlo.ts        # distributions, expression parser/interpreter, simulation loop (testable without Workers)    monteCarlo.test.tsscripts/  dev-node.ts          # dev server that runs the handler in plain Node, no wrangler

Resource limits

Set from the start, not bolted on after: max 10 variables, 100–100,000 trials (default 10,000), 500-character expressions, binomial n ≤ 1,000, poisson lambda ≤ 1,000, and a discrete-outcome cap of 20. On top of the individual caps, a combined sampling-budget check (trials × sum(per-variable cost) ≤ 5,000,000) rejects combinations that would be individually within limits but jointly too expensive — e.g. 100,000 trials against a binomial(n=1000) variable.

Running it locally

⚠️ Note on wrangler dev: the real Cloudflare Workers runtime (workerd) requires macOS 13.5+. If your Mac has an older version, wrangler dev (and npm run dev) will fail. This project includes a plain-Node shim that runs the exact same fetch() handler without needing workerd.

1. Install dependencies

bash
npm install

2. Run the unit tests

bash
npm test

3a. If your wrangler dev works (macOS 13.5+, Linux, Windows)

bash
npm run dev

3b. If wrangler dev fails because of the macOS version

bash
npm run dev:node

Starts at http://localhost:8787/mcp, reading CDP credentials from ~/.mcp-tools-factory-credentials.env (shared across all tools in this factory).

4. Test with curl

bash
# 1) initializecurl -s -X POST http://localhost:8787/mcp \  -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-test","version":"0.0.1"}}}'
# 2) tools/listcurl -s -X POST http://localhost:8787/mcp \  -H "Content-Type: application/json" \  -H "Accept: application/json, text/event-stream" \  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
# 3) tools/call — simulate_monte_carlo (two dice, P(sum > 9 | first die == 6))curl -s -X POST http://localhost:8787/mcp \  -H "Content-Type: application/json" \  -H "Accept: application/json, text/event-stream" \  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"simulate_monte_carlo","arguments":{"variables":[{"name":"d1","distribution":{"type":"discrete","values":[1,2,3,4,5,6],"weights":[1,1,1,1,1,1]}},{"name":"d2","distribution":{"type":"discrete","values":[1,2,3,4,5,6],"weights":[1,1,1,1,1,1]}}],"event":"d1 + d2 > 9","condition":"d1 == 6","trials":40000,"seed":3}}}'

Responses come as Server-Sent Events (event: message + data: {...}); the data: line is the usual JSON-RPC response.

Deploy and listings

Deployed at https://simulate-monte-carlo.encodari.workers.dev/mcp (Cloudflare Workers). Published on the official MCP registry, Smithery, mcp.so, and with an open PR to awesome-mcp-servers.

What it doesn't do (yet)

  • Charges on Base mainnet with real money. To switch back to testnet (Base Sepolia, eip155:84532) during development, change NETWORK in src/payments.ts.
  • No database or persistent state between calls (beyond the billing config, cached in memory per isolate — see src/payments.ts).
  • The 95% confidence interval uses the normal (Wald) approximation, which is imprecise near probabilities close to 0 or 1 — good enough for a quick estimate, not a substitute for exact binomial confidence intervals in high-stakes use.

來源:README.md,提交 1347a3f

工具

0
工具後設資料尚未被收錄。

版本歷史

1
  1. v1.0.0最新Sep 16, 2026