Skip to main content
Glama

execute_python_code

Execute Python code within 3D Slicer to automate medical image processing tasks, manipulate scene elements, and perform calculations in the visualization environment.

Instructions

Execute Python code in 3D Slicer.

Parameters: code (str): The Python code to execute.

The code parameter is a string containing the Python code to be executed in 3D Slicer's Python environment. The code should be executable by Python's exec() function. To get return values, the code should assign the result to a variable named __execResult.

Examples:

  • Create a sphere model: {"tool": "execute_python_code", "arguments": {"code": "sphere = slicer.vtkMRMLModelNode(); slicer.mrmlScene.AddNode(sphere); sphere.SetName('MySphere'); __execResult = sphere.GetID()"}}

  • Get the number of nodes in the current scene: {"tool": "execute_python_code", "arguments": {"code": "__execResult = len(slicer.mrmlScene.GetNodes())"}}

  • Calculate 1+1: {"tool": "execute_python_code", "arguments": {"code": "__execResult = 1 + 1"}}

Returns: dict: A dictionary containing the execution result.

If the code execution is successful, the dictionary will contain the following key-value pairs:
- "success": True
- "message": The result of the code execution. If the code assigns the result to `__execResult`, the value of `__execResult` is returned, otherwise it returns empty.

If the code execution fails, the dictionary will contain the following key-value pairs:
- "success": False
- "message": A string containing an error message indicating the cause of the failure. The error message may come from the Slicer Web Server or the Python interpreter.

Examples:

  • Successful execution: {"success": True, "message": 2} # Assuming the result of 1+1 is 2

  • Successful execution: {"success": True, "message": "vtkMRMLScene1"} # Assuming the created sphere id is vtkMRMLScene1

  • Python execution error: {"success": False, "message": "Server error: name 'slicer' is not defined"}

  • Connection error: {"success": False, "message": "Connection error: ..."}

  • HTTP error: {"success": False, "message": "HTTP Error 404: Not Found"}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes

Implementation Reference

  • The @mcp.tool() decorator registers the tool, and the function implements the core logic: sends the provided Python code via POST to Slicer's /exec endpoint, parses the JSON response, extracts __execResult if present, and handles various errors (HTTP, JSON, connection). The detailed docstring serves as input/output schema.
    @mcp.tool()
    def execute_python_code(code: str) -> dict:
        """
        Execute Python code in 3D Slicer.
    
        Parameters:
        code (str): The Python code to execute.
    
        The code parameter is a string containing the Python code to be executed in 3D Slicer's Python environment.
        The code should be executable by Python's `exec()` function. To get return values, the code should assign the result to a variable named `__execResult`.
    
        Examples:
        - Create a sphere model: {"tool": "execute_python_code", "arguments": {"code": "sphere = slicer.vtkMRMLModelNode(); slicer.mrmlScene.AddNode(sphere); sphere.SetName('MySphere'); __execResult = sphere.GetID()"}}
        - Get the number of nodes in the current scene: {"tool": "execute_python_code", "arguments": {"code": "__execResult = len(slicer.mrmlScene.GetNodes())"}}
        - Calculate 1+1: {"tool": "execute_python_code", "arguments": {"code": "__execResult = 1 + 1"}}
    
        Returns:
            dict: A dictionary containing the execution result.
    
            If the code execution is successful, the dictionary will contain the following key-value pairs:
            - "success": True
            - "message": The result of the code execution. If the code assigns the result to `__execResult`, the value of `__execResult` is returned, otherwise it returns empty.
    
            If the code execution fails, the dictionary will contain the following key-value pairs:
            - "success": False
            - "message": A string containing an error message indicating the cause of the failure. The error message may come from the Slicer Web Server or the Python interpreter.
    
        Examples:
        - Successful execution: {"success": True, "message": 2}  # Assuming the result of 1+1 is 2
        - Successful execution: {"success": True, "message": "vtkMRMLScene1"} # Assuming the created sphere id is vtkMRMLScene1
        - Python execution error: {"success": False, "message": "Server error: name 'slicer' is not defined"}
        - Connection error: {"success": False, "message": "Connection error: ..."}
        - HTTP error: {"success": False, "message": "HTTP Error 404: Not Found"}
        """
        api_url = f"{SLICER_WEB_SERVER_URL}/exec"
        headers = {'Content-Type': 'text/plain'}
        try:
            # Smart proxy handling: disable for localhost, use system default for others
            response = requests.post(api_url, data=code.encode('utf-8'), headers=headers, proxies=get_proxy_config(api_url))
            result_data = response.json()
            
            if isinstance(result_data, dict) and not result_data.get("success", True):
                return {
                    "success": False,
                    "message": result_data.get("message", "Unknown Python execution error")
                    }
                
            return {
                "success": True,
                "message": result_data.get("__execResult") if isinstance(result_data, dict) and "__execResult" in result_data else result_data
                }
        except requests.exceptions.HTTPError as e:
            return {
                "success": False,
                "message": f"HTTP Error {e.response.status_code}: {str(e)}"
                }
        except json.JSONDecodeError:
            return {
                "success": False,
                "message": f"Invalid JSON response: {response.text}"
                }
        except requests.exceptions.RequestException as e:
            return {
                "success": False,
                "message": f"Connection error: {str(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 delivers substantial behavioral information. It explains the execution environment (3D Slicer's Python environment), the execution mechanism (Python's exec() function), how to capture return values (assign to __execResult), and detailed success/failure response patterns including specific error types. The only gap is lack of information about permissions, rate limits, or side effects.

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

Conciseness4/5

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

The description is well-structured with clear sections (Parameters, Examples, Returns) but could be more front-loaded. The initial statement is clear, but some redundancy exists (e.g., explaining the code parameter twice). Most sentences earn their place by providing essential information, though minor trimming could improve conciseness.

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

Completeness5/5

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

Given the tool's complexity (arbitrary code execution), lack of annotations, and no output schema, the description provides comprehensive context. It covers execution mechanics, return value handling, success/failure scenarios with concrete examples, and error types. For a powerful tool with zero structured metadata, this description provides nearly everything an agent needs to use it correctly.

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?

With 0% schema description coverage for the single parameter, the description fully compensates by providing rich semantic context. It explains that 'code' is executable Python code, specifies it should work with exec(), provides concrete examples showing proper formatting, and explains the special __execResult variable for return values. This goes far beyond what the bare schema provides.

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 ('Execute Python code') and the target environment ('in 3D Slicer'), distinguishing it from siblings like capture_screenshot and list_nodes. It provides a precise verb+resource combination that leaves no ambiguity about the tool's function.

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

Usage Guidelines3/5

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

The description implies usage context through examples (creating models, getting node counts, calculations) but doesn't explicitly state when to use this tool versus alternatives. There's no guidance on prerequisites, limitations, or comparison with sibling tools, leaving the agent to infer appropriate use cases from the examples provided.

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/zhaoyouj/mcp-slicer'

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