AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Support Bounded Same-Call 401 Recovery For Externally Managed Credentials In Langchain.Mcp

The langchain.mcp MCPAdapter lacks a supported path for externally managed bearer credentials to recover from HTTP 401 by re-reading tokens and retrying the same operation. The existing FastMCP/httpx2.Auth injection seam is undocumented and untested for this scenario, and terminal 401 errors are often swallowed or converted to generic errors by the MCP SDK, blocking classification. This issue requests a bounded, request-local retry mechanism and proper error propagation.

highConfidence 85%Langchain

Origin Analysis

The MCPAdapter delegates authentication entirely to FastMCP, which only provides static token injection or full OAuth flow. There is no built-in hook for applications to re-read credentials on 401. Additionally, the MCP SDK (2.1.1) maps non-JSON 401 HTTP errors to generic JSON-RPC INTERNAL_ERROR, losing HTTP status for authentication classification, and legacy SSE errors are logged but not forwarded, preventing reliable terminal rejection handling.
1. Set up an MCP server protected by bearer token authentication. 2. Obtain an initial valid token A and create a FastMCP Client with a custom httpx2.Auth that always sends A. 3. Revoke token A on the server. 4. Call a tool through MCPAdapter using this client. 5. Observe that the request gets a 401, but the terminal error is either generic (Streamable HTTP POST) or the stream silently retries (GET) without providing a classifiable authentication error. 6. Note that there is no way to asynchronously re-read a new token B and retry within the same tool invocation.

Fixing Code Block

Edge Case Audit

This fix relies on httpx2.Auth being present and stable across FastMCP versions; future changes to FastMCP or httpx2 could alter the auth flow contract. The implementation assumes the external get_token callback is thread-safe and idempotent; concurrent 401s may trigger multiple token refreshes, potentially causing race conditions or excessive load on the credential store. If the underlying MCP SDK continues to swallow 401 status (e.g., converting to generic INTERNAL_ERROR), terminal rejection may still be misclassified even with correct auth retry. Rollback: remove the custom Auth object from the FastMCP client configuration to revert to previous static-token or OAuth behavior. Additional defensive measures: add logging/monitoring for credential store failures, ensure get_token has a timeout, and consider caching token with a short TTL to reduce redundant refreshes.

Ecosystem Topology