
Simengine
io.github.cogswellspacely8-star由 GitHub 帳號 cogswellspacely8-star 發布v3.0.1更新於 Oct 27, 2026
Monte Carlo decision-intelligence over MCP: simulate, optimize, and decide under uncertainty.
概覽
依 JSON 領域設定執行蒙地卡羅模擬,讓助理量化不確定性、檢驗安全限制、最佳化控制參數,並給出繼續或升級的判定。
- 可以做什麼
- 以檔案或內嵌 JSON 設定執行蒙地卡羅模擬,回傳分布統計、軌跡、直方圖與文字說明
- 依機率限制與 CVaR 限制以及加權適應度分數評估結果
- 用遺傳最佳化器演化控制參數,找出符合安全界線的最佳策略
- 用觀測資料透過貝氏共軛更新收斂參數分布
- 驗證並儲存領域設定,並把模擬結果轉成繼續或升級的決策關卡
- 依模擬結果產生獨立的 HTML 報告
- 適用情境
- 適合助理需要針對充滿不確定性的結果(現金流、營收、虧損風險、合約或定價選擇)作答,且應以分布與限制檢驗而非單一估計值回應的情境。也適合需要在行動前設定明確繼續或升級門檻的多步驟代理。
- 執行需求
- 以 stdio 方式在本機執行,透過 uvx 從 simengine-mcp 這個 PyPI 套件安裝;執行時只需 Python 3.8 以上。選用的本機網頁介面與 HTTP API 使用 8420 埠。選用的自然語言提問介面需要 LLM 後端,透過 SIMENGINE_LLM_BACKEND 等變數設定,使用對應服務商時還需 OPENAI_API_KEY 或 ANTHROPIC_API_KEY。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 Simengine,將其新增到工作區。
- 為需要使用其工具的對話啟用該服務。
Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。
其他 MCP 客戶端
參照 儲存庫 中的啟動說明。
README
SimEngine
A domain-agnostic Monte Carlo simulation and decision intelligence system.
Zero dependencies. Pure Python stdlib. Local web UI. Runs anywhere Python runs.
SimEngine turns uncertainty into numbers you can act on. Define your variables, your logic, and your risk tolerances in a JSON config. The engine runs thousands of simulated futures, scores them, and — if you ask — evolves toward the best strategy that still respects your safety constraints.
Think of it as a calculator for uncertainty.
Quick Start
That is it. No pip install, no Docker, no Node, no build step. Python 3.8+ is the only requirement.
Install as an MCP server
Listed on the official MCP registry. Hosted, no-install endpoint: join the waitlist.
Optional Native Acceleration
The default engine remains pure Python. A Rust workspace now lives at the repo root for optional acceleration of metric reducers, trajectory bands, risk evaluation, histograms, and native pre-sampling of simple numeric variable distributions.
This is opt-in and does not change the baseline workflow above.
Workspace layout
Build the native extension
After that, the existing Python engine will automatically use the native
reducers and the native batch sampler when simengine_native is importable.
If the module is missing or fails, SimEngine falls back to the existing
Python implementation.
The batch sampler is conservative:
- it only activates for plain numeric variable params
- it stays off for correlated configs
- it can be disabled explicitly with
SIMENGINE_DISABLE_NATIVE_SAMPLING=1
This keeps the expression engine, accumulators, and metrics in Python while moving a larger chunk of the Monte Carlo loop into Rust.
There is also a narrower native fast path for stochastic expressions:
binomial(n, p)can be delegated to Rust when the extension is installed- it can be disabled explicitly with
SIMENGINE_DISABLE_NATIVE_EXPR_SAMPLING=1
This helps domains whose step_logic relies heavily on binomial(...) while
still leaving general expression evaluation in Python.
On the Python side, repeated expressions are now compiled once and reused
across Monte Carlo runs. That cache can be disabled explicitly with
SIMENGINE_DISABLE_EXPR_CACHE=1 for benchmarking or troubleshooting.
The diagnostics module applies the same idea to its AST-only safe evaluator:
parsed trees are reused across calls, and that cache can be disabled with
SIMENGINE_DISABLE_SAFE_EXPR_CACHE=1.
What It Does
- Monte Carlo simulation -- Run 5,000+ parallel futures for any domain you can describe in JSON.
- Safety constraints -- Chance constraints ("at most 15% probability of going broke") and CVaR constraints ("the average worst-case loss must not exceed $X").
- Genetic optimizer -- Evolve control parameters toward the best outcome while respecting safety bounds. Crossover, mutation, elitism, tournament selection.
- Bayesian updating -- Feed observed data back into your model. Conjugate priors (Beta-Binomial, Gamma-Poisson, Normal-Normal) tighten distributions as evidence arrives.
- Diagnostics -- Convergence analysis (proves your sample size is sufficient), sensitivity analysis (ranks which inputs drive the output), deterministic baseline comparison (quantifies the value of simulation over spreadsheet math).
- Web UI -- Histograms, trajectory fans, risk gauges, scenario comparison with control sweeps and input diffs, domain wizard, Bayesian update modal, export to standalone HTML report.
- AI agent integration -- POST a config inline to
/api/simulateand get structured results back. No files needed. LLMs can use SimEngine as a tool (llms.txtat the repo root andGET /llms.txtorient them). - Validated calibration -- A sqlite forecast ledger scores predictions with proper scoring rules (Brier / log-loss / CRPS), and the pipeline is backtested on ~2,800 walk-forward monthly forecasts over decades of public FRED data. Run it yourself:
cd v3 && python3 backtest.py(offline, from committed snapshots). Results: docs/backtests/.
Architecture
All production code lives in v3/.
Domain Config Schema
A domain config is a single JSON file that fully describes the simulation. The v3 schema separates variables into three semantic categories, which matters for Bayesian updating and optimization.
Published contract: the machine-readable JSON Schema (Draft 2020-12) is served live at GET /api/schema — hand it to any AI to author a valid config in one shot. A plain-language field reference is in docs/schema-reference.md. The schema is verified against every shipped domain in the test suite.
Top-Level Fields
Variable Definition
All three variable categories (parameters, controls, exogenous) share the same structure:
Available Distributions
Step Logic
An ordered list of computations executed each time step. Each entry has a target name and either an expr (expression string) or a sample (inline distribution):
Available expression functions: min, max, abs, round, sum, len, int, float, sqrt, log, exp, ceil, floor, pow, random(), gauss(mu, sigma), binomial(n, p), clamp(val, lo, hi), range(). Ternary expressions work: 100 if x > 0 else 0.
Accumulators
Running state that persists across time steps:
Metrics
Final measurements computed after all steps complete:
Safety Constraints
Fitness and Tunable
The optimizer maximizes a weighted sum of fitness components while respecting safety constraints. Each component is an expression evaluated against the metric statistics (e.g., total_revenue_median, ending_cash_p10):
Fitness expressions can reference any metric stat in the form {metric_name}_{stat} where stat is one of: mean, median, std, p10, p25, p75, p90.
Safety violations apply a 30% penalty per violated constraint. The optimizer learns to avoid them.
API Reference
The server runs at http://localhost:8420. All POST endpoints accept and return JSON. CORS headers are included on all responses.
GET /api/domains
List all available domain configs.
Response:
GET /api/domain/{filename}
Load a specific domain config by filename.
Response: The full JSON domain config object.
POST /api/simulate
Run a Monte Carlo simulation.
Request (file-based):
Request (inline config -- for AI agents):
Response:
POST /api/evolve
Run the genetic optimizer to find optimal control settings.
Request:
Response:
POST /api/validate
Validate a domain config without running a full simulation. Runs a 10-iteration test to catch expression errors.
Request:
Response:
Or on failure:
POST /api/save-domain
Validate and save a domain config to the domains/ directory.
Request:
Response:
POST /api/update
Bayesian update: feed observed data into a domain config and get updated parameter distributions plus a preview simulation.
Request:
Response:
POST /api/report
Generate a standalone HTML report from simulation results.
Request:
Response: HTML document (Content-Type: text/html). Self-contained, no external dependencies. Save it, email it, print it.
CLI Usage
kernel.py
Short flags: -g (generations), -p (population), -w (workers), -o (output).
diagnostics.py
You can combine flags: --convergence --sensitivity --baseline runs all three.
Creating a New Domain
There are three ways to create a domain config.
1. Web UI Wizard
Open http://localhost:8420, click the domain wizard, and fill in the form. The wizard generates a valid config, validates it, and saves it to the domains/ directory.
2. Copy the Template
Edit my_problem.json. The template includes inline documentation in the _guide field and a working example structure. Replace the placeholder variables, logic, and metrics with your own.
3. Generate with an LLM
Describe your problem to an LLM and ask it to produce a SimEngine v3 domain config. Validate it before use:
Or POST the config directly to /api/simulate with {"config": {...}} -- it will either run or return an error.
Minimum Viable Config
The smallest config that will run:
Bayesian Updating
SimEngine supports conjugate Bayesian updates that tighten your parameter distributions as real-world data arrives.
How It Works
- You start with a prior -- the distribution you specified in the config (e.g.,
triangular(0.02, 0.05, 0.12)for churn rate). - You observe real data (e.g., actual monthly churn:
[0.04, 0.06, 0.03, 0.05]). - The engine computes the posterior distribution using the appropriate conjugate update.
- The config is rewritten with tighter distributions that reflect both your prior belief and the evidence.
Supported Methods
Method Selection
The method is chosen in this order:
- Explicit
calibration.update_methodin the variable definition. - Auto-inferred from the distribution type and parameter range (values in [0,1] get Beta-Binomial; integer-valued Poisson gets Gamma-Poisson; everything else gets Normal-Normal).
Via the API
The response includes the updated config, a diagnostic report showing prior vs. posterior, and a preview simulation with the updated parameters.
Via Python
AI Agent Integration
SimEngine is designed to be used as a tool by LLMs and AI agents. The key feature is inline config support: POST a full domain config directly to /api/simulate without saving any files.
The Pattern
- The agent describes a problem as a SimEngine domain config (JSON).
- The agent POSTs
{"config": {...}, "n_simulations": 5000, "seed": 42}to/api/simulate. - The agent reads the structured response: stats, safety evaluation, fitness score, narrative.
- The agent reasons about the results and either reports back or adjusts the config and re-runs.
Example: Agent Tool Call
What Agents Get Back
The /api/simulate response includes everything an agent needs to reason about the outcome:
stats-- Full distribution statistics for every metric (mean, median, std, p10/p25/p75/p90).safety-- Pass/fail on every constraint with actual probabilities.fitness-- Single scalar score for comparing scenarios.narrative-- Human-readable summary text.trajectories-- Time-series percentile bands for trend analysis.histograms-- Binned data for distribution shape analysis.
Scenario Comparison
To compare alternatives, an agent can POST multiple configs (varying the controls) and compare fitness scores, safety evaluations, or specific metric percentiles across the responses.
Decision Gate: decide_under_uncertainty (MCP)
Multi-step agents compound overconfident point answers. The decide_under_uncertainty MCP tool turns a simulation into a proceed / escalate verdict: it runs the Monte Carlo, measures how much of the outcome distribution lands inside a range you accept, and returns the flag plus the full distribution and a plain-English reason.
It models outcome risk -- the spread of results given uncertain inputs -- not the language model's own token confidence. The two are complementary; do not conflate them.
Arguments: metric (required), acceptable ({"min": ..., "max": ...}, at least one bound), min_confidence (probability mass that must land in range to proceed, default 0.8), plus domain or inline config, and optional seed / n_simulations.
See docs/decision-gate.md for the full agent pattern.
Calibration & Track Record
A Monte Carlo engine will always emit a confident-looking distribution. The only thing that separates "a calculator that produces plausible numbers" from "a forecasting instrument with a demonstrated hit rate" is a track record scored against reality. v3/calibration.py is that spine -- pure stdlib, zero dependencies.
Proper scoring rules: brier_score, log_loss, crps_sample.
Forecast ledger: record a forecast now, resolve it against the real outcome later, score how well-calibrated you have been over time.
Brier 0.0 is perfect; 0.25 is the score of always guessing 50/50; 1.0 is worst. Log-loss punishes confident-and-wrong forecasts harder. Lower is better for both. Time is the moat: the track record only accumulates if logging starts now.
Real-Time Data (opt-in)
The core engine is offline and pure-stdlib. The v3/feeds/ package is the optional bridge to live data — the only part of SimEngine that touches the network, still using only urllib (no new dependencies), and never imported by the core.
The first adapter, feeds/polymarket.py, turns a live Polymarket prediction-market price into a calibrated prior: a market-implied probability becomes a SimEngine variable you can drop into a domain config and then tighten with the Beta-Binomial updater as your own evidence arrives. Price in → prior → posterior, not price in → price out.
See docs/feeds.md. Market prices are treated as internal simulation inputs, never a rebroadcast feed or trade signal.
Ask SimEngine Anything (natural language)
Don't want to write a config? Describe your decision in plain words and let an LLM build the model for you. SimEngine drafts a config, validates it against the engine, repairs any errors, runs the simulation, and explains the result — so even small local models stay reliable, because the engine grounds whatever the model produces.
This is opt-in and stdlib-only. It defaults to a local model via Ollama — free, private, no API key. Set an environment variable to use a hosted model instead.
CLI
Flags: --n (simulations), --seed, --save NAME (persist the config to domains/), --show-config, --json, --model NAME, --backend.
Web
Open http://localhost:8420, click Ask anything, type your question, and run. You get a plain-language answer, the key numbers, the safety verdict, and the generated model — which you can save as a reusable domain.
API
POST /api/ask with {"question": "...", "n_simulations": 3000, "seed": 42} returns {config, results, explanation, attempts, valid}.
Backends (environment variables)
Decision support and scenario analysis only — never financial advice or a trade signal.
What the Numbers Mean
When you run a simulation, each metric reports:
- Mean -- Average across all simulated futures.
- Median -- The 50th percentile. Half of futures are above, half below.
- P10 -- Pessimistic. Only 10% of futures are worse.
- P90 -- Optimistic. Only 10% of futures are better.
- Std -- Standard deviation. Width of the distribution.
- CVaR(alpha) -- The average outcome in the worst alpha% of futures. This is the number that risk-aware decision makers care about most.
Safety constraints translate directly to decision language:
- Chance constraint: "The probability of [metric] falling [below/above] [threshold] must not exceed [X]%."
- CVaR constraint: "In the worst [alpha]% of scenarios, the average [metric] must be at least [min_cvar]."
Documentation
New to SimEngine? Start with the plain-language guide. It explains what SimEngine is, how to read results, who it is for, how to explain it to others, and how to model your own decision — no background required.
Peer review reports and the system design paper are available on request. Contact the maintainer for access.
License
SimEngine uses an open-core model.
- Engine, server, kernels, diagnostics, Rust acceleration, and domain library — Apache License 2.0. Free to use, modify, self-host, embed in your own products, and redistribute under the terms of that license.
- Hosted SimEngine MCP service (operated by OtrovertLabs) — Commercial license. Subscription tiers for managed hosting, OAuth, persistent state, SLAs, and enterprise features.
Self-hosting the open-source engine is and will remain free. The commercial license applies only to the hosted service and managed features that are not part of the open-source distribution.
SimEngine is an OtrovertLabs product, published by Venture Horizon LLC.
For commercial licensing, enterprise inquiries, or partnerships: https://otrovertlabs.com/contact
來源:README.md,提交 fca4a6f
工具
0版本歷史
1- v3.0.1最新Sep 16, 2026
評分
已滿足適用檢查項的 50%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通25 分
請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。
- 已宣告認證方式10 分
請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分
