Skip to content

fix(code): proxy MCP requests locally to keep OAuth tokens fresh#1713

Merged
skoob13 merged 7 commits into
mainfrom
fix/mcp-reconnection-2
Apr 17, 2026
Merged

fix(code): proxy MCP requests locally to keep OAuth tokens fresh#1713
skoob13 merged 7 commits into
mainfrom
fix/mcp-reconnection-2

Conversation

@skoob13
Copy link
Copy Markdown
Contributor

@skoob13 skoob13 commented Apr 17, 2026

Problem

MCP transports bake Authorization headers at construction time. When the OAuth access token rotates during a long-running agent session, every subsequent MCP call against the PostHog MCP server (and other authed installations) keeps sending the stale bearer and gets rejected. Tearing the transport down on every rotation is expensive and racy.

Changes

  • New McpProxyService: local loopback HTTP server that forwards MCP requests to their real targets, injecting a fresh token via AuthService.authenticatedFetch on every hop. Handles buffered JSON responses and SSE streams, and retries once with a force-refreshed token when the MCP body encodes an auth failure as a JSON-RPC error (200 OK + authentication_failed).
  • AgentAuthAdapter routes the built-in posthog server and every authed installation through the proxy instead of embedding the bearer in the MCP config.
  • AuthService proactively schedules a refresh 30 min before expiry, but AgentService registers a blocker so refreshes are deferred while any agent turn is in flight and flushed once all sessions go idle. Debug menu gains "Schedule refresh" and "Force refresh" items.
  • _posthog/refresh_mcp ACP extension reserved for client-driven reconnect flows.

How did you test this code?

  • Unit tests updated for the new McpProxyService dependency in AgentAuthAdapter and AgentService (pnpm --filter code test).
  • Manually exercised via the dev build: triggered "Force refresh" mid-turn and confirmed subsequent MCP tool calls continue working with the rotated token.

Publish to changelog?

no

cc @PostHog/team-posthog-ai

skoob13 added 3 commits April 17, 2026 17:06
No longer needed — the MCP proxy fetches a fresh token per request via
authenticatedFetch, so proactive refresh ahead of expiry doesn't add value.
Drop the timer, blocker/pending mechanism, the "Schedule refresh" menu item,
and the session-idle flush wiring. Also strip two debug logs left from the
investigation.
@skoob13 skoob13 merged commit d37f1ca into main Apr 17, 2026
15 checks passed
@skoob13 skoob13 deleted the fix/mcp-reconnection-2 branch April 17, 2026 15:45
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.

2 participants