nsforge-mcp
NSForge is an MCP server for turning concepts into verified, provenance-tracked symbolic formulas and executable code through deterministic derivation workflows.
Step-by-step derivation engine: start/resume sessions, load formulas, substitute, simplify, solve, differentiate, integrate, record steps, add human knowledge notes, rollback, insert/delete steps, and complete derivations.
Saved derivation repository: list, get, search, update metadata, delete, and view stats for previously completed formulas.
SymPy-MCP handoff: export current derivation state for SymPy, import results back, and check handoff status.
Formula discovery: search and fetch formulas from Wikidata, BioModels, and SciPy constants; list categories, PK models, kinetic laws, and physical constants.
Expression tooling: parse, validate, and extract symbols from mathematical expressions.
Symbolic calculation: limits, series expansions, summations, inequality solving (single and systems), probability distributions and statistics.
Algebra and transforms: expand, factor, collect, trig/power/radical/combinatorial simplification, partial fractions, cancel, common denominators, Laplace/Fourier transforms and inverses.
Verification: symbolic equality, derivative/integral checks, solution verification, dimensional analysis, and reverse verification.
Code and document generation: Python functions, LaTeX derivations, Markdown reports, and standalone SymPy scripts.
Autonomous task orchestration: plan, run, and explore Derivation Task Specs with ranking of verified candidates.
Agent assistance: next-step suggestion ranking, plus health and capability manifest introspection.
Optional music tools (when enabled) for symbolic tones to waveform/spectrum/WAV generation.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@nsforge-mcp derive body fat-adjusted volume of distribution"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
🔥 Neurosymbolic Forge (NSForge)
Turn concepts into verifiable, traceable formulas. NSForge is an MCP server that forges new formulas through deterministic, provenance-tracked derivation — the AI orchestrates, tools reify.
🌐 English | 繁體中文
💡 Why NSForge?
LLMs are great at understanding and planning, but doing symbolic math by hand makes them hallucinate, contradict themselves, and produce unverifiable results. NSForge draws a clean line:
The LLM does… | NSForge does… |
Understand the question | Precise symbolic computation |
Plan the derivation | Track every step's provenance |
Explain the result | Verify (dimensions, boundary, equivalence) |
— | Store the formula, generate code |
North star: every symbol, equation, value, and line of code in a result has a tool call as its birth certificate. The amount the AI computes by hand approaches zero.
NSForge is NOT a formula database — it's a derivation factory. Formulas are inputs (from SymPy‑MCP, Wikidata, BioModels, you); the operators (compose · substitute · solve · verify · prove) are the product.
Related MCP server: ReasonForge
🪜 The Reification Ladder
The core idea: climb from a fuzzy concept to executable, provenance-bound code, one deterministic rung at a time.
flowchart LR
C["💭 CONCEPT<br/>a goal"] --> S["🔤 SYMBOL<br/>typed + units"]
S --> D["🧩 DERIVATION<br/>composed"]
D --> V{"✅ verify"}
V -->|"fails"| D
V -->|"passes"| A["⚙️ ALGORITHM<br/>code"]
A -. "emitted only if ledger complete" .-> L[["📒 provenance ledger"]]
C -.-> L
S -.-> L
D -.-> L📖 Deep dive: Reification-ladder direction · General-formula-exploration roadmap
🌍 Ecosystem: don't reinvent the wheel
NSForge works with other MCP servers, not against them.
flowchart TB
subgraph SY["🔢 sympy-mcp · 32 tools"]
direction LR
SY1["Base formulas: F=ma, PV=nRT, Arrhenius"]
SY2["Constants · ODE / PDE / matrices"]
end
subgraph NS["🔨 nsforge-mcp · 91 tools — YOU ARE HERE"]
direction LR
NS1["Derivation framework<br/>compose · verify · code"]
NS2["Provenance repository"]
NS3["Formula search<br/>Wikidata · BioModels · SciPy"]
end
subgraph US["🎯 usolver-mcp · optional"]
US1["Z3 · OR-Tools · CVXPY · HiGHS"]
end
SY -->|"base formulas"| NS
NS -->|"prepared model"| US
NS -->|"stores CREATED formulas"| REPO[("formulas/derivations")]✅ Belongs in NSForge | ❌ Use another tool |
Temperature-corrected drug elimination | Basic physics formulas → sympy-mcp |
Body-fat-adjusted volume of distribution | Physical constants → sympy-mcp |
Renal-function dose adjustments | Clinical scores → medical-calc-mcp |
Custom composite PK/PD models | Textbook formulas → references |
📦 Installation
Requirements: Python 3.12+ and uv (recommended).
uv add nsforge-mcp # or: pip install nsforge-mcpgit clone https://github.com/u9401066/nsforge-mcp.git
cd nsforge-mcp
uv sync --all-extras
uv run python -c "import nsforge; print(nsforge.__version__)"Configure as an MCP server
{
"mcpServers": {
"nsforge": { "command": "uvx", "args": ["nsforge-mcp"] }
}
}MCP 2.1 contract and tool profiles
NSForge 0.4.0 exactly pins the stable MCP Python SDK 2.1.1 and protocol revision
2026-07-28. The 91-tool catalog and legacy response dictionaries remain
compatible. A fixed startup profile keeps discovery focused without deleting a
capability:
| Tools | Intended use |
| 82 | v0.3-compatible surface; |
| 17 | Recommended resource-first, strict agent workflow |
| 35 | Stateless symbolic calculation, simplification, and verification |
| 35 | Workflow plus session editing and handoff operations |
| 91 | Complete compatibility/discovery surface, including music |
Profiles are frozen when the server starts; an unknown value fails closed.
Compact profiles reject unknown fields and enforce declared enum and numeric
constraints. Their concise descriptions come from the central ToolSpec
registry, which also drives runtime metadata and the capability manifest.
The machine-readable manifest is schema v4.
MCP 2 clients also receive:
explicit
structured_output=Truewhile preserving the existingstructuredContent+ text dual channel;protocol
isErroron application failures without changing the legacy body;a title, icon, behavioral annotations, and namespaced
_metaon every tool;nsforge://manifest,nsforge://health,nsforge://north-star, thensforge://derivations/{result_id}compatibility resource, and immutablensforge://runs/{run_id},nsforge://runs/{run_id}/events, detachednsforge://sessions/{session_id}, andnsforge://artifacts/{sha256}resource templates;phase-event-driven progress,
ResourceLinkblocks for completed runs and verification-bound artifacts, resource-updated notifications, and OpenTelemetry tool/session/run correlation.
The compact workflow uses an allowlisted no-eval expression parser. Strict task runs atomically persist immutable tenant-scoped runs, ordered phase events, provenance nodes, verification evidence, and content-addressed artifacts through a SQLite Unit of Work. Verification failure, missing or stale evidence, caller assertion, wrong tenant/subject digest, or incomplete provenance blocks artifact code generation.
Relevant process settings are NSFORGE_TENANT_ID (default local),
NSFORGE_RUN_DB (default data/nsforge-strict.sqlite3), and
NSFORGE_ARTIFACT_ROOT (default ./artifacts). Tenant IDs are opaque slugs;
output paths must resolve inside the artifact root.
stdio remains the default. To opt in to a loopback Streamable HTTP endpoint:
NSFORGE_MCP_TRANSPORT=streamable-http \
NSFORGE_MCP_HOST=127.0.0.1 \
NSFORGE_MCP_PORT=8000 \
NSFORGE_MCP_PATH=/mcp \
uv run nsforge-mcpEvery HTTP bind enables MCP 2.1 Host/Origin validation against DNS rebinding. A non-loopback bind additionally requires an explicit acknowledgement and Host allowlist, for example:
NSFORGE_MCP_TRANSPORT=streamable-http \
NSFORGE_MCP_HOST=0.0.0.0 \
NSFORGE_MCP_ALLOW_REMOTE=1 \
NSFORGE_MCP_ALLOWED_HOSTS=mcp.example.com,mcp.example.com:* \
uv run nsforge-mcpBrowser clients must also set an exact NSFORGE_MCP_ALLOWED_ORIGINS list. An
empty Origin allowlist accepts non-browser requests with no Origin header and
rejects every supplied Origin. These checks are not authentication: put remote
HTTP behind real authentication, authorization, and TLS. NSFORGE_TENANT_ID
scopes strict run/resource lookups, but it is process configuration rather than
caller authentication. Without a trusted IdP or principal resolver, one server
instance remains one tenant trust boundary. Legacy sessions and saved results
still use process globals plus JSON/YAML compatibility storage, so pass an
explicit session_id to every stateful legacy call. Neither compatibility
state nor the strict SQLite store is shared across replicas; horizontal scaling
requires shared state, artifact storage, and distributed coordination.
NSFORGE_MCP_HTTP_JSON_RESPONSE=1 is opt-in and cannot
stream request-scoped progress; leave its default 0 for progress notifications.
MCP Tasks is not implemented by Python SDK 2.1.1, so NSForge does not advertise
a private imitation. Cancelling an await around asyncio.to_thread cannot stop
the worker thread; NSForge therefore never emits a false terminal progress event,
while calls with timeout_s continue to use a terminable process. That isolated
process persists the same canonical phase events but replays their progress only
after it returns; live per-phase delivery is the default non-timeout path.
🎬 How it works — SymPy-MCP first
The golden rule: compute & verify with SymPy-MCP, then record with NSForge (provenance + human insight at every step).
flowchart LR
A["🤖 LLM<br/>understand + plan"] --> B["🔢 SymPy-MCP<br/>compute + verify"]
B --> C["🔨 NSForge<br/>record step + provenance"]
C --> D{"more<br/>steps?"}
D -->|"yes"| B
D -->|"no"| E["✅ complete<br/>stored formula + code"]Task | Tool | Why |
Math computation | SymPy-MCP | Full ODE / PDE / matrix support |
Formula display |
| User confirms each step |
Knowledge storage | NSForge | Provenance, searchable |
Dimension check | NSForge | Physical-unit verification |
🧭 Autonomous task orchestration (L2 / L3)
Hand NSForge a declarative Derivation Task Spec (DTS) and it runs the whole ladder for you. task_explore turns a single answer into a space of verified answers: it runs the base derivation plus every alternative, then ranks the survivors.
flowchart TD
DTS["📋 Derivation Task Spec"] --> BASE["base derivation"]
DTS --> ALT1["alternative 1"]
DTS --> ALT2["alternative 2"]
BASE --> V["verify · acceptance oracles · provenance"]
ALT1 --> V
ALT2 --> V
V --> RANK["🏆 ranked candidates<br/>verified · oracles passed · simpler"]task_plan— reify a DTS into an ordered, provenance-tagged plantask_run— run the ladder end-to-end; return run/artifact links and phase progress (optional hardtimeout_s)task_explore— return all branches with immutable evidence and linked artifacts
🎛️ Step-by-step control
Navigate and edit a derivation like a version-controlled document. Expressions are immutable (that keeps verification honest) — to change a result, rollback to a valid state and re-derive.
stateDiagram-v2
direction LR
[*] --> deriving
deriving --> deriving: get_step / update_step / insert_note
deriving --> earlier: rollback
earlier --> deriving: re-derive a new path
deriving --> [*]: complete + savederivation_get_step · derivation_update_step · derivation_rollback · derivation_insert_note · derivation_delete_step — see the tool reference.
🛠️ Tools at a glance — 91 catalog tools · 17 in the recommended workflow profile
Module | # | What it does |
🔥 Derivation engine | 31 | Stateful sessions: compose, step, track, store |
🔢 Calculation | 12 | Limits, series, sums, inequalities, probability |
🔣 Advanced algebra & transforms | 14 | expand/factor/apart… + Laplace / Fourier |
✅ Verification | 6 | Equality, derivative, integral, dimensions |
🌐 Formula search | 6 | Wikidata, BioModels, SciPy constants |
💻 Code generation | 4 | Python, LaTeX, report, SymPy script |
📝 Expression | 3 | Parse, validate, extract symbols |
🧭 Task orchestration | 3 |
|
🧭 Suggester | 1 | Retrieval-augmented next-step ranking |
🎵 Music (full or legacy opt-in) | 9 | Symbolic tones → waveform, spectrum, WAV |
🧩 Runtime self-description | 2 |
|
📖 Full list with every tool: Tool Reference · machine-readable
capabilities.json
✅ Verification harness
One command is the ground truth. python scripts/check.py runs 14 gates — a green run is the definition of "done".
lint · format · type · security · import · manifest · mcp · test · bench · generic · provenance · package · harness · diffmcp — MCP 2.1 discovery, schemas, metadata, payload compatibility, resources, prompts, and legacy-client mode
security — no high-severity Bandit finding in executable source
bench — known derivations reproduce correctly
generic — unseen, randomly-composed formulas derive correctly (proves NSForge is a derivation calculus, not a hand-built library)
provenance — every benchmark derivation carries a complete tool-provenance ledger (no hand-derived leaks)
package — build sdist/wheel, inspect runtime assets, install in isolation, and smoke-test installed MCP
harness — version, manifest, and gate/document parity guard the verifier itself
python scripts/check.py # all gates
python scripts/check.py --json # machine-readable (for agents)📚 Derivation repository
Derived formulas are stored with derivation metadata and a lineage summary — LaTeX, SymPy form, the base formulas combined, step descriptions, verification status, and clinical/physical context.
Derivation | Domain | Description |
PK | First-order elimination + Arrhenius | |
PK/PD | Henderson-Hasselbalch + Emax | |
PK | Saturable kinetics + temperature | |
PBPK | Vd adjustment for body composition |
🐍 Worked example:
examples/npo_antibiotic_analysis.py
🧠 Agent skills
NSForge ships 20 pre-built skills that teach agents how to use the tools — 7 NSForge workflows (nsforge-derivation-workflow, nsforge-formula-search, nsforge-verification-suite, …) plus 13 general development skills.
🔗 Optional: NSForge → USolver
NSForge derives the domain-smart formula; USolver finds the math-optimal values.
flowchart LR
N["🔨 NSForge<br/>derive modified formula"] --> P["derivation_prepare_for_optimization"]
P --> U["🎯 USolver<br/>Z3 · OR-Tools · CVXPY"]
U --> R["optimal parameters"]📖 Skill:
nsforge-usolver-collab
🏗️ Architecture & development
DDD with a pure domain core and a replaceable MCP layer (nsforge core has no MCP dependency).
uv sync --all-extras # set up
uv run pytest # tests
python scripts/check.py # full harness (14 gates)
uv run nsforge-mcp # start the server🗺️ Roadmap
Reification-ladder phases 1–6 are live (engine → benchmarks → suggester → self-correction → provenance → explore mode). Remaining: Lean4 formal verification (optional) and multi-agent infrastructure.
📄 License
NSForge — Forge new formulas through verified derivation · Where Neural meets Symbolic
Available Tools
82 toolsapart_expressionA
Partial fraction decomposition.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Decomposes rational functions into sum of simpler fractions.
CRITICAL FOR:
- Inverse Laplace transform
- Integration of rational functions
- Compartment model analysis
- Transfer function decomposition
Args:
expression: Rational function to decompose
variable: Variable for decomposition (auto-detect if None)
full: Return full decomposition (default: False)
Returns:
Partial fraction decomposition with LaTeX
Examples:
# Simple decomposition
apart_expression("(x**2 + 3*x + 2)/(x**2 + 5*x + 6)", "x")
→ {"result": "1 - 2/(x + 3)", ...}
# Compartment model transfer function
apart_expression("dose*k12 / ((s + λ1)*(s + λ2))", "s")
→ {"result": "A/(s + λ1) + B/(s + λ2)", ...}
# Prepare for inverse Laplace!
# Integration preparation
apart_expression("1/(x**2 - 1)", "x")
→ {"result": "1/(2*(x - 1)) - 1/(2*(x + 1))", ...}
# Complex poles
apart_expression("1/(x**2 + 1)", "x")
→ {"result": "-I/(2*(x - I)) + I/(2*(x + I))", ...}
Inputs: expression (required), full, variable. Returns: object
calculate_limitA
Calculate the limit of an expression.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Use cases:
- Steady-state analysis (t → ∞)
- Boundary behavior (x → 0)
- Asymptotic behavior
- L'Hôpital's rule situations
Args:
expression: The expression to take limit of
variable: The variable approaching the point
point: The point to approach (can be "oo", "-oo", "0", "1", etc.)
direction: Direction of approach
- "+-" or "": Two-sided (default)
- "+": From the right (x → 0⁺)
- "-": From the left (x → 0⁻)
Returns:
Limit result with LaTeX
Examples:
# Steady-state concentration
calculate_limit("C0 * exp(-k*t)", "t", "oo")
→ {"result": "0", "latex": "0"}
# Indeterminate form (0/0)
calculate_limit("sin(x)/x", "x", "0")
→ {"result": "1", "latex": "1"}
# One-sided limit
calculate_limit("1/x", "x", "0", direction="+")
→ {"result": "oo", "latex": "\infty"}
Inputs: point (required), variable (required), expression (required), direction. Returns: object
calculate_seriesA
Calculate series expansion of an expression.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Use cases:
- Approximate functions near a point
- Linearization (order=1)
- Small-signal analysis
- Perturbation methods
Args:
expression: The expression to expand
variable: The expansion variable
point: The expansion point (default: "0" for Maclaurin series)
order: Number of terms (default: 6)
series_type: Type of series
- "taylor": Taylor/Maclaurin series (default)
- "laurent": Laurent series (for singularities)
- "fourier": Fourier series (periodic functions)
Returns:
Series expansion with LaTeX
Examples:
# Maclaurin series of sin(x)
calculate_series("sin(x)", "x", "0", order=5)
→ {"result": "x - x**3/6 + x**5/120", ...}
# Taylor series around x=1
calculate_series("ln(x)", "x", "1", order=4)
→ {"result": "-1 + x - (x-1)**2/2 + ...", ...}
# Linearization (first-order approximation)
calculate_series("exp(-E/(R*T))", "T", "T0", order=1)
Inputs: variable (required), expression (required), order, point, +1 more. Returns: object
calculate_summationA
Calculate symbolic summation.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Use cases:
- Finite sums (Σ from n=1 to N)
- Infinite series (Σ from n=1 to ∞)
- Partition functions
- Probability mass functions
Args:
expression: The summand (term being summed)
index: Summation index variable
lower: Lower bound (integer or symbol)
upper: Upper bound (integer, symbol, or "oo" for infinity)
Returns:
Summation result with LaTeX
Examples:
# Finite sum: Σ k from k=1 to n
calculate_summation("k", "k", "1", "n")
→ {"result": "n*(n+1)/2", ...}
# Infinite geometric series: Σ r^n from n=0 to ∞
calculate_summation("r**n", "n", "0", "oo")
→ {"result": "1/(1-r)", "condition": "|r| < 1"}
# Partition function: Σ exp(-E_i/(k*T)) from i=0 to N
calculate_summation("exp(-E*i/(k*T))", "i", "0", "N")
Inputs: index (required), lower (required), upper (required), expression (required). Returns: object
cancel_expressionA
Cancel common factors in rational expression.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Reduces rational functions to lowest terms by canceling common factors.
Use cases:
- Simplify PK models
- Remove singularities
- Numerical stability
- Standard form
Args:
expression: Rational expression to cancel
Returns:
Canceled expression with LaTeX
Examples:
# Simple cancellation
cancel_expression("(x**2 - 1)/(x - 1)")
→ {"result": "x + 1", ...} # Removed (x-1) factor
# PK clearance
cancel_expression("(V*CL)/(V)")
→ {"result": "CL", ...}
# Multiple factors
cancel_expression("(x**2 - 4)/(x**2 + 4*x + 4)")
→ {"result": "(x - 2)/(x + 2)", ...}
# Remove common exponentials
cancel_expression("exp(-k*t)*C0 / exp(-k*t)")
→ {"result": "C0", ...}
Inputs: expression (required). Returns: object
check_dimensionsA
Check dimensional consistency of an expression.
Uses sympy.physics.units for dimensional analysis.
Args:
expression: Expression to check
units_map: Map of symbol to SI unit string
e.g., {"v": "m/s", "m": "kg", "F": "N"}
Returns:
Dimensional analysis result
Examples:
check_dimensions("F", {"F": "kg*m/s**2"})
→ dimension: [mass]*[length]/[time]**2
check_dimensions("m*a", {"m": "kg", "a": "m/s**2"})
→ dimension: [mass]*[length]/[time]**2 (Force)
Inputs: units_map (required), expression (required). Returns: object
collect_expressionA
Collect terms by specified variable(s).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Groups expression by powers of variable, useful for:
- Polynomial standard form
- Coefficient extraction
- Preparing for numerical evaluation
Args:
expression: Expression to collect
variable: Variable(s) to collect by (string or list)
evaluate: Evaluate coefficients (default: True)
exact: Use exact arithmetic (default: False)
Returns:
Collected expression with LaTeX
Examples:
# Collect by x
collect_expression("x*y + x - 3 + 2*x**2 - y*x**2 + x**3", "x")
→ {"result": "x**3 + x**2*(2 - y) + x*(y + 1) - 3", ...}
# Extract polynomial coefficients
collect_expression("a*x**2 + b*x + c + x**2", "x")
→ {"result": "x**2*(a + 1) + b*x + c", ...}
# Multiple variables
collect_expression("x*y + x*z + y*z", ["x", "y"])
→ Groups by x and y powers
# PK: Collect by exp terms
collect_expression("A*exp(-alpha*t) + B*exp(-beta*t)", "exp(-alpha*t)")
→ {"result": "A*exp(-alpha*t) + B*exp(-beta*t)", ...}
Inputs: variable (required), expression (required), exact, evaluate. Returns: object
combsimp_expressionA
Simplify combinatorial expressions (factorials, binomials).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Simplifies expressions involving:
- Factorials: n!/(n-k)!
- Binomial coefficients: C(n,k)
- Permutations: P(n,k)
Use cases:
- Taylor series coefficients
- Probability calculations
- Statistical formulas
- Series expansions
Args:
expression: Expression with factorials/binomials
Returns:
Simplified expression with LaTeX
Examples:
# Falling factorial
combsimp_expression("factorial(n)/factorial(n - 3)")
→ {"result": "n*(n - 1)*(n - 2)", ...}
# Binomial identity
combsimp_expression("binomial(n, k) * factorial(k)")
→ {"result": "factorial(n)/factorial(n - k)", ...}
# Taylor coefficient
combsimp_expression("x**n / factorial(n)")
→ Standard form for Taylor series
# Rising factorial
combsimp_expression("rf(x, 3)")
→ {"result": "x*(x + 1)*(x + 2)", ...}
Inputs: expression (required). Returns: object
define_distributionA
Define a probability distribution.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP! Uses sympy.stats module.
═══════════════════════════════════════════════════════════════════════
Use cases:
- Model measurement uncertainty
- Population variability in pharmacokinetics
- Error propagation
- Monte Carlo preparation
Supported distributions:
- Continuous: normal, exponential, uniform, gamma, beta, lognormal
- Discrete: poisson, binomial, geometric
Args:
distribution_type: Type of distribution
parameters: Distribution parameters (as strings for symbolic)
name: Name of the random variable
Returns:
Distribution definition with PDF/PMF
Examples:
# Normal distribution
define_distribution("normal", {"mean": "mu", "std": "sigma"}, "X")
# Exponential (for waiting times)
define_distribution("exponential", {"rate": "lambda"}, "T")
# Log-normal (for PK parameters)
define_distribution("lognormal", {"mean": "mu", "std": "sigma"}, "CL")
Inputs: parameters (required), distribution_type (required), name. Returns: object
derivation_abortA
放棄當前推導
會話仍然保存在磁碟上,可以之後用 derivation_resume 恢復。
Returns:
操作結果
Inputs: session_id. Returns: object
derivation_add_noteB
在推導中加入說明(不是計算步驟)
═══════════════════════════════════════════════════════════════════════
用於記錄「人類知識」- 不是計算,而是洞見、假設、警告、修正建議
═══════════════════════════════════════════════════════════════════════
這很重要!數學推導不只是公式變換,還包含:
- 為什麼選擇這個模型
- 這個假設何時會失效
- 臨床/物理意義是什麼
- 需要注意什麼
Args:
note: 說明內容
note_type: 說明類型
- "assumption": 假設條件
- "limitation": 限制/警告
- "observation": 觀察/洞見
- "correction": 修正建議
- "clinical": 臨床意義
- "physical": 物理意義
related_variables: 相關的變數
related_step: 相關的步驟編號(可選)
Returns:
記錄結果
Example:
# 在代入 Arrhenius 後加入說明
derivation_add_note(
note="酵素活性 vs 溫度不是線性的!在高溫 (>42°C) 酵素會變性,"
"此時 Arrhenius 方程不再適用。應考慮加入校正因子 γ(T)。",
note_type="limitation",
related_variables=["V_max", "T"]
)
# 加入修正建議
derivation_add_note(
note="建議加入 Hill-type 校正因子:γ(T) = 1 / (1 + (T/T_denat)^n)",
note_type="correction",
related_variables=["gamma", "T_denat"]
)
Inputs: note (required), note_type, session_id, related_step, +1 more. Returns: object
derivation_completeA
完成推導並自動存檔
標記推導為完成,返回完整的推導記錄。
Agent 應該提供描述性知識(公式的物理/臨床意義、使用時機等)。
Args:
description: 公式描述(物理/化學/臨床意義)
clinical_context: 臨床應用場景(何時使用這個公式)
assumptions: 推導假設條件
limitations: 使用限制
references: 參考文獻
tags: 標籤(用於分類和搜尋)
auto_save: 是否自動存檔(預設 True)
Returns:
完整推導記錄,包含:
- 最終表達式
- 所有步驟
- 使用的公式及其來源
- 溯源資訊
- 存檔路徑(如果 auto_save=True)
Example:
derivation_complete(
description="Temperature-corrected drug elimination rate combining first-order kinetics with Arrhenius equation",
clinical_context="Use when adjusting drug dosing for febrile patients or hypothermia protocols",
assumptions=["First-order elimination kinetics", "Arrhenius temperature dependence"],
limitations=["Valid only for temperature range 32-42°C", "Assumes linear protein binding"],
references=["Goodman & Gilman Ch.2", "Atkins Physical Chemistry Ch.22"],
tags=["pharmacokinetics", "temperature", "elimination"]
)
Inputs: tags, auto_save, references, session_id, +4 more. Returns: object
derivation_delete_savedA
刪除已存檔的推導結果
⚠️ 警告:此操作不可逆!推導記錄和 YAML 檔案都會被刪除。
Args:
result_id: 推導結果 ID
confirm: 必須設為 True 才會執行刪除(安全機制)
Returns:
刪除結果
Example:
# 必須明確確認才能刪除
derivation_delete_saved("temp_corrected_elimination", confirm=True)
Inputs: result_id (required), confirm. Returns: object
derivation_delete_stepA
刪除單一步驟
═══════════════════════════════════════════════════════════════════════
⚠️ 只能刪除最後一步!
═══════════════════════════════════════════════════════════════════════
如需刪除中間步驟,請使用 derivation_rollback() 回滾到該步驟之前,
然後重新執行推導。
Args:
step_number: 步驟編號(必須是最後一步)
Returns:
刪除結果
Example:
derivation_delete_step(16) # 假設有 16 步,刪除最後一步
→ {"success": True, "deleted_step": {...}, "new_step_count": 15}
Inputs: step_number (required), session_id. Returns: object
derivation_differentiateC
對當前表達式微分(帶人類知識記錄)
Args:
variable: 微分變數
order: 階數(預設 1)
description: 操作描述
notes: 人類洞見
assumptions: 這步的假設
limitations: 這步的限制
Returns:
微分結果
Inputs: variable (required), notes, order, session_id, +3 more. Returns: object
derivation_export_for_sympyA
導出當前推導狀態給 SymPy-MCP
═══════════════════════════════════════════════════════════════════════
🔄 HANDOFF 機制 - 當 NSForge 無法處理時,交給 SymPy-MCP!
═══════════════════════════════════════════════════════════════════════
使用時機:
- 需要解 ODE/PDE
- 需要矩陣運算
- 需要複雜的 SymPy 操作(如 limit, series, dsolve)
- NSForge 工具返回錯誤時
這個工具會輸出:
1. 所有已定義的變數(可直接貼到 intro_many)
2. 當前表達式(可直接貼到 introduce_expression)
3. 建議的下一步操作
Returns:
包含可直接使用的 SymPy-MCP 指令
Example:
# NSForge 中遇到無法處理的操作
derivation_export_for_sympy()
→ {
"intro_many_command": "intro_many(['k', 'T', 'Ea', 'R'], 'real positive')",
"current_expression": "k * exp(-Ea/(R*T))",
"suggested_actions": [...]
}
# 然後在 SymPy-MCP 中執行
intro_many(['k', 'T', 'Ea', 'R'], 'real positive')
introduce_expression("k * exp(-Ea/(R*T))", "arrhenius")
Inputs: session_id, include_variables, include_current_expression. Returns: object
derivation_get_savedA
取得已存檔的推導結果詳情
Args:
result_id: 推導結果 ID
Returns:
完整的推導結果,包含:
- 公式表達式
- 推導步驟
- 來源公式
- 臨床/物理意義
- 使用限制
- 參考文獻
Example:
derivation_get_saved("temp_corrected_elimination")
→ {"success": True, "name": "...", "expression": "...", ...}
Inputs: result_id (required). Returns: object
derivation_get_stepA
取得單一步驟的詳細資訊
用於檢視特定步驟的完整記錄,包含:
- 操作類型和描述
- 輸入/輸出表達式
- SymPy 指令
- 人類知識(notes、assumptions、limitations)
Args:
step_number: 步驟編號(1-based)
Returns:
步驟詳情
Example:
derivation_get_step(11)
→ {"success": True, "step": {"step_number": 11, "operation": "substitute", ...}}
Inputs: step_number (required), session_id. Returns: object
derivation_get_stepsC
取得所有推導步驟
返回完整的步驟歷史,包含:
- 每步的操作類型
- 輸入輸出表達式
- SymPy 指令
- 時間戳
Returns:
步驟列表
Inputs: session_id. Returns: object
derivation_handoff_statusB
顯示 Handoff 狀態和可用選項
這個工具幫助你了解:
1. NSForge 能做什麼
2. 什麼需要交給 SymPy-MCP
3. 當前推導的狀態
Returns:
Handoff 狀態和建議
Inputs: session_id. Returns: object
derivation_import_from_sympyA
從 SymPy-MCP 導入結果回 NSForge
═══════════════════════════════════════════════════════════════════════
🔄 HANDOFF 機制 - 把 SymPy-MCP 的結果帶回 NSForge 繼續!
═══════════════════════════════════════════════════════════════════════
使用時機:
- 在 SymPy-MCP 完成複雜計算後
- 想要繼續使用 NSForge 的步進式記錄
- 需要為 SymPy-MCP 的結果加入人類知識
這個工具會:
1. 將 SymPy-MCP 的結果記錄為新步驟
2. 更新當前表達式
3. 記錄使用的假設和限制
Args:
expression: SymPy-MCP 返回的表達式(字串格式)
operation_performed: 執行了什麼操作(如 "Solved ODE")
sympy_tool_used: 使用的 SymPy-MCP 工具名稱
latex: LaTeX 格式(可選,會自動生成)
notes: 額外說明
assumptions_used: 使用的假設(從 SymPy-MCP 的 intro 來的)
limitations: 這個結果的限制
Returns:
導入結果
Example:
# SymPy-MCP 解完 ODE 後
derivation_import_from_sympy(
expression="C*exp(k*t)",
operation_performed="Solved first-order ODE",
sympy_tool_used="dsolve_ode",
notes="General solution with integration constant C",
assumptions_used=["k is real positive", "t is real"],
limitations=["Requires initial condition to determine C"]
)
Inputs: expression (required), sympy_tool_used (required), operation_performed (required), latex, +4 more. Returns: object
derivation_insert_noteA
在指定位置插入說明
═══════════════════════════════════════════════════════════════════════
📝 用於在推導中間補充說明,不改變計算流程
═══════════════════════════════════════════════════════════════════════
插入後會自動重新編號後續步驟。
Args:
after_step: 在此步驟之後插入(0 = 最開頭)
note: 說明內容
note_type: 說明類型
- "assumption": 📋 假設條件
- "limitation": ⚠️ 限制/警告
- "observation": 💡 觀察/洞見
- "correction": 🔧 修正建議
- "clinical": 🏥 臨床意義
- "physical": 🔬 物理意義
related_variables: 相關變數
Returns:
插入結果
Example:
# 在步驟 5 和 6 之間插入說明
derivation_insert_note(
after_step=5,
note="此處假設達穩態,實際臨床可能需要 5 個半衰期",
note_type="clinical",
related_variables=["t_half"]
)
→ {"success": True, "inserted_at": 6, "new_step_count": 17}
Inputs: note (required), after_step (required), note_type, session_id, +1 more. Returns: object
derivation_integrateA
對當前表達式積分(帶人類知識記錄)
Args:
variable: 積分變數
lower: 下界(可選,定積分時需要)
upper: 上界(可選,定積分時需要)
description: 操作描述
notes: 人類洞見
assumptions: 這步的假設
limitations: 這步的限制
Returns:
積分結果
Inputs: variable (required), lower, notes, upper, +4 more. Returns: object
derivation_list_savedB
列出所有已存檔的推導結果
Args:
category: 類別篩選(可選)
Returns:
已存檔的推導列表
Example:
derivation_list_saved()
→ {"success": True, "results": ["temp_corrected_elimination", ...], "count": 5}
Inputs: category. Returns: object
derivation_list_sessionsA
列出所有推導會話
Returns:
所有會話列表
Inputs: no named parameters. Returns: object
derivation_load_formulaA
載入公式到當前會話
支援多種格式輸入:
- SymPy 字串: "C_0 * exp(-k*t)"
- LaTeX: "C_0 e^{-kt}" 或 "\frac{dC}{dt} = -kC"
- 字典: {"expression": "...", "variables": {...}}
Args:
formula: 公式(多種格式)
formula_id: 公式 ID(可選,自動生成)
source: 來源標記 ("user_input", "textbook", "sympy_builtin", "derived", "external_mcp")
source_detail: 詳細來源(如 "Goodman & Gilman Ch.2")
name: 公式名稱
description: 公式描述
Returns:
載入結果
Examples:
# SymPy 格式
derivation_load_formula("C_0 * exp(-k*t)", formula_id="one_compartment")
# LaTeX 格式
derivation_load_formula("\frac{dC}{dt} = -k \cdot C")
# 字典格式(含變數資訊)
derivation_load_formula({
"expression": "k_ref * exp(E_a/R * (1/T_ref - 1/T))",
"name": "Arrhenius temperature correction",
"variables": {
"k_ref": {"description": "Reference rate constant", "unit": "1/h"},
"E_a": {"description": "Activation energy", "unit": "J/mol"},
"T": {"description": "Temperature", "unit": "K"},
}
})
Inputs: formula (required), name, source, formula_id, +3 more. Returns: object
derivation_prepare_for_optimizationA
準備推導結果給優化求解器(如 USolver)
將 NSForge 推導的符號公式轉換為優化求解器可用的格式。
工作流程:
1. NSForge 推導修正後的公式(考慮領域知識)
2. 調用此工具取得優化器輸入格式
3. 送給 USolver 等優化器找最優解
Returns:
優化器輸入資料
Example:
# 在 NSForge 完成推導後
derivation_prepare_for_optimization()
→ {
"function_str": "dose/15.875 * exp(-0.476*t/15.875)",
"variables": ["dose", "t"],
"parameters": {"CL": 0.476, "V1": 15.875},
"suggested_constraints": [
"dose >= 0.01",
"dose <= 0.10",
"t >= 0"
],
"usolver_template": "..."
}
Inputs: session_id. Returns: object
derivation_record_stepA
記錄一個推導步驟(從 SymPy-MCP 或手動)
═══════════════════════════════════════════════════════════════════════
這是 SymPy-MCP 和 NSForge 之間的橋樑!
═══════════════════════════════════════════════════════════════════════
用途:
1. 在 SymPy-MCP 計算後,把結果記錄到 NSForge 會話
2. 可以加入 notes 說明「為什麼這步要這樣做」
3. 保持完整的推導歷史
工作流程:
1. SymPy-MCP: intro + introduce_expression + substitute...
2. SymPy-MCP: print_latex_expression (確認結果)
3. NSForge: derivation_record_step (記錄這步 + 加入說明)
4. 重複 1-3
5. NSForge: derivation_complete
Args:
expression: SymPy 格式的表達式(從 SymPy-MCP 結果複製)
description: 這步做了什麼
latex: LaTeX 格式(可選,會自動生成)
notes: 額外說明(非計算性的人類知識!)
例如:「這裡假設線性,但酵素活性實際上是 S 型曲線」
source: 來源 ("sympy_mcp", "manual", "literature")
operation_type: 操作類型 ("substitute", "simplify", "solve", "custom")
set_as_current: 是否設為當前表達式(預設 True)
Returns:
記錄結果
Example:
# 在 SymPy-MCP 計算完成後
derivation_record_step(
expression="C*V_max_ref*exp(E_a*(1/T_ref - 1/T)/R)/(C + K_m)",
description="Substituted Arrhenius equation for Vmax",
notes="假設 Vmax 的溫度依賴遵循 Arrhenius,但實際上酵素在高溫會變性",
source="sympy_mcp"
)
Inputs: expression (required), description (required), latex, notes, +4 more. Returns: object
derivation_repository_statsA
取得推導庫統計資訊
Returns:
統計資訊:
- 總數
- 已驗證數量
- 未驗證數量
- 分類統計
Example:
derivation_repository_stats()
→ {"total": 10, "verified": 5, "categories": {"pk": 3, "pd": 2, ...}}
Inputs: no named parameters. Returns: object
derivation_resumeA
恢復暫停的推導會話
如果推導過程中斷,可以用這個工具恢復。
Args:
session_id: 會話 ID
Returns:
會話狀態
Inputs: session_id (required). Returns: object
derivation_rollbackA
回滾到指定步驟
═══════════════════════════════════════════════════════════════════════
⚡ 這是「跳回某一步」的核心工具!
═══════════════════════════════════════════════════════════════════════
保留指定步驟及之前的所有步驟,刪除之後的步驟。
回滾後可以從該步驟繼續推導(走不同的路徑)。
Args:
to_step: 回滾到的步驟編號(1-based,該步驟會保留)
0 = 清空所有步驟,從頭開始
Returns:
回滾結果,包含:
- 刪除了哪些步驟
- 當前的表達式
- 新的步驟數
Example:
# 假設有 16 步,發現第 11 步開始走錯方向
derivation_rollback(to_step=10)
→ {
"success": True,
"rolled_back_to": 10,
"deleted_count": 6,
"deleted_steps": [11, 12, 13, 14, 15, 16],
"current_expression": "CL_int*(1 - f_b)",
"message": "Rolled back to step 10. Deleted 6 step(s)."
}
# 現在可以從步驟 10 的表達式繼續,走不同的推導路徑
Inputs: to_step (required), session_id. Returns: object
derivation_search_savedA
搜尋已存檔的推導結果
在公式名稱、描述、標籤中搜尋關鍵字。
Args:
query: 搜尋關鍵字
Returns:
符合的推導結果列表
Example:
derivation_search_saved("temperature")
→ {"success": True, "results": [{"id": "...", "name": "...", ...}], "count": 2}
Inputs: query (required). Returns: object
derivation_showA
顯示當前推導狀態和公式(類似 SymPy-MCP 的 print_latex_expression)
═══════════════════════════════════════════════════════════════════════
⚠️ 重要:Agent 必須在每次推導操作後調用此工具向用戶展示結果!
═══════════════════════════════════════════════════════════════════════
這個工具確保用戶能看到:
1. 當前公式的 LaTeX 渲染結果
2. 推導進度(第幾步)
3. 會話名稱和狀態
Args:
format: 輸出格式
- "all": 完整資訊(預設)
- "latex": 只返回 LaTeX
- "sympy": 只返回 SymPy 字串
- "summary": 簡短摘要
show_steps: 是否顯示所有步驟歷史
Returns:
當前公式和推導狀態
Example:
derivation_show()
→ {
"latex": "C_{0} e^{- k t}",
"sympy": "C_0*exp(-k*t)",
"session_name": "drug_elimination",
"step_count": 3,
"status": "active",
"display_text": "📊 **drug_elimination** (Step 3)\n\n$$C_{0} e^{- k t}$$"
}
Inputs: format, session_id, show_steps. Returns: object
derivation_simplifyA
簡化當前表達式(帶人類知識記錄)
Args:
method: 簡化方法
- "auto": 自動選擇(預設)
- "trig": 三角函數簡化
- "radical": 根式簡化
- "expand_then_simplify": 先展開再簡化
description: 操作描述
notes: 人類洞見
assumptions: 這步的假設
limitations: 這步的限制
Returns:
簡化結果
Inputs: notes, method, session_id, assumptions, +2 more. Returns: object
derivation_solve_forA
求解變數(帶人類知識記錄)
將當前表達式求解為指定變數的函數。
Args:
variable: 要求解的變數
description: 操作描述
notes: 人類洞見
assumptions: 這步的假設
limitations: 這步的限制
Returns:
求解結果(可能有多個解)
Example:
derivation_load_formula("m*a - F", formula_id="newton")
derivation_solve_for(
variable="a",
notes="假設質量不變",
assumptions=["Constant mass"]
)
→ a = F/m
Inputs: variable (required), notes, session_id, assumptions, +2 more. Returns: object
derivation_startA
開始新的推導會話
這是所有推導的起點。會話會自動持久化,防止中斷。
Args:
name: 推導名稱(如 "溫度修正消除率")
description: 推導描述
author: 作者
Returns:
會話資訊
Example:
derivation_start("temp_corrected_elimination", "Temperature-corrected drug elimination rate")
→ {"session_id": "a1b2c3d4", "name": "temp_corrected_elimination", ...}
Inputs: name (required), author, description. Returns: object
derivation_statusC
取得當前會話狀態
Returns:
當前會話詳細狀態
Inputs: session_id. Returns: object
derivation_substituteA
代入操作(帶人類知識記錄)
將公式中的變數替換為另一個表達式。
這是組合公式的關鍵操作。
═══════════════════════════════════════════════════════════════════════
⚡ 每一步都可以加入人類知識!
═══════════════════════════════════════════════════════════════════════
Args:
variable: 要替換的變數名
replacement: 替換的表達式
in_formula: 在哪個公式中代入(預設為當前)
description: 操作描述
notes: 人類洞見(為什麼這樣做、觀察、警告)
assumptions: 這步的假設條件
limitations: 這步的限制
Returns:
代入結果(含記錄的知識)
Example:
derivation_substitute(
variable="k",
replacement="k_ref * exp(E_a/R * (1/T_ref - 1/T))",
description="Apply Arrhenius equation for temperature dependence",
notes="⚠️ 假設 V_max 遵循 Arrhenius,但酵素在 >42°C 會變性",
assumptions=["Temperature range 32-42°C", "No enzyme denaturation"],
limitations=["Not valid for high temperature"]
)
Inputs: variable (required), replacement (required), notes, in_formula, +4 more. Returns: object
derivation_suggest_nextA
Rank candidate next steps for a derivation by relevance.
Retrieval-augmented: you supply ``candidates`` retrieved from open sources
(``formula_search`` over Wikidata/BioModels/SciPy, the session's formulas,
or generic operations); this tool ranks them by how well they advance the
derivation. A candidate scores highest when it defines a symbol currently
in ``current_expression`` (so it can be substituted in) and matches the
goal's terms.
Args:
goal: What the derivation is trying to reach (natural language).
current_expression: The expression derived so far, e.g. "C0*exp(-k*t)".
candidates: Each ``{"id", "expression"?, "description"?, "kind"?,
"provides"?}`` — a formula, modification, or operation.
Returns:
``{"success", "goal", "suggestions": [{"id", "score", "kind",
"expression", "rationale"}]}`` ordered best-first.
Inputs: goal (required), candidates (required), current_expression (required). Returns: object
derivation_update_savedA
更新已存檔推導的元資料
允許 Agent 更新推導的描述性知識、分類、驗證狀態等。
不能修改推導表達式本身(那需要重新推導)。
Args:
result_id: 推導結果 ID
name: 新名稱
description: 新描述
clinical_context: 新臨床情境
assumptions: 新假設清單
limitations: 新限制清單
references: 新參考文獻
tags: 新標籤
category: 新分類
verified: 驗證狀態
verification_method: 驗證方法
Returns:
更新結果
Example:
derivation_update_saved(
"temp_corrected_elimination",
description="Updated description with more details",
tags=["pharmacokinetics", "temperature", "elimination", "fever"],
verified=True,
verification_method="dimensional_analysis + clinical_validation"
)
Inputs: result_id (required), name, tags, category, +7 more. Returns: object
derivation_update_stepA
更新步驟的元資料
═══════════════════════════════════════════════════════════════════════
⚠️ 只能更新「說明性」欄位,不能改變計算結果!
═══════════════════════════════════════════════════════════════════════
可更新的欄位:
- description: 步驟描述
- notes: 人類洞見、觀察、解釋
- assumptions: 這步的假設條件
- limitations: 這步的限制
不可更新(需要用 rollback 重做):
- 表達式
- 操作類型
Args:
step_number: 步驟編號(1-based)
description: 新描述(None = 不更新)
notes: 新註記(None = 不更新)
assumptions: 新假設(None = 不更新)
limitations: 新限制(None = 不更新)
Returns:
更新結果
Example:
derivation_update_step(
step_number=11,
notes="此假設在高溫時不成立",
limitations=["Valid only for T < 42°C"]
)
Inputs: step_number (required), notes, session_id, assumptions, +2 more. Returns: object
distribution_probabilityA
Calculate probability P(condition).
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Args:
distribution_type: Type of distribution
parameters: Distribution parameters
condition: Condition string using X as the random variable
- "X < 5", "X > 2", "X >= 3", "X <= 1"
- "2 < X < 5" (between two values)
Returns:
Probability (symbolic or numeric)
Examples:
# P(X < 0) for standard normal
distribution_probability("normal", {"mean": "0", "std": "1"}, "X < 0")
→ {"probability": "1/2", ...}
# P(1 < X < 3) for exponential
distribution_probability("exponential", {"rate": "lambda"}, "1 < X < 3")
Inputs: condition (required), parameters (required), distribution_type (required). Returns: object
distribution_statsA
Compute statistics of a distribution.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Args:
distribution_type: Type of distribution
parameters: Distribution parameters
stats_to_compute: Which statistics (default: all available)
- "mean", "variance", "std", "skewness", "kurtosis", "entropy"
Returns:
Computed statistics
Examples:
distribution_stats("normal", {"mean": "mu", "std": "sigma"})
→ {"mean": "mu", "variance": "sigma**2", "std": "sigma", ...}
Inputs: parameters (required), distribution_type (required), stats_to_compute. Returns: object
evaluate_numericA
Evaluate expression numerically.
⚠️ USE AFTER SYMBOLIC WORK: This tool is for final numeric evaluation
after you've done symbolic calculations with SymPy-MCP.
Correct Workflow:
1. Use SymPy-MCP for symbolic calculations (solve, simplify, etc.)
2. Use print_latex_expression() to show result to user
3. Use this tool for final numeric values
Args:
expression: Expression to evaluate
values: Numeric values for all variables
precision: Decimal precision
Returns:
Numeric result
Examples:
evaluate_numeric("sin(pi/4)", {}) → 0.707107
evaluate_numeric("m * v**2 / 2", {"m": 70, "v": 10}) → 3500.0
Inputs: values (required), expression (required), precision. Returns: object
expand_expressionA
Expand algebraic expression.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
DETERMINISTIC: Always expands products and powers (unlike `simplify()`).
Use cases:
- Expand polynomial products: (x+1)(x-1) → x²-1
- Expand powers: (x+a)² → x²+2ax+a²
- Prepare for coefficient extraction
- Expand logarithms: log(xy) → log(x)+log(y)
Args:
expression: Expression to expand
deep: Expand recursively into subexpressions (default: True)
modulus: Modular arithmetic (for finite fields)
power_base: Expand (x*y)^n → x^n*y^n (default: True)
power_exp: Expand x^(a+b) → x^a*x^b (default: True)
mul: Expand products (default: True)
log: Expand log(xy) → log(x)+log(y) (default: True)
multinomial: Use multinomial expansion (default: True)
basic: Apply basic expansion rules (default: True)
Returns:
Expanded expression with LaTeX
Examples:
# Polynomial expansion
expand_expression("(x + 1)**2")
→ {"result": "x**2 + 2*x + 1", ...}
# Product expansion
expand_expression("(x + y)*(x - y)")
→ {"result": "x**2 - y**2", ...}
# Exponential expansion
expand_expression("exp(x + y)")
→ {"result": "exp(x)*exp(y)", ...}
# Log expansion
expand_expression("log(x*y)")
→ {"result": "log(x) + log(y)", ...}
# PK model: Expand dose calculation
expand_expression("dose/(V1 + V2) * exp(-k*t)")
→ {"result": "dose*exp(-k*t)/(V1 + V2)", ...}
# Michaelis-Menten expanded
expand_expression("(V_max*S + V_max*I)/(K_m + S)")
→ {"result": "V_max*S/(K_m + S) + V_max*I/(K_m + S)", ...}
Inputs: expression (required), log, mul, deep, +5 more. Returns: object
extract_symbolsA
Extract symbols from an expression with inferred metadata.
Args:
expression: Mathematical expression
context: Optional context hint (e.g., "mechanics", "thermodynamics")
Returns:
List of symbols with:
- name: Symbol name
- type: Inferred type (real, positive_real, integer, etc.)
- suggested_unit: Suggested SI unit based on context
- description: Inferred description
Examples:
extract_symbols("F = m*a", context="mechanics")
→ [
{"name": "F", "type": "real", "suggested_unit": "N", "description": "Force"},
{"name": "m", "type": "positive_real", "suggested_unit": "kg", "description": "Mass"},
{"name": "a", "type": "real", "suggested_unit": "m/s²", "description": "Acceleration"}
]
Inputs: expression (required), context. Returns: object
factor_expressionA
Factorize algebraic expression.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
DETERMINISTIC: Always attempts factorization (unlike `simplify()`).
Use cases:
- Find roots: x²-1 → (x-1)(x+1) ⇒ roots at x=±1
- Simplify rational functions
- Characteristic equations (eigenvalues)
- Stability analysis (find poles)
Args:
expression: Expression to factorize
deep: Factor recursively into subexpressions (default: False)
modulus: Modular arithmetic (for finite fields)
Returns:
Factored expression with LaTeX
Examples:
# Quadratic factorization
factor_expression("x**2 - 1")
→ {"result": "(x - 1)*(x + 1)", ...}
# Find roots
factor_expression("x**2 + 5*x + 6")
→ {"result": "(x + 2)*(x + 3)", ...}
# Compartment model characteristic equation
factor_expression("s**2 + (k12 + k21 + k10)*s + k21*k10")
→ {"result": "(s + λ1)*(s + λ2)", ...} # eigenvalues
# Rational function numerator
factor_expression("C**2 - K_m**2")
→ {"result": "(C - K_m)*(C + K_m)", ...}
# Difference of cubes
factor_expression("x**3 - 8")
→ {"result": "(x - 2)*(x**2 + 2*x + 4)", ...}
Inputs: expression (required), deep, modulus. Returns: object
formula_categoriesA
列出可用的公式分類
獲取各資料來源支援的分類,用於更精確的搜尋。
Args:
source: 資料來源
- "all": 所有來源(預設)
- "wikidata", "biomodels", "scipy"
Returns:
{
"success": true,
"categories": {
"wikidata": ["mechanics", "thermodynamics", ...],
"biomodels": ["pharmacokinetics", "enzyme_kinetics", ...],
"scipy": ["fundamental", "electromagnetic", ...]
}
}
Inputs: source. Returns: object
formula_constantsA
列出物理常數
從 SciPy CODATA 2018 獲取物理常數。
Args:
category: 分類
- "fundamental": 基本常數(c, h, G)
- "electromagnetic": 電磁常數
- "atomic": 原子常數
- "conversion": 換算因子
query: 搜尋關鍵字(可選)
Returns:
物理常數列表(含數值、單位、不確定度)
Example:
# 列出所有基本常數
formula_constants(category="fundamental")
# 搜尋電子相關常數
formula_constants(query="electron")
Inputs: query, category. Returns: object
formula_getA
獲取公式詳細資訊
根據 ID 獲取完整的公式資訊,包括 LaTeX、SymPy 表達式、變數定義等。
Args:
formula_id: 公式識別碼
- Wikidata: Q 號(如 "Q179057")
- BioModels: 模型 ID(如 "BIOMD0000000012")
- SciPy: 常數名(如 "speed_of_light")
source: 資料來源
- "wikidata": Wikidata(預設)
- "biomodels": BioModels
- "scipy": SciPy 常數
Returns:
{
"success": true,
"formula": {
"id": "Q179057",
"name": "Reynolds number",
"latex": "Re = \frac{\rho v L}{\mu}",
"sympy_str": "rho * v * L / mu",
"variables": {
"rho": {"description": "密度", "unit": "kg/m³"},
"v": {"description": "流速", "unit": "m/s"},
"L": {"description": "特徵長度", "unit": "m"},
"mu": {"description": "動力黏度", "unit": "Pa·s"}
},
"source": "wikidata",
"url": "https://www.wikidata.org/wiki/Q179057"
}
}
Example:
# 獲取 Wikidata 公式
formula_get("Q179057", source="wikidata")
# 獲取 BioModels 模型
formula_get("BIOMD0000000012", source="biomodels")
# 獲取物理常數
formula_get("speed_of_light", source="scipy")
Inputs: formula_id (required), source. Returns: object
formula_kinetic_lawsA
獲取 BioModels 模型的動力學公式
從 SBML 模型中提取所有動力學方程式。
Args:
model_id: BioModels 模型 ID(如 "BIOMD0000000012")
Returns:
{
"success": true,
"model_id": "BIOMD0000000012",
"kinetic_laws": [
{
"reaction_id": "v1",
"name": "Enzyme binding",
"math": "k1 * E * S",
"parameters": [
{"id": "k1", "value": "0.1", "units": "per_second"}
]
}
]
}
Example:
formula_kinetic_laws("BIOMD0000000012")
Inputs: model_id (required). Returns: object
formula_pk_modelsA
搜尋藥動學 (PK) 模型
專門從 BioModels 搜尋藥動學相關模型。
Args:
query: 搜尋關鍵字(如 "absorption", "elimination")
drug: 藥物名稱(可選)
limit: 返回數量上限
Returns:
藥動學模型列表
Example:
# 搜尋吸收模型
formula_pk_models(query="absorption")
# 搜尋特定藥物
formula_pk_models(drug="warfarin")
Inputs: drug, limit, query. Returns: object
formula_searchA
搜尋公式(跨多個來源)
這是科學運算 Agent 的核心工具,可從多個權威來源檢索準確的公式。
使用直接精確檢索(非 RAG),確保公式正確性。
Args:
query: 搜尋關鍵字
- 英文名稱: "Reynolds number", "Arrhenius equation"
- 領域術語: "pharmacokinetics", "Michaelis-Menten"
source: 資料來源
- "all": 搜尋所有來源(預設)
- "wikidata": 僅 Wikidata(跨領域)
- "biomodels": 僅 BioModels(藥學/生物)
- "scipy": 僅 SciPy 常數
domain: 限定領域(可選)
- "mechanics", "thermodynamics", "electromagnetism"
- "pharmacokinetics", "pharmacodynamics", "enzyme_kinetics"
limit: 返回數量上限
Returns:
{
"success": true,
"results": [
{
"id": "Q179057",
"name": "Reynolds number",
"latex": "Re = \frac{\rho v L}{\mu}",
"sympy_str": "rho * v * L / mu",
"source": "wikidata",
"url": "https://www.wikidata.org/wiki/Q179057"
}
],
"total": 1,
"sources_searched": ["wikidata"]
}
Example:
# 搜尋雷諾數
formula_search("Reynolds number")
# 搜尋藥動學模型
formula_search("one compartment", source="biomodels")
# 按領域搜尋
formula_search("diffusion", domain="thermodynamics")
Inputs: query (required), limit, domain, source. Returns: object
fourier_transform_expressionA
Fourier transform: f(x) → F(k).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 2 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Transforms spatial/time function to frequency domain.
USE CASES:
- Periodic dosing analysis (repeated administration)
- Spectral analysis (frequency components)
- Signal processing (filter design)
- Diffusion problems (spatial frequency)
Args:
expression: Space/time-domain expression f(x)
space_var: Space/time variable (default: "x")
freq_var: Frequency variable (default: "k")
Returns:
Fourier transform F(k)
Examples:
# Gaussian pulse
fourier_transform_expression("exp(-x**2)", "x", "k")
→ {"result": "sqrt(pi)*exp(-pi**2*k**2)", ...}
# Exponential decay
fourier_transform_expression("exp(-abs(x))", "x", "k")
→ {"result": "2/(1 + k**2)", ...}
# Rectangular pulse
fourier_transform_expression("Heaviside(x+1) - Heaviside(x-1)", "x", "k")
→ {"result": "2*sin(k)/k", ...}
# PK: Periodic dosing spectrum
# Analyze frequency components of repeated doses
Inputs: expression (required), freq_var, space_var. Returns: object
generate_derivation_reportB
Generate a complete derivation report in Markdown.
Args:
problem: Problem description
given: Given parameters {"symbol": "value with unit"}
steps: Derivation steps
results: Final results {"symbol": "expression"}
verification: Optional verification status
Returns:
Markdown report
Inputs: given (required), steps (required), problem (required), results (required), +1 more. Returns: object
generate_latex_derivationA
Generate LaTeX documentation for a derivation.
Args:
title: Derivation title
steps: List of {"description": str, "latex": str}
final_result: Final result in LaTeX
Returns:
LaTeX document string
Inputs: steps (required), title (required), final_result (required). Returns: object
generate_python_functionA
Generate a Python function from VERIFIED derivation steps.
═══════════════════════════════════════════════════════════════════════
⚠️ PREREQUISITE: All expressions must be verified with SymPy-MCP first!
═══════════════════════════════════════════════════════════════════════
Correct workflow:
1. Use SymPy-MCP to derive and verify each expression
2. Use print_latex_expression() to show results to user
3. User confirms the derivation is correct
4. Call this tool with the verified expressions
The generated code uses SymPy for computation, ensuring correctness.
This is NOT Agent-generated code - it's assembled from verified steps.
Args:
name: Function name (e.g., "calculate_seatbelt_tension")
description: Function docstring description
parameters: List of {"name": str, "type": str, "description": str}
steps: List of {"description": str, "expression": str, "result_var": str}
return_vars: Variables to return
Returns:
Generated Python code
Example:
generate_python_function(
name="calculate_tension",
description="Calculate seatbelt tension from collision",
parameters=[
{"name": "M1", "type": "float", "description": "Vehicle 1 mass (kg)"},
{"name": "M2", "type": "float", "description": "Vehicle 2 mass (kg)"},
{"name": "v", "type": "float", "description": "Initial velocity (m/s)"},
{"name": "m", "type": "float", "description": "Person mass (kg)"},
{"name": "k", "type": "float", "description": "Seatbelt constant (N/m)"},
],
steps=[
{"description": "Final velocity after collision",
"expression": "M1 * v / (M1 + M2)",
"result_var": "v_f"},
{"description": "Velocity change",
"expression": "v - v_f",
"result_var": "delta_v"},
{"description": "Maximum tension",
"expression": "delta_v * sqrt(m * k)",
"result_var": "T_max"},
],
return_vars=["v_f", "delta_v", "T_max"]
)
Inputs: name (required), steps (required), parameters (required), description (required), +1 more. Returns: object
generate_sympy_scriptA
Generate a standalone SymPy script for a computation.
This generates a complete, runnable Python script that can be
executed independently to reproduce the derivation.
Args:
expressions: List of {"name": str, "expr": str, "description": str}
operations: List of operations to perform
{"op": "simplify|solve|diff|integrate", "input": str, ...}
Returns:
Complete Python script
Example:
generate_sympy_script(
expressions=[
{"name": "momentum", "expr": "m1*v1 + m2*v2", "description": "Total momentum"},
],
operations=[
{"op": "solve", "input": "momentum = (m1+m2)*v_f", "for": "v_f"},
]
)
Inputs: operations (required), expressions (required). Returns: object
inverse_fourier_transform_expressionA
Inverse Fourier transform: F(k) → f(x).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 2 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Transforms frequency domain back to spatial/time domain.
USE CASES:
- Reconstruct signal from spectrum
- Inverse filter design
- Synthesize periodic patterns
- Diffusion problem solutions
Args:
expression: Frequency-domain expression F(k)
freq_var: Frequency variable (default: "k")
space_var: Space/time variable (default: "x")
Returns:
Spatial/time-domain function f(x)
Examples:
# Lorentzian spectrum
inverse_fourier_transform_expression("1/(1 + k**2)", "k", "x")
→ {"result": "pi*exp(-abs(x))", ...}
# Sinc function
inverse_fourier_transform_expression("Heaviside(k+1) - Heaviside(k-1)", "k", "x")
→ {"result": "sin(x)/(pi*x)", ...}
# PK: Reconstruct concentration profile from spectrum
Inputs: expression (required), freq_var, space_var. Returns: object
inverse_laplace_transform_expressionA
Inverse Laplace transform: F(s) → f(t).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 2 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Transforms s-domain (Laplace) back to time-domain.
CRITICAL FOR:
- Getting time response from transfer function
- Multi-compartment PK model solutions
- Impulse/step response analysis
- Converting algebraic solutions back to ODE solutions
Args:
expression: Frequency-domain expression F(s)
freq_var: Frequency variable (default: "s")
time_var: Time variable (default: "t")
Returns:
Time-domain function f(t)
Examples:
# Simple pole
inverse_laplace_transform_expression("1/(s + k)", "s", "t")
→ {"result": "exp(-k*t)*Heaviside(t)", ...}
# Two-compartment model (after partial fractions)
inverse_laplace_transform_expression("A/(s + λ1) + B/(s + λ2)", "s", "t")
→ {"result": "A*exp(-λ1*t) + B*exp(-λ2*t)", ...}
# Step response
inverse_laplace_transform_expression("1/(s*(s + k))", "s", "t")
→ {"result": "(1 - exp(-k*t))/k", ...}
# PK: Bolus injection response
inverse_laplace_transform_expression("dose/(V*(s + k))", "s", "t")
→ {"result": "dose*exp(-k*t)/V", ...}
# WORKFLOW: Use with apart_expression!
# 1. apart_expression("F(s)", "s") → partial fractions
# 2. inverse_laplace_transform_expression(...) → f(t)
Inputs: expression (required), freq_var, time_var. Returns: object
laplace_transform_expressionA
Laplace transform: f(t) → F(s).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 2 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Transforms time-domain functions to s-domain (Laplace domain).
CRITICAL FOR:
- ODE solving (time → algebraic in s-domain)
- Stability analysis (poles in s-plane)
- Transfer functions (system response)
- Compartment model analysis
Args:
expression: Time-domain expression f(t)
time_var: Time variable (default: "t")
freq_var: Frequency variable (default: "s")
Returns:
Laplace transform F(s) with convergence conditions
Examples:
# Exponential decay
laplace_transform_expression("exp(-k*t)", "t", "s")
→ {"result": "1/(s + k)", "convergence": "Re(s) > -Re(k)"}
# Compartment elimination
laplace_transform_expression("C0*exp(-k*t)", "t", "s")
→ {"result": "C0/(s + k)", ...}
# Step function response
laplace_transform_expression("Heaviside(t)", "t", "s")
→ {"result": "1/s", "convergence": "Re(s) > 0"}
# Dosing with absorption
laplace_transform_expression("D*ka*exp(-ka*t)", "t", "s")
→ {"result": "D*ka/(s + ka)", ...}
# PK: Convert ODE to algebra
# dC/dt + k*C = 0 → s*C(s) - C(0) + k*C(s) = 0
Inputs: expression (required), freq_var, time_var. Returns: object
nsforge_healthA
Liveness + inventory: server name, version, tool count, engine versions.
A connected agent calls this first to confirm the server is up and learn
what it is talking to — no repo access required.
Inputs: no named parameters. Returns: object
nsforge_manifestA
Return the full capability manifest (tools, gates, commands, north star).
The runtime mirror of ``docs/agent/capabilities.json`` — how an agent
discovers every tool and how to verify a change.
Inputs: no named parameters. Returns: object
parse_expressionA
Parse a mathematical expression into SymPy-computable form.
This tool converts human-readable formula notation into validated SymPy
expressions, extracting symbols and their relationships.
Args:
expression: Mathematical expression (e.g., "v' = M1*v*cos(θ)/(M1+M2)")
description: Optional description of what this formula represents
symbol_hints: Optional hints for symbol types (e.g., {"m": "positive_real"})
Returns:
Parsed expression with:
- sympy_expr: SymPy expression string
- symbols: List of extracted symbols with inferred types
- latex: LaTeX representation
- is_equation: Whether it's an equation (has '=')
Examples:
parse_expression("F = m*a")
→ {"sympy_expr": "Eq(F, m*a)", "symbols": ["F", "m", "a"], ...}
parse_expression("∫x²dx", description="Integral of x squared")
→ {"sympy_expr": "Integral(x**2, x)", ...}
Inputs: expression (required), description, symbol_hints. Returns: object
powsimp_expressionA
Simplify powers and exponentials.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Combines and simplifies powers using algebraic rules.
Use cases:
- Combine exponentials: exp(x)*exp(y) → exp(x+y)
- Simplify powers: x²·x³ → x⁵
- Nested powers: (x^a)^b → x^(ab)
Args:
expression: Expression to simplify
deep: Apply to subexpressions (default: False)
combine: How to combine bases
- "all": Combine all (default)
- "base": Only combine same base
- "exp": Only exponentials
force: Force transformation even if not valid for all values
Returns:
Simplified expression with LaTeX
Examples:
# Combine powers
powsimp_expression("x**2 * x**3")
→ {"result": "x**5", ...}
# Nested powers
powsimp_expression("(x**a)**b")
→ {"result": "x**(a*b)", ...}
# Exponentials
powsimp_expression("exp(x)*exp(y)")
→ {"result": "exp(x + y)", ...}
# PK: Combine elimination terms
powsimp_expression("exp(-k*t)*exp(-k*τ)")
→ {"result": "exp(-k*(t + τ))", ...}
Inputs: expression (required), deep, force, combine. Returns: object
query_assumptionsA
Query properties of an expression based on assumptions.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP! Uses sympy.assumptions module.
═══════════════════════════════════════════════════════════════════════
Use cases:
- Check if expression is always positive
- Verify domain validity
- Check for potential singularities
Available queries:
- positive, negative, nonnegative, nonpositive
- real, imaginary, complex
- integer, rational, irrational
- even, odd, prime
- finite, infinite, zero, nonzero
Args:
expression: Expression to query about
query: Property to check
assumptions: Assumptions about symbols
{"x": ["positive", "real"], "n": ["integer"]}
Returns:
Query result (True, False, or None if unknown)
Examples:
# Is x**2 always positive?
query_assumptions("x**2", "positive", {"x": ["real", "nonzero"]})
→ {"result": True, ...}
# Is exp(x) always real?
query_assumptions("exp(x)", "real", {"x": ["real"]})
→ {"result": True, ...}
Inputs: query (required), expression (required), assumptions. Returns: object
radsimp_expressionA
Simplify radicals (square roots, cube roots, etc.).
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Rationalizes denominators and simplifies radical expressions.
Use cases:
- Rationalize denominators: 1/(√3+√2)
- Simplify nested radicals
- Standard form for half-life calculations
- Geometric mean calculations
Args:
expression: Expression to simplify
symbolic: Allow symbolic radicals (default: True)
max_terms: Maximum terms in denominator for rationalization
Returns:
Simplified expression with LaTeX
Examples:
# Rationalize denominator
radsimp_expression("1/(sqrt(3) + sqrt(2))")
→ {"result": "-sqrt(2) + sqrt(3)", ...}
# Simplify radical
radsimp_expression("sqrt(12)")
→ {"result": "2*sqrt(3)", ...}
# PK: Half-life with roots
radsimp_expression("ln(2)/sqrt(k1*k2)")
→ {"result": "sqrt(k1*k2)*ln(2)/(k1*k2)", ...}
# Nested radicals
radsimp_expression("sqrt(2 + sqrt(2))")
→ Attempts simplification
Inputs: expression (required), symbolic, max_terms. Returns: object
refine_expressionA
Simplify expression using assumptions.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
SymPy can simplify expressions differently when it knows
properties of the variables. For example:
- sqrt(x**2) → x when x is positive
- Abs(x) → x when x is positive
Args:
expression: Expression to refine
assumptions: Assumptions about symbols
Returns:
Refined expression
Examples:
# sqrt(x**2) simplifies to x when x is positive
refine_expression("sqrt(x**2)", {"x": ["positive"]})
→ {"result": "x", ...}
# Abs simplifies under assumptions
refine_expression("Abs(a*b)", {"a": ["positive"], "b": ["positive"]})
→ {"result": "a*b", ...}
Inputs: expression (required), assumptions (required). Returns: object
reverse_verifyA
Verify a result by applying the reverse operation.
This is a key verification method:
- Derivative → integrate back
- Integral → differentiate back
- Solve → substitute back
Args:
result_expr: The computed result
original_expr: The original expression
operation: "differentiate", "integrate", or "solve"
variable: Variable involved
Returns:
Verification result
Examples:
reverse_verify("3*x**2", "x**3", "differentiate")
→ Integrates 3*x² and checks if it gives x³
reverse_verify("x**3/3", "x**2", "integrate")
→ Differentiates x³/3 and checks if it gives x²
Inputs: operation (required), result_expr (required), original_expr (required), variable. Returns: object
solve_inequalityA
Solve a single inequality.
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Use cases:
- Find valid parameter ranges
- Stability conditions
- Convergence criteria
- Domain restrictions
Args:
inequality: The inequality (use <, >, <=, >=)
variable: Variable to solve for
domain: Domain restriction ("real", "positive", "integer")
Returns:
Solution set with interval notation
Examples:
# Simple inequality
solve_inequality("x**2 - 4 < 0", "x")
→ {"result": "(-2, 2)", "latex": "-2 < x < 2"}
# Rational inequality
solve_inequality("(x-1)/(x+2) >= 0", "x")
→ {"result": "(-oo, -2) ∪ [1, oo)", ...}
# With domain restriction
solve_inequality("x**2 < 9", "x", domain="positive")
→ {"result": "(0, 3)", ...}
Inputs: variable (required), inequality (required), domain. Returns: object
solve_inequality_systemA
Solve a system of inequalities (find the intersection).
═══════════════════════════════════════════════════════════════════════
🆕 NOT AVAILABLE IN SYMPY-MCP!
═══════════════════════════════════════════════════════════════════════
Use cases:
- Find valid parameter ranges satisfying multiple constraints
- Optimization feasibility regions
- Multiple stability conditions
Args:
inequalities: List of inequalities
variable: Variable to solve for
Returns:
Solution set (intersection of all solutions)
Examples:
# Multiple constraints
solve_inequality_system(["x > 0", "x < 10", "x**2 < 25"], "x")
→ {"result": "(0, 5)", ...}
# Therapeutic window
solve_inequality_system(["C > MIC", "C < toxic_level"], "C")
Inputs: variable (required), inequalities (required). Returns: object
symbolic_equalA
Check if two expressions are symbolically equivalent.
Useful for quick verification of derivation steps.
For more thorough verification, use verify.py tools.
Args:
expr1: First expression
expr2: Second expression
Returns:
Whether expressions are equivalent
Examples:
symbolic_equal("(x+1)**2", "x**2 + 2*x + 1") → True
symbolic_equal("sin(x)**2 + cos(x)**2", "1") → True
Inputs: expr1 (required), expr2 (required). Returns: object
task_exploreA
Explore a branching derivation tree from a DTS.
Runs the base derivation plus each ``alternatives`` candidate through the
full loop and returns ALL candidates -- each with its acceptance result
and provenance -- ranked best-first (verified > more oracles passed >
simpler). Unlike task_run (which self-corrects to the first passing
branch), this surfaces the whole space of verified answers.
Args:
spec: A DTS dict (see task_plan); ``alternatives`` are the branches.
timeout_s: Optional hard wall-clock cap (seconds). When set, the
exploration runs in a separate process and is killed if it
overruns, returning {"success": False, "timed_out": True}.
Returns:
{"success", "concept", "candidates": [...]} ranked best-first.
Inputs: spec (required), timeout_s. Returns: object
task_planA
Reify a Derivation Task Spec (DTS) into an ordered plan of tool calls.
Each planned step names the tool that would produce it (provenance),
spanning the reification ladder: symbol -> derivation -> algorithm.
Args:
spec: A DTS dict with keys: name, goal, given, unknowns, assumptions,
base_formulas, modifications, acceptance, metadata.
Returns:
{"success": bool, "spec": str, "total": int, "steps": [...]}.
Inputs: spec (required). Returns: object
task_runA
Run the DTS through the reification ladder.
Concept (validation), symbol (registry), and derivation (composing base
formulas via substitution + solving on the SymPy engine) rungs execute
deterministically; when a derivation is produced, the algorithm rung
reifies it into a Python function. The composed formula is returned in
"derived_expression" and the code in "generated_code".
Args:
spec: A DTS dict (see task_plan).
timeout_s: Optional hard wall-clock cap (seconds). When set, the
derivation runs in a separate process and is killed if it
overruns, returning {"success": False, "timed_out": True}.
Returns:
{"success", "spec", "derived_expression", "generated_code", "phases"}.
Inputs: spec (required), timeout_s. Returns: object
together_expressionA
Combine rational expressions over a common denominator.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Combines separate fractions into a single fraction.
Use cases:
- Combine clearance terms
- Total bioavailability
- Multiple dosing routes
- Fraction addition
Args:
expression: Sum of rational expressions
deep: Apply to subexpressions (default: False)
Returns:
Combined expression with LaTeX
Examples:
# Simple addition
together_expression("1/x + 1/y")
→ {"result": "(x + y)/(x*y)", ...}
# Multiple clearances
together_expression("CL_renal/V + CL_hepatic/V")
→ {"result": "(CL_renal + CL_hepatic)/V", ...}
# Complex fractions
together_expression("1/(x-1) + 1/(x+1)")
→ {"result": "2*x/(x**2 - 1)", ...}
# PK: Total clearance
together_expression("Q/V1 + CL/V1")
→ {"result": "(Q + CL)/V1", ...}
Inputs: expression (required), deep. Returns: object
trigsimp_expressionA
Simplify trigonometric expressions.
═══════════════════════════════════════════════════════════════════════
🆕 PHASE 1 - NOT IN SYMPY-MCP OR NSFORGE v0.2.3!
═══════════════════════════════════════════════════════════════════════
Applies trigonometric identities to simplify expressions.
Use cases:
- Simplify sin²+cos² → 1
- Simplify tan(x) → sin(x)/cos(x)
- Oscillating chemical reactions
- Phase analysis in PK/PD
Args:
expression: Expression to simplify
deep: Apply to subexpressions (default: False)
recursive: Apply repeatedly (default: False)
method: Simplification method
- "matching": Pattern matching (default, fast)
- "groebner": Gröbner basis (slower, more powerful)
- "combined": Try both
Returns:
Simplified expression with LaTeX
Examples:
# Pythagorean identity
trigsimp_expression("sin(x)**2 + cos(x)**2")
→ {"result": "1", ...}
# Tan identity
trigsimp_expression("sin(x)/cos(x)")
→ {"result": "tan(x)", ...}
# Double angle
trigsimp_expression("2*sin(x)*cos(x)")
→ {"result": "sin(2*x)", ...}
# Oscillating kinetics
trigsimp_expression("sin(omega*t)**2 + cos(omega*t)**2")
→ {"result": "1", ...}
Inputs: expression (required), deep, method, recursive. Returns: object
validate_expressionA
Validate a mathematical expression for correctness.
Checks syntax, symbol consistency, and optionally dimensional consistency.
Args:
expression: Expression to validate
expected_symbols: List of symbols that should appear
check_dimensions: Whether to perform dimensional analysis
units_map: Map of symbol to unit (e.g., {"v": "m/s", "m": "kg"})
Returns:
Validation result with:
- valid: Whether expression is valid
- issues: List of issues found
- warnings: Non-critical warnings
Examples:
validate_expression("F = m*a", expected_symbols=["F", "m", "a"])
→ {"valid": True, ...}
validate_expression("F = m*a + v", units_map={"F": "N", "m": "kg", "a": "m/s²", "v": "m/s"})
→ {"valid": False, "issues": ["Dimension mismatch: m*a (N) + v (m/s)"]}
Inputs: expression (required), units_map, check_dimensions, expected_symbols. Returns: object
verify_derivativeC
Verify a derivative by computing and comparing.
Args:
function: Original function
claimed_derivative: Claimed derivative
variable: Variable (default: "x")
Returns:
Verification result
Examples:
verify_derivative("x**3", "3*x**2") → verified: True
Inputs: function (required), claimed_derivative (required), variable. Returns: object
verify_equalityA
Verify that two expressions are symbolically equal.
Args:
expression1: First expression
expression2: Second expression
Returns:
Verification result
Examples:
verify_equality("(x+1)**2", "x**2 + 2*x + 1") → verified: True
verify_equality("sin(x)**2 + cos(x)**2", "1") → verified: True
Inputs: expression1 (required), expression2 (required). Returns: object
verify_integralA
Verify an integral by differentiating the result.
Args:
integrand: Original function to integrate
claimed_integral: Claimed integral result
variable: Variable (default: "x")
Returns:
Verification result
Examples:
verify_integral("x**2", "x**3/3") → verified: True
Inputs: integrand (required), claimed_integral (required), variable. Returns: object
verify_solutionA
Verify that a value satisfies an equation.
Args:
equation: Equation ("lhs = rhs" or "expr" for expr = 0)
solution: Claimed solution
variable: Variable (default: "x")
Returns:
Verification result
Examples:
verify_solution("x**2 - 4 = 0", "2") → verified: True
Inputs: equation (required), solution (required), variable. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 82 tools
Most tools have distinct purposes with detailed descriptions, but there are clear overlaps: symbolic_equal and verify_equality both check expression equivalence, and derivation_show/derivation_status both display session state. The large set of algebraic manipulation tools (expand, factor, collect, trigsimp, etc.) is individually distinct but adds cognitive load for selection.
Tool names are mostly snake_case but follow inconsistent patterns: noun_verb prefixes (derivation_*, formula_*) are mixed with verb_noun names (calculate_limit, solve_inequality, verify_equality). Outliers like symbolic_equal and nsforge_health break the convention, making the naming predictable only within subfamilies.
With 82 tools, this server is far beyond the typical 3-15 tool scope and falls in the extreme category for tool count. The sheer number overwhelms an agent's ability to understand and coordinate the full surface, even though the domain is broad.
The tool set covers the symbolic mathematics and derivation domain very thoroughly: session management, formula lookup, algebraic manipulation, calculus, transforms, verification, report/code generation, and task planning. Minor gaps exist (no direct ODE solver or matrix operations), but handoff tools to SymPy-MCP fill those niches, so the surface is largely complete.
Related MCP Connectors
Exact arithmetic, algebra, calculus, physics, chemistry and finance with a checkable formula.
AI-callable calculators and engineering models with real formulas. No hallucinated math.
Scientific compute for AI agents: symbolic, numerical, quantum, chemistry, ODE. Paid via x402.
Deterministic signed verification of numeric & financial claims for AI agents & spreadsheets.
Related MCP Servers
- AlicenseBqualityBmaintenanceEnables mathematical formula visualization and analysis through interactive plotting, formula validation, and symbolic computation. Supports both Desmos API integration and local matplotlib rendering for creating 2D mathematical graphs.510Apache 2.0
- AlicenseNot gradedqualityDmaintenanceProvides a suite of deterministic math tools powered by SymPy to handle algebra, calculus, linear algebra, and statistics via the Model Context Protocol. It enables smaller language models to delegate complex computations to a verified symbolic backend for accurate and reliable results.Apache 2.0
- AlicenseBqualityBmaintenanceMCP server for symbolic computation that enables AI agents to perform step-by-step derivations, transform formulas, and verify results with full provenance, combining natural language with formal mathematical operations.4113Apache 2.0
- AlicenseNot gradedqualityDmaintenanceProvides deterministic tools for symbolic math, equation solving, relation verification, reasoning structure audits, and validated CAD primitives, returning evidence artifacts for every result.MIT