Repository navigation
fix: remove stdin timeout for hooks and SDK MCP servers - #731
Merged
Merged
Conversation
wait_for_result_and_end_input() applied a 60-second timeout before closing stdin, even when hooks or SDK MCP servers were active. If the conversation exceeded this timeout, stdin was closed prematurely, breaking the bidirectional control protocol and causing hook callbacks to fail with 'Stream closed' errors. Remove the timeout entirely when hooks or SDK MCP servers are configured. The _first_result_event is guaranteed to fire: either when the result message arrives normally, or in _read_messages' finally block if the process exits early. This ensures stdin stays open for the full conversation duration. Fixes #730
Contributor
Author
E2E Test ResultsUnit tests pass (2/2 selected): E2E test script -- creates an SDK MCP server with a Test script"""E2E test for PR #731: remove stdin timeout for hooks/SDK MCP servers."""
import asyncio
import datetime
import sys
import time
from claude_agent_sdk import (
ClaudeAgentOptions,
create_sdk_mcp_server,
query,
tool,
)
tool_called = False
tool_call_time = None
@tool("get_current_time", "Returns the current date and time", {})
async def get_current_time(args):
global tool_called, tool_call_time
tool_called = True
tool_call_time = datetime.datetime.now().isoformat()
print(f"[TOOL CALLED] get_current_time invoked at {tool_call_time}", flush=True)
return {
"content": [
{"type": "text", "text": f"The current date and time is: {tool_call_time}"}
]
}
async def main():
time_server = create_sdk_mcp_server(
name="time-server", version="1.0.0", tools=[get_current_time]
)
options = ClaudeAgentOptions(
mcp_servers={"time": time_server},
allowed_tools=["mcp__time__get_current_time"],
permission_mode="acceptEdits",
max_turns=3,
system_prompt="Use get_current_time tool directly when asked for time. Be brief.",
)
start = time.monotonic()
messages = []
mcp_server_connected = False
async for message in query(prompt="What time is it?", options=options):
msg_type = type(message).__name__
if msg_type == "SystemMessage":
data = getattr(message, "data", {})
servers = data.get("mcp_servers", [])
for s in servers:
if s.get("name") == "time" and s.get("status") == "connected":
mcp_server_connected = True
messages.append(message)
elapsed = time.monotonic() - start
print(f"Completed in {elapsed:.1f}s, {len(messages)} messages, MCP connected: {mcp_server_connected}")
assert mcp_server_connected and len(messages) > 0
if __name__ == "__main__":
asyncio.run(main())Output: The SDK MCP server |
qing-ant
enabled auto-merge (squash)
March 25, 2026 20:56
bhosmer-ant
approved these changes
Mar 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
wait_for_result_and_end_input()applied a 60-second timeout (viaCLAUDE_CODE_STREAM_CLOSE_TIMEOUT) before closing stdin, even when hooks or SDK MCP servers required the bidirectional control protocol to remain open. Any conversation exceeding 60 seconds would have stdin closed prematurely, causing hook callbacks to fail with "Stream closed" errors.Fix
Remove the timeout entirely when hooks or SDK MCP servers are configured. Instead, wait unconditionally for the
_first_result_event, which is guaranteed to fire:type: "result"message arrives_read_messages()'sfinallyblockBefore:
After:
Also removes the now-unused
_stream_close_timeoutinstance variable and its per-instanceos.environ.getcall fromQuery.__init__. TheCLAUDE_CODE_STREAM_CLOSE_TIMEOUTenv var is still used inclient.pyfor the separate initialize timeout.Tests
2 new regression tests in
TestNoTimeoutForHooksAndMcpServers:test_hooks_wait_without_timeout— verifiesend_inputis NOT called until the result event firestest_no_hooks_closes_immediately— verifies immediateend_inputwhen no hooks/MCP serversAll 329 tests pass. Lint (
ruff check) and type check (mypy) clean.E2E Verification
Verified with live SDK instance (v0.1.50, CLI 2.1.84):
PreToolUsehook for Read tool was called successfully, stdin stayed open for the full control protocol exchange, query completed without errorsFixes #730