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.
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
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes |
Implementation Reference
- src/mcp_slicer/mcp_server.py:118-184 (handler)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)}" }