Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions agent_core/core/impl/mcp/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {{
Expand All @@ -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 = {}
Expand Down
50 changes: 50 additions & 0 deletions tests/test_mcp_adapter_names.py
Original file line number Diff line number Diff line change
@@ -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, "<mcp handler>", "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