Skip to content

fix(mcp): auth-aware gateway MCP, stdio stderr, login reauth#280

Merged
leggetter merged 8 commits intomainfrom
fix/mcp-not-logged-in-error
Apr 2, 2026
Merged

fix(mcp): auth-aware gateway MCP, stdio stderr, login reauth#280
leggetter merged 8 commits intomainfrom
fix/mcp-not-logged-in-error

Conversation

@leggetter
Copy link
Copy Markdown
Collaborator

Summary

Implements the auth-aware gateway mcp behavior and MCP stdio hygiene from the MCP + Gateway project plan.

Gateway / Cobra

  • No API key: requireGatewayProject is skipped so MCP can start; auth via hookdeck_login.
  • API key present: Same requireGatewayProject as other gateway commands.
  • Execute(): For hookdeck gateway mcp, errors and login-required messages go to stderr; no interactive hookdeck login on stdout.
  • argvContainsGatewayMCP ignores global flags (--profile, -p, etc.).

MCP

  • hookdeck_login always registered; reauth: true clears stored credentials and starts device login (URL in tool result).
  • hookdeck_projects list/use failures that match heuristics (401/403, etc.) append hedged copy suggesting hookdeck_login with reauth: true.
  • Config.ClearMCPProfileCredentials for reauth (disk when viper loaded, else memory-only).

Tests

  • Unit: pkg/cmd (gateway pre-run, argv), pkg/gateway/mcp, pkg/config.
  • Acceptance (-tags=mcp): subprocess gateway mcp, separate stdout/stderr, JSON-RPC initialize, auth/unauth/outpost/missing-project scenarios (RunGatewayMCPSubprocess + stdin pipe kept open).

Follow-ups

Release

  • Includes minor-level MCP behavior (reauth + hints); align version with hookdeck-cli-release + README Releasing.

Made with Cursor

leggetter and others added 3 commits April 1, 2026 11:55
- Skip requireGatewayProject for gateway mcp when no API key; enforce when key present
- Route gateway mcp errors and login-required messages to stderr; no interactive login
- argvContainsGatewayMCP skips global flags (e.g. --profile, -p)
- Always register hookdeck_login with optional reauth; clear credentials then device login
- Hedged list-projects failure hint suggesting reauth for 401/403-style errors
- ClearMCPProfileCredentials for memory-only or persisted config
- Acceptance: subprocess gateway mcp with stdin pipe; stdout JSON-RPC hygiene

Made-with: Cursor
- Rename ClearMCPProfileCredentials to ClearActiveProfileCredentials; document disk vs memory paths
- Logout uses the same helper as MCP reauth; zeroProfileCredentialFields helper
- RemoveAllProfiles clears in-memory credential fields after wiping the file (parity with logout -a)
- Rename config test to match new API

Made-with: Cursor
* fix(review): tighten error matching, add safety comments, revert noise

- tool_projects_errors.go: match "status code: 4xx" instead of bare
  "401"/"403" to avoid false positives on IDs or timestamps
- tool_login.go: remove `_ = ctx` suppression, add TODO for context
  propagation to polling goroutine, document happens-before on
  loginState.err via channel close
- root.go: add maintenance comment linking flagNeedsNextArg to init()
- helpers.go: revert unrelated Attempt struct alignment change

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

* fix(review): ListProjects returns *APIError, add reauth + argv tests

- projects.go: use checkAndPrintError instead of manual status check so
  ListProjects errors are structured *APIError — the errors.As path in
  shouldSuggestReauthAfterListProjectsFailure now matches directly
- tool_projects_errors_test.go: unit tests for reauth hint logic covering
  APIError 401/403, plain error fallback, and false-positive resistance
- root_argv_test.go: document boolean-flag-between-subcommands limitation

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

* fix(mcp): cancel login polling goroutine on MCP session close

Thread the request context into the login polling goroutine so it
stops promptly when the MCP transport closes, instead of running for
up to ~4 minutes after the client disconnects.

WaitForAPIKey blocks with time.Sleep and doesn't accept a context, so
we run it in an inner goroutine and select on both its result channel
and ctx.Done(). The inner goroutine is bounded by loginMaxAttempts.

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

---------

Co-authored-by: Claude <noreply@anthropic.com>
leggetter and others added 5 commits April 1, 2026 13:20
* fix(review): tighten error matching, add safety comments, revert noise

- tool_projects_errors.go: match "status code: 4xx" instead of bare
  "401"/"403" to avoid false positives on IDs or timestamps
- tool_login.go: remove `_ = ctx` suppression, add TODO for context
  propagation to polling goroutine, document happens-before on
  loginState.err via channel close
- root.go: add maintenance comment linking flagNeedsNextArg to init()
- helpers.go: revert unrelated Attempt struct alignment change

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

* fix(mcp): cancel login polling goroutine on MCP session close

Thread the request context into the login polling goroutine so it
stops promptly when the MCP transport closes, instead of running for
up to ~4 minutes after the client disconnects.

WaitForAPIKey blocks with time.Sleep and doesn't accept a context, so
we run it in an inner goroutine and select on both its result channel
and ctx.Done(). The inner goroutine is bounded by loginMaxAttempts.

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

* fix(mcp): use session-level context for login polling, not per-request

The per-request ctx passed to MCP tool handlers is cancelled when the
handler returns. The previous commit selected on that ctx in the login
polling goroutine, which killed the poll immediately after returning
the browser URL — breaking in-MCP authentication.

Fix: add a sessionCtx field to Server, set it in Run() (called by
RunStdio and tests), and select on that instead. The session context
is only cancelled when the MCP transport closes (stdin EOF), which is
the correct signal to abandon login polling.

Also adds TestLoginTool_PollSurvivesAcrossToolCalls: a regression test
that starts a login flow, lets the mock auth complete between tool
calls, and verifies the client is authenticated on the second call.
This would have caught the per-request ctx bug.

https://claude.ai/code/session_01EpXZqTmgybtjgmSALukH8d

---------

Co-authored-by: Claude <noreply@anthropic.com>
- Wait loginPollInterval before second hookdeck_login in PollSurvives test
- SaveActiveProfileAfterLogin: skip disk persist when viper nil (tests)
- CLIRunner: retry transient HTTP 500 like 502 for acceptance flakes

Made-with: Cursor
Omit X-Team-ID/X-Project-ID on GET /cli-auth/validate via clientForCLIAuthValidate
so a valid CLI key is not rejected when config.toml has a stale project_id.

After successful validate on the existing-key login path, persist project_id,
project_mode, and project_type from the response.

Add Profile Apply* helpers for validate, poll, and CI responses; use them from
login, interactive login, and MCP hookdeck_login. requireGatewayProject now
applies the full validate response (including project_id) without clearing
guest_url.

Tests: auth validate headers, profile apply helpers, LoadConfigFromFile,
gateway resolve-from-validate integration.

Made-with: Cursor
Document GOMODCACHE for agent shells, prompt-first elevated execution, and
point CLAUDE.md at AGENTS.md as the single source for agent instructions.

Made-with: Cursor
Include changed flag names (not values) as command_flags in
X-Hookdeck-CLI-Telemetry JSON. Wire CollectChangedFlagNames from root
initTelemetry. Add unit tests and acceptance test for login --api-key
and --cli-key over the recording proxy.

Made-with: Cursor
@leggetter leggetter marked this pull request as ready for review April 2, 2026 10:46
@leggetter leggetter merged commit e027484 into main Apr 2, 2026
12 checks passed
@leggetter leggetter deleted the fix/mcp-not-logged-in-error branch April 2, 2026 10:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant