Repository navigation
fix(tui,mcp): show MCP servers that failed to start in /mcp, bound to their server and with credentials redacted - #835
Vasanthdev2004 wants to merge 41 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughMCP startup failures now flow from the CLI runtime into TUI state. The ChangesMCP failure visibility
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant MCPRuntime
participant CLI
participant TUIModel
participant MCPState
participant MCPView
MCPRuntime->>CLI: Return skipped server failures
CLI->>TUIModel: Pass MCPSkipped through tui.Options
TUIModel->>MCPState: Build failed server state
MCPState->>MCPView: Provide redacted failure reason
MCPView->>MCPView: Sanitize and bound rendered output
Possibly related PRs
Suggested reviewers: Merge Risk:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/cli/app_mcp_skipped_test.go (1)
63-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that the failure reason is forwarded.
The test only verifies the server name. Also assert
MCPSkipped[0].Errcontains"connection refused"so a regression that drops the recorded error cannot pass.Proposed test strengthening
if len(launchedOptions.MCPSkipped) != 1 || - launchedOptions.MCPSkipped[0].Name != "docs" { + launchedOptions.MCPSkipped[0].Name != "docs" || + launchedOptions.MCPSkipped[0].Err == nil || + launchedOptions.MCPSkipped[0].Err.Error() != "connection refused" { t.Fatalf("MCPSkipped = %#v, want the failure startup recorded", launchedOptions.MCPSkipped) }As per coding guidelines, add a regression test for behavior changes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/app_mcp_skipped_test.go` around lines 63 - 66, Strengthen the existing MCPSkipped assertion in the test by also verifying that MCPSkipped[0].Err contains “connection refused,” while preserving the current server-name check and failure-count validation.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/cli/app_mcp_skipped_test.go`:
- Around line 63-66: Strengthen the existing MCPSkipped assertion in the test by
also verifying that MCPSkipped[0].Err contains “connection refused,” while
preserving the current server-name check and failure-count validation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6847c24c-e809-446d-80a2-a6db7325507d
📒 Files selected for processing (8)
internal/cli/app.gointernal/cli/app_mcp_skipped_test.gointernal/tui/command_views.gointernal/tui/mcp_failed_state_test.gointernal/tui/mcp_state.gointernal/tui/mcp_view.gointernal/tui/model.gointernal/tui/options.go
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
anandh8x
left a comment
There was a problem hiding this comment.
The failed-state wiring and secret redaction look good, but the new failure-reason rendering needs terminal sanitization before merge.
BuildMCPViewState passes redaction.ErrorMessage(err, ...) into MCPServerView.Error, and mcpManagerServerLines inserts that value directly into the rendered lines. Redaction removes credentials but does not remove ANSI/OSC sequences, other control characters, or embedded newlines. I reproduced this with an MCP error containing connection refused\x1b[2J\n› forged · enabled; the resulting server line retained both the escape sequence and newline unchanged. A server-controlled handshake error can therefore manipulate the terminal or forge extra /mcp rows.
Please normalize the displayed reason to safe single-line terminal text: strip ANSI/OSC and control characters, flatten CR/LF, apply a reasonable length cap, and add a regression covering escape and newline injection.
Everything else in the change looks correct, and the focused tests and CI are green.
c7421d9
|
@anandh8x fixed in Before the fix the panel rendered your payload as: Escape sequence intact, forged row on its own line.
Two regressions, both of which fail on the previous commit: one asserts no escape byte survives, no line carries its own newline, the forged text never starts a row, and the real reason still shows. The other pushes 5000 characters through and asserts the line stays bounded. Re-requesting you and @kevincodex1, since the push dismissed his approval. One thing worth flagging beyond this PR: the same class exists at |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/tui/mcp_view.go`:
- Around line 192-238: Bound MCPServerView.Error before processing in the
sanitizer around the visible rune conversion and strings.Builder accumulation.
Verify whether Runtime.Skipped() already imposes a strict size limit; if not,
limit the raw input before converting to []rune and stop accumulating once the
maxMCPReasonLen display budget is reached, while preserving ANSI stripping,
whitespace normalization, and truncation behavior.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 63dc33b5-a906-45b6-b233-5fc22f09514c
📒 Files selected for processing (2)
internal/tui/mcp_failed_state_test.gointernal/tui/mcp_view.go
|
Pushed one more commit for the bot's finding, which was real. The 400 rune cap ran at the end, so the sanitizer walked the whole server string first, and escape sequences get consumed without producing output. 64KB of The bot's other claim on #866 (duplicate |
gnanam1990
left a comment
There was a problem hiding this comment.
Verdict: Approve
Verified empirically on the branch (checked out, built).
What I checked
- Gut-the-fix: forcing the failure branch off (
mcp_state.go:71) so a skipped server renders as "enabled" turns the TUI MCP tests red. The tests exercise the behavior. - Precedence is right and tested: a server that is both disabled and recorded-failed shows as "disabled", not "failed" (
mcp_state.go:66-69), and this is asserted directly (mcp_failed_state_test.go:45— "disabled to win over a recorded failure"). Correct — a server you turned off was never expected to connect. - Reason is redacted before display (
redaction.ErrorMessage,mcp_state.go:73) — invariant 6, so a path/credential in a startup error can't leak into the panel. Empty-error fallback ("server did not start") is handled too. - Skipped set reaches the panel via
MCPSkipped: mcpRuntime.Skipped(); companion to #822 which did the same forzero mcp check. - Clean scope — every file is the MCP panel or its plumbing.
Worth a quick confirm (non-blocking)
- On reconnect (
zero mcp enableafter a failure), the panel is rebuilt from a freshSkippedset, so it should flip back to enabled — worth a sanity check that the runtime clears the entry on a successful re-register.
Good fix.
jatmn
left a comment
There was a problem hiding this comment.
I found issues that need to be addressed before this is ready.
Merge and review state
- Review decision: GitHub still reports
CHANGES_REQUESTED(anandh8x’s review onbe580766is not dismissed). Terminal sanitization and raw-input bounding from that review look addressed on the current head, but the merge gate still needs a fresh approval on6521c367. gnanam1990 approved on6521c367; CodeRabbit approved on the same head. - Mergeability:
MERGEABLE, no conflict markers in the PR diff.mergeStateStatusisBLOCKEDpending required reviews. - Checks: All CI / CodeQL / Zero Review / CodeRabbit checks passed on head.
Prior review alignment
gnanam1990’s approval is valid for what they checked: skipped servers map to failed, disabled wins over recorded failure, reasons are redacted at build (redaction.ErrorMessage), MCPSkipped reaches the TUI, and the focused tests go red when the failure branch is gutted. Those checks exercise buildMCPServerViews, renderMCPView, and m.mcpText() — not the bare /mcp manager overlay entry point. Their non-blocking note about enable clearing Skipped on reconnect is separate from this finding; live reconnect from the TUI is out of scope per the author, and mcpSkipped remains a startup snapshot.
That approval does not negate the remaining gap below: state and redaction work on the transcript/renderMCPView path, but the overlay users get from bare /mcp still omits the reason line.
Findings
- [P2] Bare
/mcpshowsfailedin the manager overlay but not the failure reason
internal/tui/model.go(commandMCP→openMCPManager),internal/tui/mcp_manager.go(mcpManagerOverlay,mcpManagerServerMeta,mcpManagerSelectionDetail),internal/tui/mcp_view.go(mcpManagerServerLines,renderMCPView)
Empty/mcphas long routed toopenMCPManager()— this PR did not change that. What it did change is meaningful:buildMCPServerViewsnow marks skipped servers asfailed, so the overlay meta and detail pane correctly sayfailedinstead of the pre-PRenabledwith missing tools. The recorded reason, however, is rendered only inmcpManagerServerLinesinsiderenderMCPView(). The overlay never readsserver.Erroror callssanitizeTerminalReason, so a user who types/mcpafter a startup warning sees the right state but not the “why” issue #825 and this PR’s description target. TherenderMCPViewpath does show the sanitized reason — on/mcp listand other transcript subcommands, and in transcript output appended after manager actions such as check or list — but the primary overlay surface is still incomplete relative to the stated fix.TestModelMCPPanelReportsStartupFailuresexercisesm.mcpText()/renderMCPView(), not the bare/mcpentry point. Please surface the sanitized reason in the manager overlay (list meta, selection detail, or both), reusing the samesanitizeTerminalReasonpathmcpManagerServerLinesalready uses.
ff70596
6521c36 to
ff70596
Compare
An empty /mcp opens the manager overlay, and it reported the state without the reason. The recorded "why" was rendered only by mcpManagerServerLines inside renderMCPView, which serves /mcp list and the transcript, so the panel said "failed" and stopped exactly where someone goes to find out why after the startup warning has scrolled away. The reason now sits in the selection detail, directly under the header and above the target, through the same sanitizeTerminalReason path the transcript uses. TestModelMCPPanelReportsStartupFailures drives m.mcpText() and passes with or without this, which is how the gap survived review. The new tests drive openMCPManager().mcpManagerOverlay() instead. Mutation-verified: feeding the sanitizer an empty reason fails the first one. The sanitization test deliberately does not search for a bare escape byte. The overlay is lipgloss-styled and therefore full of escape sequences it wrote itself, so the assertion is that the SERVER's payload did not survive: no clear-screen sequence, and no row carrying the forged text on its own. The sanitizer collapses the newline, so the forged text stays inert on the reason line rather than becoming an entry of its own. Reported by jatmn on #835.
|
Rebased onto main and fixed the overlay gap. Thanks @jatmn, that was exactly right and the reason it survived review is worth stating. The finding. Bare Why it got through. One thing I got wrong while writing the sanitization test, worth recording. My first version asserted the overlay contained no The rebase. Two conflicts against #884:
@anandh8x your changes-requested predates the terminal-sanitization work you asked for, which landed a while back; a re-look when you have a moment would unblock this. |
jatmn
left a comment
There was a problem hiding this comment.
I found issues that need to be addressed before this is ready.
Findings
- [P1] Redact the configured server credentials before retaining its error
internal/tui/mcp_state.go:73
ErrorMessageis called with empty options, even though remote MCP clients send every value inMCPServerConfig.Headers. A server can echo an arbitrary configured value (for exampleX-Workspace-Credential: <value>) in its failed startup response; that value is not covered by the generic redaction patterns, is saved inMCPServerView.Error, and is newly rendered in both/mcpsurfaces and the session transcript. Pass the configured secret values into redaction (and cover an echoed custom header); this also avoids relying on the syntacticAuthorization:matcher, which terminal control bytes can evade before the later sanitizer removes them.
|
@jatmn @gnanam1990 this push dismissed your approvals, sorry. It merges main at 2ffe183 and renames this branch's imports to the Twigpine module path from #1105, which the branch needed before it could build on main. The only conflicts were the import blocks in |
…the C1 fixture TestShortConfiguredValuesDoNotShredTheMessage checked only that "connection refused" survived, so it passed just as well with the 1 and the true redacted, which are the values it exists to protect. It now compares the whole message. The C1 control fixture held a raw U+0090, which staticcheck reports as ST1018. It is written as an escape now; the input is the same.
|
One more push on top of the rename: 761fbd3 carries the two CodeRabbit test fixes I had held since September so as not to dismiss approvals. The short-value test now compares the whole message, and the C1 splitter is written as an escape sequence instead of a raw invisible character. Test-only; |
jatmn
left a comment
There was a problem hiding this comment.
I rechecked this PR on head 27218dc (full diff, focused tests, blind search). One code item remains before I’d approve; the rest of what I raised on 42a95b9 (redaction pipeline, arg boundaries, manager ConfigKey, optional completion, collision/enable paths, etc.) is addressed on current head or is explicitly out of scope for #825.
Merge readiness
- Branch is not behind
origin/main; required CI on27218dcis green. - My CHANGES_REQUESTED on
42a95b9is stale relative to this head—treat it as superseded by this note once the finding below is fixed (or tell me if you want any prior thread item re-opened with a specific repro on27218dc).
🟡 P2 — Use each row’s ConfigKey in transcript MCP action hints
📍 Where: internal/tui/mcp_view.go (mcpServerActionLine, consumed from mcpManagerServerLines in the /mcp transcript text).
💥 What fails: The panel lists suggested CLI commands with the canonical runtime name, not the configuration map key:
actions := []string{"zero mcp check " + name} // name = strings.TrimSpace(server.Name)For a server stored under a padded key such as " docs ", the row displays as docs but zero mcp check (and siblings) look up cfg.Servers[serverName] by exact key. The manager overlay already dispatches check/disable/enable/remove with ConfigKey; copying the transcript hint runs the wrong command or reports “not configured” while the panel still shows a failed server.
🔎 Root cause: This PR split display identity (Name, trimmed runtime) from action identity (ConfigKey, exact map key) and wired ConfigKey through the manager, but the transcript action line still builds commands from Name only—the last in-diff operator surface missing from the same identity contract you already applied in mcp_manager.go.
📜 Stated contract:
ConfigKey is the EXACT key in the configuration map, untrimmed. Actions address the config by that key, so it is the only identity that can select one row when a padded alias renders under the same canonical name.
🏷️ Attribution: Incomplete fix on this PR at 27218dc. Misleading hints for padded keys existed at merge-base too; what’s new is the documented ConfigKey rule and manager compliance—transcript hints need to match in the same pass.
📌 In this PR:
internal/tui/mcp_view.go—mcpServerActionLine/mcpManagerServerLinestranscript actions (must useConfigKey)internal/tui/mcp_manager.go— already correct (do not regress)
🔒 Unchanged on main: CLI key lookup; stderr / mcp check redaction (still generic redaction.ErrorMessage as before this PR’s panel work).
🔧 Required correction: Build every zero mcp … hint in mcpServerActionLine from server.ConfigKey (shell-quote when the key contains whitespace or shell metacharacters). Add a regression test with a padded key that the action line includes the exact map key, not only the trimmed display name.
🛠️ Author fix: Fix transcript action hints and the test in one pass; leave manager dispatch, CLI, registration, stderr, and mcp check redaction alone unless you’re deliberately expanding scope.
🚫 Out of scope for this round: Panel-grade redaction on stderr / mcp check / ACP; optional MCP “enabled” while background registration runs; view cache keyed on late-failure count only; in-session re-register after config edits (per your PR note).
The commands printed under each server in the /mcp transcript were built from the trimmed display name, while check, enable, disable and remove look the server up by its exact config key. For a padded key such as " docs " the hint reported "not configured", and for an alias pair it addressed the other entry. The manager overlay already dispatches with ConfigKey; the transcript hints now use it too. A key with space padding is double-quoted, which keeps the spaces in POSIX shells, PowerShell, cmd and /mcp. Padding that cannot be typed back from a terminal line, such as a tab, gets no key-addressed hint. oauth login keeps the trimmed name, because it matches the normalized server list rather than the config map.
|
@jatmn fixed in 3a9dcb0, plus a merge of main. The check, enable, disable and remove hints in the transcript now use Two cases don't use the key:
|
jatmn
left a comment
There was a problem hiding this comment.
I found four issues that need to be addressed before this is ready. The latest transcript action-hint fix is correct, including the author's distinction between exact configuration keys and OAuth's normalized names. I also verified the explanations about disabled aliases, the overlap-versus-cut tests, and the deliberately excluded reconnect/stderr behavior.
Reviewed head 2c36c67ac8be29ff13b59b18f580ac656b9cb6e0 against merge-base and live main 4247a07aba0f89c3c2597314a33edaede56be70c.
Merge readiness
The branch is mergeable and 0 commits behind main; no rebase or release-metadata conflict was found. All 12 executed checks succeeded; CodeRabbit was skipped. GitHub reports BLOCKED / CHANGES_REQUESTED, so fresh review approval is needed after the fixes. The closed #822 diagnostic issue is complementary, and merged #1113 supplies the OAuth fields involved below; neither supersedes #835.
Findings
🟠 P1 — Include supported runtime credentials in the new failure-redaction input
📍 Where: internal/mcp/oauth_store.go:286-294 (SecretValues) and internal/tui/mcp_state.go:915-921 (environment collection).
💥 What fails: Three real startup paths disclose an opaque credential in both the transcript panel text and manager detail:
- With
auth: oauthand no configured OAuth block, a stored dynamically registeredClientSecretis submitted on refresh. A token endpoint'serror_descriptionecho is displayed verbatim. - A credential in the discovered/stored
TokenEndpointis likewise absent from the new redaction input. A real failing token POST that echoes itsworkspacequery value exposes it. - A stdio child can inherit
COMPANY_TOKENfrom the launching environment, as the documented secret-manager setup permits. When the child reports that value while failing initialization, the new reason displays it even though Target contains no credential.
I reproduced the last case with a real child through the existing execution adapter's supported degraded path; its environment scrubber leaves this unlisted variable available. All three corresponding display probes pass at the merge base, where startup error text is not rendered.
🔎 Root cause: The new safety input is reconstructed from configured fields and only part of stored OAuth material:
values = append(values, stored.AccessToken, stored.RefreshToken)
// The configured-environment collector separately visits only raw.Env.It misses accessible credentials that the supported startup paths actually use. The token-context fingerprints also receive the incomplete stored set.
📜 Stated contract:
“Redact success and error paths (including stderr).” —
AGENTS.md
“ClientSecret is sensitive.” — the existing
StoredTokencontract
“A secret manager that injects the env var your MCP server reads on its own (the command and args then run inside that environment).” —
docs/EXTENDING.md
🏷️ Attribution: PR-introduced disclosure. Stored discovery fields and inherited environment already exist on base/main, but the newly added failure-reason path exposes them. This is not a request to repair the older stderr policy.
📌 In this PR:
| Surface | Current result |
|---|---|
oauth_store.go:SecretValues and its new tests |
Access/refresh tokens covered; stored client secret and token-endpoint credential components missing |
mcp_state.go:mcpServerSecretValues |
Configured headers/env/args/URL/OAuth covered; inherited sensitive stdio variables missing |
registry.go, cli/app.go, tui/model.go, command_views.go |
Capture/current-context handling consumes the same incomplete credential inputs |
mcp_view.go and mcp_manager.go |
Both consume the resulting unsafe reason; shared input correction should protect both |
🔒 Unchanged on main: Login, refresh, environment merging/scrubbing, and token persistence already implement these startup sources. Public client IDs, scopes, expiry, token types and ordinary environment metadata are not credentials.
🔧 Required correction: Extend the PR's new safety-input collection to cover the stored client secret, credential-bearing stored token-endpoint components using the existing URL rules, and inherited credential-named stdio variables such as COMPANY_TOKEN. Keep capture/current context consistent for mutable stored material. Preserve read-only enumeration, existing bounds, ordinary metadata and current configured-value protection. Verify real refresh/child failures through both displays, including relevant credential-change suppression.
🛠️ Author fix: Close the missing-input rule across every row above in one pass, including source comments and regression fixtures. Do not fix only the OAuth example or only the environment example; do not require a new observation architecture or plaintext credential store.
🚫 Out of scope: OAuth protocol changes, sandbox environment policy, introspecting secrets created inside arbitrary wrapper scripts, unrelated logging and reconnect behavior.
🟠 P1 — Preserve query credential provenance across raw and decoded spellings
📍 Where: internal/tui/mcp_state.go:1103-1134 (mcpURLSecretValues).
💥 What fails: Real HTTP registration failures expose configured URL credentials in both displays:
?api%5Fkey=%73crtfollowed by a value-only echo of%73crt: Target recognizes the decoded sensitive key and masks it, but Error prints the recoverable raw credential spelling.?workspace=opaque%2Dworkspace%2D9f3c2b7&filter=a;bfollowed by a decoded-value echo: the unrelated semicolon error causes the valid decoded workspace candidate to be discarded. An unrelated invalid escape has the same effect. A normal valid-query control is protected.
🔎 Root cause: The raw pass classifies an undecoded key, while the decoded pass is discarded wholesale on any query parse error. Raw and decoded representations therefore lose either their credential classification or their membership in the candidate set.
if isSensitiveMCPDisplayKey(rawKey) { /* ... */ }
query, err := url.ParseQuery(parsed.RawQuery)
if err != nil {
return known, values
}📜 Stated contract:
“Redact success and error paths (including stderr).” —
AGENTS.md
The existing TestShortValuesUnderSensitiveKeysAreRedacted and TestPercentEncodedEndpointCredentialsAreRedacted assert the specific supported contracts: known credentials bypass the readability floor, and configured escaped/decoded URL values remain protected.
🏷️ Attribution: PR-introduced. The collector and rendered failure reason are new; identical real transport/display probes do not expose these values at base/live main.
📌 In this PR:
| Surface | Current result |
|---|---|
| Main server URL | Both failures reproduced |
| Positional/separate/packed URL-valued stdio arguments | Same mcpURLSecretValues collector |
| Configured OAuth token, authorization, registration and issuer URLs | Same collector |
| Target query renderer, fragment collector and raw userinfo-password handling | Already retain the relevant decoded-key/per-value provenance; preserve these |
| New URL/provenance/assembled-state tests | Cover valid escaped values, but not escaped short-value keys or a valid pair beside a parse error |
🔒 Unchanged on main: URL admission and generic redaction. The accepted URL loader does not reject these query strings; this finding does not require changing that policy.
🔧 Required correction: Classify each raw query value using its decoded key, retaining both supported value spellings with that classification. Preserve independently decodable pairs when another pair fails. Use the corrected shared helper for every listed caller, with regression controls for ordinary short metadata and all demonstrated combinations.
🛠️ Author fix: Fix the query extraction rule and all listed caller coverage together. Do not patch one parameter name or one URL source; do not rewrite core URL validation or generic redaction.
🚫 Out of scope: New encoding schemes, broad configuration rejection rules and unrelated CLI output.
🟠 P1 — Mark interrupted HTTP error details as incomplete
📍 Where: internal/mcp/network_client.go:643-646 (httpStatusError).
💥 What fails: An HTTP or SSE server returns 500 with Content-Length: 2048, sends only the first 24 bytes of a configured 32-byte opaque credential, then closes. The real client retains those bytes, but ErrorDetailTruncated is false. Both new failure displays show Qw7ZmPr4aBcD9eFgH2jKlM6n, 24 of the 32 secret bytes. Complete-body controls remain protected.
🔎 Root cause: The new incompleteness signal recognizes only the size cutoff and discards the body-read failure:
body, _ := io.ReadAll(io.LimitReader(response.Body, maxHTTPErrorDetail+1))
truncated := len(body) > maxHTTPErrorDetailA short partial body cannot match the complete configured credential, and neither this false marker nor the local 20 KiB bound activates the existing tail repair.
📜 Stated contract:
“Redact success and error paths (including stderr).” —
AGENTS.md
The existing TestCredentialPrefixCutByTheHTTPReaderIsNotDisplayed protects credential prefixes cut at the producer; this is an observable interrupted-read variant of that same boundary.
🏷️ Attribution: PR-activated disclosure. Base/main already discard the read error, but do not render this startup body in the MCP views. The PR adds both the reason consumers and the incomplete producer marker. Identical HTTP/SSE display probes pass at base.
📌 In this PR:
httpStatusError: shared by HTTP POST, SSE stream GET and SSE POST.ErrorDetailTruncated/redactMCPFailureReason: existing new consumer correctly repairs marked partial text.- Both reason renderers: affected through shared state.
- New producer/truncation tests: size-cut and complete-body cases covered; read-error case absent.
🔒 Unchanged on main: Network transport architecture and old stderr/check behavior.
🔧 Required correction: Treat a failed body read as incomplete, or withhold its partial detail while retaining useful status context. Preserve byte bounds and complete-response behavior. If reusing the flag, keep size slicing dependent on actual body length so a short failed read cannot panic. Add interrupted-response regressions through real HTTP/SSE registration and both consumers.
🛠️ Author fix: Close the shared producer incompleteness rule for every listed route in one pass. Reuse the existing marker/tail handling; do not replace the networking framework or expand this into arbitrary partial-string recognition.
🚫 Out of scope: Detecting prefixes deliberately authored as complete error messages or changing unrelated error-output policy.
🟡 P2 — Isolate the new startup-wiring test from user token stores
📍 Where: internal/cli/app_mcp_skipped_test.go:31-68.
💥 What fails: The test leaves newMCPTokenStore at its production default. Running this exact new test with simulated user ZERO_MCP_OAUTH_TOKENS_PATH / ZERO_OAUTH_TOKENS_PATH values migrated the seeded legacy token, renamed its original file and created the unified store. On Windows, the helper sets only APPDATA, while both OAuth paths fall back through HOME/USERPROFILE; an inherited keyring backend also bypasses a temporary config path.
The reproduction used only review-owned simulated user files.
🔎 Root cause: Redirecting the config root does not isolate the credential-store constructor or its migration/backend selection.
📜 Stated contract:
“Tests must not read or write the developer's real config, cache, or state directories.”
“Redirect every root the code under test resolves, not just config.” —
AGENTS.md
🏷️ Attribution: PR-introduced test defect. This test file and constructor invocation path are absent at base/live main. The old shared helper's limitations do not justify adding another uncontained caller.
📌 In this PR:
- New startup test: production token constructor and inherited backend/path settings remain active.
- New direct token-store helpers in
internal/mcpandinternal/tui: already use explicit temporary paths andEnv: map[string]string{}. - New CLI identity/check tests: non-OAuth stdio paths do not invoke this token constructor.
🔒 Unchanged on main: Credential-store and legacy-migration implementations; unrelated older tests.
🔧 Required correction: Supply an explicitly temporary file-backed token store with an isolated environment in this new test, or equivalent complete local isolation that also prevents legacy migration and host-keyring access. The existing dependency seam and store options already support this.
🛠️ Author fix: Contain every credential-store resolution reached by the new startup test in one pass, and verify seeded user paths remain untouched. Do not redesign the store or repair unrelated main tests.
🚫 Out of scope: Shared storage architecture and repository-wide test cleanup.
Needs maintainer decision
A child can interpret --api-key -Q... as a value, but the current collector intentionally treats a following dash-prefixed item as another flag; its negative test explicitly preserves --api-key --verbose. A real-child probe confirms the separated spelling can expose an opaque value, while equals/packed spellings redact it. There is no established child-independent grammar resolving that ambiguity. I am not requiring parser expansion or removal of the existing negative control in this PR; support for that separated form needs an explicit product choice.
Reviewed contract coverage
| Lifecycle / ordering | Changed entry points and siblings checked | Operator claims |
|---|---|---|
| Configure -> prospectively validate -> existing locked atomic write -> reload -> adopt/invalidate | Add, enable, disable, remove, manager actions and wizard; active/disabled aliases and exact/runtime identities | No changed markdown/help/generated operator files; quoted transcript hints now address exact keys |
| Critical/optional capture -> retain -> completion -> consume -> config/token change -> close | Connect/list/validation, snapshot/getter/channel, Init/handler/cache, both displays, replacement/disable/logout and runtime cancellation | Reconnect and pending optional labels remain the documented scope exclusions |
| Error -> bound -> normalize/redact -> partial-tail repair -> display | Configured/stored/inherited source matrix; HTTP/SSE body producer; real stdio capture | In-memory transcript exposure verified; no claim that these command rows are directly persisted to session storage |
| Shared field/source | Producer / load | Capture / consumer | Tests | Docs / renderer |
|---|---|---|---|---|
| Exact key / runtime Name | JSON, name validation, active uniqueness | Exact actions vs canonical observations/tool counts/OAuth | Padded keys, aliases, collisions, receiving CLI and hint tests | Source comments consistent; latest hint fix verified |
| Configured credential fields and URL components | Existing normalization and shared arg/URL parsing | Reason and Target classifiers | Short/escaped/split/padded/bounded fixtures plus query counterexamples | Both displays traced; no changed operator-doc claim |
| Stored access/refresh/client-secret/endpoint and inherited sensitive env | Store/login/refresh; documented env injection and launch merge/scrub | Pre-connect/current context and both reasons | Real refresh/child probes; credential-change controls inspected | F1 covers omitted inputs; public identifiers/metadata preserved |
| Partial-body signal | HTTP/SSE size/read boundary and error wrapping | Existing tail suppression | Complete, size-cut and interrupted-body probes | F3 closes incomplete producer signaling |
Malformed-input review covered empty/trailing/next flags, packed and equals boundaries, base64 padding, positional URLs, escaped query/fragment data, invalid URL fallback, independently invalid query pairs, wrong config shapes/types, missing transport requirements, invalid names/hosts/schemes, nil stores/errors, oversized values and UTF-8 cuts. The findings require local safety corrections, not new admission policy.
Validation
go build ./...andgo vet ./internal/tui ./internal/mcp ./internal/redaction ./internal/clipassed.- Affected-package tests passed for MCP, redaction and CLI. The TUI package's only failure was
TestRelativeAgeFormatsLastActivity(2025-05-31versus2025-06-01); the identical failure reproduces at base. - Focused MCP/credential tests with
-racepassed across TUI, MCP and CLI. - Review-owned overlay probes exercised real HTTP/SSE/stdio paths, both displays, immutable-base comparisons and simulated user-store migration. The reviewed checkout is unchanged.
- Redact what Login stores for refresh: the registered client secret, and the stored token endpoint, taken apart by the same URL rules as configured endpoints. Both now feed the credential fingerprint on the capture and display sides, so a rotated secret or a changed endpoint withholds an older reason. - Redact credential-named variables a stdio child inherits from this process, with the readability floor, since a name match in the inherited environment is as often a switch as a secret. - Classify each query value by its decoded key and decode the pairs one at a time, so an escaped short credential keeps its classification and a value beside an unparsable pair keeps its decoded spelling. - Treat a failed body read as a cut, so a server that drops the connection part way through a credential no longer leaves an unmarked prefix. - Withhold the reason when a terminal escape would eat part of a credential, which left every other byte of it on screen. - Give the startup wiring test its own token store, so it no longer migrates or creates the user's token files. Reported by @jatmn.
|
@jatmn thanks, all four are fixed in 56c7d55. Stored and inherited credentials.
Query provenance. Each query pair is now decoded on its own, and both spellings are classified by the decoded key. Interrupted bodies. Test isolation. The startup test gets a temporary file store with an empty environment through One more I found while doing this. A bare ESC eats the byte after it, and a CSI eats its final byte. So a server that put one in front of a byte of an echoed credential got every other byte shown, and the old "bare escape byte" split case only passed because the whole value was gone. The reason is now also read with those bytes kept, and if a configured value only appears in that reading, the details are withheld. A sequence that eats nothing of the credential still rejoins it for normal redaction. Each fix was reverted on its own and its tests fail for the stated reason (13 mutations). Full suite, build, smoke, vet for windows/linux/darwin, govulncheck for linux and windows, and the pinned lint over On |
jatmn
left a comment
There was a problem hiding this comment.
I rechecked this PR on head 56c7d55013cd86db5fdb5d89e7c03b745e85c4f1 (full diff, primary review, controller-run blind passes, GitHub/CI evidence). The startup-failure visibility work matches #825, and the redaction/identity fixes from prior review rounds are present on this head.
Merge readiness
- Branch freshness:
fix/825-mcp-panel-shows-failuresmatches liveorigin/mainat2e10a4b60b5ef8ebbf18bde8aea6dbfc65c7b43b(0 commits behind). Merge-base for the PR diff is4247a07aba0f89c3c2597314a33edaede56be70c. - CI: All 12 executed checks on the latest GitHub run are green (Unit Tests & Coverage, Race Detector, smoke matrix, Zero Review, etc.). CodeRabbit skipped.
- Local validation: Review relied on CI plus static inspection of the changed packages (
gowas not available in the review environment).
Needs maintainer decision
Separated --api-key -<opaque> argv spelling: A stdio child can treat a dash-prefixed next token as another flag; the collector deliberately does not redact that ambiguous shape (see PR “Known limit” and existing negative control around --api-key --verbose). Equals/packed spellings are covered. Whether to expand parsing for the separated form needs an explicit product decision; I am not requiring it in this PR.
Findings
🟢 Thanks for the contribution. I do not see any actionable issues from my review on head 56c7d550.
Prior CHANGES_REQUESTED items on older heads (stored OAuth material in the redaction input, per-pair query classification, HTTP body read incompleteness, startup test token-store isolation, transcript ConfigKey action hints) are addressed in the current tree. Out-of-scope items called out in the PR and earlier reviews remain out of scope here (in-session reconnect after enable, panel-grade redaction on stderr / bare zero mcp check output, separated dash-prefixed credential argv without a child grammar).
…ws-failures #1193 changed httpStatusError on main: a response to a request that carried the injected AI/ML API key drops its body, and a 401 from that server gets an authentication hint. Both are kept, with this branch's truncation marking. The hint now goes before the body rather than after it, so the retained body stays at the end of the message, which is the only place the display repairs a cut credential. A new unit test pins that order. Two tests moved with main: - #1189 made configured secrets match across separator bytes, so a credential split by a bare ESC is now redacted with the reason kept instead of withheld. The escape test expects that, and its real-HTTP case now uses a CSI that eats a credential byte, which still withholds. - #1193 added the opt-in aimlapi default, which sorts first and is disabled, so the startup-split collision test skips disabled defaults.
|
@jatmn this push dismissed your approval, sorry. #1193 landed with an overlapping change to
One thing I noticed but left alone: the key #1193 injects never reaches config, so it isn't among the panel's candidates. The status path is covered because it drops the body, but a JSON-RPC error is returned as the server wrote it (
|
jatmn
left a comment
There was a problem hiding this comment.
I found issues that need to be addressed before this is ready.
Merge readiness
🟡 P2 — Rebase onto current main before merge
📍 Where: Branch fix/825-mcp-panel-shows-failures @ a38336c vs live origin/main
💥 What fails: Live origin/main (e034a938 and descendants) is not an ancestor of this head. The recent merge at a38336c integrated main through the #1193 overlap; three commits landed on main after that merge-base (16ccd787): #1202, #1204, #1203. GitHub may still report the PR as mergeable, but repository review policy treats a stale target base as a hard blocker independent of a clean three-dot diff on the older base.
🔎 Root cause: The branch tip has not yet been rebased or merged forward onto the current target head.
📜 Stated contract:
Rebase onto the current PR base (
mainor stacked target) before review. A stale head that rolls back mainline commits is a hard blocker, not a merge-time detail.
🏷️ Attribution: Target-branch drift — not a regression introduced by the MCP diff alone. The author’s November merge addressed #1193 conflict resolution; the remaining gap is commits that landed on main afterward.
📌 In this PR:
- Branch update — rebase or merge
origin/mainthroughe034a938(or whatevermainis at merge time) and re-run required CI on the result
🔒 Unchanged on main: Upstream commits outside this PR’s scope should arrive via rebase, not by re-implementing them here.
🔧 Required correction: Rebase onto current main, resolve any conflicts (recent main includes TUI perf changes in #1203 that are adjacent to this work), and confirm checks on the updated head.
🛠️ Author fix: Rebase or merge-forward only; preserve the MCP failure-observation, identity, and redaction behaviour already on this branch.
|
@jatmn merged current main (ef1ca39: #1202, #1204, #1203, #1208, #1198 and the 0.13.0 release) in 57c8c2f. It merged without conflicts;
|
jatmn
left a comment
There was a problem hiding this comment.
I rechecked this PR on head 57c8c2ff011ffc06f3e2826a8c0b8d38d4027b0d. I do not see merge-blocking code defects for #825 on this head. The substantive feedback from me, anandh8x, CodeRabbit, and gnanam1990 is implemented in the tree. What remains before merge is mostly GitHub review metadata, plus two small test nits I would like tightened.
Merge readiness
🟡 P2 — CHANGES_REQUESTED on GitHub does not match current head
📍 Where: Twigpine/zero#835 review decision
💥 What fails: GitHub still reports CHANGES_REQUESTED. anandh8x’s review on be580766 (terminal sanitization) was never dismissed or replaced on a newer head, even though that work is on 57c8c2ff. My last clean approval was on 56c7d550 (since dismissed); my follow-up on a38336c was rebase-only and is satisfied now.
🔎 Root cause: Merge blocking follows review records on older SHAs, not automatic re-evaluation when the branch moves.
📜 Stated contract:
We expect required reviews on the current head after rebase.
🏷️ Attribution: Process — not a regression in the MCP diff on 57c8c2ff.
📌 In this PR:
- Fresh maintainer approval on
57c8c2ff(or dismiss staleCHANGES_REQUESTEDreviews after others confirm head behavior)
🔧 Required correction: I will approve once the two P3 test items below are fixed (or I am comfortable merging without them — they are optional for me but cheap for the author). anandh8x or another maintainer should re-confirm terminal sanitization on this head so GitHub unblocks.
🛠️ Author fix: No product change for this row; reply on-thread that prior items land on 57c8c2ff and push the small test asserts if you take the P3 nits.
🚫 Out of scope: Re-implementing fixes that are already on head.
🟢 Branch freshness — satisfied
At review time, origin/main is an ancestor of head (ef1ca39 merge-base, 0 commits behind). My Nov 7 rebase note is addressed by merges through 57c8c2ff. Required CI on the latest run is green.
How I verified earlier requests (head 57c8c2ff)
I did not treat resolved threads or author replies as proof by themselves; I re-read the changed paths and ran focused tests.
| Who | What they asked for | My verdict on head | Where I checked |
|---|---|---|---|
| anandh8x | Terminal-safe failure reasons (strip escapes/controls/newlines) | Done | redactMCPFailureReason, sanitizeTerminalReason in mcp_view.go / mcp_manager.go; mcp_failed_state_test.go |
| anandh8x | Reason length cap | Done | maxMCPReasonLen, maxMCPReasonRawLen |
| Me | Configured header/env/URL in failure redaction | Done | mcpServerSecretValues, ExtraSecretValues in redactMCPFailureReason |
| Me | Redact after terminal rejoiners | Done | RedactString(stripTerminalRejoiners(...)); escapeSwallowedSecret |
| Me | --header / -H stdio credential args |
Done | isMCPHeaderFlag in sensitiveMCPArgValues (mcp_state.go ~1452) |
| Me | Bound raw error before redaction | Done | boundMCPFailureError; mcp_raw_bound_test.go |
| Me | Bare /mcp manager overlay shows the reason |
Done | mcp_manager.go ~451 |
| Me | Open manager refreshes when optional startup completes | Done | mcp_startup_completion_test.go, mcpStartupCompletedMsg |
| Me | Disabled alias must not discard enabled server’s failure | Done | canonicalMCPServers excludes disabled in mcp_skipped_invalidation.go |
| Me | URL args + per-pair query credential classification | Done | mcpURLSecretValues (~1171–1192) |
| Me | Interrupted HTTP body → incomplete detail / tail repair | Done | httpStatusError readErr; ErrorDetailTruncated; producer tests |
| Me | Startup wiring test must not touch user token stores | Done | newMCPTokenStore + user-file asserts in app_mcp_skipped_test.go |
| CodeRabbit | Whole-message short-value test | Done | 761fbd3a; mcp_error_redaction_test.go ~78; thread resolved |
| CodeRabbit | C1 literal → escape (ST1018) | Done | mcp_failure_redaction_test.go; thread resolved |
| CodeRabbit | app_mcp_skipped_test assert Err |
Not done (nit) | Name only (~95–97) |
| CodeRabbit | Canonical-name test assert tool count | Not done (nit) | Failure/name only |
| CodeRabbit | Bound sanitizer input before heavy walk | Done for panel path | Ingress bound in redactMCPFailureReason; raw cap in sanitizeTerminalReason ~297 |
| gnanam1990 | Gut test, disabled-wins, build-time redaction | Done | Still holds on head |
| Author | stderr warning unchanged; panel is additive | Matches | app.go ~885 — intentional |
| Author | In-TUI enable without reconnect OOS | Unchanged | PR body |
Author replies: Vasanth’s “Fixed in 761fbd3” for the two CodeRabbit test threads matches what I see in the files. Mutation and overlay claims line up with the tests on head. The known --api-key -Q... limit stays as I already called a maintainer decision, not a blocker for this PR.
What I am not asking for here: Panel-grade redaction on startup stderr or bare zero mcp check output. I marked that out of scope on 56c7d550; this PR correctly focuses on /mcp and the transcript path wired through BuildMCPViewState.
Findings
🔵 P3 — Assert skipped error text in startup wiring test
📍 Where: internal/cli/app_mcp_skipped_test.go (~95–97)
💥 What fails: A regression can drop SkippedServer.Err while the test still passes.
🔎 Root cause: CodeRabbit’s nit was never applied; the author reasonably prioritized token-store isolation in the same test.
📜 Stated contract:
We add regression tests that pin behavior, not just wiring side effects.
🏷️ Attribution: PR-introduced test gap.
📌 In this PR:
TestRunPassesSkippedMCPServersToTheTUIassertions
🔧 Required correction: Also assert MCPSkipped[0].Err contains connection refused (or the exact error string you stub).
🛠️ Author fix: Extend the existing assertion in that test only.
🚫 Out of scope: Broader CLI test refactors.
🔵 P3 — Canonical-name test should pin tool count lookup
📍 Where: internal/tui/mcp_canonical_name_test.go (~33–46)
💥 What fails: Tool count keyed by canonical name can regress while failure state still passes.
🔎 Root cause: CodeRabbit nit; the test documents name/failure matching only.
📜 Stated contract: The comment in mcp_state.go about raw-key lookup also losing tool counts names the regression class.
🏷️ Attribution: PR-introduced test gap.
📌 In this PR:
- Same parameterized cases — registry fixture with a
docstool +ToolCountassert
🔧 Required correction: One small registry per case and assert ToolCount.
🛠️ Author fix: Test-only change in the existing table-driven test.
🚫 Out of scope: View logic changes.
Needs maintainer decision
Separated --api-key -<opaque> argv — unchanged from the PR “Known limit”. I am not requiring argv-parser expansion in this PR unless we explicitly want that product behavior.
Validation
- I ran focused
go teston head for./internal/mcp/...,./internal/cli/..., and./internal/tui/...(MCP-related filters) — pass. - PR CI: required checks green on the latest GitHub run.
- I rechecked my prior P1 items on
57c8c2ffin the checkout, not only thread resolution and commit messages.
The startup wiring test checked only the skipped server's name, so a change that dropped the error /mcp renders as the reason still passed. It now asserts the error as well. The canonical-name test covered failure lookup but not the tool count, which the same raw-key lookup would lose. Each case now also builds the view for a running server with one registered tool and asserts the count.
|
@jatmn both test nits are in 280bdc1, and 73b445b merges current main (clean, nothing from main dropped).
Full @anandh8x your terminal sanitization request from be58076 is in this head ( |
jatmn
left a comment
There was a problem hiding this comment.
I rechecked Twigpine/zero#835 on head 73b445b826137f16d116b7616edc14f7d6d00e69. The #825 panel contract is implemented on this head: failed servers show with redacted, terminal-sanitized reasons; disabled still wins; identity, credential context, and invalidation behavior match the tests and PR description. I do not see merge-blocking code defects in the diff for this head.
Merge readiness
🟡 P2 — Security & Code Health failed on the latest PR run (govulncheck linux)
📍 Where: CI run 42959887291, job Security & Code Health
💥 What fails: The govulncheck (linux) step failed on the PR head run. The same workflow job on live main at 17fcd266 completed successfully on run 42732134991.
🔎 Root cause: Unknown from this environment — full job logs could not be retrieved (host disk full). The failure is not explained by unit/smoke/race jobs, which passed on the same run.
📜 Stated contract:
AGENTS.md: govulncheck is a hard gate for merge.
🏷️ Attribution: Uncertain until the report is read; treat as merge-blocking until green or explained.
📌 In this PR:
- Re-run
Security & Code Healthon73b445bafter merge-base sync, or fix any new symbol exposure govulncheck reports for this branch
🔧 Required correction: Green govulncheck (linux) on the merge head, or a maintainer-confirmed false positive with documented rationale.
🛠️ Author fix: If the report points at this branch, address only the reported import/call path; do not drive-by bump unrelated packages.
🚫 Out of scope: Fixing unrelated main vulnerabilities unrelated to this diff.
🟢 Branch freshness and conflict risk — satisfied
origin/main (17fcd266) is the merge base of head; the latest commit is a merge of main into the branch with import-path conflict resolution only (73b445b). mergeable is MERGEABLE.
🟢 Unit / smoke / race CI — satisfied
Unit tests, smoke (all OS), race detector, lint, and Zero Review passed on run 42959887291.
Findings
(No merge-blocking code findings on this head.)
Needs maintainer decision
Separated --api-key <opaque> argv (credential passed as the next argv that looks like a flag) remains the documented known limit in the PR body. I am not treating it as a blocker for #825 unless product owners want argv rewriting in this PR.
🟢 Thanks for the contribution. I do not see any actionable code issues from my review on 73b445b; address the govulncheck merge-readiness row above before merge.
jatmn
left a comment
There was a problem hiding this comment.
LGTM on head 73b445b826137f16d116b7616edc14f7d6d00e69.
#825 is satisfied here: failed MCP servers show in /mcp with redacted, terminal-sanitized reasons; disabled still wins; server identity, credential fingerprints, and skipped-invalidation behavior match the tests I rechecked on this head.
No merge-blocking code defects in the diff for this head.
Merge note: the latest run's govulncheck (linux) step failed while unit/smoke/race were green; I could not pull logs here. Worth a re-run or quick read of that report before merge per AGENTS.md, not a code finding on this branch.
Fixes #825. Companion to #822, which fixed the same blind spot in
zero mcp check./mcpworked out each server's state from the config file: disabled if you turned it off, enabled otherwise. But MCP registration is best-effort: a server that can't be reached gets recorded and startup carries on. So a server that never connected showed up as enabled, its tools quietly missing, and nothing in the panel said why.Startup does know: it prints a warning per skipped server to stderr. That's gone by the time you notice, and
/mcpis exactly where you go afterwards to ask what's actually running.So the skipped set now reaches the panel, and a server that failed renders as failed with the reason under it:
Two details worth calling out:
The reason comes from the server, so it goes through
redaction.ErrorMessagebefore it's rendered. A handshake error that echoes theAuthorizationheader back would otherwise print the bearer token straight into the transcript. There's a test for that.Disabled wins over failed. If you turned a server off it was never expected to connect, and calling it failed would be misleading.
The stderr warning is unchanged. Non-interactive users still get it, and the panel is an addition rather than a replacement.
Still not fixed, and out of scope here: enabling a server from inside the TUI updates the config but doesn't reconnect anything, so it'll show as enabled while not actually running until you restart. That's pre-existing and a bigger change; happy to file it separately if you'd like.
Known limit: a credential handed over as a separate argument that starts with a dash (
--api-key -Qx...) is read as the next flag rather than a value, so a child that echoes it is not redacted. Without the child's own grammar, a dash-prefixed item is as likely to be an option; the=and packed spellings of the same flag are covered.Verified with mutation testing: eight mutations across the state builder, the renderer, and both wiring points, all killed.
TestAltScreenTranscriptScrollKeepsFooterFixedandTestBuildServeScopeKeepsLexicalPathsfail on my Windows box on cleanmaintoo (the second needs symlink privilege).What else this grew into
Review turned up more than the panel, and those fixes are all here too, so the original title undersold it (thanks @euxaristia). From the most code to the least:
TokenStore.SecretValuesandSecretMaterial. Each value is redacted in its plain, escaped and split forms, and the text has a fixed size bound. A body cut short, by the size limit or by a dropped connection, loses a trailing credential prefix, and a reason whose terminal escapes would eat part of a credential is withheld.internal/redaction/overlapping_secrets_test.goand the MCP tests pin the forms.CredentialFingerprintof its credential values. So a renamed or colliding alias doesn't show another server's failure, and neither does a server whose credentials changed since startup.Summary by CodeRabbit
New Features
/mcppanel.Bug Fixes