is there any way to stop response generation for s...
# ask-ai
n
is there any way to stop response generation for sometime basically when i am calling tool using mcp but it is getting timeout and on that error response generation is happening but i want to off that response generation is there any way i can do this ?
t
Thanks for reaching out, Darshak. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to prevent the LLM from producing a response when your MCP tool call times out. Yes — you can stop response generation by handling the timeout inside the tool and returning nothing. What to do: 1. Wrap the MCP call in a try/except. 2. On timeout, catch the exception and return
None
(or return nothing). That completes the tool silently and prevents the agent from generating a reply. 3. If you want a controlled LLM-visible error instead, raise
ToolError("...")
. Example:
Copy code
@function_tool()
async def my_mcp_tool(context: RunContext, param: str):
    try:
        result = await asyncio.wait_for(call_mcp_backend(param), timeout=5.0)
        return result
    except asyncio.TimeoutError:
        return None  # prevents LLM response
    except Exception as e:
        raise ToolError("Tool failed due to timeout or error.")
Would you like sample code tailored to your MCP client or help adding logging/metrics for these timeouts? Sources: Tool definition and use | LiveKit docs
n
i am using mcp client not any @function_tool()
Copy code
mcp.MCPServerHTTP(
            url=url,
            timeout=20,
            client_session_timeout_seconds=20,
        )
t
Thanks — you're using the MCP client directly. I can help, but I need one quick detail to give a concrete solution: Where and how is the agent invoking the MCP-loaded tool? Specifically: • Are you calling the MCP client from inside an Agent/AgentSession callback (so the LLM can see the tool result), or from application code outside the agent loop? • Can you share the minimal snippet showing the call that times out (how you invoke
MCPServerHTTP
and use it to run the tool)? If you prefer a short path: if the agent receives the MCP tool result, you need to intercept the tool response/error before it’s returned to the agent and either return
None
or raise a
ToolError
. If the MCP client call happens outside the agent, handle the timeout there and do not forward any string result to the agent. Tell me which case matches your setup and paste the snippet and I’ll suggest exact code. Sources: Tool definition and use | LiveKit docs | Remote method calls | LiveKit docs
n
Copy code
session = AgentSession(
    stt=stt,
    llm=llm,
    tts=tts,
    vad=vad,
    turn_detection="vad",
    mcp_servers=mcp_servers,
    preemptive_generation=preemptive_generation,
    min_endpointing_delay=min_endpointing_delay,
    min_interruption_duration=min_interruption_duration,
    user_away_timeout=first_user_away_step,
    allow_interruptions=allow_interruptions,
)
i am initializing as above my session so it is handle internally
t
Thanks — you're using
AgentSession
with
mcp_servers
so the MCP tooling is loaded and invoked internally. To give a precise solution I need one quick clarification: Do you control the MCP tool implementation (the server that AgentSession calls)? Or can you only change code on the client side where you create the
AgentSession
? • If you control the MCP server: modify the tool to catch timeouts and either return
None
(no output) or raise
ToolError("...")
depending on whether you want silence or a controlled LLM-visible error. • If you cannot change the MCP server: would you be able to intercept tool results on the client/agent side (e.g., a callback or hook) before the agent forwards them to the LLM? If so, you can filter timeouts there and return
None
to suppress the response. Tell me which of the two applies and, if you control the MCP server, paste the tool handler snippet that performs the potentially-timing-out work — I’ll provide the exact code to return
None
on timeout or raise
ToolError
as appropriate.
n
give me both ways then i will decide
t
Thanks — below are both concrete options (server-side and client-side) you can choose from. I kept examples minimal so you can drop them into your code. 1) Server-side (modify MCP tool) • Catch timeouts inside the MCP tool handler and either return no output or return an error marker the client can detect. • To suppress LLM reply entirely, return an empty/none result rather than a string. Example (MCP tool pseudocode):
Copy code
import asyncio
from mcp.server.models import ToolResult

async def handle_tool(request):
    try:
        result = await asyncio.wait_for(fetch_external(request), timeout=5.0)
        return ToolResult(output=result)
    except asyncio.TimeoutError:
        # Option A: silent — return no output
        return ToolResult(output=None)
        # Option B: explicit error (client can then decide to suppress LLM)
        # return ToolResult(error="timeout")
When you control the server, this is simple and reliable. Use Option A to avoid any LLM-visible output; use Option B if you want the client to choose whether to show an error. 2) Client-side (intercept inside AgentSession) • Intercept tool results before the LLM node runs and skip calling the LLM when you detect a timeout/error. • Two ways: listen to a tool-executed event or override the session’s
llm_node
to short-circuit inference. A. Event listener (conceptual)
Copy code
@session.on("function_tools_executed")
def on_tools_executed(ev):
    for call, out in ev.zipped():
        if out and out.is_error and "timeout" in (out.output or ""):
            session.interrupt()       # stop any ongoing TTS/speech
            session.skip_next_llm = True  # flag to prevent next inference
B. Override
llm_node
(recommended for full suppression)
Copy code
class MyAgent(Agent):
    async def llm_node(self, chat_ctx, tools, model_settings):
        # detect recent tool error/timeout in chat context
        last = chat_ctx.messages[-1].content if chat_ctx.messages else ""
        if "timeout" in last or getattr(self, "skip_next_llm", False):
            self.skip_next_llm = False
            return  # yields nothing => no LLM response
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            yield chunk
Which to pick • If you control the MCP server: implement server-side Option A (return None) — simplest. • If you cannot change the server or want centralized control: use the client-side
llm_node
override to reliably suppress inference and stop speech. Would you like the exact client-side override adapted to your AgentSession setup (I can show the full subclass and where to attach it)? Sources: Tool definition and use | LiveKit docs | Events and error handling | LiveKit docs | Pipeline nodes and hooks | LiveKit docs
n
Copy code
ERROR:livekit.agents:exception occurred while executing tool
Traceback (most recent call last):
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/anyio/streams/memory.py", line 111, in receive
    return self.receive_nowait()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/anyio/streams/memory.py", line 106, in receive_nowait
    raise WouldBlock
anyio.WouldBlock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/anyio/_core/_tasks.py", line 120, in fail_after
    yield cancel_scope
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/mcp/shared/session.py", line 274, in send_request
    response_or_error = await response_stream_reader.receive()
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/anyio/streams/memory.py", line 119, in receive
    await receive_event.wait()
  File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/locks.py", line 213, in wait
    await fut
asyncio.exceptions.CancelledError: Cancelled via cancel scope 13a583750; reason: deadline exceeded

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/mcp/shared/session.py", line 273, in send_request
    with anyio.fail_after(timeout):
  File "/opt/homebrew/Cellar/python@3.11/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 158, in __exit__
    self.gen.throw(typ, value, traceback)
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/anyio/_core/_tasks.py", line 123, in fail_after
    raise TimeoutError
TimeoutError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 526, in _traceable_fnc_tool
    val = await function_callable()
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/livekit/agents/llm/mcp.py", line 100, in _tool_called
    tool_result = await self._client.call_tool(name, raw_arguments)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/mcp/client/session.py", line 349, in call_tool
    result = await self.send_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/darshakjankat/IdeaProjects/uacode3/ai/python/livekit-agent/.venv/lib/python3.11/site-packages/mcp/shared/session.py", line 276, in send_request
    raise McpError(
mcp.shared.exceptions.McpError: Timed out while waiting for response to ClientRequest. Waited 20.0 seconds.
t
Thanks — I see the MCP client timeout stack trace. Below are focused, actionable fixes for both sides so you can pick one (or combine them). Server-side (best if you control the MCP tool) • Catch the timeout in the tool handler and return no output so the agent gets nothing to feed the LLM. • Or return a clear error marker (e.g., "timeout") that the client can detect. Example (MCP tool):
Copy code
import asyncio
from mcp.server.models import ToolResult

async def handle_tool(request):
    try:
        result = await asyncio.wait_for(fetch_external(request), timeout=5.0)
        return ToolResult(output=result)
    except asyncio.TimeoutError:
        # Silent: returns no output (prevents LLM response)
        return ToolResult(output=None)
        # Or explicit error the client can inspect:
        # return ToolResult(error="timeout")
Client-side (when MCP tools are loaded in AgentSession) • Intercept tool results before the LLM runs and skip LLM inference when you detect a timeout/error. • Recommended: override
llm_node
to short-circuit inference reliably. Example override (client):
Copy code
class MyAgent(Agent):
    async def llm_node(self, chat_ctx, tools, model_settings):
        last = chat_ctx.messages[-1].content if chat_ctx.messages else ""
        # detect timeout marker or flag set by event handler
        if "timeout" in last or getattr(self, "suppress_next_llm", False):
            self.suppress_next_llm = False
            return  # yields nothing -> no LLM response
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            yield chunk
Alternate client-side: listen for the function-tools event, set a flag, and call
session.interrupt()
to stop TTS if needed:
Copy code
@session.on("function_tools_executed")
def on_tools_executed(ev):
    for call, out in ev.zipped():
        if out and out.is_error and "timeout" in (out.output or ""):
            session.interrupt()
            session.suppress_next_llm = True
Quick tuning tips • Your traceback shows the MCP client timed out after 20s (McpError). If appropriate, increase
timeout
and
client_session_timeout_seconds
on
MCPServerHTTP
or reduce the server-side wait to match your expected latency. • Combine both: have the server return a timeout marker and the client short-circuit LLM — most reliable. Which option do you want to implement first — server change or client override? I can provide a drop-in patch for your AgentSession setup.
n
what if llm is RealtimeModel ?
t
Good question — RealtimeModel changes how inference and output are produced (streaming, possibly via a separate realtime node), but the same two strategies still apply. Here’s what to do for RealtimeModel, with concise actionable options. Server-side (recommended if you can change the MCP tool) • On timeout, have the MCP tool return no usable output (e.g.,
ToolResult(output=None)
) or an explicit error marker (
ToolResult(error="timeout")
). • RealtimeModel will only see whatever the agent forwards; if the tool returns nothing, there’s nothing to stream. Client-side (when tools are loaded by AgentSession using RealtimeModel) • Intercept tool results before the realtime LLM node starts streaming and skip/short-circuit the realtime node when you detect a timeout. Two practical ways: 1) Override
llm_node
/ realtime entry point to short-circuit
Copy code
class MyAgent(Agent):
    async def llm_node(self, chat_ctx, tools, model_settings):
        last = chat_ctx.messages[-1].content if chat_ctx.messages else ""
        if "timeout" in last or getattr(self, "suppress_next_llm", False):
            self.suppress_next_llm = False
            return  # yields nothing => realtime model will not stream
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            yield chunk
• This prevents the realtime model from starting any output stream for that turn. 2) Use the function-tools event to stop ongoing realtime output
Copy code
@session.on("function_tools_executed")
def on_tools_executed(ev):
    for call, out in ev.zipped():
        if out and out.is_error and "timeout" in (out.output or ""):
            session.interrupt()            # stops any ongoing TTS/streamed speech
            session.suppress_next_llm = True
• Call
session.interrupt()
to halt any in-progress TTS or streaming audio immediately. Notes specific to RealtimeModel • RealtimeModel may begin streaming as soon as the node is invoked; ensure your interception runs before that node is invoked (override
llm_node
) or immediately interrupt streaming once you detect the timeout. • Combining server-side (return None/error) + client-side override gives the most reliable suppression for realtime streaming. If you want, I can adapt the
llm_node
override to the exact AgentSession subclass you’re using so it wires into your current session instance. Which would you like me to prepare — the override implementation or the MCP tool change?