Skip to content
Open
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
2 changes: 2 additions & 0 deletions agent_core/core/impl/mcp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
StdioTransport,
SSETransport,
WebSocketTransport,
StreamableHTTPTransport,
MCPServerConnection,
set_client_info,
get_client_info,
Expand All @@ -39,6 +40,7 @@
"StdioTransport",
"SSETransport",
"WebSocketTransport",
"StreamableHTTPTransport",
"MCPServerConnection",
"set_client_info",
"get_client_info",
Expand Down
46 changes: 38 additions & 8 deletions agent_core/core/impl/mcp/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,21 @@ 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
import concurrent.futures
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 @@ -162,11 +167,19 @@ async def async_call():
# Use run_coroutine_threadsafe to schedule on the MCP client's event loop
# This works from any thread (including ThreadPoolExecutor workers)
future = asyncio.run_coroutine_threadsafe(async_call(), loop)
return future.result(timeout=60)
wait = mcp_client.handler_timeout(_server)
try:
return future.result(timeout=wait)
except concurrent.futures.TimeoutError:
future.cancel() # do not leave the call running unseen
return {{
"status": "error",
"message": f"MCP tool {{_server}}/{{_tool}} did not finish within {{wait:g}}s",
}}
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 Expand Up @@ -199,7 +212,7 @@ def mcp_tool_to_registered_action(
RegisteredAction ready for registration
"""
# Generate unique action name
action_name = f"mcp_{server_name}_{tool.name}"
action_name = MCPActionAdapter.action_name(server_name, tool.name)

# Build description with MCP context
description_parts = [f"[MCP:{server_name}]"]
Expand Down Expand Up @@ -321,3 +334,20 @@ def unregister_mcp_tools(server_name: str) -> int:
logger.debug(f"Unregistered MCP action: {action_name}")

return count

@staticmethod
def action_name(server_name: str, tool_name: str) -> str:
"""The action name an MCP tool is registered under."""
return f"mcp_{server_name}_{tool_name}"

@staticmethod
def unregister_actions(action_names) -> int:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unregister_mcp_tools (line 308) is now unused.

This new method replaces it, and nothing calls the old one any more. The old one still has the bug this docstring describes: removing server "foo" also removes "foo_bar"'s tools. Could you delete it so nobody uses it again by mistake?

"""Unregister exactly these actions (unlike unregister_mcp_tools,
whose prefix match also hits a server whose name extends this one,
e.g. "foo" and "foo_bar")."""
count = 0
for action_name in list(action_names):
if registry_instance._registry.pop(action_name, None) is not None:
count += 1
logger.debug(f"Unregistered MCP action: {action_name}")
return count
Loading