Skip to content

Commit f44d512

Browse files
ftnextcopybara-github
authored andcommitted
fix: load validated MCP toolsets under adk web
Merge #6736 Fixes #6735 PiperOrigin-RevId: 990732970
1 parent d312c0e commit f44d512

3 files changed

Lines changed: 218 additions & 10 deletions

File tree

‎contributing/samples/mcp/tool_mcp_stdio_notion_config/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ Only set this when you trust every agent config the process will load.
4545

4646
### 5. Run the Agent
4747

48-
Use `adk run` to run the agent and interact with your Notion workspace.
48+
Use `adk run` or `adk web` to run the agent and interact with your Notion
49+
workspace. The stdio opt-in above is required for either command.
4950

5051
## Example Queries
5152

‎src/google/adk/agents/config_agent_utils.py‎

Lines changed: 89 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import typing
2525
from typing import Any
2626
from typing import List
27+
from typing import NoReturn
2728
from typing import Optional
2829
from typing import TYPE_CHECKING
2930
import warnings
@@ -824,20 +825,99 @@ def _set_enforce_yaml_key_denylist(value: bool) -> None:
824825
_ENFORCE_YAML_KEY_DENYLIST = value
825826

826827

827-
def _check_config_for_blocked_keys(node: Any, filename: str) -> None:
828-
"""Recursively check if the configuration contains any blocked keys."""
828+
def _validate_mcp_toolset_args(args: Any) -> None:
829+
"""Validates McpToolset args without resolving a code reference."""
830+
from ..tools.mcp_tool.mcp_toolset import McpToolsetConfig
831+
832+
McpToolsetConfig.model_validate(args)
833+
834+
835+
# Entries in this set must be built-in tools whose validator treats the
836+
# YAML input as data only. The name is matched literally; it is never
837+
# imported or otherwise resolved from the configuration.
838+
_MCP_TOOLSET_NAMES = frozenset({
839+
"MCPToolset",
840+
"McpToolset",
841+
"google.adk.tools.MCPToolset",
842+
"google.adk.tools.McpToolset",
843+
"google.adk.tools.mcp_tool.MCPToolset",
844+
"google.adk.tools.mcp_tool.McpToolset",
845+
"google.adk.tools.mcp_tool.mcp_toolset.MCPToolset",
846+
"google.adk.tools.mcp_tool.mcp_toolset.McpToolset",
847+
})
848+
_BUILTIN_LLM_AGENT_NAMES = frozenset({
849+
"Agent",
850+
"LlmAgent",
851+
"google.adk.agents.Agent",
852+
"google.adk.agents.LlmAgent",
853+
"google.adk.agents.llm_agent.Agent",
854+
"google.adk.agents.llm_agent.LlmAgent",
855+
})
856+
857+
858+
def _raise_blocked_key(key: str, filename: str) -> NoReturn:
859+
raise ValueError(
860+
f"Blocked key {key!r} found in {filename!r}. "
861+
f"The '{key}' field is not allowed in agent configurations "
862+
"because it can execute arbitrary code."
863+
)
864+
865+
866+
def _check_node_for_blocked_keys(node: Any, filename: str) -> None:
867+
"""Recursively checks a non-tool configuration node for blocked keys."""
829868
if isinstance(node, dict):
830869
for key, value in node.items():
831870
if key in _BLOCKED_YAML_KEYS:
832-
raise ValueError(
833-
f"Blocked key {key!r} found in {filename!r}. "
834-
f"The '{key}' field is not allowed in agent configurations "
835-
"because it can execute arbitrary code."
836-
)
837-
_check_config_for_blocked_keys(value, filename)
871+
_raise_blocked_key(key, filename)
872+
_check_node_for_blocked_keys(value, filename)
838873
elif isinstance(node, list):
839874
for item in node:
840-
_check_config_for_blocked_keys(item, filename)
875+
_check_node_for_blocked_keys(item, filename)
876+
877+
878+
def _check_tool_configs_for_blocked_keys(
879+
tools: list[Any], filename: str
880+
) -> None:
881+
"""Checks tool configs, allowing args only for registered built-ins."""
882+
for tool in tools:
883+
if not isinstance(tool, dict):
884+
_check_node_for_blocked_keys(tool, filename)
885+
continue
886+
887+
tool_name = tool.get("name")
888+
is_mcp_toolset = (
889+
isinstance(tool_name, str) and tool_name in _MCP_TOOLSET_NAMES
890+
)
891+
for key, value in tool.items():
892+
if key not in _BLOCKED_YAML_KEYS:
893+
_check_node_for_blocked_keys(value, filename)
894+
continue
895+
if not is_mcp_toolset:
896+
_raise_blocked_key(key, filename)
897+
try:
898+
_validate_mcp_toolset_args(value)
899+
except (TypeError, ValueError) as e:
900+
raise ValueError(
901+
f"Invalid {key!r} for safe built-in tool {tool_name!r} "
902+
f"in {filename!r}."
903+
) from e
904+
905+
906+
def _check_config_for_blocked_keys(node: Any, filename: str) -> None:
907+
"""Checks blocked keys with a narrow exception for safe built-in tools."""
908+
if not isinstance(node, dict):
909+
_check_node_for_blocked_keys(node, filename)
910+
return
911+
912+
agent_class = node.get("agent_class", "LlmAgent")
913+
is_builtin_llm_agent = (
914+
isinstance(agent_class, str) and agent_class in _BUILTIN_LLM_AGENT_NAMES
915+
)
916+
for key, value in node.items():
917+
if key == "tools" and is_builtin_llm_agent and isinstance(value, list):
918+
_check_tool_configs_for_blocked_keys(value, filename)
919+
else:
920+
_check_node_for_blocked_keys({key: value}, filename)
841921

842922

843923
_ENFORCE_DENYLIST = True

‎tests/unittests/agents/test_agent_config.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from google.adk.agents.parallel_agent import ParallelAgent
3737
from google.adk.agents.sequential_agent import SequentialAgent
3838
from google.adk.models.lite_llm import LiteLlm
39+
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
3940
from pydantic import BaseModel
4041
from pydantic import ValidationError
4142
import pytest
@@ -815,6 +816,132 @@ def test_from_config_blocks_args_key_when_enforced(tmp_path: Path):
815816
config_agent_utils._set_enforce_yaml_key_denylist(False)
816817

817818

819+
@pytest.fixture
820+
def enforce_yaml_key_denylist(monkeypatch: pytest.MonkeyPatch):
821+
monkeypatch.setattr(config_agent_utils, "_ENFORCE_YAML_KEY_DENYLIST", True)
822+
823+
824+
@pytest.mark.parametrize(
825+
("agent_class_line", "tool_name"),
826+
[
827+
("", "McpToolset"),
828+
("", "MCPToolset"),
829+
("agent_class: Agent\n", "McpToolset"),
830+
("agent_class: Agent\n", "MCPToolset"),
831+
(
832+
"agent_class: google.adk.agents.Agent\n",
833+
"google.adk.tools.MCPToolset",
834+
),
835+
],
836+
)
837+
def test_load_config_from_path_allows_registered_mcp_toolset_args(
838+
tmp_path: Path,
839+
enforce_yaml_key_denylist: None,
840+
agent_class_line: str,
841+
tool_name: str,
842+
):
843+
"""A registered remote McpToolset loads through the public config API."""
844+
config_file = tmp_path / "agent.yaml"
845+
agent_class_entry = (
846+
f" {agent_class_line}" if agent_class_line else ""
847+
)
848+
config_file.write_text(dedent(f"""\
849+
{agent_class_entry} name: mcp_agent
850+
instruction: Use the MCP tools.
851+
tools:
852+
- name: {tool_name}
853+
args:
854+
streamable_http_connection_params:
855+
url: https://example.com/mcp
856+
"""))
857+
agent = config_agent_utils.from_config(str(config_file))
858+
859+
assert isinstance(agent.tools[0], McpToolset)
860+
861+
862+
def test_load_config_from_path_allows_opted_in_stdio_mcp_toolset_args(
863+
tmp_path: Path,
864+
monkeypatch: pytest.MonkeyPatch,
865+
enforce_yaml_key_denylist: None,
866+
):
867+
"""The stdio opt-in also permits its nested command args under web."""
868+
config_file = tmp_path / "agent.yaml"
869+
config_file.write_text(dedent("""\
870+
name: mcp_agent
871+
instruction: Use the MCP tools.
872+
tools:
873+
- name: McpToolset
874+
args:
875+
stdio_connection_params:
876+
server_params:
877+
command: npx
878+
args:
879+
- -y
880+
- example-mcp-server
881+
"""))
882+
monkeypatch.setenv("ADK_ALLOW_CONFIG_STDIO_MCP_SERVERS", "1")
883+
agent = config_agent_utils.from_config(str(config_file))
884+
885+
assert isinstance(agent.tools[0], McpToolset)
886+
887+
888+
def test_load_config_from_path_blocks_unregistered_tool_args(
889+
tmp_path: Path,
890+
enforce_yaml_key_denylist: None,
891+
):
892+
"""Tool args remain blocked unless the built-in has a safe validator."""
893+
config_file = tmp_path / "agent.yaml"
894+
config_file.write_text(dedent("""\
895+
name: custom_agent
896+
instruction: Use the custom tool.
897+
tools:
898+
- name: my_package.create_tool
899+
args:
900+
command: unsafe
901+
"""))
902+
with pytest.raises(ValueError, match="Blocked key 'args' found"):
903+
config_agent_utils.from_config(str(config_file))
904+
905+
906+
def test_load_config_from_path_rejects_invalid_mcp_toolset_args(
907+
tmp_path: Path,
908+
enforce_yaml_key_denylist: None,
909+
):
910+
"""McpToolset args cannot supply executable callback fields."""
911+
config_file = tmp_path / "agent.yaml"
912+
config_file.write_text(dedent("""\
913+
name: mcp_agent
914+
instruction: Use the MCP tools.
915+
tools:
916+
- name: McpToolset
917+
args:
918+
streamable_http_connection_params:
919+
url: https://example.com/mcp
920+
httpx_client_factory: os.system
921+
"""))
922+
with pytest.raises(ValueError, match="Invalid 'args' for safe built-in"):
923+
config_agent_utils.from_config(str(config_file))
924+
925+
926+
def test_load_config_from_path_does_not_allow_args_outside_tool_list(
927+
tmp_path: Path,
928+
enforce_yaml_key_denylist: None,
929+
):
930+
"""A custom agent's tools field cannot opt into the built-in exception."""
931+
config_file = tmp_path / "agent.yaml"
932+
config_file.write_text(dedent("""\
933+
agent_class: my_package.CustomAgent
934+
name: custom_agent
935+
tools:
936+
- name: McpToolset
937+
args:
938+
streamable_http_connection_params:
939+
url: https://example.com/mcp
940+
"""))
941+
with pytest.raises(ValueError, match="Blocked key 'args' found"):
942+
config_agent_utils.from_config(str(config_file))
943+
944+
818945
# --- Discriminator contract ---------------------------------------------
819946

820947

0 commit comments

Comments
 (0)