Skip to main content
Glama
GaloisHLee
by GaloisHLee

SageMath Evaluate

sagemath_evaluate

Execute SageMath mathematical computations locally to solve equations, perform symbolic algebra, and analyze data using a configured SageMath installation.

Instructions

Evaluate SageMath code locally

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
timeoutMsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
stderrYes
stdoutYes
exitCodeYes
timedOutYes
durationMsYes

Implementation Reference

  • Core handler function that evaluates the provided SageMath code: writes code to a temporary .sage file, spawns the 'sage' process to execute it, handles timeout via runProcess helper, collects stdout/stderr/exitCode/duration/timedOut, cleans up temp dir, and returns the result.
    export async function evaluateSage(code: string, timeoutMs = 10000): Promise<SageRunResult & { tmpDir?: string }> {
      const sage = getSageExecutable();
      const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-sage-'));
      const scriptPath = path.join(tmpRoot, 'script.sage');
      await fs.writeFile(scriptPath, code, 'utf8');
    
      const result = await runProcess(sage, [scriptPath], timeoutMs);
    
      // Attempt cleanup
      try { await fs.rm(tmpRoot, { recursive: true, force: true }); } catch {}
    
      return { ...result };
    }
  • Input/output schemas using Zod: input requires 'code' string and optional 'timeoutMs'; output matches SageRunResult structure (stdout, stderr, exitCode, durationMs, timedOut).
    {
      title: 'SageMath Evaluate',
      description: 'Evaluate SageMath code locally',
      inputSchema: {
        code: z.string(),
        timeoutMs: z.number().int().positive().optional(),
      },
      outputSchema: {
        stdout: z.string(),
        stderr: z.string(),
        exitCode: z.number().nullable(),
        durationMs: z.number(),
        timedOut: z.boolean(),
      },
    },
  • src/index.ts:41-69 (registration)
    Registers the 'sagemath_evaluate' tool on the MCP server, providing title/description/schemas and a thin async handler wrapper that calls evaluateSage and formats MCP response with text content and structured JSON.
    server.registerTool(
      'sagemath_evaluate',
      {
        title: 'SageMath Evaluate',
        description: 'Evaluate SageMath code locally',
        inputSchema: {
          code: z.string(),
          timeoutMs: z.number().int().positive().optional(),
        },
        outputSchema: {
          stdout: z.string(),
          stderr: z.string(),
          exitCode: z.number().nullable(),
          durationMs: z.number(),
          timedOut: z.boolean(),
        },
      },
      async ({ code, timeoutMs }) => {
        const result = await evaluateSage(code, timeoutMs ?? 10000);
        const structured = result as unknown as Record<string, unknown>;
        return {
          content: [{
            type: 'text',
            text: `SageMath evaluation response (structured JSON below)\n${JSON.stringify(structured)}`,
          }],
          structuredContent: structured,
        };
      }
    );
  • Key helper function to spawn a child process (sage), pipe stdout/stderr, enforce timeout with SIGKILL, handle errors/spawn failures, and resolve with SageRunResult including duration and timedOut flag. Used by both evaluateSage and getSageVersion.
    async function runProcess(cmd: string, args: string[], timeoutMs: number): Promise<SageRunResult> {
      const start = Date.now();
      let stdout = '';
      let stderr = '';
      let timedOut = false;
    
      return new Promise<SageRunResult>((resolve) => {
        let child: ReturnType<typeof spawn> | undefined;
        try {
          child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
        } catch (err: any) {
          resolve({
            stdout: '',
            stderr: `Failed to spawn process: ${err?.message || String(err)}`,
            exitCode: null,
            durationMs: Date.now() - start,
            timedOut: false,
          });
          return;
        }
    
        const t = setTimeout(() => {
          timedOut = true;
          try { child?.kill('SIGKILL'); } catch {}
        }, Math.max(1, timeoutMs));
    
        // Handle asynchronous spawn errors (e.g., command not found)
        child.on('error', (err) => {
          clearTimeout(t);
          resolve({
            stdout: '',
            stderr: `Process error: ${err?.message || String(err)}`,
            exitCode: null,
            durationMs: Date.now() - start,
            timedOut,
          });
        });
    
        child.stdout?.on('data', (d) => { stdout += d.toString(); });
        child.stderr?.on('data', (d) => { stderr += d.toString(); });
    
        child.on('close', (code) => {
          clearTimeout(t);
          resolve({
            stdout,
            stderr,
            exitCode: code,
            durationMs: Date.now() - start,
            timedOut,
          });
        });
      });
    }
  • TypeScript interface defining the structure of Sage execution results, matching the outputSchema in registration.
    export interface SageRunResult {
      stdout: string;
      stderr: string;
      exitCode: number | null;
      durationMs: number;
      timedOut: boolean;
    }
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.

Install Server

Other Tools

Latest Blog Posts

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/GaloisHLee/mcp-server-sagemath'

If you have feedback or need assistance with the MCP directory API, please join our Discord server