execute_python
Execute Python code in a persistent REPL environment with variable retention between runs. Use this tool to run Python scripts, test code snippets, and maintain state across multiple executions.
Instructions
Execute Python code and return the output. Variables persist between executions.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | Python code to execute | |
| reset | No | Reset the Python session (clear all variables) |
Implementation Reference
- src/mcp_python/server.py:82-142 (handler)Executes the provided Python code in a persistent namespace, captures stdout/stderr, handles reset option, formats output or errors, returns as TextContent.if name == "execute_python": code = arguments.get("code") if not code: raise ValueError("Missing code parameter") # Check if we should reset the session if arguments.get("reset", False): self.global_namespace.clear() self.global_namespace["__builtins__"] = __builtins__ return [ types.TextContent( type="text", text="Python session reset. All variables cleared." ) ] # Capture stdout and stderr stdout = io.StringIO() stderr = io.StringIO() try: # Execute code with output redirection with redirect_stdout(stdout), redirect_stderr(stderr): exec(code, self.global_namespace) # Combine output output = stdout.getvalue() errors = stderr.getvalue() # Format response result = "" if output: result += f"Output:\n{output}" if errors: result += f"\nErrors:\n{errors}" if not output and not errors: # Try to get the value of the last expression try: last_line = code.strip().split('\n')[-1] last_value = eval(last_line, self.global_namespace) result = f"Result: {repr(last_value)}" except (SyntaxError, ValueError, NameError): result = "Code executed successfully (no output)" return [ types.TextContent( type="text", text=result ) ] except Exception as e: # noqa: F841 # Capture and format any exceptions error_msg = f"Error executing code:\n{traceback.format_exc()}" return [ types.TextContent( type="text", text=error_msg ) ]
- src/mcp_python/server.py:35-49 (schema)Defines the input schema for execute_python tool: required 'code' string, optional 'reset' boolean.inputSchema={ "type": "object", "properties": { "code": { "type": "string", "description": "Python code to execute", }, "reset": { "type": "boolean", "description": "Reset the Python session (clear all variables)", "default": False } }, "required": ["code"], },
- src/mcp_python/server.py:32-50 (registration)Registers the execute_python tool in the list_tools handler, including name, description, and input schema.types.Tool( name="execute_python", description="Execute Python code and return the output. Variables persist between executions.", inputSchema={ "type": "object", "properties": { "code": { "type": "string", "description": "Python code to execute", }, "reset": { "type": "boolean", "description": "Reset the Python session (clear all variables)", "default": False } }, "required": ["code"], }, ),
- src/mcp_python/server.py:16-18 (helper)Initializes the shared global namespace used for persistent variable state across execute_python calls.self.global_namespace = { "__builtins__": __builtins__, }