Repository navigation
Description
Summary
identityPropagatingRoundTripper in pkg/vmcp/client/client.go captures the request *auth.Identity once at backend client creation time and re-injects that snapshot on every outgoing backend HTTP request, overriding the fresh identity placed onto the request context by TokenValidator.Middleware moments earlier. This bypasses the transparent upstream-token refresh performed in GetAllValidTokens and results in stale upstream access tokens being injected by UpstreamInjectStrategy / TokenExchangeStrategy for the entire lifetime of the backend client.
Users are observing a forced re-auth roughly every 24 hours. This matches the access-token lifespan of common upstream providers and is consistent with the captured-identity bug rather than with any embedded-auth-server refresh-token expiry (which is configurable up to 30 days and validated to be ≥1h in pkg/authserver/server/provider.go).
Root cause
The bug is a two-path identity flow that doesn't reconnect:
Path A — per-request refresh, works correctly
pkg/auth/token.go:1203 TokenValidator.Middleware runs on every incoming request, including tool calls. It calls loadUpstreamTokens → InProcessService.GetAllValidTokens (pkg/auth/upstreamtoken/service.go:86) which transparently refreshes any expired upstream access tokens via the configured UpstreamTokenRefresher and writes the fresh map into identity.UpstreamTokens. The fresh identity is then attached to the request context via auth.WithIdentity at pkg/auth/token.go:1245.
Path B — captured at session-init, becomes stale
defaultClientFactory in pkg/vmcp/client/client.go:271 constructs the backend client's transport chain at SessionFactory.MakeSession() time. At pkg/vmcp/client/client.go:319-324, the identity is snapshotted once:
identity, _ := auth.IdentityFromContext(ctx)
baseTransport = &identityPropagatingRoundTripper{
base: baseTransport,
identity: identity, // captured here, held for session lifetime
isHealthCheck: healthcontext.IsHealthCheck(ctx),
}On every subsequent outgoing request, identityPropagatingRoundTripper.RoundTrip at pkg/vmcp/client/client.go:195-207 overrides whatever identity is on the request context with the captured one:
func (i *identityPropagatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
if i.identity != nil {
ctx = auth.WithIdentity(ctx, i.identity) // discards fresh identity from Path A
}
...
}The downstream auth strategies read identity from the (now overridden) context and inject the captured stale token:
pkg/vmcp/auth/strategies/upstream_inject.go:80—token := identity.UpstreamTokens[providerName]pkg/vmcp/auth/strategies/tokenexchange.go:124—subjectToken = identity.UpstreamTokens[config.SubjectProviderName]pkg/vmcp/auth/strategies/aws_sts.go:136—bearerToken = identity.UpstreamTokens[cfg.SubjectProviderName]
So tokens are refreshed at the vMCP edge on every tool call (Path A), then immediately discarded by the backend roundtripper (Path B) before they can be used.
Observed user-facing behavior
- vMCP session opens; tool calls succeed.
- Tool calls continue to succeed for ~the upstream provider's access-token lifespan, even though the captured token is never refreshed at the backend layer.
- Once the captured access token passes its upstream-side expiry, every tool call to that backend starts returning 401 from the upstream API.
- Users perceive this as needing to re-authenticate. The cadence (~24h) tracks the shortest-lived upstream AT in the session's backend set, not anything ToolHive-configurable.
Why the existing safety nets don't catch this today
- [vMCP] Handle auth credential expiration with retry and proactive refresh #3869 ([vMCP] Handle auth credential expiration with retry and proactive refresh) — reactive 401/403 client recreation. Open, not implemented.
- [vMCP] Proactive auth credential refresh via per-request identity resolution (Phase 2) #3877 ([vMCP] Proactive auth credential refresh via per-request identity resolution) — Phase 2, whose Part 1 acceptance criterion is exactly the fix below. Open, not implemented.
- Reference: THV-0038 — Session-scoped client lifecycle.
This issue is filed separately from #3877 to flag that the Part 1 fix has a concrete user-visible impact (daily forced re-auth) and is worth landing on its own ahead of the rest of #3877's scope.
Suggested fix
Make identityPropagatingRoundTripper source identity from the live request context instead of from a captured field. Sketch:
type identityPropagatingRoundTripper struct {
base http.RoundTripper
isHealthCheck bool
// identity field removed
}
func (i *identityPropagatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
// If mcp-go reconstructed this request with context.Background() (as it does
// for streamable-HTTP Close()), there will be no identity on ctx. In that
// case we can't recover one — health-check requests don't need it; for
// session-bound requests the caller is responsible for propagating context.
if i.isHealthCheck {
ctx = healthcontext.WithHealthCheckMarker(ctx)
req = req.Clone(ctx)
}
return i.base.RoundTrip(req)
}Constructor at pkg/vmcp/client/client.go:319-324 drops the identity capture:
baseTransport = &identityPropagatingRoundTripper{
base: baseTransport,
isHealthCheck: healthcontext.IsHealthCheck(ctx),
}Open question for implementation: the existing comment at pkg/vmcp/client/client.go:314-318 documents that mcp-go's Close() issues a DELETE built from context.Background() which loses identity. The current capture-at-construction behavior was intentional for that path. With the fix, that DELETE will arrive without identity. Two options:
- Skip identity injection for the streamable-HTTP DELETE (it's a session-teardown request; upstream auth on a DELETE may not be needed).
- Capture only what is strictly needed for teardown (e.g., a token specifically for the DELETE) and inject it only on requests where
req.Context()carries no identity. This preserves teardown while letting normal requests use the fresh per-request identity.
Whichever path is chosen, the invariant must be: a non-nil identity in req.Context() is never silently overridden by a captured one.
Reproduction
- Configure a vMCP with one or more
MCPServerEntrybackends usingupstreamInjectoutgoing auth, against an upstream IDP whose access tokens expire in less than 24 hours (most providers default to 1h–24h). - Authenticate through vMCP from an MCP client and exercise a tool against the upstream backend (succeeds).
- Keep the session open and idle past the upstream's access-token lifespan. Do not restart the client or close the session.
- Make another tool call to the same backend. Expected: vMCP refreshes the upstream token transparently and the call succeeds. Actual: the captured AT is used; the upstream returns 401; the call fails.
A targeted unit test on identityPropagatingRoundTripper.RoundTrip should assert that an identity placed on req.Context() is preserved into the outgoing request and is not replaced by a different identity captured at construction time.
Acceptance criteria
-
identityPropagatingRoundTripperno longer holds a captured*auth.Identityfield, OR if it does, that field is never used to override an identity already present onreq.Context(). - A fresh identity placed on
req.Context()byTokenValidator.MiddlewarereachesUpstreamInjectStrategy.Authenticate/TokenExchangeStrategy.Authenticate/AWSSTSStrategy.Authenticateunchanged. - The streamable-HTTP
Close()/DELETE path (where mcp-go usescontext.Background()) continues to function without panicking or erroring on missing identity. - Unit tests cover: (a) identity present in
req.Context()is propagated, (b) identity absent inreq.Context()is handled gracefully for the DELETE/teardown path, (c)isHealthCheckmarker behavior is preserved. - Integration test that idles a vMCP session past the upstream AT lifespan and asserts the next tool call succeeds via transparent refresh.
Related
- [vMCP] Proactive auth credential refresh via per-request identity resolution (Phase 2) #3877 — Phase 2 follow-up (this is essentially Part 1 of that issue, filed separately for prioritization).
- [vMCP] Handle auth credential expiration with retry and proactive refresh #3869 — Phase 1 reactive retry safety net.
- THV-0038 — Session-scoped client lifecycle RFC.
Activity
Consolidate #5323 identity invariant; doc immutability
Move unparam shield onto headersFor helper
Preserve fresh per-request identity in vMCP backend transports (#5335)
Stop fabricating partial identity in RestoreSession
Stop fabricating partial identity in RestoreSession
Stop fabricating partial identity in RestoreSession (#5650)
Pin the confidentiality invariants of the vMCP bridge cells
Pin the confidentiality invariants of the vMCP bridge cells
Pin the confidentiality invariants of the vMCP bridge cells
Bridge era-mismatched client×backend cells in vMCP (#6006)