Skip to main content
Glama
GaloisHLee
by GaloisHLee

MCP SageMath Server

基于 Model Context Protocol (MCP) 的本地 SageMath 服务端,当前提供两项工具:

  • sagemath_version:查询本地 SageMath 版本。

  • sagemath_evaluate:执行 SageMath 脚本并返回标准输出/错误。

  • sagemath_health:轻量级自检,验证 SageMath 可用性。

项目处于早期预览阶段(v0.0.1)。

功能概览

  • 双传输模式:默认 STDIO,可通过环境变量切换到 HTTP(同时支持 GET /mcpPOST /mcp)。

  • 无状态 HTTP 会话:避免重复初始化导致的错误。

  • 可靠的子进程封装:当 SageMath 不可用时返回结构化错误,不会崩溃。

  • 可配置的 SageMath 路径:支持源代码配置与环境变量覆盖,默认回退到系统 PATH。

Related MCP server: GeoGebra MCP Server

环境要求

  • Node.js 18 及以上版本(推荐 20+)。

  • 本地已安装 SageMath,并能够通过命令行访问其可执行文件。

配置 SageMath 路径

项目在运行时按照以下优先级查找 SageMath 可执行文件:

  1. src/config.ts 中的 config.sagePath(若设置为非空字符串)。

  2. 环境变量 SAGE_PATH

  3. 系统 PATH 中的 sage 命令。

默认情况下,config.sagePath 会读取 SAGE_PATH 环境变量的值;如需固定路径,可在该文件内显式填写,例如:

export const config = {
  sagePath: "/opt/sage/bin/sage",
};

安装

  • 本项目根目录下执行

npm install

运行方式

STDIO(默认模式)

  • 构建:npm run build

  • 运行:node dist/index.js

  • 测试示例客户端:

    npx -y tsx src/test/stdio-client.ts

HTTP 模式(需手动启用)

  • 启动开发服务器:

    MCP_TRANSPORT=http npm run dev
  • 默认监听 http://localhost:3000/mcp,可通过 PORT 环境变量调整端口。

  • 开箱测试:

    MCP_TRANSPORT=http npx -y tsx src/test/client.ts
  • 端点说明:

    • GET /mcp:用于 SSE/流式 JSON-RPC。

    • POST /mcp:标准 JSON-RPC over HTTP。

MCP 客户端配置示例

STDIO

{
  "mcpServers": {
    "sagemath-server": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "autoApprove": ["sagemath_version", "sagemath_evaluate"],
      "env": {
        // "SAGE_PATH": "/absolute/path/to/sage" // 可选
      }
    }
  }
}

HTTP

{
  "mcpServers": {
    "sagemath-server-http": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "env": {
        "MCP_TRANSPORT": "http",
        "PORT": "3000"
      }
    }
  }
}

提供的工具

sagemath_version

  • 输出字段:stdout, stderr, exitCode, durationMs, timedOut

  • 适用于检测 SageMath 是否安装及版本信息。

sagemath_evaluate

  • 输入:

    • code (string) — 必填,SageMath 脚本。

    • timeoutMs (number) — 可选,超时时间,默认 10000 ms。

  • 输出同上。

  • 执行流程:将代码写入临时文件后调用 SageMath 执行。

sagemath_health

  • 无输入;尝试执行 print(1+1)

  • 输出字段:ok(布尔)、message(字符串)、details(包含 stdout/stderr/exitCode 等)。

  • 用途:Agent 在启动前快速探活。

测试

  • STDIO 回归测试:npx -y tsx src/test/stdio-client.ts

  • HTTP 回归测试:MCP_TRANSPORT=http npx -y tsx src/test/client.ts

面向 Agent 的兼容性提示(Claude / Trae / 其他 MCP 客户端)

  • 统一结构化输出:所有工具均返回 structuredContent(JSON 对象),并附带简短文本提示;不再需要从 content[0].text 手动 JSON 解析。

  • 推荐探活流程:HTTP/STDIO 连接后先调用 sagemath_health 确认 SageMath 可用,再调用其他工具。

  • HTTP 端点:默认 http://localhost:3000/mcp(可改 PORT)。支持 GET /mcp(SSE/流式 JSON-RPC)与 POST /mcp

  • STDIO:直接执行 node dist/index.js(或开发模式 npx -y tsx src/index.ts)。

  • 安全提示sagemath_evaluate 可执行任意 Sage 代码;HTTP 模式建议放在受控网络或加鉴权/限流。

配置示例(可折叠)

~/.config/modelcontext/mcp.json 里增加:

{
  "mcpServers": {
    "sagemath-server": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "autoApprove": ["sagemath_version", "sagemath_evaluate", "sagemath_health"],
      "env": {
        // "SAGE_PATH": "/absolute/path/to/sage"
      }
    }
  }
}

希望走 HTTP 时,可改用:

{
  "mcpServers": {
    "sagemath-server-http": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "env": {
        "MCP_TRANSPORT": "http",
        "PORT": "3000"
      },
      "client": {
        "url": "http://localhost:3000/mcp"
      }
    }
  }
}

若希望 Claude 直接以 STDIO 启动:

{
  "mcpServers": {
    "sagemath-server": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "autoApprove": ["sagemath_version", "sagemath_evaluate", "sagemath_health"],
      "env": {
        // "SAGE_PATH": "/absolute/path/to/sage"
      }
    }
  }
}

Claude Desktop/MCP 配置中添加:

{
  "mcpServers": {
    "sagemath-server-http": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-sagemath/dist/index.js"],
      "env": {
        "MCP_TRANSPORT": "http",
        "PORT": "3000"
      },
      "client": {
        "url": "http://localhost:3000/mcp"
      }
    }
  }
}
{
  "mcpServers": {
    "sagemath-server-dev": {
      "command": "npx",
      "args": [
        "-y",
        "tsx",
        "/Users/halois/workdir/Toolkit/mcps/mcp-server-sagemath/src/index.ts"
      ],
      "autoApprove": ["sagemath_version", "sagemath_evaluate", "sagemath_health"],
      "env": {
        // "SAGE_PATH": "/absolute/path/to/sage"
      }
    }
  }
}
{
  "mcpServers": {
    "sagemath-server-http": {
      "command": "node",
      "args": ["/Users/halois/workdir/Toolkit/mcps/mcp-server-sagemath/dist/index.js"],
      "env": {
        "MCP_TRANSPORT": "http",
        "PORT": "3000"
        // "SAGE_PATH": "/absolute/path/to/sage"
      },
      "client": {
        "url": "http://localhost:3000/mcp"
      },
      "autoApprove": ["sagemath_version", "sagemath_evaluate", "sagemath_health"]
    }
  }
}

安全提示

  • sagemath_evaluate 可运行任意 SageMath 代码,请仅在可信环境使用。

  • 建议在需要时结合容器或沙箱进一步隔离,并设置资源配额。

Roadmap

  • 扩展更多 SageMath 功能(绘图、符号计算等)。

  • 优化长时间任务的会话复用与资源管理。

  • 增强错误分类与限流策略。

许可证

MIT License,详见 LICENSE

鸣谢

更新日志

  • 0.0.2(未发布):增加 sagemath_health 自检工具;统一工具返回的 structuredContent,客户端无需手动解析 content;README 增补 Codex/Claude STDIO/HTTP 配置示例。

  • 0.0.1:初始版本,提供 sagemath_versionsagemath_evaluate

Available Tools

3 tools
sagemath_evaluateSageMath EvaluateB

Evaluate SageMath code locally

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYes
timeoutMsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
stderrYes
stdoutYes
exitCodeYes
timedOutYes
durationMsYes

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool evaluates code 'locally,' which implies execution in a SageMath environment, but doesn't specify security implications, resource usage, error handling, or output format. The presence of a timeout parameter hints at execution limits, but this isn't explained in the description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste. It's front-loaded with the core purpose and avoids unnecessary elaboration, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (code evaluation with potential side-effects), no annotations, and an output schema (which handles return values), the description is minimally adequate. It states what the tool does but lacks crucial details like safety warnings, execution context, or error behavior, leaving gaps for the agent to navigate.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the schema provides no parameter documentation. The description doesn't mention parameters at all, failing to compensate for the coverage gap. However, with only 2 parameters (code and timeoutMs), the baseline is moderate, as the agent might infer usage from common patterns (code to evaluate and optional timeout).

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Evaluate') and resource ('SageMath code'), with the qualifier 'locally' providing useful context. However, it doesn't differentiate from sibling tools like sagemath_health or sagemath_version, which likely serve different purposes (health checks and version queries rather than code evaluation).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. There's no mention of prerequisites, limitations, or comparison with sibling tools. The agent must infer usage from the tool name and context alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

sagemath_healthSageMath Health CheckA

Lightweight self-check of SageMath availability and basic readiness

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
okYes
detailsNo
messageYes

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It describes the tool as a 'lightweight self-check' which implies it's a read-only, non-destructive operation that tests availability and readiness. However, it doesn't specify what 'readiness' entails, potential error conditions, or performance characteristics like execution time.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that clearly communicates the core functionality without unnecessary words. It's appropriately sized for a simple health check tool and front-loads the essential information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (zero parameters, has output schema), the description is reasonably complete. The output schema will handle return value documentation, so the description appropriately focuses on purpose. However, it could better address when to use this versus sibling tools for full completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters with 100% schema description coverage. The description appropriately doesn't discuss parameters since none exist, maintaining focus on the tool's purpose. This meets the baseline expectation for parameterless tools.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Lightweight self-check of SageMath availability and basic readiness.' It specifies the verb ('self-check') and resource ('SageMath'), but doesn't explicitly differentiate from sibling tools like 'sagemath_version' which might provide similar system information.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'sagemath_evaluate' or 'sagemath_version', nor does it specify scenarios where a health check is appropriate versus other diagnostic operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

sagemath_versionSageMath VersionA

Get local SageMath version information

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
stderrYes
stdoutYes
exitCodeYes
timedOutYes
durationMsYes

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It indicates a read-only operation ('Get') but doesn't disclose behavioral traits such as performance characteristics, error handling, or what specific information is returned. It's minimally adequate but lacks depth.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with no wasted words. It's front-loaded with the core purpose, making it easy to understand quickly. Every part of the sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (0 parameters, no annotations, but with an output schema), the description is reasonably complete for its purpose. However, it could benefit from more context about the output format or usage scenarios, especially with sibling tools present.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the input structure. The description adds no parameter details, which is acceptable here, but doesn't compensate for any gaps since there are none. Baseline is 4 for zero parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get') and resource ('local SageMath version information'), making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'sagemath_health' which might also provide version-related information, preventing a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like 'sagemath_health' or 'sagemath_evaluate'. The description implies usage for retrieving version info but lacks explicit context, prerequisites, or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv1.0.0
    • First observedsagemath_evaluate
    • First observedsagemath_health
    • First observedsagemath_version

TDQS

B3.4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: sagemath_evaluate executes code, sagemath_health checks system readiness, and sagemath_version retrieves version info. There is no overlap in functionality, making tool selection straightforward for an agent.

Naming Consistency5/5

All tool names follow a consistent snake_case pattern with the 'sagemath_' prefix followed by a descriptive action (evaluate, health, version). This uniformity enhances predictability and readability across the tool set.

Tool Count3/5

With only 3 tools, the server feels thin for a SageMath domain, which typically involves complex mathematical operations. While the tools cover basic evaluation and system checks, more operations (e.g., for algebra, calculus, or plotting) would be expected for a comprehensive server.

Completeness2/5

The tool surface is severely incomplete for a SageMath server. It lacks core mathematical operations like solving equations, symbolic manipulation, or numerical computation, leaving significant gaps that will hinder agents from performing typical SageMath tasks beyond simple code evaluation.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    A secure mathematical computation sandbox that enables LLMs to perform symbolic math operations like algebra, calculus, and equation solving via SymPy. It features low-latency execution through pre-warmed process pools and provides standardized JSON outputs for reliable agent integration.
    1
    2
    MIT