toolsets.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. """Toolset helpers: get/resolve/validate named tool groups (static TOOLSETS + registry-registered)."""
  2. from typing import Dict, List, Any, Set, Optional, Tuple
  3. # Shared tool list for CLI and all messaging platform toolsets (edit once, all
  4. # platforms follow). Desktop GUI affordances are deliberately NOT here: they live
  5. # in `desktop_ui`/`project`, enabled per desktop-sourced session by the GUI gateway
  6. # (tui_gateway/server.py::_load_enabled_toolsets). HA, kanban and computer_use
  7. # entries are further gated by their tools' check_fns.
  8. _HERMES_CORE_TOOLS = [
  9. "web_search", "web_extract",
  10. "terminal", "process_manage",
  11. "read_file", "write_file", "patch", "search_files",
  12. "vision_analyze", "image_generate",
  13. "skills_list", "skill_view", "skill_manage",
  14. "browser_exec", # THE browser: Python over CDP (browser-harness)
  15. "browser_cdp", "browser_dialog",
  16. "browser_vault", # rides with the browser; deferred by default (tools.tool_search.defer)
  17. "text_to_speech",
  18. "todo_list", "memory",
  19. "session_search",
  20. "clarify",
  21. "execute_code", "delegate_task",
  22. "cronjob_manage",
  23. "kanban_show", "kanban_list",
  24. "kanban_complete", "kanban_block", "kanban_request_review",
  25. "kanban_request_changes",
  26. "kanban_heartbeat",
  27. "kanban_comment", "kanban_create", "kanban_link",
  28. "kanban_unblock",
  29. "kanban_attach", "kanban_attach_url", "kanban_attachments",
  30. "computer_use",
  31. # Service-gated connector account status and authorization links.
  32. "manage_connections",
  33. ]
  34. # Webhook payloads are untrusted third-party content: no file/system execution.
  35. _HERMES_WEBHOOK_SAFE_TOOLS = ["web_search", "web_extract", "vision_analyze", "clarify"]
  36. _FEISHU_TOOLS = [
  37. "feishu_doc_read", "feishu_drive_list_comments", "feishu_drive_list_comment_replies",
  38. "feishu_drive_reply_comment", "feishu_drive_add_comment",
  39. ]
  40. _YUANBAO_TOOLS = ["yb_query_group_info", "yb_query_group_members", "yb_send_dm", "yb_search_sticker", "yb_send_sticker"]
  41. def _ts(description, tools=(), includes=(), **extra):
  42. """One TOOLSETS entry (fresh lists per entry; extra keys such as posture pass through)."""
  43. return {"description": description, "tools": list(tools), "includes": list(includes), **extra}
  44. def _bundle(description, extras=()):
  45. """A `hermes-*` platform bundle: the shared core tools plus optional platform extras."""
  46. return _ts(description, _HERMES_CORE_TOOLS + list(extras))
  47. def _core_without(*excluded, kanban=True):
  48. """_HERMES_CORE_TOOLS minus *excluded* (and, unless kanban=True, every kanban_* tool); order preserved."""
  49. return [t for t in _HERMES_CORE_TOOLS if t not in excluded and (kanban or not t.startswith("kanban_"))]
  50. # Coding posture: everything you reach for while pairing on code; drops messaging,
  51. # tts, image_gen, cron, kanban and computer-use.
  52. _CODING_TOOLS = _core_without("image_generate", "text_to_speech", "cronjob_manage", "computer_use", kanban=False)
  53. # Toolsets a CLIENT adds to its own sessions (tui_gateway/server.py::_gui_surface_toolsets), never
  54. # config: another surface lacking them made no configuration choice.
  55. CLIENT_SURFACE_TOOLSETS = frozenset({"project", "desktop_ui", "catalog"})
  56. # Core toolset definitions: individual tools or references to other toolsets.
  57. TOOLSETS = {
  58. # Basic toolsets - individual tool categories
  59. "web": _ts("Web research and content extraction tools", ["web_search", "web_extract"]),
  60. "search": _ts("Web search only (no content extraction/scraping)", ["web_search"]),
  61. "x_search": _ts(
  62. "Search X (Twitter) posts and threads via xAI's built-in x_search Responses "
  63. "tool. Read-only public X discovery; use the xurl skill for authenticated X "
  64. "API reads and account actions. Available when xAI credentials are configured "
  65. "(SuperGrok OAuth or XAI_API_KEY). Off by default; enable in `hermes tools` → "
  66. "X (Twitter) Search.",
  67. ["x_search"],
  68. ),
  69. "vision": _ts("Image analysis and vision tools", ["vision_analyze"]),
  70. "video": _ts("Video analysis and understanding tools (opt-in, not in default toolset)", ["video_analyze"]),
  71. "image_gen": _ts("Creative generation tools (images)", ["image_generate"]),
  72. "video_gen": _ts(
  73. "Video generation tools. Single ``video_generate`` tool covers text-to-video "
  74. "(prompt only) and image-to-video (prompt + image_url), plus "
  75. "reference-to-video. Provider-specific edit/extend workflows may appear as "
  76. "separate tools. Configure via ``hermes tools`` → Video Generation.",
  77. ["video_generate", "xai_video_edit", "xai_video_extend"],
  78. ),
  79. "computer_use": _ts(
  80. "Background desktop control via cua-driver (macOS/Windows/Linux) — "
  81. "screenshots, mouse, keyboard, scroll, drag. Does NOT steal the user's cursor "
  82. "or keyboard focus. Works with any tool-capable model.",
  83. ["computer_use"],
  84. ),
  85. "terminal": _ts("Terminal/command execution and process management tools", ["terminal", "process_manage"]),
  86. "skills": _ts(
  87. "Access, create, edit, and manage skill documents with specialized "
  88. "instructions and knowledge",
  89. ["skills_list", "skill_view", "skill_manage"],
  90. ),
  91. # web_search belongs to `web`/`search` only. Listing it here too let
  92. # `disabled_toolsets: [browser]` (headless/Docker deployments) strip
  93. # web_search from every session, because disabled toolsets are a strict
  94. # end-of-pipeline subtraction (#17309, #64503).
  95. "browser": _ts(
  96. "Browser automation: drive a real browser with Python over CDP (navigate, "
  97. "click, type, extract, screenshots), raw CDP, dialogs and vault logins",
  98. [t for t in _HERMES_CORE_TOOLS if t.startswith("browser_")],
  99. ),
  100. "cronjob": _ts(
  101. "Cronjob management tool - create, list, update, pause, resume, remove, and "
  102. "trigger scheduled tasks",
  103. ["cronjob_manage"],
  104. ),
  105. "file": _ts(
  106. "File manipulation tools: read, write, patch (with fuzzy matching), and "
  107. "search (content + files)",
  108. ["read_file", "write_file", "patch", "search_files"],
  109. ),
  110. "tts": _ts("Text-to-speech: convert text to audio with Edge TTS (free), ElevenLabs, OpenAI, or xAI", ["text_to_speech"]),
  111. "todo": _ts("Task planning and tracking for multi-step work", ["todo_list"]),
  112. "memory": _ts("Persistent memory across sessions (personal notes + user profile)", ["memory"]),
  113. "context_engine": _ts("Runtime tools exposed by the active context engine"),
  114. "session_search": _ts("Search and recall past conversations with summarization", ["session_search"]),
  115. "connections": _ts("Remote connector discovery, execution, and account authorization", ["manage_connections"]),
  116. "project": _ts("Desktop Projects — create/switch named workspaces (GUI sessions only)", ["desktop_project"]),
  117. "bot_room": _ts("Verified text-only Group Chat turn capabilities"),
  118. # GUI-renderer affordances, enabled per desktop-sourced SESSION by the GUI
  119. # gateway (tui_gateway/server.py::_load_enabled_toolsets) — never by a
  120. # process env var, which is blind to a desktop client on a remote backend.
  121. "desktop_ui": _ts(
  122. "Desktop GUI affordances — in-app terminal/browser panes, pane focus, "
  123. "reactions, appearance (GUI sessions only)",
  124. ["read_terminal", "close_terminal", "desktop_preview", "drive_preview",
  125. "annotate_preview", "read_window_below", "focus_pane", "react_to_message",
  126. "gui_tour", "show_tip", "set_theme"],
  127. ),
  128. "onboarding": _ts("First-run onboarding cards; folded in only for the onboarding chat (tui_gateway/methods_onboarding.py)",
  129. ["setup_beat"], platforms=frozenset({"desktop"})),
  130. # ``platforms``: the session platforms this toolset exists for (TOOLSET_SESSION_PLATFORMS).
  131. "catalog": _ts(
  132. "Desktop catalog plugin/skill install requests through the approval card (GUI sessions only)",
  133. ["manage_catalog"],
  134. platforms=frozenset({"desktop"}),
  135. ),
  136. "clarify": _ts("Ask the user clarifying questions (multiple-choice or open-ended)", ["clarify"]),
  137. "code_execution": _ts("Run Python scripts that call tools programmatically (reduces LLM round trips)", ["execute_code"]),
  138. "delegation": _ts("Spawn subagents with isolated context for complex subtasks", ["delegate_task"]),
  139. "kanban": _ts(
  140. "Kanban multi-agent coordination — only active when the agent is spawned by "
  141. "the kanban dispatcher (HERMES_KANBAN_TASK env set). The dispatcher runs "
  142. "inside the gateway by default; see `kanban.dispatch_in_gateway` in "
  143. "config.yaml. Lets workers mark tasks done with structured handoffs, enter "
  144. "first-class review (request_review — not a block), return review changes, "
  145. "block for human input, heartbeat during long ops, comment on threads, attach "
  146. "files, and (for orchestrators) list, unblock, and fan out tasks.",
  147. [t for t in _HERMES_CORE_TOOLS if t.startswith("kanban_")],
  148. ),
  149. "discord": _ts("Discord read and participate tools (fetch messages, search members, create threads)", ["discord"]),
  150. "discord_admin": _ts("Discord server management (list channels/roles, pin messages, assign roles)", ["discord_admin"]),
  151. "yuanbao": _ts("Yuanbao platform tools - group info, member queries, DM, stickers", _YUANBAO_TOOLS),
  152. "feishu_doc": _ts("Read Feishu/Lark document content", ["feishu_doc_read"]),
  153. "feishu_drive": _ts("Feishu/Lark document comment operations (list, reply, add)", _FEISHU_TOOLS[1:]),
  154. # Scenario-specific toolsets
  155. "debugging": _ts("Debugging and troubleshooting toolkit", ["terminal", "process_manage"], includes=["web", "file"]),
  156. "safe": _ts("Safe toolkit without terminal access", [], includes=["web", "vision", "image_gen"]),
  157. # Coding posture, auto-selected in a code workspace (agent/coding_context.py).
  158. # `desktop_ui` is folded in separately by the GUI gateway for desktop sessions.
  159. # posture=True: per-session posture, never auto-recovered into platform tool
  160. # config (see the non-configurable-toolset recovery loop in hermes_cli/tools_config.py).
  161. "coding": _ts(
  162. "Coding-focused toolset: files, terminal, search, web docs, skills, todo, "
  163. "delegate, vision, browser",
  164. _CODING_TOOLS,
  165. posture=True,
  166. ),
  167. # Full Hermes toolsets (CLI + messaging platforms). All share the core tools;
  168. # there is deliberately no agent-callable send_message tool. hermes-acp is the
  169. # coding posture minus the interactive clarify UI.
  170. "hermes-acp": _ts(
  171. "Editor integration (VS Code, Zed, JetBrains) — coding-focused tools without "
  172. "messaging, audio, or clarify UI",
  173. [t for t in _CODING_TOOLS if t != "clarify"],
  174. ),
  175. "hermes-api-server": _ts(
  176. "OpenAI-compatible API server — full agent tools accessible via HTTP (no "
  177. "interactive UI tools like clarify or send_message)",
  178. _core_without("text_to_speech", "clarify", "computer_use", kanban=False),
  179. ),
  180. "hermes-cli": _bundle("Full interactive CLI toolset - all default tools plus cronjob management"),
  181. # Mirrors hermes-cli; `hermes tools` platform config filters it down and
  182. # _get_platform_tools() drops _DEFAULT_OFF_TOOLSETS unless user-enabled.
  183. "hermes-cron": _bundle("Default cron toolset - same core tools as hermes-cli; gated by `hermes tools`"),
  184. "hermes-telegram": _bundle("Telegram bot toolset - full access for personal use (terminal has safety checks)"),
  185. "hermes-discord": _bundle(
  186. "Discord bot toolset - full access (terminal has safety checks via dangerous "
  187. "command approval)",
  188. ["discord", "discord_admin"],
  189. ),
  190. "hermes-whatsapp": _bundle("WhatsApp bot toolset - similar to Telegram (personal messaging, more trusted)"),
  191. "hermes-slack": _bundle("Slack bot toolset - full access for workspace use (terminal has safety checks)"),
  192. "hermes-signal": _bundle("Signal bot toolset - encrypted messaging platform (full access)"),
  193. "hermes-bluebubbles": _bundle("BlueBubbles iMessage bot toolset - Apple iMessage via local BlueBubbles server"),
  194. "hermes-email": _bundle("Email bot toolset - interact with Hermes via email (IMAP/SMTP)"),
  195. "hermes-mattermost": _bundle("Mattermost bot toolset - self-hosted team messaging (full access)"),
  196. "hermes-matrix": _bundle("Matrix bot toolset - decentralized encrypted messaging (full access)"),
  197. "hermes-dingtalk": _bundle("DingTalk bot toolset - enterprise messaging platform (full access)"),
  198. "hermes-feishu": _bundle("Feishu/Lark bot toolset - enterprise messaging via Feishu/Lark (full access)", _FEISHU_TOOLS),
  199. "hermes-weixin": _bundle("Weixin bot toolset - personal WeChat messaging via iLink (full access)"),
  200. "hermes-qqbot": _bundle("QQBot toolset - QQ messaging via Official Bot API v2 (full access)"),
  201. "hermes-wecom": _bundle("WeCom bot toolset - enterprise WeChat messaging (full access)"),
  202. "hermes-wecom-callback": _bundle("WeCom callback toolset - enterprise self-built app messaging (full access)"),
  203. "hermes-yuanbao": {
  204. "description": "Yuanbao Bot 元宝消息平台工具集 - 群信息、成员查询、私聊、贴纸表情",
  205. "tools": _HERMES_CORE_TOOLS + _YUANBAO_TOOLS,
  206. "module": "tools.yuanbao_tools",
  207. "includes": [],
  208. },
  209. "hermes-sms": _bundle("SMS bot toolset - interact with Hermes via SMS (Twilio)"),
  210. "hermes-webhook": _ts("Webhook toolset - receive and process external webhook events", _HERMES_WEBHOOK_SAFE_TOOLS),
  211. "hermes-gateway": _ts(
  212. "Gateway toolset - union of all messaging platform tools",
  213. [],
  214. includes=[
  215. "hermes-telegram", "hermes-discord", "hermes-whatsapp", "hermes-slack",
  216. "hermes-signal", "hermes-bluebubbles", "hermes-email",
  217. "hermes-sms", "hermes-mattermost", "hermes-matrix", "hermes-dingtalk",
  218. "hermes-feishu", "hermes-wecom", "hermes-wecom-callback", "hermes-weixin",
  219. "hermes-qqbot", "hermes-webhook", "hermes-yuanbao",
  220. ],
  221. ),
  222. }
  223. # Toolset -> the session platforms it exists for, from the specs that carry ``platforms``.
  224. TOOLSET_SESSION_PLATFORMS = {name: spec["platforms"] for name, spec in TOOLSETS.items() if "platforms" in spec}
  225. # Captured before create_custom_toolset() can add user-named tools: shared metrics may export only
  226. # these names, so a plugin, MCP server or custom toolset name never leaves the machine.
  227. BUILTIN_TOOL_NAMES = frozenset(tool for spec in TOOLSETS.values() for tool in spec["tools"])
  228. BUILTIN_TOOLSET_NAMES = frozenset(TOOLSETS)
  229. def _registry():
  230. """Live tool registry, or None when tools.registry can't be imported."""
  231. try:
  232. from tools.registry import registry
  233. return registry
  234. except Exception:
  235. return None
  236. def _registry_call(method: str, default):
  237. """registry.<method>() or *default* when the registry is unavailable or the call fails."""
  238. try:
  239. return getattr(_registry(), method)()
  240. except Exception: # registry None (AttributeError) or the call failed
  241. return default
  242. def _registry_generation() -> tuple[int, int]:
  243. reg = _registry()
  244. return (id(reg), getattr(reg, "_generation", 0)) if reg is not None else (0, 0)
  245. def get_toolset(name: str, *, include_registry: bool = True) -> Optional[dict[str, Any]]:
  246. """Toolset definition, or None if unknown.
  247. include_registry=True merges plugin/overlay tools registered into this toolset
  248. and resolves registry-only (plugin/MCP) toolsets and aliases; False returns a
  249. copy of the static TOOLSETS entry only, so platform reverse-mapping is
  250. unaffected by registry additions.
  251. Args: name (str): Name of the toolset include_registry (bool): When True (default), merge in tools that
  252. plugins/overlays registered into this toolset via the registry. Platform reverse-mapping in
  253. ``_get_platform_tools`` uses False so that a tool registered into a toolset but absent from a platform's
  254. static composite does not drop the whole toolset from inference. See issue #49622.
  255. """
  256. toolset = TOOLSETS.get(name)
  257. if not include_registry:
  258. return {**toolset, "tools": list(toolset.get("tools", [])), "includes": list(toolset.get("includes", []))} if toolset else None
  259. registry = _registry()
  260. if registry is None:
  261. return toolset if toolset else None
  262. if toolset:
  263. merged_tools = set(toolset.get("tools", [])) | set(registry.get_tool_names_for_toolset(name))
  264. # An MCP server named like a built-in toolset ("browser", "memory") registers a bare
  265. # alias to its `mcp-<name>` toolset; without this union the static entry shadows it and the
  266. # server's tools never reach the model even though discovery registered them.
  267. alias_target = registry.get_toolset_alias_target(name)
  268. if alias_target and alias_target != name:
  269. merged_tools |= set(registry.get_tool_names_for_toolset(alias_target))
  270. return {**toolset, "tools": sorted(merged_tools)}
  271. if name in _get_plugin_toolset_names():
  272. # Plugin toolset; shown as its MCP server alias when one exists.
  273. registry_toolset = name
  274. alias = _display_alias(name, _get_registry_toolset_aliases())
  275. description = f"MCP server '{alias}' tools" if alias else f"Plugin toolset: {name}"
  276. else:
  277. registry_toolset = registry.get_toolset_alias_target(name)
  278. if not registry_toolset:
  279. return None
  280. description = f"MCP server '{name}' tools"
  281. return {"description": description, "tools": registry.get_tool_names_for_toolset(registry_toolset), "includes": []}
  282. def bundle_non_core_tools(toolset_name: str) -> set[str]:
  283. """A bundle's tools minus _HERMES_CORE_TOOLS (one level of includes).
  284. Disabling a `core + extras` bundle must not strip the core tools every other
  285. toolset shares. One `includes` pass suffices (only hermes-gateway nests
  286. bundles). Unknown names: full resolution minus core.
  287. """
  288. core = set(_HERMES_CORE_TOOLS)
  289. ts_def = get_toolset(toolset_name)
  290. if not (ts_def and "tools" in ts_def):
  291. return set(resolve_toolset(toolset_name)) - core
  292. to_remove = set(ts_def["tools"])
  293. for inc_def in map(get_toolset, ts_def.get("includes", [])):
  294. if inc_def and "tools" in inc_def:
  295. to_remove.update(inc_def["tools"])
  296. return to_remove - core
  297. # Memo keyed on (name, include_registry, id(registry), registry generation, profile scope);
  298. # engages only at the public entry (visited is None). The scope is part of the key because a
  299. # multiplexed process resolves ``mcp-<server>`` per profile overlay: without it profile B got
  300. # profile A's tool names for a server B never connected (#106005).
  301. _resolve_toolset_memo: dict[tuple[str, bool, int, int, str], list[str]] = {}
  302. def _plugin_platform_bundle(name: str) -> list[str]:
  303. """Implicit `hermes-<platform>` bundle for a registered plugin platform: core
  304. tools plus whatever the plugin registered under the platform name. [] otherwise."""
  305. if not name.startswith("hermes-"):
  306. return []
  307. platform_name = name[len("hermes-"):]
  308. try:
  309. from gateway.platform_registry import platform_registry
  310. if not platform_registry.is_registered(platform_name):
  311. return []
  312. except Exception:
  313. return []
  314. tools = set(_HERMES_CORE_TOOLS)
  315. try:
  316. tools.update(e.name for e in _registry_call("get_all_entries", ()) if e.toolset == platform_name)
  317. except Exception:
  318. pass
  319. return list(tools)
  320. def resolve_toolset(name: str, visited: set[str] | None = None, *, include_registry: bool = True) -> list[str]:
  321. """Recursively resolve a toolset (and its includes) to a sorted tool-name list.
  322. include_registry=False resolves the static TOOLSETS view only.
  323. Args: name (str): Name of the toolset to resolve visited (Set[str]): Set of already visited toolsets
  324. (for cycle detection) include_registry (bool): When True (default), include tools that plugins/overlays
  325. registered into a toolset. Platform reverse-mapping uses False so a registry-added tool cannot drop the
  326. whole toolset from inference (see #49622 and ``_get_platform_tools``).
  327. """
  328. external_call = visited is None
  329. if external_call:
  330. memo_key = (name, include_registry, *_registry_generation(), _registry_call("current_scope_key", ""))
  331. cached = _resolve_toolset_memo.get(memo_key)
  332. if cached is not None:
  333. return list(cached)
  334. visited = set()
  335. # "all"/"*" span every toolset so new toolsets are included automatically, except the ones a
  336. # session platform gates: a profile gets those only when its config names them.
  337. if name in {"all", "*"}:
  338. all_tools: set[str] = set()
  339. for toolset_name in get_toolset_names():
  340. if toolset_name not in TOOLSET_SESSION_PLATFORMS:
  341. all_tools.update(resolve_toolset(toolset_name, visited.copy(), include_registry=include_registry))
  342. return sorted(all_tools)
  343. # Diamond include or cycle: [] silently — the tools are collected via another path.
  344. if name in visited:
  345. return []
  346. visited.add(name)
  347. toolset = get_toolset(name, include_registry=include_registry)
  348. if not toolset:
  349. return _plugin_platform_bundle(name) if include_registry else []
  350. tools = set(toolset.get("tools", []))
  351. for included_name in toolset.get("includes", []):
  352. tools.update(resolve_toolset(included_name, visited, include_registry=include_registry))
  353. result = sorted(tools)
  354. if external_call:
  355. if len(_resolve_toolset_memo) >= 256: # stale-generation entries are never hit again
  356. _resolve_toolset_memo.clear()
  357. _resolve_toolset_memo[memo_key] = list(result)
  358. return result
  359. def _get_plugin_toolset_names() -> set[str]:
  360. """Registry toolset names absent from the static TOOLSETS dict."""
  361. return {n for n in _registry_call("get_registered_toolset_names", ()) if n not in TOOLSETS}
  362. def _get_registry_toolset_aliases() -> dict[str, str]:
  363. return _registry_call("get_registered_toolset_aliases", {})
  364. def _display_alias(ts_name: str, aliases: dict[str, str]) -> Optional[str]:
  365. """First non-static alias pointing at *ts_name*, or None."""
  366. return next((a for a, canonical in aliases.items() if canonical == ts_name and a not in TOOLSETS), None)
  367. def _plugin_display_names() -> list[str]:
  368. """Plugin toolset names, shown under their first non-static alias when one exists."""
  369. aliases = _get_registry_toolset_aliases()
  370. return [_display_alias(n, aliases) or n for n in _get_plugin_toolset_names()]
  371. def get_all_toolsets() -> dict[str, dict[str, Any]]:
  372. """All toolset definitions: static plus plugin-registered."""
  373. result = dict(TOOLSETS)
  374. aliases = _get_registry_toolset_aliases()
  375. for display_name in _plugin_display_names():
  376. toolset = None if display_name in result else get_toolset(display_name)
  377. if toolset:
  378. result[display_name] = toolset
  379. # Static names an MCP server also aliases show the merged view get_toolset() resolves.
  380. for name in TOOLSETS.keys() & aliases.keys():
  381. result[name] = get_toolset(name) or result[name]
  382. return result
  383. def get_toolset_names() -> list[str]:
  384. """Sorted names of all toolsets (static + plugin), excluding aliases."""
  385. return sorted(set(TOOLSETS.keys()) | set(_plugin_display_names()))
  386. def session_platform_tool_drops(platform: Optional[str]) -> frozenset:
  387. """Tools of every platform-gated toolset that a session on *platform* does not get."""
  388. return frozenset(tool for name, platforms in TOOLSET_SESSION_PLATFORMS.items() if platform not in platforms
  389. for tool in resolve_toolset(name))
  390. def session_disabled_toolsets(
  391. disabled: Optional[list[str]], platform: Optional[str], *, oneshot: bool = False,
  392. ) -> Optional[list[str]]:
  393. """*disabled* plus every platform-gated toolset a session on *platform* does not get, and for a *oneshot*
  394. session the toolsets nobody is there to use (``agent.oneshot_footprint.ONESHOT_DISABLED_TOOLSETS``). An agent
  395. stores this as its ``disabled_toolsets``, so the tool list, the tool_search listing and bridge, MCP refreshes
  396. and delegate children (which inherit it) all subtract the gated tools in ``_select_tool_names``."""
  397. from agent.oneshot_footprint import ONESHOT_DISABLED_TOOLSETS
  398. gated = [name for name, platforms in TOOLSET_SESSION_PLATFORMS.items() if platform not in platforms]
  399. gated += ONESHOT_DISABLED_TOOLSETS if oneshot else ()
  400. gated = [name for name in gated if name not in (disabled or ())]
  401. return [*(disabled or ()), *gated] if gated else disabled
  402. def tool_selection_key(enabled: Optional[list[str]], disabled: Optional[list[str]]) -> tuple:
  403. """The toolset selection a tools[] snapshot was built from, order-free. Recorded next to the registry
  404. generation: the tools[] freeze (``tools.mcp_tool_agent``) holds new tools back only while neither moved."""
  405. return frozenset(enabled) if enabled is not None else None, frozenset(disabled or ())
  406. def agent_tool_drops(agent: Any) -> frozenset:
  407. """Tool names *agent* never carries, whatever its toolsets resolved to: the side-agent drops and
  408. the toolsets its session platform does not get. Applied at load, MCP refresh and prefix restore."""
  409. from tools.connectors.turn import side_agent_tool_drops
  410. return side_agent_tool_drops(agent) | session_platform_tool_drops(getattr(agent, "platform", None))
  411. def agent_tool_surface(agent: Any, tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
  412. """*tools* as *agent* carries them: :func:`agent_tool_drops` removed and, in a one-shot session or a gateway
  413. session that joins its delegations in the turn (``delegation.gateway_mode``), the joined ``delegate_task``
  414. variant (``agent.oneshot_footprint.oneshot_tool_schemas``). Applied to FRESH definitions (load, MCP refresh)
  415. before any merge: a pinned or carried entry keeps the bytes already sent."""
  416. from agent.oneshot_footprint import agent_is_oneshot, oneshot_tool_schemas
  417. from tools.delegate_tool_config import agent_joins_delegation
  418. drops = agent_tool_drops(agent)
  419. tools = [tool for tool in tools if (tool.get("function") or {}).get("name") not in drops] if drops else list(tools)
  420. return oneshot_tool_schemas(tools) if agent_is_oneshot(agent) or agent_joins_delegation(agent) else tools
  421. def validate_toolset(name: str) -> bool:
  422. return (name in {"all", "*"} or name in TOOLSETS
  423. or name in _get_plugin_toolset_names() or name in _get_registry_toolset_aliases())
  424. def create_custom_toolset(name: str, description: str, tools: list[str] | None = None, includes: list[str] | None = None) -> None:
  425. """Register a runtime toolset in TOOLSETS."""
  426. TOOLSETS[name] = _ts(description, tools or [], includes or [])
  427. def get_toolset_info(name: str) -> dict[str, Any]:
  428. """Toolset definition plus its resolved tools, or None if unknown."""
  429. toolset = get_toolset(name)
  430. if not toolset:
  431. return None
  432. resolved_tools = resolve_toolset(name)
  433. return {
  434. "name": name, "description": toolset["description"],
  435. "direct_tools": toolset["tools"], "includes": toolset["includes"],
  436. "resolved_tools": resolved_tools, "tool_count": len(resolved_tools),
  437. "is_composite": bool(toolset["includes"]),
  438. }