Skip to main content
Glama
aac6fef

Mathematica MCP Server

by aac6fef

execute_mathematica_code

Execute Wolfram Language code within a secure session using a provided session ID. Perform calculations, symbolic computations, and data visualizations by submitting valid code strings to the Mathematica kernel.

Instructions

Executes a string of Wolfram Language code within a specific, active session.

To use this tool, you must provide a valid 'session_id' obtained from a previous call to 'create_session'. The code will be executed in the context of that session, meaning it can access variables and functions defined in previous calls within the same session.

Args: session_id: The unique identifier for an active session, provided by 'create_session'. Example: 'bee-sloth-auk-mole'. code: A string containing the Wolfram Language code to be executed. The code should be syntactically correct. Example 1 (simple calculation): 'Total[Range[100]]' Example 2 (symbolic computation): 'Solve[x^2 - 5x + 6 == 0, x]' Example 3 (data visualization): 'Plot[Sin[x], {x, 0, 2 Pi}]'

Returns: The direct result of the code execution from the Wolfram Engine. The data type can vary (e.g., integer, list, string, or a complex expression). For plots, it may return a representation of the graphics object.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
session_idYes

Implementation Reference

  • The @mcp.tool() decorator registers the handler function execute_mathematica_code, which verifies the session ID using AnimalIdGenerator, retrieves the WolframLanguageSession from the sessions dict, evaluates the provided code using session.evaluate(wlexpr(code)), and returns the result or raises an error.
    @mcp.tool()
    async def execute_mathematica_code(session_id: str, code: str) -> Any:
        """
        Executes a string of Wolfram Language code within a specific, active session.
    
        To use this tool, you must provide a valid 'session_id' obtained from a
        previous call to 'create_session'. The code will be executed in the
        context of that session, meaning it can access variables and functions
        defined in previous calls within the same session.
    
        Args:
            session_id: The unique identifier for an active session, provided by
                        'create_session'. Example: 'bee-sloth-auk-mole'.
            code: A string containing the Wolfram Language code to be executed.
                  The code should be syntactically correct.
                  Example 1 (simple calculation): 'Total[Range[100]]'
                  Example 2 (symbolic computation): 'Solve[x^2 - 5x + 6 == 0, x]'
                  Example 3 (data visualization): 'Plot[Sin[x], {x, 0, 2 Pi}]'
    
        Returns:
            The direct result of the code execution from the Wolfram Engine. The data
            type can vary (e.g., integer, list, string, or a complex expression).
            For plots, it may return a representation of the graphics object.
        """
        # 验证 session_id 格式和校验和
        if not id_generator.verify(session_id):
            raise ValueError("Invalid session ID. It might be malformed or tampered with.")
    
        # 查找会话
        session = sessions.get(session_id)
        if not session:
            raise ValueError(f"Session with ID '{session_id}' not found or has been closed.")
    
        try:
            # 将字符串代码转换为 wlexpr 对象并执行
            result = session.evaluate(wlexpr(code))
            return result
        except Exception as e:
            raise RuntimeError(f"An error occurred during execution in session '{session_id}': {e}") from e
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by explaining session context persistence ('can access variables and functions defined in previous calls'), execution constraints ('code should be syntactically correct'), and return value variability. It doesn't mention potential errors, timeouts, or resource limits, keeping it from a perfect score.

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?

Well-structured with a clear opening sentence stating purpose, followed by usage guidelines, then detailed parameter explanations with examples, and finally return value information. Every sentence adds value with no redundancy.

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?

For a 2-parameter tool with no annotations and no output schema, the description provides excellent coverage of purpose, usage, parameters, and return behavior. It could be slightly more complete by mentioning potential error cases or execution limits, but it's very thorough for the given context.

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

Parameters5/5

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

Schema description coverage is 0%, so the description must compensate fully. It provides detailed semantics for both parameters: 'session_id' is explained as a unique identifier from 'create_session' with an example format, and 'code' is described with syntax requirements and three concrete examples showing different use cases.

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

Purpose5/5

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

The description clearly states the specific action ('Executes a string of Wolfram Language code') and resource ('within a specific, active session'), distinguishing it from sibling tools like 'create_mathematica_session' and 'close_mathematica_session' which handle session lifecycle rather than code execution.

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

Usage Guidelines5/5

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

Explicitly states when to use ('within a specific, active session') and prerequisites ('must provide a valid session_id obtained from a previous call to create_session'), and distinguishes from alternatives by specifying the session context requirement.

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

Related 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/aac6fef/mathematica_mcp'

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