narrow-chef-71655
12/02/2025, 3:06 PMtall-airline-16756
12/02/2025, 3:06 PMtall-airline-16756
12/02/2025, 3:07 PMNone (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:
@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 docsnarrow-chef-71655
12/02/2025, 3:10 PMmcp.MCPServerHTTP(
url=url,
timeout=20,
client_session_timeout_seconds=20,
)tall-airline-16756
12/02/2025, 3:10 PMMCPServerHTTP 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 docsnarrow-chef-71655
12/02/2025, 3:21 PMsession = 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 internallytall-airline-16756
12/02/2025, 3:21 PMAgentSession 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.narrow-chef-71655
12/02/2025, 3:22 PMtall-airline-16756
12/02/2025, 3:23 PMimport 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)
@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)
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 docsnarrow-chef-71655
12/02/2025, 3:34 PMERROR: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.tall-airline-16756
12/02/2025, 3:34 PMimport 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):
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:
@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.narrow-chef-71655
12/02/2025, 3:41 PMtall-airline-16756
12/02/2025, 3:41 PMToolResult(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
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
@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?