fix(client): honor named agent tool groups (#8472)

This commit is contained in:
ZephyrWang 2026-11-22 08:57:38 +08:00 committed by GitHub
parent 559c2ccc95
commit 9809784e95
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 84 additions and 10 deletions

View File

@ -358,8 +358,10 @@ class DeerFlowClient:
self._loaded_agent_config = agent_config
memory_enabled = getattr(agent_config, "memory_enabled", True) is not False
mcp_plugins = getattr(agent_config, "mcp_plugins", None)
tool_groups = getattr(agent_config, "tool_groups", None)
# Delegation reads this run's metadata, including when the graph is cached.
config.setdefault("metadata", {})["mcp_plugins"] = mcp_plugins
config["metadata"]["tool_groups"] = tool_groups
authorization_identity = None
if self._app_config.authorization.enabled:
@ -386,6 +388,7 @@ class DeerFlowClient:
self._agent_name,
memory_enabled,
frozenset(mcp_plugins) if mcp_plugins is not None else None,
frozenset(tool_groups) if tool_groups is not None else None,
frozenset(self._available_skills) if self._available_skills is not None else None,
self._checkpoint_channel_mode,
self._checkpoint_snapshot_frequency,
@ -466,7 +469,7 @@ class DeerFlowClient:
)
max_total_subagents = effective_total_subagents_per_run(cfg.get("max_total_subagents"), self._app_config)
tools = self._get_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins)
tools = self._get_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=tool_groups)
# Add framework-provided tools before authorization so Layer 1 sees
# every capability that can become model-visible.
@ -576,11 +579,11 @@ class DeerFlowClient:
logger.info("Agent created: agent_name=%s, model=%s, thinking=%s", self._agent_name, model_name, thinking_enabled)
@staticmethod
def _get_tools(*, model_name: str | None, subagent_enabled: bool, mcp_plugins: list[str] | None = None):
def _get_tools(*, model_name: str | None, subagent_enabled: bool, mcp_plugins: list[str] | None = None, groups: list[str] | None = None):
"""Lazy import to avoid circular dependency at module level."""
from deerflow.tools import get_available_tools
return get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins)
return get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=groups)
@staticmethod
def _serialize_tool_calls(tool_calls) -> list[dict]:

View File

@ -1529,7 +1529,7 @@ class TestClientMcpSelection:
config["metadata"] = {"existing": "preserved", "mcp_plugins": ["installation-B"]}
client._ensure_agent(config)
keys.append(client._agent_config_key)
assert config["metadata"] == {"existing": "preserved", "mcp_plugins": selection}
assert config["metadata"] == {"existing": "preserved", "mcp_plugins": selection, "tool_groups": None}
# Changing the saved config takes effect only after reset_agent().
mcp_client.load_config.return_value = AgentConfig(name="researcher", mcp_plugins=["installation-B"])
@ -1543,6 +1543,70 @@ class TestClientMcpSelection:
class TestEnsureAgent:
@pytest.mark.parametrize(
("groups", "expected"),
[(None, {"read_file", "write_file"}), ([], set()), (["file:read"], {"read_file"})],
)
def test_named_agent_tool_groups_reach_model_and_delegation(self, client, tmp_path, monkeypatch, groups, expected):
import httpx
from langchain_openai import ChatOpenAI
from deerflow.config.app_config import AppConfig
from deerflow.config.sandbox_config import SandboxConfig
paths = Paths(tmp_path)
monkeypatch.setattr("deerflow.config.paths._paths", paths)
agent_dir = paths.user_agent_dir("test-user", "researcher")
agent_dir.mkdir(parents=True)
(agent_dir / "config.yaml").write_text(json.dumps({"name": "researcher", "tool_groups": groups}), encoding="utf-8")
app_config = AppConfig(
models=[],
sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"),
tools=[
{"name": "read_file", "group": "file:read", "use": "deerflow.sandbox.tools:read_file_tool"},
{"name": "write_file", "group": "file:write", "use": "deerflow.sandbox.tools:write_file_tool"},
],
)
app_config.tool_search.enabled = False
monkeypatch.setattr("deerflow.config.app_config._app_config", app_config)
monkeypatch.setattr("deerflow.config.app_config._app_config_is_custom", True)
client._app_config = app_config
client._agent_name = "researcher"
requests = []
def respond(request):
requests.append(json.loads(request.content))
chunk = {"id": "chatcmpl-groups", "choices": [{"index": 0, "delta": {"content": "Done"}, "finish_reason": "stop"}]}
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n")
# Retain saved config loading, tool assembly, graph execution and SDK
# serialization. Prompt/middleware assembly is unrelated to selection.
with httpx.Client(transport=httpx.MockTransport(respond)) as transport:
model = ChatOpenAI(model="offline", api_key="offline-placeholder", http_client=transport, use_responses_api=False)
with (
patch("deerflow.client.create_chat_model", return_value=model),
patch("deerflow.client.build_middlewares", return_value=[]),
patch("deerflow.client.apply_prompt_template", return_value="Answer briefly."),
patch("deerflow.client.get_enabled_skills_for_config", return_value=[]),
patch.object(ExtensionsConfig, "from_file", return_value=ExtensionsConfig()),
patch("deerflow.runtime.checkpointer.get_checkpointer", return_value=None),
):
client._ensure_agent(client._get_runnable_config("group-test"), context={"user_id": "test-user"})
with patch.object(client._agent, "stream", wraps=client._agent.stream) as stream:
assert client.chat("Hello", thread_id="group-test", user_id="test-user") == "Done"
assert client.chat("Again", thread_id="group-test", user_id="test-user") == "Done"
(agent_dir / "config.yaml").write_text(json.dumps({"name": "researcher", "tool_groups": ["file:write"]}), encoding="utf-8")
client.reset_agent()
assert client.chat("Refresh", thread_id="group-test", user_id="test-user") == "Done"
assert len(requests) == 3
for request, selected in zip(requests, [expected, expected, {"write_file"}], strict=True):
names = {item["function"]["name"] for item in request["tools"]}
assert names & {"read_file", "write_file"} == selected
assert "present_files" in names # Built-ins retain their existing policy.
for call in stream.call_args_list:
assert call.kwargs["config"]["metadata"]["tool_groups"] == groups
@pytest.mark.parametrize(
("agent_name", "agent_config", "expected_memory_enabled"),
[
@ -1976,6 +2040,7 @@ class TestEnsureAgent:
True,
None,
None,
None,
"full",
10,
get_effective_user_id(),

View File

@ -791,7 +791,7 @@ def _stub_client_assembly(monkeypatch) -> dict[str, str]:
)
monkeypatch.setattr("deerflow.client.create_agent", lambda **kwargs: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *args, **kwargs: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: []) # noqa: ARG005
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",

View File

@ -539,7 +539,7 @@ def test_client_ensure_agent_filters_skills_by_authorization(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -592,7 +592,7 @@ def test_client_ensure_agent_noop_when_authorization_disabled(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -884,7 +884,7 @@ def test_client_wires_skill_authorization_into_middleware(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -969,7 +969,7 @@ def test_client_filter_candidates_reuse_catalog_loader(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *a, **kw: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
lambda skills, *, enabled, container_base_path, skill_authorization=None: SimpleNamespace(describe_skill_tool=None, skill_names=frozenset()),
@ -1151,7 +1151,7 @@ def test_client_skill_surface_uses_one_effective_user(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *a, **kw: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
lambda skills, *, enabled, container_base_path, skill_authorization=None: SimpleNamespace(describe_skill_tool=None, skill_names=frozenset()),

View File

@ -52,6 +52,12 @@ delegations: `null` inherits all enabled MCP plugins, `[]` selects none, and
installation IDs select only those plugins. Call `client.reset_agent()` after
editing the saved agent configuration to refresh the selection.
The named agent's `tool_groups` also selects configured and extension tools for
the embedded lead agent and its delegations. `null` inherits all groups, `[]`
selects no groups, and a list selects those groups. Built-in tools and MCP plugin
selection retain their own policies. Call `client.reset_agent()` after changing
the saved group selection.
`DeerFlowClient.stream()` includes `summary_text` in each `values` event. This is the current compacted context summary, or `None` when absent. Consumers can record changes without reading checkpoint internals; repeated snapshots may carry the same summary, and an initial snapshot may already contain one from an earlier turn.
DeerFlow can be used as an embedded Python library without running the full HTTP services. The `DeerFlowClient` provides direct in-process access to all agent and Gateway capabilities, returning the same response schemas as the HTTP Gateway API.