From 8b1dfe01da0175f36d627df54f059d34b3cfc61e Mon Sep 17 00:00:00 2001 From: Rohan Date: Mon, 23 Nov 2026 17:56:49 +0530 Subject: [PATCH] mcp: insert server and tool names into generated handlers with repr() MCP tool names are chosen by the MCP server and can contain any character, including quotes, backslashes and newlines. Build the generated handler source with repr() literals, so every server and tool name is kept exactly as a string, in the docstring as well as in the values the handler uses. Action names and calls are unchanged. Adds tests with names containing quotes, newlines, triple quotes and a line continuation. Co-Authored-By: Claude Opus 5.5 --- agent_core/core/impl/mcp/adapter.py | 16 +++++---- tests/test_mcp_adapter_names.py | 50 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 tests/test_mcp_adapter_names.py diff --git a/agent_core/core/impl/mcp/adapter.py b/agent_core/core/impl/mcp/adapter.py index e34a32d1..42dcaca8 100644 --- a/agent_core/core/impl/mcp/adapter.py +++ b/agent_core/core/impl/mcp/adapter.py @@ -132,16 +132,20 @@ def create_mcp_handler_with_source( Returns: Tuple of (handler_function, source_code_string) """ - # Generate the source code as a string with values baked in + # Generate the source code as a string with values baked in. + # Server and tool names can contain any character (the server picks + # its tool names), so they are inserted with repr(), which always + # gives a valid string literal for them. # Note: We use double braces {{ }} for dict literals since this is an f-string - source_code = f'''def mcp_handler(input_data): - """MCP tool handler for {server_name}/{tool_name}.""" + docstring = f"MCP tool handler for {server_name}/{tool_name}." + source_code = f"""def mcp_handler(input_data): + {docstring!r} import asyncio from agent_core.core.impl.mcp.client import mcp_client from agent_core.utils.logger import logger - _server = "{server_name}" - _tool = "{tool_name}" + _server = {server_name!r} + _tool = {tool_name!r} # Remove any internal parameters (starting with _) tool_args = {{ @@ -166,7 +170,7 @@ async def async_call(): except Exception as e: logger.error(f"Error calling MCP tool {{_server}}/{{_tool}}: {{e}}") return {{"status": "error", "message": str(e)}} -''' +""" # Create the actual function by executing the source local_ns = {} diff --git a/tests/test_mcp_adapter_names.py b/tests/test_mcp_adapter_names.py new file mode 100644 index 00000000..0fe9e3bd --- /dev/null +++ b/tests/test_mcp_adapter_names.py @@ -0,0 +1,50 @@ +"""Generated MCP tool handlers keep server and tool names as plain strings. + +A tool's name comes from the MCP server and may contain quotes, newlines +or backslashes. The generated handler must hold it unchanged as a string, +both when the action is defined and when the agent calls it. +""" + +from __future__ import annotations + +from typing import Dict + +import pytest + +from agent_core.core.impl.mcp.adapter import MCPActionAdapter +from agent_core.core.impl.mcp.server import MCPTool + + +@pytest.mark.parametrize( + "tool_name", + [ + 'x"; open(MARKER, "w").close(); _ = "', + 'x"\nopen(MARKER, "w").close()\n_ = "', + 'y"""\nopen(MARKER, "w").close()\n"""', + "z\\\nopen(MARKER, 'w').close()", + ], +) +def test_names_with_quotes_and_newlines_stay_strings(tmp_path, tool_name): + marker = tmp_path / "marker" + name = tool_name.replace("MARKER", repr(str(marker))) + handler, source = MCPActionAdapter.create_mcp_handler_with_source( + f'srv"{name}', name + ) + compile(source, "", "exec") # still valid Python + namespace: Dict = {} + exec(source, namespace) # how the action system defines it + assert not marker.exists() + code = namespace["mcp_handler"].__code__ + assert name in code.co_consts and f'srv"{name}' in code.co_consts + # ...and how it runs it when the agent uses the tool. The call itself + # fails (no MCP client here); what matters is that the name did not run. + namespace["mcp_handler"]({}) + handler({}) + assert not marker.exists() + + +def test_a_registered_tool_with_quotes_in_its_name_round_trips(tmp_path): + tool = MCPTool(name='echo"; import os #', description="d", input_schema={}) + action = MCPActionAdapter.mcp_tool_to_registered_action("srv", tool, "mcp_srv") + assert action.metadata.name == 'mcp_srv_echo"; import os #' + assert 'echo"; import os #' in action.handler.__code__.co_consts