Skip to main content
Glama

exec_mcp_tool

Execute tools on remote MCP servers by specifying target server, tool name, and parameters to route requests through the MCP Router service discovery system.

Instructions

Execute a tool on a target MCP server.

Args:
    target_server_name: Name of the target server
    target_tool_name: Name of the tool to execute
    parameters: Parameters for the tool

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
target_server_nameYes
target_tool_nameYes
parametersYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'exec_mcp_tool' MCP tool. It retrieves the target server's endpoint from the discovery service and dispatches to either SSE or HTTP execution helpers based on the endpoint type.
    @mcp.tool()
    async def exec_mcp_tool(
        target_server_name: str, 
        target_tool_name: str, 
        parameters: Dict[str, Any]
    ) -> str:
        """
        Execute a tool on a target MCP server.
        
        Args:
            target_server_name: Name of the target server
            target_tool_name: Name of the tool to execute
            parameters: Parameters for the tool
        """
        try:
            # Get target server endpoint
            target_endpoint = discovery_service.get_server_endpoint(target_server_name)
            
            # Check if this is an SSE service (like AMap)
            if "sse" in target_endpoint.lower() and HAVE_SSE_SUPPORT:
                # Use SSE connection for services that require it
                return await _execute_sse_tool(target_endpoint, target_tool_name, parameters)
            else:
                # Use HTTP POST for standard MCP services
                return await _execute_http_tool(target_endpoint, target_tool_name, parameters)
        except Exception as e:
            return json.dumps({"error": str(e)}, ensure_ascii=False)
  • Pydantic BaseModel defining the input schema structure for the exec_mcp_tool, matching its parameter types.
    class ExecToolRequest(BaseModel):
        target_server_name: str
        target_tool_name: str
        parameters: Dict[str, Any]
  • Helper function that handles execution of tools on SSE-based MCP servers using MCP ClientSession and proper resource cleanup.
    async def _execute_sse_tool(endpoint: str, tool_name: str, parameters: Dict[str, Any]) -> str:
        """
        Execute a tool on a target MCP server using SSE connection.
        
        Args:
            endpoint: The SSE endpoint URL
            tool_name: Name of the tool to execute
            parameters: Parameters for the tool
        """
        exit_stack = AsyncExitStack()
        
        try:
            # Create SSE client
            sse_cm = sse_client(endpoint)
            streams = await exit_stack.enter_async_context(sse_cm)
            
            # Create session
            session_cm = ClientSession(streams[0], streams[1])
            session = await exit_stack.enter_async_context(session_cm)
            
            # Initialize session
            await session.initialize()
            
            # Execute tool
            result = await session.call_tool(tool_name, parameters)
            
            # Convert result to dict if it's a CallToolResult object
            if hasattr(result, '_asdict'):
                result = result._asdict()
            elif hasattr(result, '__dict__'):
                result = result.__dict__
            
            # Return result as JSON
            return json.dumps(result, ensure_ascii=False, default=str)
        finally:
            # Clean up
            await exit_stack.aclose()
  • Helper function that executes tools on standard HTTP-based MCP servers by sending JSON-RPC 'tools/call' requests.
    async def _execute_http_tool(endpoint: str, tool_name: str, parameters: Dict[str, Any]) -> str:
        """
        Execute a tool on a target MCP server using HTTP POST.
        
        Args:
            endpoint: The HTTP endpoint URL
            tool_name: Name of the tool to execute
            parameters: Parameters for the tool
        """
        # Construct JSON-RPC request
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "tools/call",
            "params": {
                "name": tool_name,
                "arguments": parameters
            },
            "id": 1
        }
        
        # Send request to target server
        async with httpx.AsyncClient() as client:
            response = await client.post(
                endpoint,
                json=json_rpc_request,
                headers={"Content-Type": "application/json"}
            )
            
            # Return the response from the target server
            response_data = response.json()
            return json.dumps(response_data, ensure_ascii=False)
  • mcp_router.py:114-114 (registration)
    The @mcp.tool() decorator registers the exec_mcp_tool function as an MCP tool with FastMCP.
    @mcp.tool()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool executes another tool but does not describe execution behavior such as error handling, permissions required, side effects, or response format. This is a significant gap for a tool that performs dynamic execution, as it lacks details on safety, reliability, or operational constraints.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, with a clear purpose statement followed by a parameter list. Every sentence serves a purpose, and there is no redundant or verbose content. However, the structure could be improved by integrating parameter details more seamlessly rather than a separate 'Args:' section, slightly reducing readability.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (dynamic execution with 3 parameters, nested objects, and an output schema), the description is incomplete. It lacks behavioral context, usage guidelines, and parameter details. The presence of an output schema mitigates the need to explain return values, but the description does not adequately cover execution semantics or integration with sibling tools, leaving gaps for the agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It lists parameters with brief explanations (e.g., 'Name of the target server'), but these add minimal semantic value beyond the schema's property names. The description does not explain parameter formats, constraints, or how 'parameters' should be structured, leaving key details undocumented for a tool with 3 required parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Execute a tool on a target MCP server,' specifying the verb 'execute' and resource 'tool on a target MCP server.' It distinguishes from sibling tools like 'add_mcp_server' and 'search_mcp_server' by focusing on execution rather than server management or searching. However, it lacks specificity about what types of tools can be executed or the execution context, preventing a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention prerequisites (e.g., needing an added server via 'add_mcp_server'), exclusions, or contextual cues for selection. Usage is implied only through the tool name and description, with no explicit instructions for the agent.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Maverick-LjXuan/mcp-router'

If you have feedback or need assistance with the MCP directory API, please join our Discord server