How to add pre/post say method to MCP tools

This question originally came up in our Slack community and the thread has been consolidated here for long-term reference.

Could I add some pre/post say method to tools using MCP? I know it works with native tools, but not sure if there’s support for MCP ones.

There’s no simple interface for this, but you can create a custom MCP server that wraps the original tool:

class MyMCPServer(mcp.MCPServerHTTP):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.session: AgentSession | None = None
    
    def _make_function_tool(self, name, description, input_schema, meta):
        original_tool = super()._make_function_tool(name, description, input_schema, meta)
        
        async def wrapped_tool(raw_arguments: dict):
            # Say something BEFORE the MCP call
            if self.session:
                self.session.say("Looking that up for you.")
            
            result = await original_tool(raw_arguments)
            return result
        
        return function_tool(wrapped_tool, raw_schema={
            "name": name,
            "description": description,
            "parameters": input_schema,
        })

Note: Pre-say works but the voice may be slightly delayed until the tool finishes. Post-say would require tracking when the agent finishes speaking.