Repository navigation
fix(mcp): stop a hung MCP stdio server from freezing the turn - #5346
Conversation
|
Verdict: Request changes This fixes a real freeze: a stdio MCP server that stops answering no longer hangs the agent's turn. Replies are matched by id, notifications are skipped, stderr is drained, and errors name the server. The design is sound and the real-subprocess tests are good. One regression needs a decision before merge.
Real-world evidenceN/A: there is no evidence bundle for this run. The verdict rests on static review plus the PR's stub-server tests. The PR's manual check (calling a never-answering tool from 🔍 Technical details🟡 Cold-start
Either way, add a stub test that sleeps longer than 🟡 This also matches the 🟢 🟢 Strengths
|
|
🟡 One server with a bad 🔍 Technical details
Validate inside the eligibility loop that builds try:
server_timeout(name, server_config, _CONNECT_TIMEOUT_S)
except ValueError as e:
self._failed[name] = str(e)
logger.warning(str(e))
continueThis keeps the error loud and actionable, limits it to the misconfigured server, and stops the retry on every turn. Add a test with two servers where one has |
A stdio MCP server that never answered froze the turn for good: the 30 s timeout was stored but never used, and stdout.readline() blocked with no way out. The first line read was taken as the reply, so a server that sent a log notification first had that notification returned as the tool result. An undrained stderr pipe could also fill and block a chatty server mid-write. Background threads now drain stdout into a queue and stderr into a tail buffer. send_request waits on the queue with a real deadline, returns only the reply whose id matches, skips notifications and late replies, answers server-initiated requests with method-not-found, and stops early once the agent abandons the tool call. Errors name the server's command line.
…ests Review follow-ups. Enforcing the 30 s default made any MCP tool taking 30 to 180 s fail, below the agent's own per-tool limit; tools/call now waits up to 180 s. A parse-error reply with a null id was skipped and then reported as a hang; it is raised with the server's message. A disconnect mid-request raised an unrelated AttributeError; a request now holds its own process handle and reports the disconnect. A server that exits while a child keeps its pipe open is noticed by polling, a request given up on is cancelled on the server, and errors name the server by program and package only, since arguments can carry tokens.
…ueued Second-round review follow-ups. A server that stopped reading its input blocked a large request forever and held the request lock; writes now run against the request's deadline, and a server that misses it is stopped. disconnect() killed only the parent, so the server npx or uvx started kept running with our pipes open; it now stops the whole tree. Waiting behind another request ignored Stop; it no longer does. The tools/call budget now follows GAIA_AGENT_TOOL_TIMEOUT, ending 5 s before the agent's own limit so the error names the server. A server that misses load_from_config's connect deadline is now stopped instead of left running. The stdout queue is bounded, and inline -c code never appears in a server's label.
…initialise Second-round review follow-ups, two of them red CI. The tree kill used taskkill and killpg: its nosec had no suppression entry, and its POSIX session flag broke the hidden-console test on Linux and macOS. A dead parent also defeated both, since its tree can no longer be walked. The server's descendants are now recorded with psutil every 0.5 s while it runs, and stopped on disconnect even after the parent has exited. Only a process created by this connect() is tracked, so a reused PID is never touched. A server that answered initialize with an error was left running; it is now disconnected. A test now pins tools/call to the agent's budget.
Third-round review follow-ups. The dead-parent walk stopped any process whose parent PID matched the exited server's, and Windows reuses PIDs, so disconnect could stop an unrelated program's children. The walk is gone: only processes seen as the server's own descendants are stopped, and the watcher that records them already covers an exited launcher. The watcher now backs off from 0.5 s to 8 s once the tree settles, instead of walking the process table twice a second for every server. A connect that finished between load_from_config's deadline and its check is now registered rather than lost.
…connects Fourth-round review follow-ups. Errors now name a server by its configured name and executable. A server's ping gets the empty result the MCP spec requires instead of method-not-found. A launch that fails after the process starts (no thread for a reader) stops the process instead of leaving it running. A connect given up on at load_from_config's deadline before its process existed now stops itself when it finishes, and a test pins the connect that finishes right at the deadline.
…ldren The label now takes only the program, tokenized the way the launch splits the command, so a quoted program path with spaces keeps its name; anything that isn't a plain program name shows as "?". A launch that fails after the process starts now stops the server's children too, not just the server. Tests that read a stub's PID file wait until it is written.
…eout Sixth-round review follow-ups. Server labels and launch messages are hardened, with a property test across command, argument and env shapes. A failed launch now stops the server's children even when the server itself has already exited. A server can set its own `timeout` (seconds) in its config. It raises both its request wait and load_from_config's connect deadline, for an `npx -y` or `uvx` server that downloads on first start, and a handshake that times out says so.
Seventh-round review follow-ups. Text a server sends back is now cleaned before it is cut to the length GAIA keeps, and a server's own error replies to initialize, tools/list and tools/call go through the same cleaning. The property test now covers long stderr and stdout echoes, error replies, rejected command lines and debug logging. A server's `timeout` must be finite and at most 600 s, since an infinite or NaN value brought the freeze back, and a bad one now fails only its own server instead of the whole load. The startup check records the server's children as it goes, so a launcher that dies inside it still has them stopped. Hung-server tests stop any process they leave behind.
…k timeouts Eighth-round review follow-ups. Cleaning a server's replies removed every long token of its command line, so ordinary words such as "shipping" or "--stdio" vanished from the errors a model reads, and a unit test went red. Cleaning is now limited to configured secret values, and structured reply values are cleaned before they are turned into text or logged, including at DEBUG. A server timeout is range-checked by comparison, so a huge integer is refused like infinity and NaN instead of raising OverflowError and failing every server. The leak property test now forces the MCP loggers to DEBUG and covers tools/list, tools/call and reply metadata.
Ninth-round review follow-ups. Server output is now cleaned against an explicit list of known secret values instead of shape guesses: env values and KEY=VALUE values whose name looks secret, values after secret flags judged by whole words, URL userinfo, and Authorization or Bearer header values. Each is matched raw, JSON-escaped and as a code-page-mangled decode, and dict keys are cleaned as well as values. Ordinary values such as --max-tokens 4096, -p 3000, --port=8080 and LOG_LEVEL=info stay readable. The contract is in the docstring and the spec. The startup-check child-tracking test no longer leans on the background watcher, and the tool-result debug log is pinned by a test.
Tenth-round review follow-ups. A validation error's tool schema, which is the server's own text, is now cleaned before it is added to the error or logged. A --flag=value is judged by the same whole-word rule as --flag value, so --max-tokens=4096 or --tokenizer=gpt2-xl stay readable. Contract gaps closed: AUTHORIZATION and PROXY_AUTHORIZATION count as secret names (only AUTHOR/AUTHORS are excluded), camelCase flags such as --accessToken are recognised, a URL's user-only userinfo (TOKEN@host) counts, and overlapping secrets are removed together. The 4-character floor and the JSON-number limit are documented. Tests hard-code the expected encodings and pin the PID-reuse guard.
…word Eleventh-round review follow-ups. Known secrets are now also matched as a code page writes them when a character won't fit (a "?" replacement or a backslash escape), as Python's ASCII backslash escapes, and as any JSON form written in a code page. A null-id error reply's cleaning is tested. Env names, KEY=VALUE names and flags now name a secret when their last word, matched whole, is a secret word. MAX_TOKENS, TOKENIZERS_PARALLELISM, AUTH_MODE, max_tokens=4096, --token-limit and --primary-key-id stay readable, and --no-auth takes no value. The encodings tests now write each form for real (Node-style UTF-8 JSON, cp1252 with a euro sign), so removing any single form fails a test.
…test Twelfth-round review follow-ups. A name now holds a secret when any of its words is a secret word (plurals included), unless its last word is a qualifier such as id, mode, limit, file or path, or its first a count (max, min, num); --no- and --disable- flags take no value. That catches API_KEY_2, SECRET_KEY_BASE, STRIPE_SECRET_KEY_LIVE, API_TOKENS, SECRETS and NO_PROXY_TOKEN, which the last-word rule missed, while MAX_TOKENS, AUTH_MODE and --token-limit stay readable. The previous commit said removing any single encoding fails a test; that was too broad. New stub cases now pin the ASCII backslash form and JSON written in cp1252, and the two forms no test could tell apart are gone: a strict code-page encode (replace writes the same bytes) and latin-1 (it differs from cp1252 only in C1 controls). Each form that remains, and each name-rule branch, fails a test when removed.
Thirteenth-round review follow-ups. The list of per-code-page forms is replaced by one pattern per secret. ASCII characters match themselves, with any run of escaping backslashes before \ and ". A non-ASCII character matches itself, up to four of ?, U+FFFD or any non-ASCII character, or a \xNN, \uNNNN, surrogate-pair or \UNNNNNNNN escape behind any run of backslashes. That covers JSON, JSON inside JSON, Python's escapes and any single-byte code page in one place. Correction to the previous commit: it said latin-1 differs from cp1252 only in C1 controls. That was wrong. latin-1 cannot encode the euro sign, so a latin-1 server writes "p?ss1234" for "p€ss1234", and removing latin-1 regressed that case. The new pattern covers it, and a test pins it. Name rule: - names now split at acronym and digit boundaries (APIToken, API_KEY2); - pass, pat, authtoken and apitoken are secret words; - enabled, ttl, endpoint, provider, uri and timeout are qualifiers; - SORT_KEY, PARTITION_KEY and PRIMARY_KEY are database keys, not credentials; - DISABLE_AUTH and NO_AUTH are switches, while NO_PROXY_TOKEN stays a secret. A table-driven test has one row per word, qualifier, count word and key kind, and the two false-positive rows that could never fail now can.
…e bytes Fourteenth-round review follow-ups. The per-character matcher backtracked exponentially, so 8 CJK characters and "1234" against a Chinese stderr tail took 10 s on the turn thread. It also missed code-page bytes that a UTF-8 decode collapsed into fewer characters (cp850, cp866, cp1251). The matcher now anchors on the secret's ASCII core. Each run of k non-ASCII characters is one bounded repetition of 1 to 4k units, and the match is extended over leading and trailing runs by at most 4k units. The search is linear: a 200-character run against 1 MB takes under 0.25 s, and a test pins that limit. Also: - boolean values are never redacted; - required, method, scope, prefix and through are qualifiers, and first is a leading word, so AUTH_REQUIRED and FIRST_PASS stay readable; - PGPASSWORD is a secret name; - tests pin the 4x expansion, uppercase hex, the exact fallback for mostly non-ASCII secrets, the digit-to-letter split and the edge extension.
…line Fifteenth-round review follow-ups. A secret whose ASCII core starts with a backslash or a quote compiled to an unanchored backslash run, so a long run of backslashes in output took quadratic time: 100 KB took about 3 s, and 1 MB minutes. The pattern now starts only at the first backslash of a run, and 1 MB takes 0.02 s. The stderr reader now cleans each line whole as it reads it, off the caller's thread, then keeps at most 8 KB of it. Cleaning first means the cap can't cut a secret in two. A count or order word (max, min, num, first) no longer exempts a name that has a strong secret word, so FIRST_PASSWORD and MAX_SECRET stay secret while MAX_TOKENS and FIRST_PASS stay readable.
Sixteenth-round review follow-ups. Stderr was read a whole line at a time, so a server streaming one line without a newline grew GAIA's memory one-for-one (200 MB for a 200 MB line). It is now read 12 KB at a time. That window is cleaned, its first 8 KB kept, and the rest of a longer line read and dropped. Escaped forms of a secret are redacted too. Each piece of the pattern ends in a character other than a backslash, and the piece after a run of backslashes takes none of its own, so no run is split between two pieces and the search stays linear. Names ending in attempts, age, days or retries (MAX_PASSWORD_ATTEMPTS, MAX_SECRET_AGE) stay readable, and FIRST_PASSWORD is still a secret.
3fa75b2 to
4b51b27
Compare
Server text is decoded into views that map back to the original, and each known secret is looked up in them as a plain string, so redaction stays fast on dense escapes. A stderr line keeps its first 8,192 characters, read with room for the longest form a secret can be written in.
|
Verdict: Approve with suggestions A hung MCP stdio server no longer freezes the agent's turn. Every request now has a deadline, only the matching reply is returned, Stop ends the wait, and a stopped server takes Two things are worth acting on:
Real-world evidenceN/A: no evidence bundle was produced for this run. The verdict rests on static review plus green CI, including MCP Tests on Linux and Windows and the MCPAgent and CLI integration jobs. I couldn't run pytest in this environment. The user-facing 🔍 Technical details🟡 Important
🟢 Minor
Strengths
|
The secret-finding engine had nothing to do with process I/O, so it now lives in gaia.mcp.client.redaction behind secrets_from_launch() and redact(); the transport keeps thin wrappers and finds a server's secrets once instead of re-tokenizing its launch config on every stderr line. A reply to a server's ping now shares the request's deadline, so a server that pings and then stops reading can't stretch the wait past it. The guide notes that a server timeout above the agent's tool limit ends with the agent's generic timeout.
…rness (amd#5405) Build Installers has been red on main since amd#5346. Its custom-agent MCP harness fails on both Windows and Ubuntu. That PR made a crashed MCP server's error name the server and the program it ran, but the harness still expected the old message, which didn't name either. The new message is easier to diagnose, so this updates the test instead of reverting the product change. The test now also checks that the error shows only the program's file name, not its directory or launch arguments. <details> <summary>🔍 Technical details</summary> - The expected text is built from `os.path.basename(sys.executable)` (`python` / `python.exe`), so it holds on every runner. - A slow interpreter outlives the 0.1 s startup check and dies during `initialize` instead, so the same diagnostic arrives as `Error during initialization: …` rather than `Transport error for 'dummy': …`. That race predates amd#5346 (CI wins it, a slower dev box doesn't). The test accepts either wrapper and still pins the diagnostic exactly. </details> ## Test plan - [x] `python -m pytest tests/installer/test_custom_agent_mcp_harness.py` passes locally (Windows) - [x] `python util/lint.py --black --isort` - [ ] Build Installers → Custom agent MCP harness passes on windows-latest and ubuntu-latest
…er (amd#5404) The proactive Claude reviews were failing about half the time, and each failure was lost. The code and security audits failed 5 of the last 10 nights, and the doc walkthrough failed 4 of its last 5 runs. Running three audits every night used up both Claude accounts' weekly limit by mid-week, so most of those runs stopped before reviewing anything and blamed a missing file. The next run never went back for the missed work. Now one audit runs each night between 2 and 4am Pacific, so each audit runs every third night. Each run checks Claude is available before starting, and says plainly when it isn't. It picks up everything since its last successful run, starts from what merged since then, and checks against the bug types past audits missed. The dedup pass no longer re-files duplicates that were already closed: 34 of them were closed alongside this change. ## Test plan - [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py tests/unit/test_require_claude.py tests/unit/test_recent_changes.py tests/unit/test_miss_analysis.py tests/unit/test_claude_audit_workflow_contract.py tests/unit/test_closed_duplicates.py -q` passes (277 tests) - [ ] After merge: `gh workflow run claude-audit-rotation.yml -R amd/gaia -f dry_run=true`. The summary names tonight's audit and the next five nights, and nothing is dispatched. - [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia -f dry_run=true`. Check the preflight summary: the mode, a window reading "since this audit's last successful run", the Claude probe passing, and "Recent changes read first". At the end, "Dry run confirmed: no issue created". - [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide is walked, "Using bash.exe from …" appears, and the dry-run watermark step passes (it crashed before this change). - [ ] After merge: `gh workflow run claude-security-audit.yml -R amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and the SARIF uploads. - [ ] First scheduled night (10:13 UTC): the dispatched run is titled "… rotation night N", files at most what's new, and an issue it files carries `audit-cluster` / `audit-key` markers. <details> <summary>🔍 Technical details</summary> **Root causes (last ~2 weeks)** - Code and security audits, Oct 7/10/12/13/14/17: every lens returned `is_error` in under a second with "You've hit your weekly limit". The primary account ran out on Oct 10, the secondary on Oct 12–14, both on Oct 17. The account switch fired correctly; both accounts were spent. - Walkthrough Oct 12: same weekly limit on every guide, queued over 57 hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp` images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5, the executor step's `GITHUB_OUTPUT` got UTF-16 appended by `start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application Control blocked `LemonadeServer.exe` and the job landed on Strix Halo machines; both were fixed by the move to the `xsj-dispatch` pool on Oct 1. - The walkthrough's two dry-run steps had a literal `\n` mid-command, so `dry_run=true` always failed. **Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only 10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days since epoch mod 3 → code audit, security audit, doc walkthrough. The audits lost their own crons; `workflow_dispatch` still runs any of them on demand. Deep code sweep: whenever the last successful one is over 8 days old (every third turn, retried on the next turn if it fails). **Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass: the run checked out main 7 hours before amd#3310 merged. Three duplicate pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414, amd#5199/amd#4875). Backlog matching compared findings against issue titles only, so a same-section duplicate worded differently scored 0.05–0.15, below the 0.18 threshold. Now matching includes each audit issue's own markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their keys to the open canonical, so consolidating into amd#1077/amd#4331 does not trigger re-filing. Both syntheses share the `claude-audit-issue-filing` concurrency group. The security audit files to private code scanning, not issues, so it cannot duplicate the other two. **Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466 amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442 amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436 amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064, amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875. **Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%) closed an issue an audit filed first. Missed, by title: no deadline 90 (amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27 (amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951 amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which a static read rarely catches. Noise: of the audit issues closed as duplicate or not planned, 31 were duplicates of amd#1077, 12 of the test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a checklist per class and a "Don't report" list, and all three prompts read it at run time. The code audit gets a deterministic list of calls with no deadline. The security audit's semgrep run and worklist now cover TypeScript, Go, the installer and the workflows. `scripts/audit/miss_analysis.py` refreshes the evidence monthly. **Recent changes.** Each audit's first job writes `recent-changes.md`: first-parent commits since the commit its last successful run checked out, read from the run history, with PR title, a short body excerpt and the paths each touched, capped at 30 KB. If that commit is unknown it covers 3 days and says so. </details>
A stdio MCP server that stopped answering, or stopped reading, froze the agent's turn for good: the 30 s timeout was stored but never used, and nothing could break the read or the write. A server that sent a log notification before its reply had that notification returned as the tool result. A server that logged a lot to stderr could block on the full pipe, and
npx's real server outlived disconnect. Now every request is bounded, only the matching reply is returned, Stop and an abandoned tool call end the wait, a stopped server takes its children with it, and errors name the server.Reproduced by
tests/unit/mcp/client/test_stdio_hung_server.py, which runs real stub servers: one that never replies, one that never reads, one that sends a notification first, one that floods stderr, and one that starts a child. They fail on main and pass here.🔍 Technical details
Reads: background threads drain stdout into a bounded queue and stderr into a bounded tail (at most 200 lines, each capped at 8,192 characters; a line is read in a window of at least 12,288 characters and the rest of a longer one drained in 64 K-character reads, so an endless line can't grow memory), which is still used for crash diagnostics.
send_requestwaits against one deadline, wakes every 0.25 s to checktool_cancelled()and whether the process exited, and returns only the reply whose id matches.Writes: they run against the same deadline. A server that misses it has a partial message on its pipe, so it is stopped.
Queueing: waiting behind another request also ends on Stop or the deadline.
Protocol: notifications and late replies are skipped. A server's
pinggets an empty result; any other server-initiated request gets -32601 back. A null-id error (a parse error) is raised with the server's message. A request given up on is cancelled on the server withnotifications/cancelled.Budgets:
tools/callwaits forGAIA_AGENT_TOOL_TIMEOUT(180 s by default) less 5 s, so the transport's error, which names the server, lands before the agent's generic timeout. Other requests keep the 30 s default. A server can set its owntimeoutin its config (finite, at most 600 s; a bad one fails only that server), which also stretchesload_from_config's connect deadline, for annpx -yoruvxpackage that downloads on first start.Cleanup: the server's descendants are recorded with psutil while it runs (every 0.5 s, backing off to 8 s once the tree settles), so
disconnect()stops them even after the parent (npx, a venv launcher) has exited. Only processes seen as its descendants are stopped, never ones matched by parent PID, which the OS reuses. A launcher that starts a child and exits within 0.5 s can still leave it behind. A server that missesload_from_config's connect deadline (even one whose process starts after it), answersinitializewith an error, or fails to start its readers is now stopped instead of left running.Labels: errors name the server by its configured name and executable.
Secrets in server output: GAIA's own messages never include a server's command, arguments or env. Errors and logs built from a server's text (stderr, error replies, a validation error's schema, debug logs of results) are cleaned of exactly the known secret values in its launch config, and nothing else:
KEY=VALUEvalues, and values after flags, whose name has a secret word, matched whole and camelCase-aware (API_KEY_2,SECRET_KEY_BASE,--accessToken), unless its last word is a qualifier (AUTH_MODE,--token-limit) or its first a count (MAX_TOKENS,--max-tokens=4096);--no-/--disable-flags take no value;user:pass@orTOKEN@), and Authorization or Bearer header values.Escaped forms of a secret are redacted too, and overlapping matches go together. Values under 4 characters and JSON-number echoes are out of scope. A successful tool result is returned to the agent unredacted, by design. Debug logs of raw traffic can still hold other server output.
Not done here: the user's Stop doesn't yet reach a running tool body. The agent's bounded-tool runner sets the cancel flag only on its own timeout. The transport already honours the flag, so the follow-up is a small change in
agent.py.Test plan
python -m pytest tests/unit/mcp/ tests/unit/test_child_env.py tests/unit/test_child_env_launch_sites.py tests/unit/test_windows_hidden_console.py tests/mcp/test_mcp_sdk_integration.py tests/mcp/test_mcp_cli_to_agent_workflow.py -qgaia chat. The turn ends with an error naming the server instead of hanging.