
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 分
