ajayr 7e95bef2e7
feat(mcp): per-user credential injection for shared MCP servers (#4868)
* feat(mcp): per-user credential injection for shared MCP servers

A single HTTP/SSE MCP server entry can now serve several users, each
authenticated to the remote service with their own credential. A server
opts in with a user_auth block mapping user ids to credential header
values ($ENV_VAR references supported):

  "user_auth": {
    "header": "Authorization",
    "users": { "<user-id>": "$SERVICE_TOKEN_ALICE" }
  }

The built-in user-scoped auth interceptor resolves the authenticated
runtime user on every tool call (request runtime -> ambient LangGraph
runtime -> auth config -> request-scoped user ContextVar) and rewrites
the configured header via request.override(), the same per-call
mechanism as the OAuth interceptor. It registers after OAuth in the
shared assembly so its per-user value wins the header when a server
declares both. The entry's static headers are used only for startup
tool discovery.

Fail-closed by default: an unmapped user - including the anonymous
default-user fallback - or a credential whose env reference resolved
empty gets an actionable ToolException instead of another user's
credential; on_missing: "passthrough" opts out per server. Combined
with the existing per-(user, thread) MCP session scoping this gives
credential isolation on shared servers.

Gateway API: user_auth.users values are masked in GET responses, and
PUT round-trips preserve stored credentials for masked values (same
contract as env/headers/oauth secrets); a masked value for a user id
not already stored is rejected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): address review — preserve stored user_auth sub-fields on partial PUT, warn-and-skip stdio, allow extras

Review findings from #4868:

1. A partial user_auth payload (e.g. {"enabled": false}) merged to
   users={} and default on_missing, irreversibly wiping stored
   credentials on PUT. The merge is now sub-field-aware via
   model_fields_set — omitted sub-fields carry the stored values, an
   explicitly sent users map still replaces (so full-round-trip removal
   works), masked values still swap back for stored credentials.

2. user_auth on a stdio server was a silent no-op: rewritten headers go
   to call meta, never a transport header, while deny errors still fired.
   The interceptor builder now warns and skips non-sse/http servers,
   matching the tool_call_timeout transport-mismatch convention.

3. McpUserScopedAuthConfigResponse now allows extra keys like the
   harness-side model, and extras survive masking and merge, matching
   the server-level model_extra handling.

Adds four regression tests (partial-PUT preservation, explicit-map
replacement, extras round-trip, stdio warn-and-skip).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): reject blank user_auth.header at the gateway

A blank header passed the gateway response model, was persisted, then
failed the harness-side ExtensionsConfig validator on reload — the PUT
returned 500 after the write and every later config load/startup failed
until the file was hand-edited. Mirror the harness non-blank validator
on McpUserScopedAuthConfigResponse so the PUT fails with 422 before
anything is written.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: ruff format extensions_config.py

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): harden the trust chain and masking around user-scoped credential selection

Address review round 4:
- Scrub client-supplied user_id from run context/configurable for
  external callers in inject_authenticated_user_context, before every
  early return, and restamp only from request.state.user. Now that
  user_id selects which user's credential user-scoped MCP auth injects,
  a forged value must not survive any future path that skips the
  restamp. Internal callers (IM channels, scheduler) keep supplying
  end-user identity as before (PR #3294 contract). Regression tests pin
  both the scrub and that a forged body.context.user_id can never
  resolve as another user through merge + inject ordering.
- Include the caller's own resolved user id in the fail-closed deny
  message so operators can copy the exact users key (it differs by
  deployment path), and document the key formats in the mcp.mdx doc.
- Mask sensitive extra keys inside user_auth on GET like server-level
  extras, and swap masked sentinels back for stored values on PUT via
  _merge_extra_value_preserving_masked.
- Extract the interceptor wrap loop into compose_tool_interceptors and
  pin the security property functionally: an OAuth interceptor that
  actually sets Authorization loses the final header to the per-user
  credential through the same composition the session-pool path uses.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 15:16:04 +08:00

118 lines
5.5 KiB
Python

"""Per-user credential injection for shared MCP servers.
One configured HTTP/SSE MCP server can serve several DeerFlow users, each
authenticated to the remote service with their own credential. A server opts in
by declaring a ``user_auth`` block (:class:`McpUserScopedAuthConfig`) mapping
DeerFlow user ids to credential header values. On every tool call the
interceptor resolves the authenticated user and rewrites the configured header
via ``request.override(headers=...)`` — the same per-call mechanism the OAuth
interceptor uses.
The server entry's static ``headers`` are used only for startup tool discovery
(``tools/list``); they never authenticate a user's tool call when ``user_auth``
is enabled for that server, except under an explicit ``on_missing:
"passthrough"`` opt-out.
Fail-closed by default: an unmapped user (including the anonymous
``DEFAULT_USER_ID`` fallback), or a mapped credential whose ``$ENV_VAR``
reference resolved to an empty string, gets an actionable ``ToolException``
instead of another user's credential or the discovery credential.
"""
from __future__ import annotations
import logging
from typing import Any
from langchain_core.tools import ToolException
from deerflow.config.extensions_config import ExtensionsConfig, McpUserScopedAuthConfig
from deerflow.runtime.user_context import resolve_runtime_user_id
logger = logging.getLogger(__name__)
def _current_runtime() -> Any | None:
"""Best-effort access to the LangGraph runtime for the current tool call.
``get_runtime()`` raises outside a runtime context (embedded clients, unit
tests, discovery paths); ``resolve_runtime_user_id`` accepts ``None`` and
falls back to LangGraph auth config and the request-scoped user
ContextVar, so failures here reduce accuracy but never crash the call.
"""
try:
from langgraph.runtime import get_runtime
return get_runtime()
except Exception:
return None
def build_user_scoped_auth_interceptor(extensions_config: ExtensionsConfig) -> Any | None:
"""Build a tool interceptor injecting per-user credentials, or ``None``.
Returns ``None`` when no enabled server declares an enabled ``user_auth``
block, so callers can skip registration entirely (mirrors
``build_oauth_tool_interceptor``).
"""
user_auth_by_server: dict[str, McpUserScopedAuthConfig] = {}
for server_name, server_config in extensions_config.get_enabled_mcp_servers().items():
if server_config.user_auth is None or not server_config.user_auth.enabled:
continue
if server_config.type not in ("sse", "http"):
# A stdio server has no HTTP headers: the pooled stdio path forwards
# rewritten headers as call meta, never a transport header, so the
# credential would go nowhere while deny errors still fired for
# unmapped users. Warn-and-skip matches the existing convention for
# transport/config mismatches (e.g. tool_call_timeout on non-stdio).
logger.warning(
"MCP server '%s' declares user_auth but uses the '%s' transport; user-scoped credentials only apply to 'sse'/'http' servers — ignoring user_auth for this server",
server_name,
server_config.type,
)
continue
user_auth_by_server[server_name] = server_config.user_auth
if not user_auth_by_server:
return None
async def user_scoped_auth_interceptor(request: Any, handler: Any) -> Any:
user_auth = user_auth_by_server.get(request.server_name)
if user_auth is None:
return await handler(request)
# Prefer the runtime attached to the request (set by the adapter when
# the call originates inside a graph); fall back to the ambient
# LangGraph runtime, then to resolve_runtime_user_id's own chain
# (LangGraph auth config → request-scoped user ContextVar → default).
runtime = getattr(request, "runtime", None)
if runtime is None:
runtime = _current_runtime()
user_id = resolve_runtime_user_id(runtime)
# Empty string covers a `$ENV_VAR` reference whose variable was unset:
# ExtensionsConfig.resolve_env_variables stores "" for those, and an
# empty credential must fail closed rather than send an empty header.
credential = user_auth.users.get(user_id, "")
if not credential:
if user_auth.on_missing == "passthrough":
return await handler(request)
logger.warning(
"Denied MCP tool call to server '%s': no user-scoped credential for user '%s'",
request.server_name,
user_id,
)
# The resolved id is included so the operator can copy the exact
# ``users`` key: it differs by deployment path (a safe-slug like
# ``alice-example-com-ab12cd34`` via LangGraph auth, a raw user
# UUID via the embedded Gateway). It is the caller's own id, so
# surfacing it leaks nothing across users.
raise ToolException(
f"No credential is configured for your account (user id '{user_id}') on MCP server '{request.server_name}'. Ask the operator to add this exact id to that server's user_auth.users map (or set its environment variable)."
)
updated_headers = dict(request.headers or {})
updated_headers[user_auth.header] = credential
return await handler(request.override(headers=updated_headers))
return user_scoped_auth_interceptor