-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathbatch_execute.py
More file actions
170 lines (139 loc) · 6.39 KB
/
batch_execute.py
File metadata and controls
170 lines (139 loc) · 6.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Defines the batch_execute tool for orchestrating multiple Unity MCP commands."""
from __future__ import annotations
import logging
from typing import Annotated, Any
from fastmcp import Context
from mcp.types import ToolAnnotations
from services.registry import mcp_for_unity_tool
from services.tools import get_unity_instance_from_context
from transport.unity_transport import send_with_unity_instance
from transport.legacy.unity_connection import async_send_command_with_retry
logger = logging.getLogger(__name__)
# Fallback used when the Unity-side configured limit is not yet known.
DEFAULT_MAX_COMMANDS_PER_BATCH = 25
# Hard ceiling matching the C# AbsoluteMaxCommandsPerBatch.
ABSOLUTE_MAX_COMMANDS_PER_BATCH = 100
# Module-level cache for the Unity-configured limit (populated from editor state).
_cached_max_commands: int | None = None
def strip_mcp_prefix(tool_name: str) -> str:
"""Strip MCP server namespace prefix from a tool name.
Clients may send prefixed tool names like:
- "UnityMCP:manage_gameobject" (colon-separated)
- "mcp__UnityMCP__manage_gameobject" (double-underscore, Claude Code style)
This normalizes them to the short form ("manage_gameobject").
"""
# Double-underscore format: "mcp__ServerName__tool_name"
if tool_name.startswith("mcp__") and "__" in tool_name[5:]:
suffix = tool_name.split("__", 2)[-1]
if suffix:
return suffix
# Colon format: "ServerName:tool_name"
if ":" in tool_name:
suffix = tool_name.rsplit(":", 1)[-1]
if suffix:
return suffix
return tool_name
async def _get_max_commands_from_editor_state(ctx: Context) -> int:
"""
Attempt to read the configured batch limit from the Unity editor state.
Falls back to DEFAULT_MAX_COMMANDS_PER_BATCH if unavailable.
"""
global _cached_max_commands
if _cached_max_commands is not None:
return _cached_max_commands
try:
from services.resources.editor_state import get_editor_state
state_resp = await get_editor_state(ctx)
data = state_resp.data if hasattr(state_resp, "data") else (
state_resp.get("data") if isinstance(state_resp, dict) else None
)
if isinstance(data, dict):
settings = data.get("settings")
if isinstance(settings, dict):
limit = settings.get("batch_execute_max_commands")
if isinstance(limit, int) and 1 <= limit <= ABSOLUTE_MAX_COMMANDS_PER_BATCH:
_cached_max_commands = limit
return limit
except Exception as exc:
logger.debug("Could not read batch limit from editor state: %s", exc)
return DEFAULT_MAX_COMMANDS_PER_BATCH
def invalidate_cached_max_commands() -> None:
"""Reset the cached limit so the next call re-reads from editor state."""
global _cached_max_commands
_cached_max_commands = None
@mcp_for_unity_tool(
name="batch_execute",
description=(
"Executes multiple MCP commands in a single batch for dramatically better performance. "
"STRONGLY RECOMMENDED when creating/modifying multiple objects, adding components to multiple targets, "
"or performing any repetitive operations. Reduces latency and token costs by 10-100x compared to "
"sequential tool calls. The max commands per batch is configurable in the Unity MCP Tools window "
f"(default {DEFAULT_MAX_COMMANDS_PER_BATCH}, hard max {ABSOLUTE_MAX_COMMANDS_PER_BATCH}). "
"Example: creating 5 cubes → use 1 batch_execute with 5 create commands instead of 5 separate calls."
),
annotations=ToolAnnotations(
title="Batch Execute",
destructiveHint=True,
),
)
async def batch_execute(
ctx: Context,
commands: Annotated[list[dict[str, Any]], "List of commands with 'tool' and 'params' keys."],
parallel: Annotated[bool | None,
"Attempt to run read-only commands in parallel"] = None,
fail_fast: Annotated[bool | None,
"Stop processing after the first failure"] = None,
max_parallelism: Annotated[int | None,
"Hint for the maximum number of parallel workers"] = None,
) -> dict[str, Any]:
"""Proxy the batch_execute tool to the Unity Editor transporter."""
unity_instance = get_unity_instance_from_context(ctx)
if not isinstance(commands, list) or not commands:
raise ValueError(
"'commands' must be a non-empty list of command specifications")
max_commands = await _get_max_commands_from_editor_state(ctx)
if len(commands) > max_commands:
raise ValueError(
f"batch_execute supports up to {max_commands} commands (configured in Unity); received {len(commands)}"
)
normalized_commands: list[dict[str, Any]] = []
for index, command in enumerate(commands):
if not isinstance(command, dict):
raise ValueError(
f"Command at index {index} must be an object with 'tool' and 'params' keys")
tool_name = command.get("tool")
params = command.get("params", {})
if not tool_name or not isinstance(tool_name, str):
raise ValueError(
f"Command at index {index} is missing a valid 'tool' name")
tool_name = strip_mcp_prefix(tool_name)
if params is None:
params = {}
if not isinstance(params, dict):
raise ValueError(
f"Command '{tool_name}' must specify parameters as an object/dict")
if "unity_instance" in params:
raise ValueError(
f"Command '{tool_name}' at index {index} contains 'unity_instance'. "
"Per-command instance routing is not supported inside batch_execute. "
"Set unity_instance on the outer batch_execute call to route the entire batch."
)
normalized_commands.append({
"tool": tool_name,
"params": params,
})
payload: dict[str, Any] = {
"commands": normalized_commands,
}
if parallel is not None:
payload["parallel"] = bool(parallel)
if fail_fast is not None:
payload["failFast"] = bool(fail_fast)
if max_parallelism is not None:
payload["maxParallelism"] = int(max_parallelism)
return await send_with_unity_instance(
async_send_command_with_retry,
unity_instance,
"batch_execute",
payload,
)