mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-24 13:36:19 +00:00
* 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>
87 lines
3.3 KiB
Python
87 lines
3.3 KiB
Python
"""Shared construction of MCP tool-call interceptors."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
from deerflow.config.extensions_config import ExtensionsConfig
|
|
from deerflow.mcp.oauth import build_oauth_tool_interceptor
|
|
from deerflow.mcp.user_scoped_auth import build_user_scoped_auth_interceptor
|
|
from deerflow.reflection import resolve_variable
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def build_mcp_tool_interceptors(
|
|
extensions_config: ExtensionsConfig,
|
|
*,
|
|
oauth_builder: Any = build_oauth_tool_interceptor,
|
|
user_auth_builder: Any = build_user_scoped_auth_interceptor,
|
|
resolver: Any = resolve_variable,
|
|
target_logger: logging.Logger = logger,
|
|
) -> list[Any]:
|
|
"""Build OAuth, user-scoped auth, then configured custom MCP interceptors."""
|
|
interceptors: list[Any] = []
|
|
oauth_interceptor = oauth_builder(extensions_config)
|
|
if oauth_interceptor is not None:
|
|
interceptors.append(oauth_interceptor)
|
|
|
|
# After OAuth so a server declaring both gets the per-user credential:
|
|
# interceptors wrap outermost-first, so the later-registered user-scoped
|
|
# override runs closer to the transport and wins the final header value.
|
|
user_auth_interceptor = user_auth_builder(extensions_config)
|
|
if user_auth_interceptor is not None:
|
|
interceptors.append(user_auth_interceptor)
|
|
|
|
raw_paths = (extensions_config.model_extra or {}).get("mcpInterceptors")
|
|
if isinstance(raw_paths, str):
|
|
raw_paths = [raw_paths]
|
|
elif not isinstance(raw_paths, list):
|
|
if raw_paths is not None:
|
|
target_logger.warning(
|
|
"mcpInterceptors must be a list of strings, got %s; skipping",
|
|
type(raw_paths).__name__,
|
|
)
|
|
raw_paths = []
|
|
|
|
for interceptor_path in raw_paths:
|
|
try:
|
|
builder = resolver(interceptor_path)
|
|
interceptor = builder()
|
|
if callable(interceptor):
|
|
interceptors.append(interceptor)
|
|
target_logger.info("Loaded MCP interceptor: %s", interceptor_path)
|
|
elif interceptor is not None:
|
|
target_logger.warning(
|
|
"Builder %s returned non-callable %s; skipping",
|
|
interceptor_path,
|
|
type(interceptor).__name__,
|
|
)
|
|
except Exception:
|
|
target_logger.warning(
|
|
f"Failed to load MCP interceptor {interceptor_path}",
|
|
exc_info=True,
|
|
)
|
|
return interceptors
|
|
|
|
|
|
def compose_tool_interceptors(interceptors: list[Any], base_handler: Any) -> Any:
|
|
"""Compose interceptors onion-style around ``base_handler``: first = outermost.
|
|
|
|
The later-registered interceptor runs closer to the transport, so its
|
|
header writes win over earlier ones — the property user-scoped auth relies
|
|
on to override an OAuth-injected credential. This is the single wrap
|
|
convention; the session-pool tool path composes through here so tests that
|
|
pin the override property exercise the production composition.
|
|
"""
|
|
handler = base_handler
|
|
for interceptor in reversed(interceptors):
|
|
outer = handler
|
|
|
|
async def wrapped(req: Any, _i: Any = interceptor, _h: Any = outer) -> Any:
|
|
return await _i(req, _h)
|
|
|
|
handler = wrapped
|
|
return handler
|