pycodemath
用几个字符写出数学表达式,得到精确答案或独立的、优化过的 Python/NumPy 代码——而不是让语言模型"心算"或手写数值循环。
第一次接触 "MCP"、"symbolic" 或 "ODE" 这类术语?跳到术语表。
构建为 SymPy + NumPy 之上的一层精简、严谨的封装:
削减 token —— 一条短命令进,一个精确结果出。非常适合作为 智能体工具(内置 MCP 服务器)。
优于朴素 Python 的代码 —— 生成器在输出代码前先应用符号化简 + 公共子表达式消除(CSE)(在重复子表达式上实测比朴素展开快约 ~1.7 倍)。
text → [parser] → IR (expression tree) → [engine] evaluate / simplify / solve
→ [generator] IR → CSE → Python/NumPy source安装
pip install pycodemath # core: sympy + numpy
pip install pycodemath[mcp] # + MCP server for AI agents从克隆仓库进行开发安装(可编辑安装):
pip install -e .[dev] # editable + pytest + mypy需要 Python ≥ 3.11。
Related MCP server: SymKit
快速上手
一次性 CLI(可脚本化)
下面的每条命令都是真实调用及其真实输出。
$ python -m pycodemath "diff sin(x)*x dx"
x*cos(x) + sin(x)
$ python -m pycodemath "integrate 2*x dx"
x**2
$ python -m pycodemath "solve x^2 - 4 for x"
-2, 2
$ python -m pycodemath "sin(x)^2 + cos(x)^2"
1
$ python -m pycodemath "eig [[2,1],[1,2]]"
3, 1
$ python -m pycodemath "solve_nd x^2+y^2-4; x-y for x,y at 1,1"
x = 1.4142135623746899, y = 1.4142135623746899错误输出到 stderr 并返回退出码 1,结果输出到 stdout 并返回退出码 0——
可安全地从脚本和智能体工具中调用。在 Windows 控制台上请设置
PYTHONUTF8=1。
REPL
python -m pycodemath # or just: pycodemath输入 help 查看完整命令表(导数、积分、方程求解、矩阵、求根、优化、
整套 ODE 套件以及代码生成)。
MCP 服务器(面向任意 AI 智能体的数学能力)
pip install -e .[mcp]
claude mcp add pycodemath -- python -m pycodemath.cli.mcp_server暴露一个工具 math_eval,接受与 REPL 相同的命令——智能体发送
diff sin(x)*x dx 即可精确收到 x*cos(x) + sin(x),零心算负担。
作为 Claude Code 技能使用
上面的 MCP 服务器是可移植的路径——它可以接入任何 MCP 客户端。 如果你专门使用 Claude Code,还可以 将 Pycodemath 作为技能接入,这样每当提示词需要真正的数学计算时, Claude 会自动调用该引擎(无需持续运行 MCP 进程)。
它改变了什么: 不再"心算"——大型模型可能会在算术、积分或特征值上 悄悄出错——Claude 改为调用引擎并把精确的 SymPy/NumPy 结果粘贴回来。 一条短命令进,一条精确结果出:更少的 token,没有静默错误。
部署(一次性):
pip install pycodemath # or: pip install -e . (from a clone)
mkdir -p ~/.claude/skills/pycodemath将以下内容保存为 ~/.claude/skills/pycodemath/SKILL.md:
---
name: pycodemath
description: Compute math with the local Pycodemath engine (SymPy+NumPy) instead
of in your head — derivatives, integrals, solving equations and systems
(linear and nonlinear), determinants/inverses/eigenvalues, gradients/Jacobians/
Hessians, function minima, ODEs, and optimized Python/NumPy code generation
(CSE). Use whenever the user asks to compute or verify symbolic/numerical math,
or to generate code from a formula.
---
# Pycodemath — local math engine
One command = one call (the package is pip-installed, so any working directory):
python -m pycodemath "<command>"
Result goes to stdout (exit 0); errors to stderr (exit 1). Power notation: `^` or `**`.
On Windows consoles, set `PYTHONUTF8=1`.
## Commands
| Command | Example |
|---|---|
| `<expression>` — simplify | `python -m pycodemath "sin(x)^2 + cos(x)^2"` → `1` |
| `diff <expr> d<var>` — derivative | `"diff sin(x)*x dx"` → `x*cos(x) + sin(x)` |
| `integrate <expr> d<var>` — symbolic integral | `"integrate 2*x dx"` → `x**2` |
| `solve <expr> for <var>` — solve = 0 | `"solve x^2-4 for x"` → `-2, 2` |
| `code <expr>` — CSE-optimized NumPy code | `"code (sin(x)+cos(x))^2"` |
| `det / inv / transpose / eig <A>` | `"eig [[2,1],[1,2]]"` → `3, 1` |
| `solve_system <A> = <b>` — linear system | `"solve_system [[2,1],[1,3]] = [3,5]"` |
| `root <expr> for <var> at <x0>` — numeric root | `"root x^2-2 for x at 1"` |
| `min <expr> for <var> at <x0> [method newton|bfgs]` — 1D minimum | `"min (x-3)^2 for x at 0"` |
| `grad <expr> for <x,y,...>` — symbolic gradient | `"grad x^2*y for x,y"` |
| `solve_nd <f1>; <f2> for <x,y> at <x0,y0>` — nonlinear system | `"solve_nd x^2+y^2-4; x-y for x,y at 1,1"` |
| `min_nd <expr> for <x,y> at <x0,y0> [method newton|bfgs]` — N-D minimum | `"min_nd (1-x)^2+100*(y-x^2)^2 for x,y at -1.2,1 method bfgs"` |
| limits / series / sums / ODEs | `"limit sin(x)/x for x to 0"`, `"sum 1/k^2 for k from 1 to oo"` |
Type `help` in the REPL (`python -m pycodemath`) for the full command table.
## Rules
- **When to use:** the user wants a concrete math result (derivative, integral,
equation, matrix, minimum, ODE) or optimized code from a formula. The engine is
exact — trust its output over mental arithmetic.
- **When not to use:** trivial arithmetic or conceptual questions with no compute.
- A `error: ...` line on stderr (exit 1) usually means a typo in the command, a
numerical method that did not converge, or no real solution — read the message,
it is specific.重启 Claude Code(或打开新会话),当任务需要精确数学时它会自动调用该技能。
要确认是否注册成功,运行 /help 并在技能列表中查找 pycodemath。
极限、级数与符号求和
除 diff/integrate/solve 之外,引擎还处理极限(包括单侧极限和
无穷处极限)、Taylor/Laurent 展开以及符号求和——有限或无限。全部为
带真实输出的真实调用:
$ python -m pycodemath "limit (1+1/n)^n for n to oo"
E
$ python -m pycodemath "series exp(x) for x n 4"
x**3/6 + x**2/2 + x + 1
$ python -m pycodemath "sum k for k from 1 to n"
n**2/2 + n/2
$ python -m pycodemath "sum 1/k^2 for k from 1 to oo"
pi**2/6发散级数或不存在的极限会以可读的错误信息拒绝,而不是返回符号回显。
优化:梯度下降停滞时的 Newton 与 BFGS
min / min_nd 默认使用普通梯度下降;method newton|bfgs 切换为带
Armijo 回溯线搜索的二阶方法。在 Rosenbrock 山谷上(起点 (-1.2, 1))
梯度下降在 10 000 次迭代后拒绝收敛,而 BFGS 在 36 次内收敛:
$ python -m pycodemath "min_nd (1-x)^2 + 100*(y-x^2)^2 for x,y at -1.2,1 method bfgs"
x = 0.999999999999454, y = 0.9999999999989762ODE 套件
符号求解(dsolve)加上完整的数值工具箱——标量与方程组、时间正向和
反向(t1 < t0),全部拒绝静默跳过奇点(返回可读错误而不是垃圾结果):
求解器 | 功能说明 |
| 经典定步长 RK4 |
| Dormand–Prince 5(4),自适应步长(类似 |
| 自适应 + 稠密输出:任意位置可调用 |
| 事件检测 |
| 隐式 BDF2 + Newton 法,用于刚性方程 |
| 变步长 BDF2,带局部误差控制 |
| 上述所有方法的向量变体 |
对光滑问题的自适应积分在 rtol 1e-8 下仅需 41 步:
$ python -m pycodemath "ode_adaptive y*cos(t) for y(t) from 0 to 5 at 1 rtol 1e-8"
y(5) = 0.3833049965035854 (41 adaptive steps)在经典刚性问题 y' = -1000(y - cos t) 上,显式方法对受限于
稳定性(rtol 1e-6 下需 378 步;在相同预算下定步长 RK4 返回
天文数字级别的错误有限值)。自适应 BDF 在 313 步内完成——而从慢流形
(纯刚性)出发,仅需 58 步对比 357 步:
$ python -m pycodemath "odestiff_adaptive -1000*(y-cos(t)) for y(t) from 0 to 1 at 0"
y(1) = 0.5411432587540607 (adaptive BDF, 313 implicit steps)方程组变体在 [0, 2000] 上以 μ=1000 处理 Van der Pol 振荡器,
仅需 5 332 步(约 ~1 秒)——显式方法需要 ≥ 2 000 000 步。
代码生成
code <expr> 输出独立的、经 CSE 优化的 NumPy 源码(真实输出):
$ python -m pycodemath "code (sin(x)+cos(x))^2 + (sin(x)+cos(x))^3"
import numpy as np
def f(x):
"""Pycodemath: f(x) — NumPy code."""
_c0 = np.sin(x + (1/4)*np.pi)
return 2*_c0**2*(np.sqrt(2)*_c0 + 1)Python API 还能生成独立的 ODE 积分器——包括自适应积分器和带
稠密输出的积分器,其生成的插值函数与引擎逐位一致(实测最大
差异:节点和节点间网格上均为 0.0,正向和反向均如此):
from pycodemath import parse, generate_ode_dense
art = generate_ode_dense(parse("y*cos(t)"), "t", "y")
sol = art(1.0, 0.0, 5.0, 1e-8) # standalone DOPRI5, returns an interpolant
sol(2.5) # -> 1.8193369962907706
len(sol.ts) # -> 42 accepted nodes从 API 进行事件检测:
from pycodemath import parse, solve_ode_events
ev = solve_ode_events(parse("cos(t)"), "t", 0.0, (0.0, 10.0), parse("y"), rtol=1e-8)
ev.event_times # -> [3.141593, 6.283185, 9.424778] (π, 2π, 3π)结构化结果:答案背后的证据
本包中的每个求解器现在都有 full_result=True 形式,返回证据而非
裸数字——root_find / root_find_nd / minimize / minimize_nd
返回冻结的 SolveResult(值、迭代次数、残差、是否收敛、状态),
integrate_num 返回 QuadratureResult(额外包含 error_estimate)。
默认调用不变,与之前逐位一致。
>>> from pycodemath import root_find, minimize, integrate_num, parse
>>> root_find(parse("x^2 - 2"), "x", 1.0, full_result=True)
SolveResult(value=1.4142135623746899, iterations=5, residual=4.510614104447086e-12, converged=True, status='converged')
>>> minimize(parse("-x^2"), "x", 1.0, full_result=True)
SolveResult(value=1085298990978.309, iterations=152, residual=2170597981956.618, converged=False, status='diverged')
>>> integrate_num(parse("sqrt(x)"), "x", 0.0, 1.0, tol=1e-10, full_result=True)
QuadratureResult(value=0.6666666666666469, error_estimate=2.4271240969151142e-11, evaluations=1005, refinements=201, converged=True, status='converged')converged 是唯一值得分支判断的字段,而且它是经过佐证的,而不仅仅
是"容差测试触发了":在鞍点或极大值处梯度消失会报告
status='not_a_minimum',而不是虚假的收敛。
MCP 服务器通过 structuredContent(text / solve / quadrature /
error 字段)在网络上传递相同的结构,而不仅仅是文本——客户端根据
声明的 schema 进行验证,而不是解析文本。
尾随选项 将同样的旋钮放到 REPL/一次性语法上:
$ python -m pycodemath "min x^4 for x at 1 tol 1e-5"
0.029229144526165384
$ python -m pycodemath "nintegrate sqrt(x) dx from 0 to 1 tol 1e-10"
0.6666666666666469tol <t>(用于 min / min_nd / nintegrate)、max_iter <k>(用于
min / min_nd)和 budget <s>(用于符号命令,以与 Python 中
pycodemath.time_budget(seconds) 相同的方式限制调用)是命令末尾的
key value 对,顺序不限。
拒绝执行的符号调用会说明是两种情况中的哪一种:
NoClosedFormError(引擎搜索后未找到——请尝试数值方法)或
UnsupportedFormError(该形式根本不存在对应方法)。
设计契约
引擎和生成器共享同一个 IR(
Expr/Matrix)。数值循环在编译函数上运行(
lambdify+ LRU 缓存)—— 每次迭代零 SymPy 调用。发散或定义域问题会抛出可读的
PycodemathError—— 结果中绝不出现 NaN/垃圾值。解析器只解析白名单内的数学函数——未知名称成为符号,而非 Python 代码;字符串字面量和属性访问被直接拒绝,且求值成本受限,因此单个 表达式(如
9**9**9)不会耗尽内存。测试先测量真实数值,再以余量断言——668 个测试,在 Ubuntu 和 Windows 上全部通过(含 CI 和 mypy)。
每个失败都是特定的
PycodemathError子类(ParseError、DomainError、DivergenceError、StagnationError、NonConvergenceError、NoClosedFormError、UnsupportedFormError、TimeBudgetError)——调用方可以捕获数学结果,而不是对消息做 字符串匹配。time_budget是尽力而为,不是硬保证。 它通过 CPython 自身的ctypes.PyThreadState_SetAsyncExc向运行中的线程注入异常来中断挂起—— 这是跨平台唯一可用的机制,无需每次调用都启动子进程(Windows 上 没有SIGALRM,即使在 POSIX 上也只对进程主线程生效)。在重负载或 虚拟化调度下,解释器偶尔可能错过该注入的投递,此时调用会超过预算 继续运行,而不是按时抛出TimeBudgetError——已在这样一个环境 (Python 3.13,WSL2)上直接实测。这不影响快速路径——绝大多数调用 在毫秒级完成,永远不会接近预算——也不会产生错误答案;唯一的失败 模式是"没有按要求的及时拒绝"。硬保证需要基于子进程的后备方案, 这已在路线图上但尚未实现。
术语表
为上面用到的行话提供通俗定义——供阅读本仓库的非程序员参考。
术语 | 含义 |
符号数学 | 用精确的字母和公式(如 |
数值数学 | 用实际的十进制数(如 |
SymPy / NumPy | 本项目所基于的两个开源 Python 库。SymPy 负责精确/符号数学;NumPy 负责快速数值数学。 |
解析器 | 程序中读取你输入的内容(例如 |
引擎 | 解析器理解问题后实际进行数学运算的部分——计算导数、求解方程等。 |
代码生成器("codegen") | 不只是给你一个答案,而是编写一段可直接使用的 Python 代码块来计算你的公式的部分。 |
CSE(公共子表达式消除) | 一种优化:如果公式重复计算同一个表达式两次,生成的代码只计算一次并复用结果,而不是重复工作。 |
REPL | "读取-求值-打印循环"——一种交互式提示符:你输入一条命令,得到一个答案,再输入下一条命令,依此类推(就像在终端里对话的计算器)。 |
MCP(模型上下文协议) | 一种开放标准,允许 AI 助手(如 Claude)调用外部工具——在这种情况下,AI 可以将真正的数学问题交给这个引擎处理,而不是自己猜测答案。 |
AI 代理 | 能够自主采取行动和使用工具的 AI 助手(不仅仅是聊天)——例如 Claude Code,或任何兼容 MCP 的助手。 |
Token | AI 语言模型读写的小段文本。Token 越少 = 与 AI 的交互越便宜、越快——这也是该工具返回简短精确答案而不是大段文字的原因之一。 |
类型化异常 | 带有特定命名类型的错误(例如"方程无实数解"与"你输入了无效内容"),而不是仅仅给出通用错误信息——这样程序就能针对失败原因做出正确反应。 |
| 该引擎可以随答案一起返回的结构化"证据"对象——不仅是数字,还包括用了多少步、可能偏差多少,以及是否确信答案确实正确。 |
根 / 求根 | 找到公式等于零的值(例如图形与 x 轴相交的位置)。 |
特征值 | 与矩阵(数字网格)相关的特殊数值,在物理、工程和图形学中经常出现——例如描述系统的自然振动频率或稳定方向。 |
梯度 / 雅可比矩阵 / 海森矩阵 | 多变量公式的"导数"的不同形式——梯度指向函数增长最快的方向;雅可比矩阵和海森矩阵分别是一阶和二阶导数的多变量版本。 |
ODE(常微分方程) | 描述事物随时间变化的方程(例如下落物体因重力和阻力而改变速度)。是物理、生物和工程模拟的核心。 |
RK4 / Dormand–Prince / BDF | 用于数值求解 ODE 的命名算法,逐步随时间推进。它们在速度、精度以及是否自动调整步长方面有所不同。 |
"刚性"方程 | 一种 ODE,迫使普通求解方法采用极其微小的步长才能保持精度——它需要专门的(BDF)方法才能在合理时间内求解。 |
| 一个标记,告诉其他工具"此包声明了每个函数期望和返回的数据类型(数字、文本等)"; |
CI(持续集成) | 一种自动化流程,每次代码变更时运行完整测试套件,这样错误会在发布前立即被发现,而不是发布后。 |
Wheel / sdist | Python 库分发的两种标准打包格式( |
许可证
MIT — 参见 LICENSE。
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.
No tool schema history has been recorded yet.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Precision math engine for AI agents. 203 exact methods. Zero hallucination.
Scientific compute for AI agents: symbolic, numerical, quantum, chemistry, ODE. Paid via x402.
Math.js MCP — wraps the mathjs.org API (free, no auth)
The OpenRouter for tools. One MCP connection gives any AI agent 254 hosted tools, pay per call.
Related MCP Servers
- AlicenseAqualityCmaintenanceA Model Context Protocol server that exposes 8 mathematical tools (arithmetic, algebra, calculus, matrix operations, statistics, probability, unit conversions) to any MCP-compatible AI agent, enabling mathematical computations without code.841MIT
- 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.4110Apache 2.0
- AlicenseAqualityBmaintenanceEnables advanced mathematics operations including linear algebra, vector math, symbolic computation, and calculus through MCP tools. Designed for use with Claude and other MCP-compatible LLMs.192MIT
- AlicenseAqualityBmaintenanceProvides an MCP server exposing compute, verify, and plot tools backed by Giac/Xcas for exact symbolic and numerical mathematics, enabling LLMs to solve calculus, algebra, geometry, and more with verified results.3672GPL 3.0
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/cybersora9/pycodemath'
If you have feedback or need assistance with the MCP directory API, please join our Discord server