MCP-Slicer

execute_python_code

Run Python code within 3D Slicer to manipulate models, process medical images, or perform calculations. Assign results to __execResult for retrieval. Returns execution status and output.

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

NameRequiredDescriptionDefault
codeYes

Input Schema (JSON Schema)

{ "properties": { "code": { "title": "Code", "type": "string" } }, "required": [ "code" ], "title": "execute_python_codeArguments", "type": "object" }

You must be authenticated.

Other Tools from MCP-Slicer

Related Tools

ID: kn2cl0hh2g