Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(agents): a tool node may give an agent several tools (ToolNode.tool_bindings)
trohitgee85480bbd6c
diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.mdindex cef10f8f..ab6bcda0 100644--- a/docs-internal/agent_architecture.md+++ b/docs-internal/agent_architecture.md@@ -255,7 +255,7 @@ Closure responsibilities:(excluding `component_kind == "model"`, and the Skills node, whose`uiHints.isMasterSkillEditor` marks it: tool-kind, but it feeds`input-skill`), skip a node already bound, synthesize a `tool_info` dict,- call `self._build_tool_from_node(tool_info)`, and return the new specs. Tool+ call `node_tools(self, tool_info)` (`services/agent_bindings.py`), and return the new specs. Toolconfigs get folded into the captured `tool_configs` dict so`tool_executor` can dispatch the new call.- The closure is gated on the user toggle: `UserSettings.auto_rebind_tools_after_canvas_change` (default `True`). When off, the LLM is told "Available on your next turn" in the operation summary and the closure isn't wired.@@ -268,6 +268,18 @@ with conflict details. Older histories preserve their recorded refresh path.Version 1 preparation/refresh also records plugin Activity policies for eachbound tool. See [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md).+**A node that gives several tools.** A ToolNode may stand for several tools+(`ToolNode.tool_bindings`, read from its settings: a custom MCP connector gives+one per remote tool it has on, see [MCP Connectors](mcp_connectors.md)). Every+place that builds an agent's tools goes through `node_tools`+(`services/agent_bindings.py`). It returns the one tool+`AIService._build_tool_from_node` builds, or one tool per `ToolBinding`, each+named by its binding and run with the binding's settings over the node's. Each Temporal tool entry carries a+`binding_key` (`<node id>:<key>`, or the node id for a single tool); behind+`agent-tool-binding-key-v1` the workflow drops repeats by it instead of by+`tool_node_id`, so the tools of one node are not collapsed into one. CLI agents+(Claude Code, Codex) leave such a node out, and RLM refuses it.+### Where it's calledTwo callsites in `server/services/ai.py`:diff --git a/server/nodes/agent/vertex_managed_agent/__init__.py b/server/nodes/agent/vertex_managed_agent/__init__.pyindex ace7e8ff..d0bd3691 100644--- a/server/nodes/agent/vertex_managed_agent/__init__.py+++ b/server/nodes/agent/vertex_managed_agent/__init__.py@@ -614,6 +614,7 @@ class VertexManagedAgentNode(ActionNode):if not tool_data:return [], {}from constants import AI_AGENT_TYPES+ from services.agent_bindings import node_toolsfrom services.plugin.deps import get_ai_servicefrom services.plugin.tool import inline_schema_refsfrom services.tool_identity import ensure_unique_tool_names@@ -675,10 +676,8 @@ class VertexManagedAgentNode(ActionNode):tool_info.get("node_id"),)continue- structured, config = await ai_service._build_tool_from_node(tool_info)- if structured is None:- continue- _declare(structured, config)+ for structured, config in await node_tools(ai_service, tool_info):+ _declare(structured, config)# Sub-agent support: delegation may time out and fall back to a# task_id — the cloud agent then needs check_delegated_tasks todiff --git a/server/services/agent_bindings.py b/server/services/agent_bindings.pyindex 28b2dddc..0001471c 100644--- a/server/services/agent_bindings.py+++ b/server/services/agent_bindings.py@@ -2,6 +2,44 @@from __future__ import annotationsfrom typing import Any, Iterable, Mapping+from core.logging import get_logger++logger = get_logger(__name__)+++async def node_tools(ai_service: Any, tool_info: Mapping[str, Any]) -> list:+ """The tools a connected node gives an agent, as ``(tool, config)``: the+ one ``ai_service._build_tool_from_node`` builds, or one per binding of a+ node that stands for several (``ToolNode.tool_bindings``, a custom MCP+ connector's tools). A binding's call runs with its settings over the+ node's, and its ``binding_key`` tells it apart from the node's others."""+ from services.agent_runtime import AgentToolSpec+ from services.llm.protocol import ToolDef+ from services.plugin.tool import node_tool_bindings++ try:+ bindings = await node_tool_bindings(tool_info)+ except Exception as exc: # noqa: BLE001 - skip the node, as a tool that cannot be built+ logger.error("Could not read the tools of a connected node", node_type=tool_info.get("node_type"), error=str(exc))+ return []+ if bindings is None:+ tool, config = await ai_service._build_tool_from_node(tool_info)+ return [(tool, config)] if tool is not None else []+ node_id = tool_info.get("node_id", "")+ built = []+ for binding in bindings:+ config = {+ "node_type": tool_info.get("node_type", ""),+ "node_id": node_id,+ "parameters": {**(tool_info.get("parameters") or {}), **binding.parameters},+ "label": tool_info.get("label") or tool_info.get("node_type", ""),+ "connected_services": [],+ "binding_key": f"{node_id}:{binding.key}",+ }+ definition = ToolDef(name=binding.name, description=binding.description, parameters=binding.schema)+ built.append((AgentToolSpec(definition=definition, args_schema=None, execution=config), config))+ return built+def is_runtime_tool(cls: Any) -> bool:"""Agents delegate; models and skill editors never bind as function tools."""diff --git a/server/services/ai.py b/server/services/ai.pyindex e3259a5c..68b93f61 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -17,7 +17,7 @@ import json# sentinel used to surface typed SDK errors cleanly through# ``BaseNode.execute()``.from services.plugin import NodeUserError-from services.agent_bindings import delegation_roster, is_runtime_tool, unique_node_bindings, rebind_allowed, extend_runtime_graph+from services.agent_bindings import delegation_roster, is_runtime_tool, node_tools, unique_node_bindings, rebind_allowed, extend_runtime_graphfrom services.tool_identity import DuplicateToolNameError, ensure_unique_tool_namesif TYPE_CHECKING:@@ -1095,8 +1095,7 @@ class AIService:await broadcast_status("building_tools", {"message": f"Building {len(effective_tool_data)} tool(s)...", "tool_count": len(effective_tool_data)})for tool_info in effective_tool_data:- tool, config = await self._build_tool_from_node(tool_info)- if tool:+ for tool, config in await node_tools(self, tool_info):tools.append(tool)tool_bindings.append((tool, config))tool_identities.append(@@ -1363,17 +1362,17 @@ class AIService:if tool_info["node_id"] in bound:continuetry:- tool, tool_config = await self._build_tool_from_node(tool_info)+ built = await node_tools(self, tool_info)except Exception as exc: # noqa: BLE001 — log + skip one toollogger.warning(- "[Agent] rebind: _build_tool_from_node raised for %s: %s",+ "[Agent] rebind: building tools raised for %s: %s",node_type,exc,)continue- if tool is None:+ if not built:continue- new_bindings.append((tool, tool_config or tool_info))+ new_bindings.extend((tool, tool_config or tool_info) for tool, tool_config in built)bound.add(tool_info["node_id"])new_identities = [@@ -1727,9 +1726,8 @@ class AIService:for tool_info in effective_tool_data:if task_manager_bound and tool_info.get("delegate_tool_name"):continue- # Use AI Agent's _build_tool_from_node for all tool types- tool, config = await self._build_tool_from_node(tool_info)- if tool:+ # The same tool building as the AI Agent, for all tool types+ for tool, config in await node_tools(self, tool_info):all_tools.append(tool)tool_bindings.append((tool, config))tool_identities.append(@@ -2106,17 +2104,17 @@ class AIService:if tool_info["node_id"] in bound:continuetry:- tool, tool_config = await self._build_tool_from_node(tool_info)+ built = await node_tools(self, tool_info)except Exception as exc: # noqa: BLE001logger.warning(- "[ChatAgent] rebind: _build_tool_from_node raised for %s: %s",+ "[ChatAgent] rebind: building tools raised for %s: %s",node_type,exc,)continue- if tool is None:+ if not built:continue- new_bindings.append((tool, tool_config or tool_info))+ new_bindings.extend((tool, tool_config or tool_info) for tool, tool_config in built)bound.add(tool_info["node_id"])new_identities = [diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.pyindex 9cf3b169..379d2cec 100644--- a/server/services/cli_agent/service.py+++ b/server/services/cli_agent/service.py@@ -536,12 +536,21 @@ class AICliService:if not connected_tools:return []from services.plugin.deps import get_ai_service+ from services.plugin.tool import node_tool_bindingsfrom services.tool_identity import ensure_unique_tool_namesai_service = ai_service or get_ai_service()surface: List[Dict[str, Any]] = []identities: List[Dict[str, str]] = []for tool_info in connected_tools:+ # The surface gives one tool per node; a node that gives several+ # (a custom MCP connector) is left out.+ if await node_tool_bindings(tool_info) is not None:+ logger.warning(+ "[cli_agent] skipping %r: a CLI agent can't use a node that gives several tools",+ tool_info.get("node_type"),+ )+ continuetool, execution = await ai_service._build_tool_from_node(tool_info)if tool is None or execution is None:# Skip-and-log, matching the pre-existing contract. Raisingdiff --git a/server/services/plugin/tool.py b/server/services/plugin/tool.pyindex e70a7681..c8fa3c96 100644--- a/server/services/plugin/tool.py+++ b/server/services/plugin/tool.py@@ -8,8 +8,9 @@ JSON Schema the LLM sees — derived from :class:`Params` automatically.from __future__ import annotationsfrom copy import copy, deepcopy+from dataclasses import dataclass, fieldfrom functools import lru_cache-from typing import Any, ClassVar, Dict, FrozenSet, Optional, Type+from typing import Any, ClassVar, Dict, FrozenSet, List, Mapping, Optional, Typefrom pydantic import BaseModel, ConfigDict, create_model@@ -106,6 +107,21 @@ def inline_schema_refs(schema: Dict[str, Any]) -> Dict[str, Any]:return inlined+@dataclass(frozen=True)+class ToolBinding:+ """One of the tools a node gives an agent, when it gives several."""++ #: Tells it apart within its node (a remote tool's name).+ key: str+ #: What the model calls it.+ name: str+ description: str+ #: Its arguments, as a JSON Schema object.+ schema: Dict[str, Any]+ #: Settings a call of it runs with, over the node's own.+ parameters: Dict[str, Any] = field(default_factory=dict)++class ToolNode(BaseNode, abstract=True):"""Base class for AI-Agent tool nodes (calculatorTool, currentTimeTool)."""@@ -147,6 +163,13 @@ class ToolNode(BaseNode, abstract=True):"""Return the invocation model, defaulting to persisted ``Params``."""return cls.ToolInput or cls.Params+ @classmethod+ async def tool_bindings(cls, parameters: Mapping[str, Any]) -> Optional[List[ToolBinding]]:+ """The tools this node gives an agent, from its settings. None (the+ default): the one tool built from the class. A node that stands for+ several (a custom MCP connector) returns one binding each."""+ return None+@classmethod@lru_cache(maxsize=None)def partial_config_model(cls) -> Type[BaseModel]:@@ -216,3 +239,14 @@ class ToolNode(BaseNode, abstract=True):if isinstance(result, dict) and "success" not in result:return True, result, Nonereturn super().interpret_result(result)+++async def node_tool_bindings(tool_info: Mapping[str, Any]) -> Optional[List[ToolBinding]]:+ """A connected node's :meth:`ToolNode.tool_bindings`; None for a node+ that gives one tool."""+ from services.node_registry import get_node_class++ cls = get_node_class(str(tool_info.get("node_type") or ""))+ if cls is None or not issubclass(cls, ToolNode):+ return None+ return await cls.tool_bindings(tool_info.get("parameters") or {})diff --git a/server/services/rlm/service.py b/server/services/rlm/service.pyindex d22501a5..d1ed8545 100644--- a/server/services/rlm/service.py+++ b/server/services/rlm/service.py@@ -146,8 +146,15 @@ class RLMService:if progressive_skill_tool:effective_tool_data.append(progressive_skill_tool)if ai_service is not None:+ from services.plugin.tool import node_tool_bindings+canonical_tool_data = []for tool_info in effective_tool_data:+ if await node_tool_bindings(tool_info) is not None:+ raise ValueError(+ f"An RLM agent can't use {tool_info.get('label') or tool_info.get('node_type')!r}: "+ "it gives several tools. Connect it to an AI Agent instead."+ )tool, execution = await ai_service._build_tool_from_node(tool_info)diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex 836d4243..bd3550ac 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -35,7 +35,7 @@ References:from __future__ import annotations-from services.agent_bindings import is_runtime_tool, unique_node_bindings, rebind_allowed, ParameterSnapshotDatabase, extend_runtime_graph+from services.agent_bindings import is_runtime_tool, node_tools, unique_node_bindings, rebind_allowed, ParameterSnapshotDatabase, extend_runtime_graphimport asynciofrom dataclasses import asdict@@ -1513,12 +1513,10 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:effective_tool_data.append(progressive_skill_tool)for tool_info in unique_node_bindings(effective_tool_data):try:- tool, _config = await ai_service._build_tool_from_node(tool_info)+ built = await node_tools(ai_service, tool_info)except Exception as e: # noqa: BLE001 — defensive: skip a broken toolactivity.logger.warning(f"prepare_payload: failed to build tool {tool_info.get('node_type')!r}: {e}")continue- if tool is None:- continue# Look up plugin class for activity-dispatch metadata.from services.node_registry import get_node_class@@ -1526,37 +1524,41 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:version = getattr(cls, "version", 1) if cls else 1task_queue = getattr(cls, "task_queue", "machina-default") if cls else "machina-default"- tools_payload.append(- {- "name": tool.name,- # Provider-neutral function declaration for the native- # activity branch. It is JSON-only so it can live safely in- # Temporal history and never requires rebuilding a- # StructuredTool inside the native LLM activity.- "definition": _native_tool_definition(tool),- "node_type": tool_info.get("node_type", ""),- "version": version,- "task_queue": task_queue,- "tool_node_id": tool_info.get("node_id", ""),- "parameters": tool_info.get("parameters") or {},- # Raw tool_info — what ``collect_agent_connections`` returned- # and what ``_build_tool_from_node`` accepts as input. Passed- # through the workflow verbatim so ``execute_llm_step`` can- # rebuild the real StructuredTool inside the activity.- "tool_info": tool_info,- **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}- if context.get("execution_control_version") == 1 or context.get("native_workspace_version") == 1- or context.get("browser_routing_version") == 1 or node_type == "browser_agent" else {}),- # Team leads create and dispatch durable work through Task- # Manager. Delegate descriptors stay in workflow state for- # trusted assignee resolution, but are not callable directly- # by the model.- "llm_hidden": (- node_type in {"orchestrator_agent", "ai_employee"}- and tool.name.startswith("delegate_to_")- ),- }- )+ for tool, config in built:+ tools_payload.append(+ {+ "name": tool.name,+ # Provider-neutral function declaration for the native+ # activity branch. It is JSON-only so it can live safely in+ # Temporal history and never requires rebuilding a+ # StructuredTool inside the native LLM activity.+ "definition": _native_tool_definition(tool),+ "node_type": tool_info.get("node_type", ""),+ "version": version,+ "task_queue": task_queue,+ "tool_node_id": tool_info.get("node_id", ""),+ # One entry per tool: a node that gives several+ # (ToolNode.tool_bindings) has one per binding.+ "binding_key": config.get("binding_key") or tool_info.get("node_id", ""),+ "parameters": config.get("parameters") or {},+ # Raw tool_info — what ``collect_agent_connections`` returned+ # and what ``_build_tool_from_node`` accepts as input. Passed+ # through the workflow verbatim so ``execute_llm_step`` can+ # rebuild the real StructuredTool inside the activity.+ "tool_info": tool_info,+ **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}+ if context.get("execution_control_version") == 1 or context.get("native_workspace_version") == 1+ or context.get("browser_routing_version") == 1 or node_type == "browser_agent" else {}),+ # Team leads create and dispatch durable work through Task+ # Manager. Delegate descriptors stay in workflow state for+ # trusted assignee resolution, but are not callable directly+ # by the model.+ "llm_hidden": (+ node_type in {"orchestrator_agent", "ai_employee"}+ and tool.name.startswith("delegate_to_")+ ),+ }+ )if any(tool["name"].startswith("delegate_to_") for tool in tools_payload):from services.plugin.edge_walker import format_teammate_roster_line@@ -1840,33 +1842,35 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:if database:tool_info["parameters"] = await database.get_node_parameters(str(tool_info["node_id"])) or {}try:- tool, _config = await ai_service._build_tool_from_node(tool_info)+ built = await node_tools(ai_service, tool_info)except Exception as e: # noqa: BLE001 — skip one, keep building the batchactivity.logger.warning(f"refresh_tools: failed to build tool {node_type!r}: {e}")continue- if tool is None:+ if not built:continuebound.add(tool_info["node_id"])version = getattr(cls, "version", 1)task_queue = getattr(cls, "task_queue", "machina-default")- new_tools_payload.append(- {- "name": tool.name,- "definition": _native_tool_definition(tool),- "node_type": node_type,- "version": version,- "task_queue": task_queue,- "tool_node_id": tool_info["node_id"],- "parameters": tool_info["parameters"],- "tool_info": tool_info,- **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}- if payload.get("execution_control_version") == 1 or payload.get("native_workspace_version") == 1- or payload.get("browser_runtime_version") == 1 or payload.get("browser_routing_version") == 1 else {}),- "llm_hidden": bool(team_lead_refresh and is_agent_delegate),- }- )+ for tool, config in built:+ new_tools_payload.append(+ {+ "name": tool.name,+ "definition": _native_tool_definition(tool),+ "node_type": node_type,+ "version": version,+ "task_queue": task_queue,+ "tool_node_id": tool_info["node_id"],+ "binding_key": config.get("binding_key") or tool_info["node_id"],+ "parameters": config.get("parameters") or {},+ "tool_info": tool_info,+ **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}+ if payload.get("execution_control_version") == 1 or payload.get("native_workspace_version") == 1+ or payload.get("browser_runtime_version") == 1 or payload.get("browser_routing_version") == 1 else {}),+ "llm_hidden": bool(team_lead_refresh and is_agent_delegate),+ }+ )activity.logger.info("refresh_tools: built %d tool(s) from %d operation(s)",diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex dec39cdb..fa22cfd1 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -919,9 +919,12 @@ class AgentWorkflow:if payload.get("employee_job_id"):context["employee_job_id"] = payload["employee_job_id"]binding_refresh_v2 = workflow.patched("agent-node-binding-refresh-v2")+ # A node that gives several tools (ToolNode.tool_bindings) has one+ # entry per tool, told apart by ``binding_key``.+ tool_key = "binding_key" if workflow.patched("agent-tool-binding-key-v1") else "tool_node_id"tools = (resume.get("tools") if self._execution_control.enabled and "tools" in resume else payload.get("tools")) or []if binding_refresh_v2:- tools = unique_node_bindings(tools, id_key="tool_node_id")+ tools = unique_node_bindings(tools, id_key=tool_key)duplicate_tool_error = _duplicate_visible_tool_name_error(tools)duplicate_tool_conflicts = (_duplicate_visible_tool_name_conflicts(tools)@@ -2350,8 +2353,8 @@ class AgentWorkflow:added_tools = refresh_result.get("tools") or []if binding_refresh_v2:added_tools = unique_node_bindings(- added_tools, id_key="tool_node_id",- bound=[tool.get("tool_node_id") for tool in tools if tool.get("tool_node_id")],+ added_tools, id_key=tool_key,+ bound=[tool.get(tool_key) for tool in tools if tool.get(tool_key)],)refresh_duplicate_error = _duplicate_visible_tool_name_error([*tools, *added_tools]diff --git a/server/tests/services/test_agent_bindings.py b/server/tests/services/test_agent_bindings.pyindex 2047b5f7..5e15afc6 100644--- a/server/tests/services/test_agent_bindings.py+++ b/server/tests/services/test_agent_bindings.py@@ -27,6 +27,62 @@ def test_temporal_payload_identity():assert unique_node_bindings(tools, id_key="tool_node_id", bound=["a"]) == [tools[2]]+def test_the_tools_of_one_node_are_told_apart_by_binding_key():+ tools = [+ {"tool_node_id": "a", "binding_key": "a:lookup"},+ {"tool_node_id": "a", "binding_key": "a:refund"},+ {"tool_node_id": "a", "binding_key": "a:lookup"},+ ]+ assert unique_node_bindings(tools, id_key="binding_key") == tools[:2]+ assert unique_node_bindings(tools, id_key="binding_key", bound=["a:lookup"]) == [tools[1]]+++def _bindings(*keys):+ from services.plugin.tool import ToolBinding++ async def bindings(tool_info):+ if tool_info["node_type"] != "mcpConnector":+ return None+ schema = {"type": "object", "properties": {"order": {"type": "string"}}}+ return [ToolBinding(key=key, name=f"orders__{key}", description=f"{key} an order.", schema=schema, parameters={"mcp_tool": key}) for key in keys]++ return bindings+++async def test_a_node_that_gives_several_tools_builds_one_per_binding(monkeypatch):+ from services.agent_bindings import node_tools+ from services.plugin import tool as tool_module++ monkeypatch.setattr(tool_module, "node_tool_bindings", _bindings("lookup", "refund"))+ built = await node_tools(+ SimpleNamespace(), {"node_id": "n1", "node_type": "mcpConnector", "parameters": {"mcp_connector": "mcp:orders"}, "label": "Orders"}+ )+ # Each runs with its own settings over the node's.+ assert [(tool.name, config["binding_key"], config["parameters"]) for tool, config in built] == [+ ("orders__lookup", "n1:lookup", {"mcp_connector": "mcp:orders", "mcp_tool": "lookup"}),+ ("orders__refund", "n1:refund", {"mcp_connector": "mcp:orders", "mcp_tool": "refund"}),+ ]+ assert built[0][0].definition.parameters["properties"] == {"order": {"type": "string"}}+++async def test_cli_agents_leave_out_a_node_that_gives_several_tools(monkeypatch):+ from services.cli_agent.service import AICliService+ from services.plugin import tool as tool_module++ monkeypatch.setattr(tool_module, "node_tool_bindings", _bindings("lookup"))+ built = []++ class AI:+ async def _build_tool_from_node(self, tool_info):+ built.append(tool_info["node_type"])+ return SimpleNamespace(name="calculator", description="", parameters={}, args_schema=None), {"node_id": tool_info["node_id"]}++ surface = await AICliService._canonical_tool_surface(+ [{"node_type": "mcpConnector", "node_id": "m"}, {"node_type": "calculatorTool", "node_id": "c"}], ai_service=AI()+ )+ assert built == ["calculatorTool"] and [entry["node_type"] for entry in surface] == ["calculatorTool"]++def test_team_readiness_requires_both_execution_engines_and_connection():settings = SimpleNamespace(temporal_enabled=True, temporal_agent_workflow_enabled=True)client = SimpleNamespace(is_connected=True)