Skip to main content
Glama

execute_python_code

Run Python scripts within 3D Slicer to manipulate medical images, create models, or perform calculations. Assign results to __execResult for retrieval and handle errors with detailed feedback.

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 handler function for execute_python_code tool. Registered via @mcp.tool() decorator. Posts the code to Slicer's /exec endpoint, processes __execResult, handles errors, returns {'success': bool, 'message': result or error}.
    @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)}" }
  • The @mcp.tool() decorator registers the execute_python_code handler with the FastMCP server.
    @mcp.tool()
  • Type hints (code: str -> dict) and comprehensive docstring defining input schema, examples, and output format.
    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"} """
  • Helper function used by execute_python_code (and others) for smart proxy configuration to handle localhost requests properly.
    def get_proxy_config(url: str) -> Optional[dict]: """ Get proxy configuration for requests based on URL. For localhost/127.0.0.1 connections, always disable proxy to avoid connection issues when system proxy is configured but not running. For other connections, return None to use system default proxy settings (if configured via environment variables). Args: url: The target URL for the request Returns: dict: Proxy configuration dict for requests library - For localhost: {'http': None, 'https': None} to disable proxy - For other hosts: None to use system defaults """ parsed = urlparse(url) hostname = parsed.hostname or "" # Always bypass proxy for localhost connections if hostname in ("localhost", "127.0.0.1", "::1") or hostname.startswith("127."): return {'http': None, 'https': None} # For other connections, return None to use system proxy settings # if available via HTTP_PROXY, HTTPS_PROXY environment variables return None

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

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