mcp-plan-runner 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """Run a whole plan of MCP tool calls in one call."""
mcp_plan_runner/hub.py ADDED
@@ -0,0 +1,165 @@
1
+ """Connections to the downstream MCP servers, and the tool policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import fnmatch
7
+ import json
8
+ import logging
9
+ import os
10
+ from collections.abc import AsyncIterator
11
+ from contextlib import AsyncExitStack, asynccontextmanager
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from mcp import Client, StdioServerParameters
16
+ from mcp.client.stdio import stdio_client
17
+ from mcp_types import CallToolResult, TextContent, Tool
18
+
19
+ from .plan import ToolError
20
+ from .schemas import SchemaCache, default_path
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class Hub:
27
+ """Holds one open client per server and an index of `server.tool` names."""
28
+
29
+ allow_in_plans: list[str] = field(default_factory=list)
30
+ clients: dict[str, Client] = field(default_factory=dict)
31
+ tools: dict[str, Tool] = field(default_factory=dict) # "server.tool" -> Tool
32
+ gates: dict[str, asyncio.Semaphore] = field(default_factory=dict) # calls in flight per server
33
+ schemas: SchemaCache | None = None # learns output shapes of tools without an output schema
34
+
35
+ async def connect(self, stack: AsyncExitStack, name: str, target: Any, max_parallel: int = 4,
36
+ log_path: str | None = None) -> None:
37
+ """Open a client and keep it open for the life of `stack`. A failed server is skipped.
38
+
39
+ With `log_path`, a stdio server's stderr is appended to that file.
40
+ """
41
+ self.gates[name] = asyncio.Semaphore(max(1, max_parallel))
42
+ if log_path:
43
+ target = stdio_with_log(target, log_path)
44
+ try:
45
+ client = await stack.enter_async_context(Client(target))
46
+ cursor = None
47
+ while True:
48
+ page = await client.list_tools(cursor=cursor)
49
+ for t in page.tools:
50
+ self.tools[f"{name}.{t.name}"] = t
51
+ cursor = page.next_cursor
52
+ if not cursor:
53
+ break
54
+ self.clients[name] = client
55
+ log.info("connected %s", name)
56
+ except Exception as e: # one bad server must not stop the others
57
+ log.error("could not connect %s: %s", name, e)
58
+
59
+ def why_blocked(self, full_name: str) -> str | None:
60
+ """None if the tool may run without a human check, else the reason."""
61
+ tool = self.tools.get(full_name)
62
+ if tool is None:
63
+ return "does not exist (use list_tools)"
64
+ if tool.annotations and tool.annotations.read_only_hint:
65
+ return None
66
+ if any(fnmatch.fnmatchcase(full_name, p) for p in self.allow_in_plans):
67
+ return None
68
+ return ("is not marked read-only and is not in allow_in_plans; "
69
+ "call it directly on its own server so a human can approve it")
70
+
71
+ async def call(self, full_name: str, args: dict[str, Any]) -> Any:
72
+ server, _, tool = full_name.partition(".")
73
+ async with self.gates[server]:
74
+ result = await self.clients[server].call_tool(tool, args)
75
+ try:
76
+ value = normalize(result)
77
+ except ToolError as e:
78
+ log.warning("%s error: %s", full_name, str(e)[:300])
79
+ raise
80
+ t = self.tools[full_name]
81
+ if self.schemas is not None and t.output_schema is None:
82
+ try:
83
+ self.schemas.observe(full_name, t.input_schema, value)
84
+ except Exception as e: # learning must never turn a good result into an error
85
+ log.warning("could not learn the output schema of %s: %s", full_name, e)
86
+ return value
87
+
88
+ def output_schema(self, full_name: str) -> tuple[dict[str, Any] | None, bool]:
89
+ """(schema, learned): the declared output schema, or else the one learned from results."""
90
+ t = self.tools[full_name]
91
+ if t.output_schema is not None:
92
+ return t.output_schema, False
93
+ learned = self.schemas.get(full_name, t.input_schema) if self.schemas else None
94
+ return learned, learned is not None
95
+
96
+
97
+ @asynccontextmanager
98
+ async def stdio_with_log(params: StdioServerParameters, path: str) -> AsyncIterator[Any]:
99
+ """A stdio transport that appends the server's stderr to `path`."""
100
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
101
+ # 0600: server stderr can hold secrets. fchmod also tightens a file that already exists.
102
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
103
+ os.fchmod(fd, 0o600)
104
+ with os.fdopen(fd, "a") as f:
105
+ async with stdio_client(params, errlog=f) as streams:
106
+ yield streams
107
+
108
+
109
+ def normalize(result: CallToolResult) -> Any:
110
+ """Turn a tool result into plain JSON data that plan expressions can use."""
111
+ text = [c.text for c in result.content if isinstance(c, TextContent)]
112
+ if result.is_error:
113
+ raise ToolError(" ".join(text) or "tool returned an error")
114
+ if result.structured_content is not None:
115
+ return result.structured_content
116
+ parsed = [_maybe_json(t) for t in text]
117
+ if len(parsed) == 1:
118
+ return parsed[0]
119
+ return parsed
120
+
121
+
122
+ def _maybe_json(text: str) -> Any:
123
+ try:
124
+ return json.loads(text)
125
+ except ValueError:
126
+ return text
127
+
128
+
129
+ def load_config(path: str) -> tuple[dict[str, Any], dict[str, int], list[str], dict[str, str], str | None]:
130
+ """Read the config file.
131
+
132
+ Returns (server name -> Client target, server name -> max_parallel, allow_in_plans,
133
+ server name -> stderr log path, schema cache path or None when learning is off).
134
+ """
135
+ with open(path) as f:
136
+ cfg = json.load(f)
137
+ targets: dict[str, Any] = {}
138
+ parallel: dict[str, int] = {}
139
+ logs: dict[str, str] = {}
140
+ for name, s in cfg.get("servers", {}).items():
141
+ if "." in name:
142
+ raise ValueError(f"server name {name!r} may not contain '.'")
143
+ if "url" in s:
144
+ if "log" in s:
145
+ raise ValueError(f"server {name!r}: 'log' works only for stdio servers")
146
+ targets[name] = s["url"]
147
+ else:
148
+ targets[name] = StdioServerParameters(
149
+ command=s["command"], args=s.get("args", []), env=s.get("env"), cwd=s.get("cwd"))
150
+ if "log" in s:
151
+ if not isinstance(s["log"], str) or not s["log"]:
152
+ raise ValueError(f"server {name!r}: 'log' must be a file path")
153
+ logs[name] = os.path.expanduser(s["log"])
154
+ if "max_parallel" in s:
155
+ parallel[name] = int(s["max_parallel"])
156
+ cache = cfg.get("schema_cache", True)
157
+ if cache is True:
158
+ cache_path: str | None = default_path()
159
+ elif cache is False:
160
+ cache_path = None
161
+ elif isinstance(cache, str) and cache:
162
+ cache_path = os.path.expanduser(cache)
163
+ else:
164
+ raise ValueError("'schema_cache' must be true, false or a file path")
165
+ return targets, parallel, cfg.get("allow_in_plans", []), logs, cache_path
@@ -0,0 +1,499 @@
1
+ """Plan validation and execution.
2
+
3
+ A plan is a small graph of steps that a model writes in one tool call.
4
+ The runner executes it against MCP tools and returns only the final value.
5
+
6
+ This module has no MCP dependency: the caller passes `call_tool(name, args)`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import re
14
+ import time
15
+ from collections.abc import Awaitable, Callable
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ import jmespath
20
+ from jmespath.exceptions import JMESPathError
21
+
22
+ CallFn = Callable[[str, dict[str, Any]], Awaitable[Any]]
23
+
24
+ STEP_ID = re.compile(r"^[a-z_][a-z0-9_]*$")
25
+ TEMPLATE = re.compile(r"\{\{(.+?)\}\}")
26
+ KINDS = ("call", "do", "for_each", "paginate", "return")
27
+ RESERVED = {"input"} # names a step or loop variable may not use
28
+ MAX_DEPTH = 2 # sub-plans (for_each + do) may nest this deep
29
+
30
+
31
+ class ToolError(Exception):
32
+ """A downstream tool returned an error."""
33
+
34
+
35
+ class PlanStopped(Exception):
36
+ """A limit was reached or a step failed with on_error=stop."""
37
+
38
+
39
+ PLAN_LIMITS = ("max_steps", "max_calls", "timeout_s") # the limits a plan may lower
40
+
41
+
42
+ @dataclass
43
+ class Limits:
44
+ max_steps: int = 1000
45
+ max_calls: int = 200
46
+ timeout_s: float = 120.0
47
+ max_items: int = 500 # paginate pages per step; for_each items per step and per plan
48
+ max_parallel: int = 8
49
+ max_result_chars: int = 20_000
50
+ retry_base_s: float = 1.0 # first wait before a retry; it doubles each time
51
+
52
+ def capped_by(self, requested: dict[str, Any] | None) -> Limits:
53
+ """A plan may lower these limits, never raise them. Other fields stay server-only."""
54
+ if not requested:
55
+ return self
56
+ out = Limits(**self.__dict__)
57
+ for k, v in requested.items():
58
+ if k in PLAN_LIMITS and isinstance(v, int | float) and not isinstance(v, bool) and v > 0:
59
+ setattr(out, k, min(getattr(out, k), v))
60
+ return out
61
+
62
+
63
+ # ---------------------------------------------------------------- validation
64
+
65
+
66
+ def _compile(expr: Any, where: str, errors: list[str]) -> None:
67
+ if not isinstance(expr, str):
68
+ errors.append(f"{where}: expression must be a string")
69
+ return
70
+ try:
71
+ jmespath.compile(expr)
72
+ except JMESPathError as e:
73
+ errors.append(f"{where}: bad JMESPath {expr!r}: {e}")
74
+
75
+
76
+ def _check_templates(value: Any, where: str, errors: list[str]) -> None:
77
+ if isinstance(value, str):
78
+ for m in TEMPLATE.finditer(value):
79
+ _compile(m.group(1).strip(), where, errors)
80
+ elif isinstance(value, dict):
81
+ for k, v in value.items():
82
+ _check_templates(v, f"{where}.{k}", errors)
83
+ elif isinstance(value, list):
84
+ for i, v in enumerate(value):
85
+ _check_templates(v, f"{where}[{i}]", errors)
86
+
87
+
88
+ def _targets(next_: Any, where: str, errors: list[str]) -> list[str]:
89
+ if next_ is None:
90
+ return []
91
+ if isinstance(next_, str):
92
+ return [next_]
93
+ if not isinstance(next_, list) or not next_:
94
+ errors.append(f"{where}.next: must be a step id or a non-empty list of branches")
95
+ return []
96
+ out = []
97
+ for i, b in enumerate(next_):
98
+ w = f"{where}.next[{i}]"
99
+ if not isinstance(b, dict):
100
+ errors.append(f"{w}: branch must be an object")
101
+ continue
102
+ if "if" in b:
103
+ _compile(b["if"], f"{w}.if", errors)
104
+ target = b.get("goto")
105
+ elif "else" in b:
106
+ if i != len(next_) - 1:
107
+ errors.append(f"{w}: 'else' must be the last branch")
108
+ target = b["else"]
109
+ else:
110
+ errors.append(f"{w}: branch needs 'if'+'goto' or 'else'")
111
+ continue
112
+ if not isinstance(target, str):
113
+ errors.append(f"{w}: the target must be a step id")
114
+ else:
115
+ out.append(target)
116
+ if "wait_s" in b and not _is_num(b["wait_s"]):
117
+ errors.append(f"{w}.wait_s: must be a number >= 0")
118
+ return out
119
+
120
+
121
+ def validate(plan: Any, tool_allowed: Callable[[str], str | None] | None = None) -> list[str]:
122
+ """Return a list of problems. An empty list means the plan can run.
123
+
124
+ `tool_allowed(name)` returns None if a tool may be used, or a reason if not.
125
+ """
126
+ errors: list[str] = []
127
+ if not isinstance(plan, dict):
128
+ return ["plan must be an object"]
129
+ _check_steps(plan, "plan.", "", set(), 0, tool_allowed, errors)
130
+ return errors
131
+
132
+
133
+ def _check_steps(plan: dict[str, Any], top: str, prefix: str, outer: set[str], depth: int,
134
+ tool_allowed: Callable[[str], str | None] | None, errors: list[str]) -> None:
135
+ """Check a plan or sub-plan. `outer` holds the names it can see from enclosing plans."""
136
+ steps = plan.get("steps")
137
+ if not isinstance(steps, dict) or not steps:
138
+ errors.append(f"{top}steps must be a non-empty object")
139
+ return
140
+ start = plan.get("start")
141
+ if not isinstance(start, str) or start not in steps:
142
+ errors.append(f"{top}start {start!r} is not a step id")
143
+ if not prefix and "limits" in plan and not isinstance(plan["limits"], dict):
144
+ errors.append(f"{top}limits must be an object")
145
+
146
+ for sid, step in steps.items():
147
+ w = f"{prefix}steps.{sid}"
148
+ if not STEP_ID.match(sid) or sid in RESERVED:
149
+ errors.append(f"{w}: step id must match [a-z_][a-z0-9_]* and not be 'input'")
150
+ if sid in outer:
151
+ errors.append(f"{w}: step id is already used by an outer step or loop variable")
152
+ if not isinstance(step, dict):
153
+ errors.append(f"{w}: step must be an object")
154
+ continue
155
+ kind = step_kind(step)
156
+ if kind is None:
157
+ errors.append(f"{w}: needs exactly one of call, for_each (+call or do), paginate, return")
158
+ continue
159
+
160
+ if kind == "return":
161
+ _check_templates_or_expr(step["return"], f"{w}.return", errors)
162
+ if "next" in step:
163
+ errors.append(f"{w}: a return step has no 'next'")
164
+ continue
165
+
166
+ sub = step.get("do")
167
+ if sub is None:
168
+ tool = step.get("paginate") if kind == "paginate" else step.get("call")
169
+ if not isinstance(tool, str):
170
+ errors.append(f"{w}: tool name must be a string")
171
+ elif tool_allowed is not None and (why := tool_allowed(tool)):
172
+ errors.append(f"{w}: tool {tool!r} {why}")
173
+ args = step.get("args", {})
174
+ if not isinstance(args, dict):
175
+ errors.append(f"{w}.args: must be an object")
176
+ _check_templates(args, f"{w}.args", errors)
177
+ else:
178
+ for key in ("args", "retry"):
179
+ if key in step:
180
+ errors.append(f"{w}.{key}: not allowed with 'do'; put it on the sub-plan's steps")
181
+ if step.get("on_error", "stop") not in ("stop", "skip"):
182
+ errors.append(f"{w}.on_error: must be 'stop' or 'skip'")
183
+ for key in ("parallel", "max_items", "max_pages"):
184
+ if key in step and not (_is_num(step[key]) and isinstance(step[key], int) and step[key] > 0):
185
+ errors.append(f"{w}.{key}: must be a whole number > 0")
186
+ if "retry" in step and not (_is_num(step["retry"]) and isinstance(step["retry"], int)
187
+ and step["retry"] <= 5):
188
+ errors.append(f"{w}.retry: must be a whole number from 0 to 5")
189
+
190
+ if kind == "for_each":
191
+ _compile(step["for_each"], f"{w}.for_each", errors)
192
+ var = step.get("as")
193
+ if (not isinstance(var, str) or not STEP_ID.match(var) or var in RESERVED
194
+ or var in steps or var in outer):
195
+ errors.append(f"{w}.as: needs a loop variable name; "
196
+ "it must not reuse a step id or outer name")
197
+ if sub is not None:
198
+ if depth >= MAX_DEPTH:
199
+ errors.append(f"{w}.do: sub-plans may nest at most {MAX_DEPTH} levels deep")
200
+ elif not isinstance(sub, dict):
201
+ errors.append(f"{w}.do: must be an object with start and steps")
202
+ else:
203
+ seen = outer | set(steps) | ({var} if isinstance(var, str) else set())
204
+ _check_steps(sub, f"{w}.do.", f"{w}.do.", seen, depth + 1, tool_allowed, errors)
205
+ if kind == "paginate":
206
+ for key in ("cursor_in", "cursor_out", "collect"):
207
+ if not isinstance(step.get(key), str):
208
+ errors.append(f"{w}.{key}: required string")
209
+ for key in ("cursor_out", "collect"):
210
+ if isinstance(step.get(key), str):
211
+ _compile(step[key], f"{w}.{key}", errors)
212
+
213
+ for t in _targets(step.get("next"), w, errors):
214
+ if t not in steps:
215
+ errors.append(f"{w}: next step {t!r} does not exist")
216
+
217
+
218
+ def _is_num(v: Any) -> bool:
219
+ return isinstance(v, int | float) and not isinstance(v, bool) and v >= 0
220
+
221
+
222
+ def _check_templates_or_expr(value: Any, where: str, errors: list[str]) -> None:
223
+ if isinstance(value, str) and not TEMPLATE.search(value):
224
+ _compile(value, where, errors)
225
+ else:
226
+ _check_templates(value, where, errors)
227
+
228
+
229
+ def step_kind(step: dict[str, Any]) -> str | None:
230
+ has = {k for k in KINDS if k in step}
231
+ if has == {"return"}:
232
+ return "return"
233
+ if has == {"call"}:
234
+ return "call"
235
+ if has in ({"for_each", "call"}, {"for_each", "do"}):
236
+ return "for_each"
237
+ if has == {"paginate"}:
238
+ return "paginate"
239
+ return None
240
+
241
+
242
+ # ---------------------------------------------------------------- evaluation
243
+
244
+
245
+ def evaluate(expr: str, ctx: dict[str, Any]) -> Any:
246
+ try:
247
+ return jmespath.search(expr, ctx)
248
+ except ValueError as e: # JMESPath raises plain ValueError for some inputs, e.g. slice step 0
249
+ raise PlanStopped(f"expression {expr!r} failed: {e}") from None
250
+
251
+
252
+ def render(value: Any, ctx: dict[str, Any]) -> Any:
253
+ """Fill {{expr}} templates. A string that is exactly one template keeps the native type."""
254
+ if isinstance(value, str):
255
+ found = list(TEMPLATE.finditer(value.strip()))
256
+ if len(found) == 1 and found[0].span() == (0, len(value.strip())):
257
+ return evaluate(found[0].group(1).strip(), ctx)
258
+ return TEMPLATE.sub(lambda m: _to_text(evaluate(m.group(1).strip(), ctx)), value)
259
+ if isinstance(value, dict):
260
+ return {k: render(v, ctx) for k, v in value.items()}
261
+ if isinstance(value, list):
262
+ return [render(v, ctx) for v in value]
263
+ return value
264
+
265
+
266
+ def _to_text(v: Any) -> str:
267
+ return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
268
+
269
+
270
+ def _truthy(v: Any) -> bool:
271
+ # JMESPath truthiness: false, null, "", [], {} are false. 0 is true.
272
+ return v not in (False, None, "", [], {})
273
+
274
+
275
+ # ---------------------------------------------------------------- execution
276
+
277
+
278
+ @dataclass
279
+ class _Run:
280
+ call_tool: CallFn
281
+ limits: Limits
282
+ calls: int = 0
283
+ steps: int = 0
284
+ items: int = 0 # for_each items across the whole run, all levels
285
+ trace: list[dict[str, Any]] = field(default_factory=list)
286
+ gate: asyncio.Semaphore = field(init=False) # calls in flight across the whole run
287
+
288
+ def __post_init__(self) -> None:
289
+ self.gate = asyncio.Semaphore(max(1, self.limits.max_parallel))
290
+
291
+ async def call(self, tool: str, args: dict[str, Any]) -> Any:
292
+ if self.calls >= self.limits.max_calls:
293
+ raise PlanStopped(f"max_calls ({self.limits.max_calls}) reached")
294
+ self.calls += 1
295
+ async with self.gate:
296
+ return await self.call_tool(tool, args)
297
+
298
+ async def call_retry(self, step: dict[str, Any], tool: str, args: dict[str, Any],
299
+ entry: dict[str, Any]) -> Any:
300
+ """Call a tool; on a ToolError, try again up to step["retry"] times with backoff."""
301
+ retry = step.get("retry", 0)
302
+ for attempt in range(retry + 1):
303
+ try:
304
+ return await self.call(tool, args)
305
+ except ToolError:
306
+ if attempt == retry:
307
+ raise
308
+ entry["retries"] = entry.get("retries", 0) + 1
309
+ await asyncio.sleep(self.limits.retry_base_s * 2 ** attempt)
310
+
311
+
312
+ async def run(plan: dict[str, Any], call_tool: CallFn, limits: Limits | None = None,
313
+ tool_allowed: Callable[[str], str | None] | None = None) -> dict[str, Any]:
314
+ """Validate and execute a plan. Never raises for plan problems: returns ok=False."""
315
+ errors = validate(plan, tool_allowed)
316
+ if errors:
317
+ return {"ok": False, "error": "invalid plan", "problems": errors}
318
+
319
+ lim = (limits or Limits()).capped_by(plan.get("limits"))
320
+ r = _Run(call_tool, lim)
321
+ ctx: dict[str, Any] = {"input": plan.get("input")}
322
+ try:
323
+ async with asyncio.timeout(lim.timeout_s):
324
+ result = await _execute(plan["steps"], plan["start"], ctx, r, r.trace)
325
+ out = {"ok": True, "result": result}
326
+ except TimeoutError:
327
+ out = {"ok": False, "error": f"timeout ({lim.timeout_s}s) reached"}
328
+ except (PlanStopped, ToolError, JMESPathError) as e:
329
+ out = {"ok": False, "error": str(e)}
330
+ out["calls"] = r.calls
331
+ out["trace"] = r.trace
332
+ return _cap(out, lim.max_result_chars)
333
+
334
+
335
+ async def _execute(steps: dict[str, Any], sid: str | None, ctx: dict[str, Any], r: _Run,
336
+ trace: list[dict[str, Any]]) -> Any:
337
+ """Run steps from `sid`. Each step's trace entry goes into `trace`."""
338
+ last: Any = None
339
+ while sid is not None:
340
+ if r.steps >= r.limits.max_steps:
341
+ raise PlanStopped(f"max_steps ({r.limits.max_steps}) reached at step {sid!r}")
342
+ r.steps += 1
343
+ step = steps[sid]
344
+ kind = step_kind(step)
345
+ t0 = time.monotonic()
346
+ calls0 = r.calls
347
+ entry: dict[str, Any] = {"step": sid}
348
+ trace.append(entry)
349
+
350
+ if kind == "return":
351
+ v = step["return"]
352
+ return evaluate(v, ctx) if isinstance(v, str) and not TEMPLATE.search(v) else render(v, ctx)
353
+
354
+ try:
355
+ if kind == "call":
356
+ last = await _call_step(step, ctx, r, entry)
357
+ elif kind == "for_each":
358
+ last = await _for_each(sid, step, ctx, r, entry)
359
+ else:
360
+ last = await _paginate(sid, step, ctx, r, entry)
361
+ except ToolError as e:
362
+ if step.get("on_error", "stop") == "stop":
363
+ raise ToolError(f"step {sid!r}: {e}") from None
364
+ entry["error"] = str(e)
365
+ last = None
366
+ ctx[sid] = last
367
+ entry["calls"] = r.calls - calls0
368
+ entry["ms"] = int((time.monotonic() - t0) * 1000)
369
+
370
+ sid, wait = _next(step.get("next"), ctx)
371
+ if wait:
372
+ await asyncio.sleep(wait)
373
+ return last
374
+
375
+
376
+ async def _call_step(step: dict[str, Any], ctx: dict[str, Any], r: _Run,
377
+ entry: dict[str, Any]) -> Any:
378
+ return await r.call_retry(step, step["call"], render(step.get("args", {}), ctx), entry)
379
+
380
+
381
+ async def _for_each(sid: str, step: dict[str, Any], ctx: dict[str, Any], r: _Run,
382
+ entry: dict[str, Any]) -> list[Any]:
383
+ items = evaluate(step["for_each"], ctx)
384
+ if not isinstance(items, list):
385
+ # null usually means a wrong path; fail loudly instead of looping over nothing
386
+ raise PlanStopped(f"step {sid!r}: for_each {step['for_each']!r} must give a list, "
387
+ f"got {type(items).__name__ if items is not None else 'null'}")
388
+ entry["items"] = len(items)
389
+ cap = min(step.get("max_items", r.limits.max_items), r.limits.max_items)
390
+ if len(items) > cap:
391
+ raise PlanStopped(f"step {sid!r}: {len(items)} items is more than max_items ({cap})")
392
+ if r.items + len(items) > r.limits.max_items:
393
+ raise PlanStopped(f"step {sid!r}: {len(items)} more items would pass the plan-wide limit of "
394
+ f"{r.limits.max_items} for_each items ({r.items} used so far)")
395
+ r.items += len(items)
396
+ sem = asyncio.Semaphore(max(1, min(step.get("parallel", 1), r.limits.max_parallel)))
397
+ skip = step.get("on_error", "stop") == "skip"
398
+ var = step["as"]
399
+ sub = step.get("do")
400
+
401
+ failed = False
402
+
403
+ async def one(item: Any) -> Any:
404
+ nonlocal failed
405
+ async with sem:
406
+ if failed: # an item failed while this one waited for a slot
407
+ raise asyncio.CancelledError
408
+ local = {**ctx, var: item}
409
+ try:
410
+ if sub is None:
411
+ return await r.call_retry(step, step["call"], render(step.get("args", {}), local), entry)
412
+ sub_trace: list[dict[str, Any]] = [] # kept out of the plan trace; only totals count
413
+ try:
414
+ return await _execute(sub["steps"], sub["start"], local, r, sub_trace)
415
+ finally:
416
+ _roll_up(sub_trace, entry)
417
+ except ToolError as e:
418
+ if skip:
419
+ _note_errors(entry, 1, str(e))
420
+ return {"error": str(e)}
421
+ failed = True
422
+ raise
423
+ except BaseException:
424
+ failed = True
425
+ raise
426
+
427
+ # A TaskGroup cancels the other items when one fails, so "stop" really stops.
428
+ try:
429
+ async with asyncio.TaskGroup() as tg:
430
+ tasks = [tg.create_task(one(i)) for i in items]
431
+ except BaseExceptionGroup as eg:
432
+ raise eg.exceptions[0] from None
433
+ return [t.result() for t in tasks]
434
+
435
+
436
+ def _note_errors(entry: dict[str, Any], n: int, msg: str | None) -> None:
437
+ entry["errors"] = entry.get("errors", 0) + n
438
+ if msg and "first_error" not in entry:
439
+ entry["first_error"] = msg[:200]
440
+
441
+
442
+ def _roll_up(sub_trace: list[dict[str, Any]], entry: dict[str, Any]) -> None:
443
+ """Add the retries and skipped errors of one sub-plan run to its for_each entry."""
444
+ for e in sub_trace:
445
+ if e.get("retries"):
446
+ entry["retries"] = entry.get("retries", 0) + e["retries"]
447
+ if "error" in e: # a skipped step
448
+ _note_errors(entry, 1, e["error"])
449
+ if e.get("errors"): # a nested for_each
450
+ _note_errors(entry, e["errors"], e.get("first_error"))
451
+
452
+
453
+ async def _paginate(sid: str, step: dict[str, Any], ctx: dict[str, Any], r: _Run,
454
+ entry: dict[str, Any]) -> list[Any]:
455
+ cap = min(step.get("max_pages", 20), r.limits.max_items)
456
+ args = render(step.get("args", {}), ctx)
457
+ out: list[Any] = []
458
+ pages = 0
459
+ cursor = None
460
+ while pages < cap:
461
+ page = await r.call_retry(step, step["paginate"], args, entry)
462
+ pages += 1
463
+ got = evaluate(step["collect"], page)
464
+ if isinstance(got, list):
465
+ out.extend(got)
466
+ elif got is not None:
467
+ out.append(got)
468
+ cursor = evaluate(step["cursor_out"], page)
469
+ if not cursor:
470
+ break
471
+ args = {**args, step["cursor_in"]: cursor}
472
+ entry["pages"] = pages
473
+ if cursor:
474
+ entry["truncated"] = f"stopped at max_pages ({cap}); more pages exist"
475
+ return out
476
+
477
+
478
+ def _next(next_: Any, ctx: dict[str, Any]) -> tuple[str | None, float]:
479
+ if next_ is None or isinstance(next_, str):
480
+ return next_, 0
481
+ for b in next_:
482
+ if "if" in b:
483
+ if _truthy(evaluate(b["if"], ctx)):
484
+ return b["goto"], float(b.get("wait_s", 0))
485
+ else:
486
+ return b["else"], float(b.get("wait_s", 0))
487
+ return None, 0 # no branch matched: the plan ends with the last value
488
+
489
+
490
+ def _cap(out: dict[str, Any], max_chars: int) -> dict[str, Any]:
491
+ try:
492
+ text = json.dumps(out.get("result"), ensure_ascii=False, default=str)
493
+ except (ValueError, TypeError, RecursionError) as e: # e.g. an int with more than 4300 digits
494
+ out.update(ok=False, result=None, error=f"result cannot be encoded as JSON: {type(e).__name__}")
495
+ return out
496
+ if len(text) > max_chars:
497
+ out["result"] = text[:max_chars]
498
+ out["truncated"] = f"result was {len(text)} chars, cut to {max_chars}; filter more in 'return'"
499
+ return out
File without changes