Skip to main content
Glama

execute-python

Run Python code remotely in Unreal Engine environments using the MCP Unreal Server, enabling automated node discovery and management for efficient scripting and task execution.

Instructions

在Unreal中执行Python代码

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
unattendedNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
errorNo
resultNo
successYes

Implementation Reference

  • Main handler function for the 'execute-python' tool. Validates connection to Unreal Engine, executes the provided Python code using RemoteExecution.run_command on the first available node, handles errors, and returns JSON-formatted results via TextContent.
    async def _handle_execute_python(self, arguments: dict) -> list[types.TextContent]:
        """处理Python代码执行请求。"""
        global _unreal_connection
        
        # 确保连接存在且有效
        try:
            if not _unreal_connection or not _unreal_connection.remote_nodes:
                _unreal_connection = get_unreal_connection()
                # 等待一小段时间以确保连接建立
                await asyncio.sleep(1)
                
            if not _unreal_connection or not _unreal_connection.remote_nodes:
                return [types.TextContent(type="text", text=json.dumps({
                    "success": False,
                    "error": "无法连接到Unreal实例,请确保Unreal正在运行并启用了远程执行"
                }))]
        except Exception as e:
            return [types.TextContent(type="text", text=json.dumps({
                "success": False,
                "error": f"连接Unreal失败: {str(e)}"
            }))]
    
        code = arguments.get("code")
        if not code:
            return [types.TextContent(type="text", text=json.dumps({
                "success": False,
                "error": "未提供Python代码"
            }))]
    
        unattended = arguments.get("unattended", True)
        exec_mode = MODE_EXEC_STATEMENT
        # exec_mode = MODE_EXEC_FILE
    
        try:
            # 获取第一个可用节点
            nodes = _unreal_connection.remote_nodes
            if not nodes:
                return [types.TextContent(type="text", text=json.dumps({
                    "success": False,
                    "error": "未发现任何Unreal节点"
                }))]
            
            node_id = nodes[0]["node_id"]
            _unreal_connection.open_command_connection(node_id)
            
            result = _unreal_connection.run_command(
                code, unattended=unattended, exec_mode=exec_mode
            )
            _unreal_connection.close_command_connection()
    
            # 处理Unreal返回的结果
            if not result.get("success", False):
                return [types.TextContent(type="text", text=json.dumps({
                    "success": False,
                    "error": result.get("result", "未知错误")
                }))]
    
            # 成功执行,返回结果
            return [types.TextContent(type="text", text=json.dumps({
                "success": True,
                "result": result.get("result", "")
            }))]
        except Exception as e:
            if _unreal_connection:
                try:
                    _unreal_connection.close_command_connection()
                except:
                    pass
            return [types.TextContent(type="text", text=json.dumps({
                "success": False,
                "error": f"执行失败: {str(e)}"
            }))]
  • Schema definition for 'execute-python' tool within the list_tools handler, specifying input (code string required, optional unattended boolean) and output (success boolean required, optional result/error strings).
        types.Tool(
            name="execute-python",
            description="在Unreal中执行Python代码",
            inputSchema={
                "type": "object",
                "properties": {
                    "code": {"type": "string"},
                    "unattended": {"type": "boolean", "default": True},
                },
                "required": ["code"],
            },
            outputSchema={
                "type": "object",
                "properties": {
                    "success": {"type": "boolean"},
                    "result": {"type": "string"},
                    "error": {"type": "string"}
                },
                "required": ["success"]
            }
        ),
    ]
  • Registers the 'execute-python' tool via @server.list_tools() decorator in McpUnrealServer._setup_handlers(), returning the tool definition with schema.
    @self.server.list_tools()
    async def handle_list_tools() -> list[types.Tool]:
        """列出可用的工具。"""
        return  [
            types.Tool(
                name="execute-python",
                description="在Unreal中执行Python代码",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "code": {"type": "string"},
                        "unattended": {"type": "boolean", "default": True},
                    },
                    "required": ["code"],
                },
                outputSchema={
                    "type": "object",
                    "properties": {
                        "success": {"type": "boolean"},
                        "result": {"type": "string"},
                        "error": {"type": "string"}
                    },
                    "required": ["success"]
                }
            ),
        ]
  • Dispatches 'execute-python' tool calls via @server.call_tool() to the _handle_execute_python method.
    @self.server.call_tool()
    async def handle_call_tool(
        name: str, arguments: dict | None
    ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        """处理工具执行请求。"""
        if name == "connect-unreal":
            return await self._handle_connect_unreal(arguments or {})
        elif name == "execute-python":
            return await self._handle_execute_python(arguments or {})
        raise ValueError(f"未知的工具: {name}")
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but doesn't describe important behavioral aspects: whether this executes synchronously or asynchronously, what permissions are required, how errors are handled, whether it's safe for production use, or what the 'unattended' parameter actually means behaviorally. The description is minimal and lacks critical operational context.

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

Conciseness5/5

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

The description is extremely concise - a single phrase that directly states the core function. There's zero wasted language, and it's perfectly front-loaded with the essential information. For its length, it's maximally efficient, though this conciseness comes at the cost of completeness.

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

Completeness2/5

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

Given that this is a code execution tool with no annotations, 2 parameters (one with unclear purpose), and an output schema exists, the description is insufficient. While the output schema may describe return values, the description doesn't address safety concerns, execution context, error handling, or parameter meanings. For a potentially powerful/dangerous operation like code execution, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate but doesn't. It mentions no parameters at all, leaving both 'code' and 'unattended' completely unexplained. The description doesn't clarify what format the Python code should be in, what execution environment is used, or what 'unattended' mode entails. This is inadequate for a tool with 2 parameters and 0% schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('执行Python代码' - execute Python code) and the context ('在Unreal中' - in Unreal). It specifies both verb and resource, though it doesn't need to distinguish from siblings since none exist. The purpose is unambiguous but could be more specific about what kind of Python execution this enables.

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

Usage Guidelines2/5

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

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention prerequisites, limitations, or typical use cases. With no sibling tools, differentiation isn't needed, but basic usage context would help the agent understand appropriate scenarios for this operation.

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

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/radial-hks/MCP-Unreal-Server'

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