mcp_tool_agent.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. """Live-agent tool-list maintenance after MCP (re)discovery: refreshing an
  2. AIAgent's tools/tool names, preserving the cached tools[] prefix across rebuilds,
  3. and re-injecting post-build tools."""
  4. import logging
  5. import json
  6. import threading
  7. from collections import OrderedDict
  8. from typing import Optional
  9. from tools.mcp_tool_common import _core
  10. logger = logging.getLogger("tools.mcp_tool")
  11. # Serializes in-place swaps of ``agent.tools`` / ``agent.valid_tool_names`` by
  12. # the reload RPC, gateway reload and late-binding refresh thread; the run loop
  13. # reads them during tool iteration and must never see a half-updated pair.
  14. _agent_tools_lock = threading.Lock()
  15. # (profile home, session id) -> (registry generation, toolset selection) of the tools[] this process last
  16. # pinned for that session. A rebuild from the pin in the SAME process (agent-cache eviction, ``/model``, a
  17. # fresh agent per turn) is the same conversation and gets the freeze test the between-turns refresh applies.
  18. # Another process (``--resume`` there, a fresh worker) has no entry: its generation counter is unrelated, so
  19. # it cannot tell a check_fn flip from a registration and appends as before. Bounded, oldest first.
  20. _PINNED_SNAPSHOTS: "OrderedDict[tuple, tuple]" = OrderedDict()
  21. _PINNED_SNAPSHOTS_MAX = 4096
  22. def _def_name(tool_def: dict) -> str:
  23. return (tool_def.get("function") or {}).get("name", "")
  24. def _agent_tool_defs(agent) -> list:
  25. return list(getattr(agent, "tools", None) or [])
  26. def agent_tool_names(agent) -> list:
  27. """Names of ``agent.tools`` in wire order (unnamed entries skipped)."""
  28. return [name for name in map(_def_name, _agent_tool_defs(agent)) if name]
  29. def _resolve_refresh_toolsets(agent, enabled_override, disabled_override):
  30. """Explicit reloads pass freshly-resolved toolsets (so a server just ENABLED in config is
  31. picked up) and the agent's selection is updated to match; automatic paths pass nothing
  32. and reuse the build-time selection."""
  33. enabled = getattr(agent, "enabled_toolsets", None)
  34. disabled = getattr(agent, "disabled_toolsets", None)
  35. if enabled_override is not None or disabled_override is not None:
  36. enabled = enabled_override if enabled_override is not None else enabled
  37. if disabled_override is not None:
  38. from agent.oneshot_footprint import agent_is_oneshot
  39. from toolsets import session_disabled_toolsets
  40. agent._configured_disabled_toolsets = disabled_override
  41. disabled = session_disabled_toolsets(
  42. disabled_override, getattr(agent, "platform", None), oneshot=agent_is_oneshot(agent))
  43. agent.enabled_toolsets, agent.disabled_toolsets = enabled, disabled
  44. return enabled, disabled
  45. def _tool_defs_content_changed(agent, new_defs: list) -> bool:
  46. """Byte-level diff of the serialized tool arrays (dynamic schemas change CONTENT under
  47. stable names); False if either side fails to serialize."""
  48. try:
  49. dump = lambda defs: json.dumps(defs, sort_keys=True, separators=(",", ":"), default=str)
  50. return dump(_agent_tool_defs(agent)) != dump(new_defs)
  51. except Exception:
  52. return False
  53. def _drop_session_tools(agent, new_defs: list, new_names: set) -> tuple:
  54. # Drops only: runs after a merge, where a carried or pinned entry keeps the bytes already sent. The one-shot
  55. # schema variants (``toolsets.agent_tool_surface``) shape fresh definitions, before any merge.
  56. from toolsets import agent_tool_drops
  57. drops = agent_tool_drops(agent)
  58. if not drops:
  59. return new_defs, new_names
  60. return [entry for entry in new_defs if _def_name(entry) not in drops], new_names - drops
  61. def _frozen_tool_names(registered: set) -> frozenset:
  62. """Names the tools[] freeze holds back: every name availability alone can bring into a build,
  63. the registered tools and the Tool Search bridge ``assemble_tool_defs`` adds once anything defers."""
  64. from tools.tool_search_catalog import BRIDGE_TOOL_NAMES
  65. return frozenset(registered) | frozenset(BRIDGE_TOOL_NAMES)
  66. def _publish_tool_snapshot(
  67. agent, new_defs: list, new_names: set, *, snapshot_generation: int, built_generation: int, selection: tuple,
  68. staged_engine_names: set, content_aware: bool, prefix_registered: Optional[set]) -> Optional[set]:
  69. """Single atomic read-diff-publish under ``_agent_tools_lock`` so ``added`` matches what
  70. was published and a stale (older-generation) rebuild can't overwrite a newer one. Returns
  71. the added names, or None when nothing was published (unchanged, or a newer snapshot won)."""
  72. with _agent_tools_lock:
  73. # Tolerate an agent that never set the generation (or a non-int mock).
  74. published_gen = getattr(agent, "_tool_snapshot_generation", -1)
  75. published_gen = published_gen if isinstance(published_gen, int) else -1
  76. if snapshot_generation < published_gen:
  77. return None # a newer snapshot already won
  78. current_defs = _agent_tool_defs(agent)
  79. current = {_def_name(t) for t in current_defs}
  80. if prefix_registered is not None:
  81. # Neither the registry (read after the build) nor the toolset selection moved since the last
  82. # snapshot: a name can only be new here because a check_fn flipped, and tools[] stays frozen
  83. # for that (#101367). A registration or a widened selection appends as before.
  84. recorded_selection = getattr(agent, "_tool_snapshot_selection", None)
  85. frozen = built_generation == published_gen and selection == recorded_selection
  86. held = _frozen_tool_names(prefix_registered) if frozen else frozenset()
  87. new_defs, new_names = _merge_preserving_prefix(current_defs, new_defs, prefix_registered, held)
  88. new_defs, new_names = _drop_session_tools(agent, new_defs, new_names)
  89. # Record the generation (the one read BEFORE the build: a registration that landed during it may
  90. # be missing from these definitions) and selection even when unchanged, so an in-flight older
  91. # caller can't clobber.
  92. agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
  93. agent._tool_snapshot_selection = selection
  94. # Same name set: nothing to publish, unless the caller is content_aware
  95. # (explicit reload, compaction) and the serialized schema bytes moved.
  96. if new_names == current and not (content_aware and _tool_defs_content_changed(agent, new_defs)):
  97. return None
  98. agent.tools = new_defs
  99. agent.valid_tool_names = new_names
  100. # Publish context-engine routing names atomically with the snapshot.
  101. engine_names = getattr(agent, "_context_engine_tool_names", None)
  102. if isinstance(engine_names, set):
  103. engine_names.clear()
  104. engine_names.update(staged_engine_names)
  105. return new_names - current
  106. def refresh_agent_mcp_tools(
  107. agent, *, enabled_override=None, disabled_override=None, quiet_mode: bool = True,
  108. content_aware: bool = False, preserve_prefix: bool = False) -> set:
  109. """Re-derive an already-built agent's tool snapshot from the live registry; returns the
  110. newly-added tool names (empty when unchanged). The agent snapshots ``agent.tools`` at build
  111. time, so servers that connect later (slow OAuth, ``/reload-mcp``) are invisible until
  112. rebuilt. Shared by the TUI RPC, gateway reload, late-binding thread and between-turns
  113. refresh: respects the toolset filter, diffs by tool NAME (a count compare misses an
  114. equal-size swap) and, for ``content_aware`` callers, by serialized schema bytes, re-injects the memory-provider / context-engine tools ``agent_init``
  115. appends after ``get_tool_definitions`` plus guarded session capabilities, and publishes
  116. ``(tools, valid_tool_names)`` together.
  117. ``preserve_prefix``: for rebuilds inside a live conversation the tool array is a cached
  118. request prefix and any moved byte re-prefills the whole history — existing tools keep their
  119. slot and the schema bytes already sent (a refreshed description is rendered ahead of the
  120. conversation), a still-registered tool whose ``check_fn`` merely flapped is carried forward
  121. (``check_fn`` gates exposure, never invocation), a deregistered tool is dropped, new tools
  122. append at the tail, unless neither the registry generation nor the toolset selection moved since
  123. the last snapshot: then only a ``check_fn`` flip can bring a name in, and tools[] stays frozen for
  124. it (bridge tools included). The caller owns the prompt-cache contract.
  125. With ``preserve_prefix`` off (explicit ``/reload-mcp``, and a rebuild before the
  126. first turn) a same-name schema change is published. The caller has already
  127. accepted the cache break, or nothing has been cached yet."""
  128. from model_tools import get_tool_definitions
  129. from tools.registry import registry
  130. from toolsets import agent_tool_surface, tool_selection_key
  131. enabled, disabled = _resolve_refresh_toolsets(agent, enabled_override, disabled_override)
  132. # Generation captured BEFORE the slow get_tool_definitions call (a slower caller holding an
  133. # OLDER set must not clobber a newer one); definitions computed OUTSIDE the lock.
  134. snapshot_generation = registry._generation
  135. from agent.delegation_backends import adopt_built_backend, saved_backend
  136. built_backend = saved_backend()
  137. new_defs = agent_tool_surface(agent, list(
  138. get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=quiet_mode) or []))
  139. new_names = {_def_name(t) for t in new_defs}
  140. # Post-build families re-appended on LOCALS only; live attributes untouched until publish.
  141. staged_engine_names = _reinject_post_build_tools(agent, new_defs, new_names)
  142. _reinject_authorized_dynamic_tools(agent, new_defs, new_names)
  143. # Registry membership is read OUTSIDE ``_agent_tools_lock``: taking ``registry._lock``
  144. # under the tools lock would be the first nesting of the two.
  145. prefix_registered: Optional[set] = None
  146. if preserve_prefix:
  147. try:
  148. prefix_registered = {entry.name for entry in registry.get_all_entries()}
  149. except Exception:
  150. pass # fail open to the plain rebuild
  151. else:
  152. # Explicit reload and pre-first-turn rebuild. A same-name description
  153. # change has to publish; between-turns refresh keeps preserve_prefix.
  154. content_aware = True
  155. # Read after the build and the membership read: a registration that landed meanwhile counts as one.
  156. built_generation = registry._generation
  157. added = _publish_tool_snapshot(
  158. agent, new_defs, new_names, snapshot_generation=snapshot_generation, built_generation=built_generation,
  159. selection=tool_selection_key(enabled, disabled), staged_engine_names=staged_engine_names,
  160. content_aware=content_aware, prefix_registered=prefix_registered)
  161. backend_before = getattr(agent, "_delegation_backend", None)
  162. published_gen = getattr(agent, "_tool_snapshot_generation", -1)
  163. stale = isinstance(published_gen, int) and snapshot_generation < published_gen # a newer snapshot won
  164. if prefix_registered is None and not stale: # a rebuild: route on the backend its new delegate_task is from
  165. adopt_built_backend(agent, new_defs, built_backend)
  166. if added is None:
  167. if getattr(agent, "_delegation_backend", None) != backend_before:
  168. persist_agent_tool_names(agent) # only the backend moved (two backends build one schema): pin it
  169. return set()
  170. persist_agent_tool_names(agent) # re-pin so a rebuild after agent-cache eviction restores this order
  171. return added
  172. def reprobe_tool_availability() -> None:
  173. """Explicit ``/reload-mcp`` hatch out of the tools[] freeze: drop the ``check_fn`` verdict
  174. cache AND the ``get_tool_definitions`` memo (keyed on registry generation, so it would
  175. otherwise replay the stale verdicts)."""
  176. from model_tools import _clear_tool_defs_cache
  177. from tools.registry import invalidate_check_fn_cache
  178. invalidate_check_fn_cache()
  179. _clear_tool_defs_cache()
  180. def tool_pin_version() -> str:
  181. """The code identity a tools[] pin was built by (checkout/build sha, else the release version).
  182. Cached per process: an updated checkout only reaches a process through a restart."""
  183. from hermes_cli import __version__
  184. from hermes_cli.build_info import get_code_identity
  185. identity = get_code_identity()
  186. return identity.get("sha") or identity.get("version") or __version__
  187. def persist_agent_tool_names(agent) -> None:
  188. """Best-effort: write ``agent.tools`` to the session row (freeze pin). The full definitions,
  189. keyed by the code that built them: another process or surface derives different bytes."""
  190. db = getattr(agent, "_session_db", None)
  191. session_id = getattr(agent, "session_id", None)
  192. if not db or not session_id:
  193. return
  194. try:
  195. pin = {"version": tool_pin_version(), "tools": _agent_tool_defs(agent)}
  196. if isinstance(backend := getattr(agent, "_delegation_backend", None), str) and backend:
  197. pin["delegation_backend"] = backend # what its delegate_task was built from: the session routes on it
  198. db.update_session_tool_names(session_id, pin)
  199. except Exception:
  200. logger.debug("tool_names persist skipped", exc_info=True)
  201. return
  202. _record_pinned_snapshot(agent, session_id)
  203. def _pinned_snapshot_key(session_id) -> tuple:
  204. from hermes_constants import hermes_home_key
  205. return hermes_home_key(), str(session_id)
  206. def _record_pinned_snapshot(agent, session_id) -> None:
  207. """Remember what the pin just written was built against (see ``_PINNED_SNAPSHOTS``)."""
  208. key = _pinned_snapshot_key(session_id)
  209. generation = getattr(agent, "_tool_snapshot_generation", None)
  210. selection = getattr(agent, "_tool_snapshot_selection", None)
  211. with _agent_tools_lock:
  212. _PINNED_SNAPSHOTS.pop(key, None)
  213. if isinstance(generation, int) and isinstance(selection, tuple):
  214. _PINNED_SNAPSHOTS[key] = (generation, selection)
  215. while len(_PINNED_SNAPSHOTS) > _PINNED_SNAPSHOTS_MAX:
  216. _PINNED_SNAPSHOTS.popitem(last=False)
  217. def _pin_restore_held(agent, registered: set) -> tuple[bool, frozenset]:
  218. """(pinned here, held) for a restore from this session's pin: whether this process wrote the pin (the
  219. rebuild is the same conversation), and the names it holds back: those the freeze holds when neither the
  220. registry nor the agent's toolset selection has moved since."""
  221. from tools.registry import registry
  222. session_id = getattr(agent, "session_id", None)
  223. if not session_id:
  224. return False, frozenset()
  225. with _agent_tools_lock:
  226. pinned_against = _PINNED_SNAPSHOTS.get(_pinned_snapshot_key(session_id))
  227. if pinned_against != (registry._generation, getattr(agent, "_tool_snapshot_selection", None)):
  228. return pinned_against is not None, frozenset()
  229. return True, _frozen_tool_names(registered)
  230. def _config_permitted_names(agent) -> set:
  231. """Tool names this agent's toolset selection allows before ``check_fn``: all a pin may carry
  232. forward. A client-surface toolset counts as allowed (only its client can add it, so its absence
  233. here is no config choice); ``disabled_toolsets`` still strips it."""
  234. from agent.oneshot_footprint import ONESHOT_DISABLED_TOOLSETS, agent_is_oneshot
  235. from model_tools import _select_tool_names
  236. from toolsets import CLIENT_SURFACE_TOOLSETS
  237. enabled = getattr(agent, "enabled_toolsets", None)
  238. if enabled is not None:
  239. enabled = [*enabled, *CLIENT_SURFACE_TOOLSETS]
  240. disabled = getattr(agent, "disabled_toolsets", None)
  241. if disabled and agent_is_oneshot(agent): # the one-shot gate is no config choice either: a pinned clarify stays,
  242. configured = set(getattr(agent, "_configured_disabled_toolsets", None) or ()) # unless config disables it
  243. disabled = [name for name in disabled if name not in ONESHOT_DISABLED_TOOLSETS or name in configured]
  244. return _select_tool_names(enabled, disabled, True)
  245. def _drop_gated_carried_tools(merged: list, carried: set) -> list:
  246. """A carried tool also passes the session-level schema gates the fresh build applied
  247. (``browser_exec`` needs ``terminal`` in the same array), judged on the merged array."""
  248. from model_tools import _DYNAMIC_SCHEMA_REWRITERS
  249. available = {_def_name(t) for t in merged}
  250. return [t for t in merged if _def_name(t) not in carried or _def_name(t) not in _DYNAMIC_SCHEMA_REWRITERS
  251. or _DYNAMIC_SCHEMA_REWRITERS[_def_name(t)](t, available) is not None]
  252. def _pinned_tool_defs(saved, fresh, keep_bytes=False) -> tuple:
  253. """(pinned, same_code, definitions) for a tools[] pin, either shape: a pin from the SAME code keeps
  254. its bytes; otherwise (``hermes update``, a legacy name list) each tool takes this process's
  255. definition (``fresh``, else its registry schema)."""
  256. pinned, version = (saved.get("tools") or [], saved.get("version")) if isinstance(saved, dict) else (saved, None)
  257. if not isinstance(pinned, list):
  258. return [], False, []
  259. from tools.registry import registry
  260. same_code = version is not None and version == tool_pin_version()
  261. def _pinned_def(item):
  262. name = item if isinstance(item, str) else _def_name(item) if isinstance(item, dict) else None
  263. if isinstance(item, dict) and (same_code or keep_bytes):
  264. return item
  265. if name in fresh:
  266. return fresh[name]
  267. entry = registry.get_entry(name) if name else None
  268. return {"type": "function", "function": {**entry.schema, "name": entry.name}} if entry else None
  269. return pinned, same_code, [d for d in map(_pinned_def, pinned) if d]
  270. def pinned_tool_defs(saved) -> list:
  271. """``saved``'s tool definitions as a fresh agent restores them, for an estimate with no agent built:
  272. pinned definitions keep their bytes, a legacy name list takes each tool's current registry schema."""
  273. # With no agent built yet (gateway warm-up off, failed or still running), nothing has run tool
  274. # discovery, so the registry would resolve no legacy name.
  275. import model_tools
  276. return _pinned_tool_defs(saved, {}, keep_bytes=True)[2]
  277. def restore_agent_tool_prefix(agent, saved) -> bool:
  278. """Fold a freshly built agent's ``tools`` onto the session's pin; True if changed.
  279. A fresh AIAgent (gateway cache eviction, ``--resume`` in a new process, a surface hop) has no
  280. predecessor to preserve, so the pin stands in. Pinned by the SAME code, a tool still available
  281. here keeps its pinned BYTES, whatever this process derives for it (tool_search's per-surface
  282. catalog, per-surface dynamic parameters, the ``-q`` footprint): tools[] heads every request.
  283. Pinned by other code (``hermes update``, a legacy name list) a tool's contract may have moved,
  284. so each takes its current definition. A pinned tool this process did not build is carried
  285. only while its toolset config allows it here; deregistered tools drop, new tools append. In the
  286. process that wrote the pin a pinned Tool Search bridge tool keeps its slot (it is synthesized, never
  287. registered, exactly as the between-turns refresh keeps it) and a tool new only because its ``check_fn``
  288. flipped stays out (``_pin_restore_held``)."""
  289. pinned, same_code, pinned_defs = _pinned_tool_defs(saved, {_def_name(t): t for t in _agent_tool_defs(agent)})
  290. if not pinned:
  291. return False
  292. from tools.registry import registry
  293. fresh_defs = _agent_tool_defs(agent)
  294. fresh = {_def_name(t): t for t in fresh_defs}
  295. registered_names = {entry.name for entry in registry.get_all_entries()}
  296. carried = {_def_name(d) for d in pinned_defs if _def_name(d) not in fresh and _def_name(d) in registered_names}
  297. carried &= _config_permitted_names(agent) if carried else set()
  298. pinned_here, held = _pin_restore_held(agent, registered_names)
  299. if pinned_here: # same conversation: the synthesized bridge keeps its slot, as in _merge_preserving_prefix
  300. from tools.tool_search_catalog import BRIDGE_TOOL_NAMES
  301. carried |= {_def_name(d) for d in pinned_defs if _def_name(d) in BRIDGE_TOOL_NAMES}
  302. merged = [d for d in pinned_defs if _def_name(d) in fresh or _def_name(d) in carried]
  303. pinned_names = {_def_name(d) for d in merged}
  304. merged.extend(t for t in fresh_defs if _def_name(t) not in pinned_names and _def_name(t) not in held)
  305. merged = _drop_gated_carried_tools(merged, carried)
  306. merged_names = {_def_name(t) for t in merged}
  307. _reinject_authorized_dynamic_tools(agent, merged, merged_names)
  308. merged, merged_names = _drop_session_tools(agent, merged, merged_names)
  309. changed = merged != fresh_defs
  310. if changed:
  311. with _agent_tools_lock:
  312. agent.tools = merged
  313. agent.valid_tool_names = merged_names
  314. if isinstance(saved, dict) and saved.get("delegation_backend"):
  315. from agent.delegation_backends import adopt_built_backend
  316. adopt_built_backend(agent, pinned, saved["delegation_backend"])
  317. from tools.delegate_tool import adopt_session_delegation_mode
  318. adopt_session_delegation_mode(agent) # the restored delegate_task decides joined vs background from here on
  319. if not same_code or merged != list(pinned):
  320. persist_agent_tool_names(agent)
  321. return changed
  322. def _merge_preserving_prefix(current_defs: list, new_defs: list, registered_names: set,
  323. held: frozenset | set = frozenset()) -> tuple[list, set]:
  324. """Fold a fresh tool snapshot into a live one without moving existing bytes. Ordered by
  325. ``current_defs`` (the cached request prefix): a name already sent keeps its slot and the
  326. schema bytes already sent; a name only in the live list is kept if still registered
  327. (``check_fn`` flapped), else dropped; a name only in the fresh list is appended at the tail
  328. unless it is in ``held`` (a name that can only be new because a ``check_fn`` flipped).
  329. A refreshed schema is not substituted in place. Tool JSON is rendered ahead of the
  330. conversation, so one changed description means the next prompt no longer starts with the
  331. previous one and a local prefix cache reads the whole prompt again. An explicit reload
  332. (``preserve_prefix`` off) still takes the fresh schemas.
  333. The carried entry freezes the whole schema (description and parameters), not just prose: if a
  334. server changes a live tool's input schema under the same name, the model keeps calling with
  335. the old shape and the server rejects those calls until ``/reload-mcp`` or compaction.
  336. The bridge tools are synthesized by ``assemble_tool_defs``, never registered, and a fresh
  337. snapshot omits them when the deferred set shrinks under the activation threshold: they
  338. keep their slot regardless (search reads the live catalog at dispatch)."""
  339. from tools.tool_search_catalog import BRIDGE_TOOL_NAMES
  340. fresh = {_def_name(entry): entry for entry in new_defs if _def_name(entry)}
  341. merged = []
  342. for entry in current_defs:
  343. name = _def_name(entry)
  344. replacement = fresh.pop(name, None)
  345. if replacement is not None or name in BRIDGE_TOOL_NAMES or (name and name in registered_names):
  346. merged.append(entry)
  347. merged.extend(entry for name, entry in fresh.items() if name not in held)
  348. return merged, {_def_name(t) for t in merged}
  349. def _reinject_authorized_dynamic_tools(agent, tools_list: list, name_set: set) -> None:
  350. """``message_agent`` is injected by an auth gate, never registered, so a registry-derived
  351. rebuild drops it. Scrub any stale copy from the STAGED pair and re-add it only when the live
  352. gate re-authorizes, so the publisher exposes a coherent ``(tools, valid_tool_names)``."""
  353. from tools.bot_mode_dm import MESSAGE_AGENT_TOOL_NAME, message_agent_authorized, message_agent_tool_schema
  354. tools_list[:] = [entry for entry in tools_list if _def_name(entry) != MESSAGE_AGENT_TOOL_NAME]
  355. name_set.discard(MESSAGE_AGENT_TOOL_NAME)
  356. if message_agent_authorized(agent):
  357. tools_list.append(message_agent_tool_schema())
  358. name_set.add(MESSAGE_AGENT_TOOL_NAME)
  359. def _reinject_post_build_tools(agent, tools_list: list, name_set: set) -> set:
  360. """Append memory-provider and context-engine tools onto the caller's staged ``tools_list``
  361. / ``name_set`` (never the live agent attributes), mirroring ``agent_init``'s post-build
  362. injection. Idempotent and fail-soft. Returns the context-engine routing names THIS rebuild
  363. appended: a name already owned by a registry/plugin tool is not claimed, matching agent_init."""
  364. def _add(schema) -> bool:
  365. name = schema.get("name", "") if isinstance(schema, dict) else ""
  366. if not name or name in name_set:
  367. return False
  368. tools_list.append({"type": "function", "function": schema})
  369. name_set.add(name)
  370. return True
  371. def _schema_getter(attr: str, method: str):
  372. getter = getattr(getattr(agent, attr, None) or None, method, None)
  373. return getter if callable(getter) else None
  374. enabled = getattr(agent, "enabled_toolsets", None)
  375. try:
  376. get_mem_schemas = _schema_getter("_memory_manager", "get_all_tool_schemas")
  377. if get_mem_schemas is not None:
  378. from agent.memory_manager_tools import memory_provider_tools_enabled # same gate inject_memory_provider_tools uses
  379. if memory_provider_tools_enabled(
  380. enabled, getattr(agent, "disabled_toolsets", None), memory_tool_present="memory" in name_set):
  381. for schema in get_mem_schemas():
  382. _add(schema)
  383. except Exception:
  384. logger.debug("Memory-provider tool re-injection skipped", exc_info=True)
  385. # The `context_engine` toolset is intentionally empty, so lcm_* tools exist only via this
  386. # append. Honor the enabled_toolsets gate agent_init uses, or a restricted-toolset platform
  387. # would re-leak tools the build excluded.
  388. # See #5544.
  389. staged_engine_names: set = set()
  390. try:
  391. get_schemas = _schema_getter("context_compressor", "get_tool_schemas")
  392. if (enabled is None or "context_engine" in enabled) and get_schemas is not None:
  393. # Claim the routing name only when WE appended the schema.
  394. staged_engine_names.update(s["name"] for s in get_schemas() if _add(s))
  395. except Exception:
  396. logger.debug("Context-engine tool re-injection skipped", exc_info=True)
  397. return staged_engine_names