autobot-flow 0.3.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.
Files changed (42) hide show
  1. autobot_flow/__init__.py +27 -0
  2. autobot_flow/__main__.py +7 -0
  3. autobot_flow/actions/__init__.py +0 -0
  4. autobot_flow/actions/mcp.py +612 -0
  5. autobot_flow/actions/tools.py +171 -0
  6. autobot_flow/adapters/__init__.py +1 -0
  7. autobot_flow/adapters/base.py +52 -0
  8. autobot_flow/adapters/commands.py +406 -0
  9. autobot_flow/adapters/http.py +361 -0
  10. autobot_flow/adapters/mcp_base.py +94 -0
  11. autobot_flow/adapters/mcp_sdk.py +212 -0
  12. autobot_flow/adapters/registry.py +119 -0
  13. autobot_flow/app/__init__.py +0 -0
  14. autobot_flow/app/cli.py +421 -0
  15. autobot_flow/app/runner.py +353 -0
  16. autobot_flow/app/simulate.py +172 -0
  17. autobot_flow/app/starter.py +132 -0
  18. autobot_flow/app/workflow.py +278 -0
  19. autobot_flow/authority/__init__.py +0 -0
  20. autobot_flow/authority/policy.py +99 -0
  21. autobot_flow/compiler/__init__.py +1 -0
  22. autobot_flow/compiler/planner.py +110 -0
  23. autobot_flow/effects/__init__.py +0 -0
  24. autobot_flow/harness/__init__.py +1 -0
  25. autobot_flow/harness/agent.py +106 -0
  26. autobot_flow/harness/replies.py +29 -0
  27. autobot_flow/kernel/__init__.py +0 -0
  28. autobot_flow/py.typed +0 -0
  29. autobot_flow/spec/__init__.py +6 -0
  30. autobot_flow/spec/config.py +426 -0
  31. autobot_flow/spec/flow.py +105 -0
  32. autobot_flow/spec/mcp.py +161 -0
  33. autobot_flow/spec/schemas.py +383 -0
  34. autobot_flow/spec/values.py +505 -0
  35. autobot_flow/store/__init__.py +0 -0
  36. autobot_flow/store/runs.py +300 -0
  37. autobot_flow/testing/__init__.py +0 -0
  38. autobot_flow-0.3.0.dist-info/METADATA +212 -0
  39. autobot_flow-0.3.0.dist-info/RECORD +42 -0
  40. autobot_flow-0.3.0.dist-info/WHEEL +4 -0
  41. autobot_flow-0.3.0.dist-info/entry_points.txt +2 -0
  42. autobot_flow-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,27 @@
1
+ """autobot-flow: describe a workflow in plain text, and AI agents plan it and run it."""
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ __version__ = "0.3.0"
6
+
7
+ if TYPE_CHECKING:
8
+ from autobot_flow.actions.tools import ToolError, tool
9
+ from autobot_flow.app.workflow import Workflow
10
+ from autobot_flow.spec.values import FlowError
11
+
12
+ __all__ = ["FlowError", "ToolError", "Workflow", "__version__", "tool"]
13
+
14
+ _EXPORTS = {
15
+ "FlowError": "autobot_flow.spec.values",
16
+ "ToolError": "autobot_flow.actions.tools",
17
+ "Workflow": "autobot_flow.app.workflow",
18
+ "tool": "autobot_flow.actions.tools",
19
+ }
20
+
21
+
22
+ def __getattr__(name: str) -> Any:
23
+ if name not in _EXPORTS:
24
+ raise AttributeError(f"module 'autobot_flow' has no attribute {name!r}")
25
+ from importlib import import_module
26
+
27
+ return getattr(import_module(_EXPORTS[name]), name)
@@ -0,0 +1,7 @@
1
+ """Run with python -m autobot_flow."""
2
+
3
+ import sys
4
+
5
+ from autobot_flow.app.cli import main
6
+
7
+ sys.exit(main())
File without changes
@@ -0,0 +1,612 @@
1
+ """The MCP lock file and the checks that use it. This file never imports the ``mcp`` package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import os
9
+ import tempfile
10
+ import unicodedata
11
+ from collections.abc import Callable, Coroutine, Mapping, Sequence
12
+ from dataclasses import dataclass
13
+ from fnmatch import fnmatchcase
14
+ from pathlib import Path
15
+ from typing import Any, Literal, Protocol
16
+
17
+ from pydantic import BaseModel, JsonValue
18
+
19
+ from autobot_flow.actions.tools import Tool, ToolError
20
+ from autobot_flow.adapters.mcp_base import (
21
+ Connector,
22
+ McpCallError,
23
+ McpConnection,
24
+ McpOutcomeUnknown,
25
+ McpToolError,
26
+ RawResult,
27
+ RawTool,
28
+ )
29
+ from autobot_flow.spec.config import WorkflowConfig
30
+ from autobot_flow.spec.flow import Effect, Risk
31
+ from autobot_flow.spec.mcp import (
32
+ McpCatalog,
33
+ McpServer,
34
+ McpServerPin,
35
+ McpToolDef,
36
+ tool_digest,
37
+ transport_digest,
38
+ )
39
+ from autobot_flow.spec.schemas import check_schema
40
+ from autobot_flow.spec.values import FlowError, Problem, digest, load_model
41
+
42
+ __all__ = [
43
+ "LOCK_NAME",
44
+ "McpCaller",
45
+ "McpHub",
46
+ "build_tools",
47
+ "check_pinned",
48
+ "exposed_digest",
49
+ "is_exposed",
50
+ "load_catalog",
51
+ "pin_servers",
52
+ "printable",
53
+ "save_catalog",
54
+ "tool_authority",
55
+ ]
56
+
57
+ LOCK_NAME = "autobot.mcp.lock.json"
58
+
59
+
60
+ def _lock_error(path: str, message: str) -> FlowError:
61
+ return FlowError((Problem("E_MCP_LOCK", path, message),))
62
+
63
+
64
+ def load_catalog(path: Path) -> McpCatalog:
65
+ """Read the lock file; a missing file is an empty catalog."""
66
+ try:
67
+ data = path.read_bytes()
68
+ except FileNotFoundError:
69
+ return McpCatalog()
70
+ except OSError:
71
+ raise _lock_error("", "the lock file can't be read") from None
72
+ try:
73
+ return load_model(McpCatalog, data)
74
+ except FlowError as exc:
75
+ detail = "; ".join(p.message for p in exc.problems)
76
+ raise _lock_error(
77
+ "", f"the lock file is not valid ({detail}); run: autobot-flow mcp pin"
78
+ ) from None
79
+
80
+
81
+ def save_catalog(path: Path, catalog: McpCatalog) -> None:
82
+ """Write the lock file through a temporary file beside it, then replace it."""
83
+ text = json.dumps(catalog.model_dump(mode="json"), sort_keys=True, indent=2) + "\n"
84
+ handle, name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
85
+ try:
86
+ with os.fdopen(handle, "w", encoding="utf-8") as out:
87
+ out.write(text)
88
+ os.replace(name, path)
89
+ except BaseException:
90
+ Path(name).unlink(missing_ok=True)
91
+ raise
92
+
93
+
94
+ def check_pinned(config: WorkflowConfig, catalog: McpCatalog) -> None:
95
+ """Raise E_MCP_NOT_PINNED if a configured server is unpinned or its transport changed."""
96
+ problems: list[Problem] = []
97
+ for name, server in config.mcp.items():
98
+ pin = catalog.servers.get(name)
99
+ if pin is None:
100
+ message = f"MCP server '{name}' isn't pinned; run: autobot-flow mcp pin"
101
+ elif pin.transport != transport_digest(server):
102
+ message = f"MCP server '{name}' changed since it was pinned; run: autobot-flow mcp pin"
103
+ else:
104
+ continue
105
+ problems.append(Problem("E_MCP_NOT_PINNED", f"mcp.{name}", message))
106
+ if problems:
107
+ raise FlowError(problems)
108
+
109
+
110
+ def exposed_digest(config: WorkflowConfig, catalog: McpCatalog) -> str:
111
+ """A digest of the pinned tools the config exposes. Facts and timeouts don't affect it."""
112
+ out: dict[str, JsonValue] = {}
113
+ for name, server in sorted(config.mcp.items()):
114
+ pin: McpServerPin | None = catalog.servers.get(name)
115
+ tools = pin.tools if pin is not None else []
116
+ pairs = sorted(
117
+ (tool.name, tool.digest)
118
+ for tool in tools
119
+ if any(fnmatchcase(tool.name, pattern) for pattern in server.expose)
120
+ )
121
+ out[name] = [[tool_name, tool_digest_] for tool_name, tool_digest_ in pairs]
122
+ return digest(out)
123
+
124
+
125
+ class McpCaller(Protocol):
126
+ """Anything that can call a tool on a named MCP server."""
127
+
128
+ async def call(self, server: str, tool: str, arguments: dict[str, JsonValue]) -> JsonValue: ...
129
+
130
+
131
+ class _NoModel(BaseModel):
132
+ """Placeholder: MCP tools are checked with their own JSON Schema."""
133
+
134
+
135
+ _DESCRIPTION_LIMIT = 1000
136
+
137
+
138
+ def _strip_control(text: str) -> str:
139
+ """Drop non-printing and format characters, keeping newline and tab."""
140
+ return "".join(
141
+ ch for ch in text if ch in "\n\t" or not unicodedata.category(ch).startswith("C")
142
+ )
143
+
144
+
145
+ def _clean(text: str) -> str:
146
+ """Strip control characters, then cut to the description limit."""
147
+ return _strip_control(text)[:_DESCRIPTION_LIMIT]
148
+
149
+
150
+ def _facts(server: McpServer, tool_name: str) -> tuple[Effect, Risk]:
151
+ """Defaults are change/high; matching facts can lower them, and the safer value wins."""
152
+ effects: list[Effect] = []
153
+ risks: list[Risk] = []
154
+ for pattern, facts in server.facts.items():
155
+ if fnmatchcase(tool_name, pattern):
156
+ if facts.effect is not None:
157
+ effects.append(facts.effect)
158
+ if facts.risk is not None:
159
+ risks.append(facts.risk)
160
+ effect: Effect = "change" if not effects or "change" in effects else "read"
161
+ risk: Risk = "high" if not risks or "high" in risks else "low"
162
+ return effect, risk
163
+
164
+
165
+ def tool_authority(server: McpServer, tool_name: str) -> tuple[Effect, Risk]:
166
+ """The effect and risk the config gives a tool."""
167
+ return _facts(server, tool_name)
168
+
169
+
170
+ def is_exposed(server: McpServer, tool_name: str) -> bool:
171
+ """Whether the server's ``expose`` patterns include the tool."""
172
+ return any(fnmatchcase(tool_name, pattern) for pattern in server.expose)
173
+
174
+
175
+ def printable(text: str) -> str:
176
+ """Text safe to print: control and format characters removed."""
177
+ return _strip_control(text)
178
+
179
+
180
+ def _forwarder(
181
+ hub: McpCaller, server: str, tool: str
182
+ ) -> Callable[..., Coroutine[Any, Any, JsonValue]]:
183
+ async def invoke(**arguments: JsonValue) -> JsonValue:
184
+ return await hub.call(server, tool, arguments)
185
+
186
+ return invoke
187
+
188
+
189
+ def build_tools(config: WorkflowConfig, catalog: McpCatalog, hub: McpCaller) -> list[Tool]:
190
+ """One tool per pinned tool a server exposes. Server annotations never change anything."""
191
+ tools: list[Tool] = []
192
+ for name in sorted(config.mcp):
193
+ server = config.mcp[name]
194
+ pin = catalog.servers.get(name)
195
+ if pin is None:
196
+ continue
197
+ definitions: list[McpToolDef] = sorted(pin.tools, key=lambda item: item.name)
198
+ for item in definitions:
199
+ if not any(fnmatchcase(item.name, pattern) for pattern in server.expose):
200
+ continue
201
+ if check_schema(item.input_schema):
202
+ continue
203
+ effect, risk = _facts(server, item.name)
204
+ tools.append(
205
+ Tool(
206
+ f"mcp.{name}.{item.name}",
207
+ f"[MCP server {name}] " + _clean(item.description),
208
+ effect,
209
+ risk,
210
+ _NoModel,
211
+ _forwarder(hub, name, item.name),
212
+ item.input_schema,
213
+ f"mcp:{name}",
214
+ )
215
+ )
216
+ return tools
217
+
218
+
219
+ # --- the hub ----------------------------------------------------------------------------------
220
+
221
+ _RESULT_LIMIT = 50_000
222
+ _ERROR_TEXT_LIMIT = 300
223
+ _Scrub = Callable[[str], str]
224
+
225
+
226
+ def _scrubber(secrets: list[str]) -> _Scrub:
227
+ """Replace each secret value with ``[hidden]``. Longer secrets first, empty ones ignored."""
228
+ ordered = sorted({value for value in secrets if value}, key=len, reverse=True)
229
+
230
+ def scrub(text: str) -> str:
231
+ for secret in ordered:
232
+ text = text.replace(secret, "[hidden]")
233
+ return text
234
+
235
+ return scrub
236
+
237
+
238
+ def _scrub_json(value: JsonValue, scrub: _Scrub) -> JsonValue:
239
+ """Scrub every string inside a JSON value, leaving its shape and non-text leaves untouched."""
240
+ if isinstance(value, str):
241
+ return scrub(value)
242
+ if isinstance(value, list):
243
+ return [_scrub_json(item, scrub) for item in value]
244
+ if isinstance(value, dict):
245
+ return {key: _scrub_json(item, scrub) for key, item in value.items()}
246
+ return value
247
+
248
+
249
+ @dataclass
250
+ class _Request:
251
+ """One unit of work for a session's owner task; its future carries the reply or the error."""
252
+
253
+ kind: Literal["list", "call"]
254
+ name: str | None
255
+ arguments: dict[str, JsonValue] | None
256
+ timeout: float | None
257
+ future: asyncio.Future[Any]
258
+
259
+
260
+ class _Session:
261
+ """One connection to one server, owned by a single task.
262
+
263
+ The owner task enters ``async with connector(...)`` and then serves requests from a queue one
264
+ at a time, so a call is always made from the task that owns the connection and callers never
265
+ overlap. A caller that is cancelled mid-call does not touch the connection: its future is
266
+ cancelled, the owner finishes the in-flight call and discards the result, and the next caller
267
+ is served normally.
268
+ """
269
+
270
+ def __init__(
271
+ self, server: McpServer, connector: Connector, env: Mapping[str, str], scrub: _Scrub
272
+ ) -> None:
273
+ self._server = server
274
+ self._connector = connector
275
+ self._env = env
276
+ self.scrub = scrub
277
+ self.lock = asyncio.Lock()
278
+ self._loop = asyncio.get_running_loop()
279
+ self._queue: asyncio.Queue[_Request] = asyncio.Queue()
280
+ self._ready: asyncio.Future[None] = self._loop.create_future()
281
+ self._owner: asyncio.Task[None] | None = None
282
+ self._tools: list[RawTool] | None = None
283
+ self.verified: set[str] = set()
284
+
285
+ def start(self) -> None:
286
+ self._owner = self._loop.create_task(self._run())
287
+
288
+ async def ready(self) -> None:
289
+ await self._ready
290
+
291
+ async def _run(self) -> None:
292
+ try:
293
+ async with self._connector(self._server, self._env) as conn:
294
+ self._ready.set_result(None)
295
+ while True:
296
+ request = await self._queue.get()
297
+ await self._handle(conn, request)
298
+ except asyncio.CancelledError:
299
+ self._drain()
300
+ raise
301
+ except BaseException as exc: # entering the connection failed, before any request
302
+ if not self._ready.done():
303
+ self._ready.set_exception(exc)
304
+ self._drain()
305
+ return
306
+
307
+ async def _handle(self, conn: McpConnection, request: _Request) -> None:
308
+ try:
309
+ if request.kind == "list":
310
+ reply: object = await conn.list_tools()
311
+ else:
312
+ assert request.name is not None and request.timeout is not None
313
+ reply = await conn.call_tool(request.name, request.arguments or {}, request.timeout)
314
+ except asyncio.CancelledError:
315
+ request.future.cancel()
316
+ raise
317
+ except BaseException as exc:
318
+ if not request.future.done():
319
+ request.future.set_exception(exc)
320
+ return
321
+ if not request.future.done():
322
+ request.future.set_result(reply)
323
+
324
+ def _drain(self) -> None:
325
+ """Cancel every request still waiting in the queue, so no caller hangs on a dead owner."""
326
+ while not self._queue.empty():
327
+ self._queue.get_nowait().future.cancel()
328
+
329
+ async def _submit(self, request: _Request) -> Any:
330
+ if self._owner is None or self._owner.done():
331
+ # The owner task is gone, so nothing would ever resolve the future. Fail fast with an
332
+ # unclear outcome instead of hanging. (Normal flow reconnects before reaching here.)
333
+ raise McpCallError("the connection was closed before the request could be served")
334
+ self._queue.put_nowait(request)
335
+ try:
336
+ return await request.future
337
+ except asyncio.CancelledError:
338
+ request.future.cancel()
339
+ raise
340
+
341
+ async def ensure_listed(self) -> list[RawTool]:
342
+ if self._tools is None:
343
+ request = _Request("list", None, None, None, self._loop.create_future())
344
+ tools: list[RawTool] = await self._submit(request)
345
+ self._tools = tools
346
+ return self._tools
347
+
348
+ async def invoke(self, tool: str, arguments: dict[str, JsonValue], timeout: float) -> RawResult:
349
+ request = _Request("call", tool, arguments, timeout, self._loop.create_future())
350
+ result: RawResult = await self._submit(request)
351
+ return result
352
+
353
+ async def aclose(self) -> None:
354
+ owner, self._owner = self._owner, None
355
+ if owner is None:
356
+ return
357
+ owner.cancel()
358
+ with contextlib.suppress(asyncio.CancelledError, Exception):
359
+ await owner
360
+
361
+
362
+ class McpHub:
363
+ """Calls pinned MCP tools on configured servers, one connection and one call at a time.
364
+
365
+ The hub keeps a live session per server. Any failure before a request could have reached the
366
+ server (a bad start, a failed handshake or tool listing, or a tool that drifted from its pin)
367
+ is a plain ``ToolError``: nothing happened. Once a request is sent, every outcome -- a result
368
+ the server marks as an error, a crash, a timeout, a malformed reply -- is an
369
+ ``McpOutcomeUnknown``, never a ``ToolError``, and the call is never retried. Secrets named by
370
+ ``env_from``/``headers_from`` are scrubbed from every message and result.
371
+ """
372
+
373
+ def __init__(
374
+ self,
375
+ catalog: McpCatalog,
376
+ servers: Mapping[str, McpServer],
377
+ connector: Connector,
378
+ *,
379
+ root: Path,
380
+ environ: Mapping[str, str] | None = None,
381
+ ) -> None:
382
+ self._catalog = catalog
383
+ self._servers = servers
384
+ self._connector = connector
385
+ self._root = root
386
+ self._environ = environ
387
+ self._sessions: dict[str, _Session] = {}
388
+ self._lock = asyncio.Lock()
389
+
390
+ async def call(self, server: str, tool: str, arguments: dict[str, JsonValue]) -> JsonValue:
391
+ config = self._servers.get(server)
392
+ if config is None:
393
+ raise ToolError(f"there is no MCP server named '{server}'")
394
+ while True:
395
+ session = await self._session(server, config)
396
+ scrub = session.scrub
397
+ async with session.lock:
398
+ # A concurrent caller may have dropped this session (a failed call closes and
399
+ # removes it) between resolving it and taking its lock. Its owner task is then
400
+ # gone, so reconnect on a fresh session rather than hang on a dead queue.
401
+ if self._sessions.get(server) is not session:
402
+ continue
403
+ try:
404
+ tools = await session.ensure_listed()
405
+ except asyncio.CancelledError:
406
+ raise
407
+ except Exception as exc:
408
+ await self._drop(server, session)
409
+ raise ToolError(
410
+ f"MCP server '{server}' could not be listed: {_describe(exc, scrub)}"
411
+ ) from None
412
+ self._check_drift(server, tool, session, tools)
413
+ try:
414
+ result = await session.invoke(tool, arguments, config.timeout)
415
+ except asyncio.CancelledError:
416
+ raise
417
+ except McpOutcomeUnknown:
418
+ await self._drop(server, session)
419
+ raise # already an unclear result with a scrubbed message
420
+ except Exception as exc:
421
+ await self._drop(server, session)
422
+ raise McpCallError(f"{server}.{tool}: {_describe(exc, scrub)}") from None
423
+ if result.is_error:
424
+ text = _strip_control(scrub(result.text))[:_ERROR_TEXT_LIMIT]
425
+ raise McpToolError(f"{server}.{tool} reported an error: {text}")
426
+ return _shape(result, scrub)
427
+
428
+ async def close(self) -> None:
429
+ sessions = list(self._sessions.values())
430
+ self._sessions.clear()
431
+ for session in sessions:
432
+ await session.aclose()
433
+
434
+ async def _session(self, server: str, config: McpServer) -> _Session:
435
+ async with self._lock:
436
+ existing = self._sessions.get(server)
437
+ if existing is not None:
438
+ return existing
439
+ env = dict(self._environ if self._environ is not None else os.environ)
440
+ scrub = self._build_scrubber(server, config, env)
441
+ session = _Session(self._resolve(config), self._connector, env, scrub)
442
+ session.start()
443
+ try:
444
+ await session.ready()
445
+ except asyncio.CancelledError:
446
+ await session.aclose()
447
+ raise
448
+ except Exception as exc:
449
+ await session.aclose()
450
+ raise ToolError(
451
+ f"MCP server '{server}' is unavailable: {_describe(exc, scrub)}"
452
+ ) from None
453
+ self._sessions[server] = session
454
+ return session
455
+
456
+ def _build_scrubber(self, server: str, config: McpServer, env: Mapping[str, str]) -> _Scrub:
457
+ secrets: list[str] = []
458
+ names = [*config.env_from, *config.headers_from.values()]
459
+ for name in names:
460
+ if name not in env:
461
+ raise ToolError(
462
+ f"MCP server '{server}' needs the environment variable "
463
+ f"'{name}', which is not set"
464
+ )
465
+ secrets.append(env[name])
466
+ return _scrubber(secrets)
467
+
468
+ def _resolve(self, config: McpServer) -> McpServer:
469
+ if config.cwd is None:
470
+ return config
471
+ return config.model_copy(update={"cwd": str(self._root / config.cwd)})
472
+
473
+ def _check_drift(self, server: str, tool: str, session: _Session, tools: list[RawTool]) -> None:
474
+ if tool in session.verified:
475
+ return
476
+ pinned = self._pinned_digest(server, tool)
477
+ offered = {raw.name: raw for raw in tools}.get(tool)
478
+ current = (
479
+ tool_digest(offered.name, offered.description, offered.input_schema)
480
+ if offered is not None
481
+ else None
482
+ )
483
+ if pinned is None or current is None or current != pinned:
484
+ raise ToolError(
485
+ session.scrub(
486
+ f"the tool '{tool}' on server '{server}' changed since it was pinned; "
487
+ "review it and run: autobot-flow mcp pin"
488
+ )
489
+ )
490
+ session.verified.add(tool)
491
+
492
+ def _pinned_digest(self, server: str, tool: str) -> str | None:
493
+ pin = self._catalog.servers.get(server)
494
+ if pin is None:
495
+ return None
496
+ for definition in pin.tools:
497
+ if definition.name == tool:
498
+ return definition.digest
499
+ return None
500
+
501
+ async def _drop(self, server: str, session: _Session) -> None:
502
+ async with self._lock:
503
+ if self._sessions.get(server) is session:
504
+ del self._sessions[server]
505
+ await session.aclose()
506
+
507
+
508
+ def _describe(exc: BaseException, scrub: _Scrub) -> str:
509
+ """A short ``Type: message`` for an exception. Scrub before truncating so no secret fragment
510
+ can survive a cut; the type name carries no user data."""
511
+ message = _clean(scrub(str(exc)))
512
+ return f"{type(exc).__name__}: {message}" if message else type(exc).__name__
513
+
514
+
515
+ def _shape(result: RawResult, scrub: _Scrub) -> dict[str, JsonValue]:
516
+ """Success shape: ``text`` (scrubbed, cut, with omitted notes) and ``structured``, if present.
517
+
518
+ The raw text is scrubbed and cut to the limit first, then the omitted notes are appended, so a
519
+ note about a dropped part always survives even when the text itself was long enough to be cut.
520
+ """
521
+ out: dict[str, JsonValue] = {}
522
+ text = scrub(result.text)[:_RESULT_LIMIT]
523
+ if result.omitted:
524
+ notes = "\n".join(scrub(note) for note in result.omitted)
525
+ text = f"{text}\n{notes}" if text else notes
526
+ if text:
527
+ out["text"] = text
528
+ if result.structured is not None:
529
+ out["structured"] = _scrub_json(result.structured, scrub)
530
+ return out
531
+
532
+
533
+ # --- pinning ----------------------------------------------------------------------------------
534
+
535
+
536
+ async def _list_one(
537
+ name: str, server: McpServer, connector: Connector, root: Path, environ: Mapping[str, str]
538
+ ) -> tuple[McpServerPin | None, list[str]]:
539
+ """Connect to one server and list its tools. Returns no pin when the server can't be listed."""
540
+ secrets: list[str] = []
541
+ for var in [*server.env_from, *server.headers_from.values()]:
542
+ if var not in environ:
543
+ return None, [f"{name}: needs the environment variable '{var}', which is not set"]
544
+ secrets.append(environ[var])
545
+ scrub = _scrubber(secrets)
546
+ where = (
547
+ server if server.cwd is None else server.model_copy(update={"cwd": str(root / server.cwd)})
548
+ )
549
+ try:
550
+ async with connector(where, dict(environ)) as conn:
551
+ raw = await conn.list_tools()
552
+ except Exception as exc:
553
+ return None, [f"{name}: could not list the tools ({_describe(exc, scrub)})"]
554
+ problems: list[str] = []
555
+ tools: dict[str, McpToolDef] = {}
556
+ seen: set[str] = set()
557
+ for item in sorted(raw, key=lambda tool: tool.name):
558
+ if item.name in seen:
559
+ problems.append(f"{name}: the tool '{item.name}' is offered twice; left out")
560
+ tools.pop(item.name, None)
561
+ continue
562
+ seen.add(item.name)
563
+ bad = check_schema(item.input_schema)
564
+ if bad:
565
+ detail = "; ".join(p.message for p in bad[:3])
566
+ problems.append(f"{name}: the tool '{item.name}' has an unsupported schema ({detail})")
567
+ continue
568
+ tools[item.name] = McpToolDef(
569
+ name=item.name,
570
+ description=item.description,
571
+ input_schema=item.input_schema,
572
+ annotations=item.annotations,
573
+ digest=tool_digest(item.name, item.description, item.input_schema),
574
+ )
575
+ pin = McpServerPin(
576
+ transport=transport_digest(server), tools=[tools[key] for key in sorted(tools)]
577
+ )
578
+ return pin, [scrub(text) for text in problems]
579
+
580
+
581
+ async def pin_servers(
582
+ config: WorkflowConfig,
583
+ existing: McpCatalog,
584
+ connector: Connector,
585
+ *,
586
+ root: Path,
587
+ names: Sequence[str] = (),
588
+ environ: Mapping[str, str] | None = None,
589
+ ) -> tuple[McpCatalog, list[str]]:
590
+ """List the tools of the selected servers and pin them. Never calls a tool.
591
+
592
+ A server that can't be listed keeps its old pin and is reported; so does a tool whose schema
593
+ is unsupported or whose name is offered twice (it is left out of the pin).
594
+ """
595
+ unknown = [name for name in names if name not in config.mcp]
596
+ if unknown:
597
+ raise FlowError(
598
+ [
599
+ Problem("E_MCP_SERVER", f"mcp.{name}", f"no MCP server named '{name}'")
600
+ for name in unknown
601
+ ]
602
+ )
603
+ env = dict(environ if environ is not None else os.environ)
604
+ selected = set(names) if names else set(config.mcp)
605
+ servers = dict(existing.servers)
606
+ problems: list[str] = []
607
+ for name in sorted(selected):
608
+ pin, found = await _list_one(name, config.mcp[name], connector, root, env)
609
+ problems.extend(found)
610
+ if pin is not None:
611
+ servers[name] = pin
612
+ return McpCatalog(servers=servers), problems