Build, simulate,
and question the model.

Stock & Flow is a visual systems dynamics workspace. Start with a library example, draw a system yourself, or ask the AI assistant for a draft. Inspect the assumptions, run the model, and compare what changes when parameters change.

Library entries are examples with varying levels of completeness. A completed numerical run does not establish scientific validity. Inspect initial values, equations, units and original references before interpreting the results. Failed runs report diagnostics; equations are never silently replaced with zero.

Start in the browser

Bring your own agent. Choose Connect agent to connect this page to your agent through MCP. Your agent authors and interprets the model; no server-side AI account is required. Existing manual editing and optional server AI remain available.

  1. Open the editor and choose Model Library. Search for Bank Balance with Compound Interest for a simple example. Expand a result to inspect its equations, then select Import.
  2. Select a stock, flow or variable on the diagram to edit its properties. Stocks accumulate quantities; flows change stocks per unit time; variables express parameters and calculations. Connectors show dependencies.
  3. Open Settings. Use Check inputs to inspect initial values, references and connections. The toolbar’s Inspect button opens the same report directly. Search equations, select an element to edit it, or choose Investigate numerical behavior to compare the full horizon at the current, half and quarter time steps. Download the evidence report without changing the model. Choose start, end, time step and Euler, Runge–Kutta 4 or Radau, then Apply & Run. Smaller steps can improve accuracy but require more computation. Compare runs at smaller steps before trusting a trajectory.
  4. Inspect Chart and Analytics. Existing line, area, stacked, phase, logarithmic, normalization, animation, comparison and saved-run controls remain available. AI Insights uses the configured provider when available.
  5. Use Save for your edited copy. My Models lists models saved in this browser. JSON export retains the full model; XMILE exports the supported scalar subset. Keep an exported copy for portability.

On smaller screens, the toolbar and AI, Edit and Results panels expose the same model. The separate library has category browsing, search, Simulate deep links, and JSON/XMILE downloads.

Understand a simulation

Analytics describes the recorded samples. Time-weighted means account for irregular spacing. Patterns and tail stability are qualified heuristics; raw variance comparison does not measure causal influence or parameter sensitivity. Undefined constant-series correlations are omitted, and any correlation coverage limit is reported. AI interpretation is labeled separately from statistical fallback.

Discrete periods and report outputs

Some models are recurrences tied to a declared period, such as weekly inventory accounting. Their fixed-period contract requires Euler, the exact period as the step, and a whole number of intervals. Settings show this restriction; fractional-step investigations are inapplicable rather than evidence of convergence.

A variable marked Report only can return a numeric diagnostic or a text label after each saved state. Reports appear separately from numeric charts and cannot be referenced by equations. Single quotes delimit text labels; double quotes retain their named-variable meaning. Use JSON to save these contracts; XMILE export reports an explicit incompatibility.

Euler advances using rates at the beginning of each interval. RK4 combines four derivative evaluations per interval. Settings are honored explicitly, including a nonzero start time. For continuous models, the final stop time is included with a shorter last interval if necessary. Fixed-period models require whole intervals. Recorded variables and flows correspond to the recorded stock state and time.

STEP, PULSE and RAMP, including their arguments, are evaluated at accepted simulation times and held over the following timestep for both methods. Other time-dependent equations retain normal stage evaluation. Reduce the time step to resolve off-grid events. PULSE(magnitude, first_time[, interval]) uses the XMILE magnitude signature, not Vensim’s start/width signature. A held ramp has first-order forcing accuracy even with RK4.

Smoothing and fixed-duration material delays support Euler and RK4. Fixed history delays and random functions require Euler; unsupported combinations are rejected explicitly. Set an optional integer random seed in Settings to repeat a stochastic run. The effective seed is returned with results when one is chosen automatically. A model’s explicit function seed takes precedence for that call. Different time steps do not define a coupled stochastic experiment. A negative stock can indicate an unsuitable time step or a model-domain problem; some quantities are intentionally signed, so the engine does not automatically clamp them.

Runs are limited to 500 elements, 100,000 intervals, 100,001 retained samples, 1,000,000 retained scalar values and 1,000,000 work units (elements, hidden stages and random calls per interval; RK4 charges five evaluations). Increase the time step or narrow the horizon when a run exceeds those bounds. Unknown symbols, circular algebraic dependencies, invalid operations and non-finite values return errors with context.

Stiff systems and readable failures

Select Radau explicitly for continuous differential equations with fast and slow dynamics. It chooses internal steps using relative and absolute error tolerances; the output interval controls recorded samples. Tighten tolerances to check accuracy: halving output spacing alone is not an adaptive-solver convergence test. The result includes actual solver work and evaluation counts.

Radau currently rejects random, delay/smoothing, STEP/PULSE/RAMP, explicit time-triggered branches and time-driven lookup tables, including aliases. These restrictions prevent missed forcing pulses. State-driven lookup forcing and uncertified state-triggered jumps in the differential equations are also rejected, because adaptive steps can miss narrow events. Diagnostic-only expressions and certified continuous branches remain available. Use an explicitly checked Euler or RK4 grid for these models; compare refinements and physical bounds. Save Radau settings as JSON; standard XMILE cannot represent this method.

Failed runs show the original failing equation separately from quantities blocked by it. Start with that root cause, then check units, initial conditions and the source model. The last finite state and failure time are available in investigation evidence. A missing source input remains an explicit error.

RANDOM_BINOMIAL(n,p[,seed]) supports discrete binomial sampling with integer trial counts and probabilities in [0,1]. Samples are cached per equation callsite and accepted time; trial work is bounded. For a generational model, one update per generation is part of the model definition, so halving the time step changes the stochastic process.

Connect an MCP client

For a visible working page, call open_workspace and open the private URL it returns. Keep the workspace key private. Inspect, make targeted edits, run, select a view, then confirm the browser applied the revision. Temporary sessions expire after one idle hour or a server restart; Save remains a separate action.

Page toolPurpose
open_workspaceCopy a library example or open your agent's model on a private page.
inspect_workspaceRead inputs, revisions, browser connection, actual view and diagnostics.
edit_workspace_elementsApply explicit additions/field changes atomically; retain unmentioned inputs.
update_workspace_modelReplace a complete private draft when intended, with a revision check.
run_workspaceRun the exact current model and display the same result.
set_workspace_viewShow diagram, chart, analytics or inputs; fit or select an element.
close_workspaceRevoke the connection without changing saved models.

Page tools require HTTP or SSE. Local stdio retains library and numerical tools. If the page and agent edit concurrently, revision checks and a visible draft choice prevent silent overwrites.

Use the Streamable HTTP endpoint:

https://stockandflow.live/mcp/

In a client that accepts an MCP URL, add that address. For clients configured with JSON:

{
  "mcpServers": {
    "stock-and-flow": {
      "url": "https://stockandflow.live/mcp/"
    }
  }
}

Legacy SSE clients can use https://stockandflow.live/mcp/sse. Server discovery is at /mcp/info. Local installations can launch python -m app.mcp_server over stdio from the repository root.

ToolPurpose
list_modelsSearch and filter by category, with limit and offset.
get_modelInspect a complete definition and its default settings.
validate_modelCheck structure, references and a short numerical run.
investigate_modelCompare full-horizon time steps, locate missing definitions and domain leads, and report exact model/engine hashes. No inputs are changed.
simulate_modelRun a library or inline model; return statistics and sampled data.
compare_scenariosCompare numeric parameter overrides without changing the model.
analyze_modelCalculate default-run statistics without AI.
export_model_xmileReturn XMILE for a saved or inline model.
generate_model_from_descriptionAsk the configured AI provider for a draft.
modify_existing_modelAsk for a revised draft without overwriting the source.

Numerical MCP tools do not write model files or use a paid AI provider. The two AI tools call the configured provider and may incur provider charges. Omitted simulation settings inherit the model defaults. Inputs can provide exactly one of model_id or model_json. Tool failures use MCP errors.

The server also provides systems://guide, the machine-readable capabilities at systems://engine, the resource template systems://models/{model_id}, and the investigate_system prompt.

Example investigation

Find population models. Inspect the equations and initial values of a
simple candidate, validate it, and run its default settings. Compare
the baseline with a lower birth rate. Report parameter changes,
integration method, time step, numerical sensitivity and assumptions.
Do not treat the example as a verified population forecast.

REST API

RequestPurpose
GET /api/models/catalogSmall index; supports search, category, offset and limit.
GET /api/modelsLegacy list of complete definitions.
GET /api/models/{id}Complete definition.
POST /api/investigateInspect inputs and compare up to three bounded full-horizon runs at progressively smaller steps.
POST /api/simulateSubmit model or model_id and optional time_settings.
POST /api/analyze/statisticsStatistics for supplied simulation results.
GET /api/models/{id}/export/xmileXMILE download.
POST /api/models/import/xmileUpload an XMILE file as multipart field file.

Existing create/update/delete and AI endpoints are retained. Server model storage is shared; it is not a private account vault. Do not put confidential information in public model definitions.

Imports and portability

JSON is the complete native format. Supported XMILE imports include scalar stocks, flows, auxiliaries, initial equations, time settings, graphical functions and diagram positions. Namespace quote styles and reciprocal time steps are understood. The optional run seed round-trips through a Stock & Flow namespace extension; other tools may ignore this extension. Continuous graphical functions clamp outside their range; extrapolating and discrete types retain their declared behavior. Unsupported arrays and nested models are rejected rather than silently discarded.

Model equations may use functions that another modeling tool does not implement. Check numerical agreement after moving a model between tools. See the XMILE specification and the repository tests for the supported subset.

When a run fails, Download failure report saves its exact model, effective settings and seed, causal errors and engine fingerprints. Partial API settings inherit omitted model values. XMILE export translates supported functions to standard syntax and explicitly rejects conversions that would change semantics or seeded streams.