青榆牧 a94b2d8897
feat(mcp): map request-scoped secrets to MCP HTTP/SSE headers (#5010)
* feat(mcp): map request-scoped secrets to HTTP/SSE headers

`user_auth` binds a credential to a configured DeerFlow user, so a caller
that picks the credential per request — a multi-tenant gateway, a per-run
API key, one shared MCP server fronting several environments — had to
register one MCP server entry per credential.

Add a declarative `mcpServers.<server>.headers_from_context` block mapping
HTTP header names to keys of the run request's `config.context.secrets`
carrier. A new built-in interceptor resolves the mapping on every tool call
and rewrites those headers, mirroring `user_scoped_auth`. The config file
stores names only, never a credential, so the Gateway returns the block
unmasked.

Registered after OAuth and `user_auth` in the interceptor chain: the later
interceptor runs closer to the transport, and the value chosen for this one
request is the most specific, so it wins. Fail-closed by default — a mapped
key missing from the request raises a `ToolException` naming only that key,
because falling back to the server's discovery credential would send one
tenant's call under another tenant's authority. `on_missing: "passthrough"`
opts out.

Durable background tasks are excluded: `McpTaskToolCaller` drives status and
cancel polls after the Agent run ends, where no run context exists, so the
fail-closed interceptor would deny every poll. Those calls keep using
server-level credentials, and a server declaring both `headers_from_context`
and `task_toolsets` now logs a warning.

Also corrects the custom-interceptor example in docs/MCP_SERVER.md (and the
matching claim in skills/AGENTS.md), which read request secrets from
`langgraph.config.get_config()["context"]`. That key is `None` inside a tool
call — the run context rides the LangGraph runtime, not the RunnableConfig
propagated to child runnables — so interceptors written from that example
never saw a value. The example now reads `request.runtime`, and
tests/test_mcp_context_headers.py pins LangGraph's runtime-injection rule by
driving a real langchain-mcp-adapters tool through a real graph with the
ambient-runtime fallback disabled.

Closes #5005

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

* fix(mcp): resolve credential headers case-insensitively, carry them on durable submit

Review follow-ups on `headers_from_context`.

HTTP field names are case-insensitive, but every dict on the path to the wire
is not: `build_server_params` copies the operator's static `headers` spelling
verbatim, and langchain-mcp-adapters merges interceptor overrides into the
connection with a plain `{**connection_headers, **override_headers}` splat. A
static `authorization` and an injected `Authorization` therefore both reached
httpx as separate field lines, and a server reading the field with a
single-value accessor got the static discovery credential — inverting the
documented `headers` < `oauth` < `user_auth` < `headers_from_context`
precedence and running a per-request call under the shared credential.

Normalizing inside the interceptor cannot fix that on its own: the adapter
builds the request with `headers=None`, so an interceptor never sees the
connection's static headers and cannot displace them however it spells its own
key. A new `mcp/headers.py::apply_header_overrides` therefore drops any key
differing only in case and emits the spelling the connection already uses.
Applied to `headers_from_context`, `user_auth`, the OAuth interceptor, the
OAuth discovery-header write, and the durable-task connection merge, which all
carried the same collision. `headers_from_context.headers` now also rejects one
header mapped under two spellings at config load, in both the harness model and
the Gateway mirror.

Durable submit now carries the mapped headers, as docs/MCP_SERVER.md already
promised. `McpTaskToolCaller` disabled the interceptor for the whole caller, but
that caller serves submit as well as the polls, and submit is awaited inline
inside the Agent's tool call — where the run's LangGraph runtime is still the
ambient contextvar, so no secret has to be threaded through `TaskSubmitRequest`
or reach durable storage. The caller builds one chain and keeps a second view of
it without the context-headers interceptor; `call_tool` takes
`request_scoped_headers`, set only by `OrdinaryMcpTaskDriver.submit`. Status and
cancel keep server-level credentials, so background polls still cannot fail
closed, and the startup warning now describes the half it actually covers.

`_merge_preserving_secrets` restores masked extras inside `headers_from_context`
instead of writing the `***` sentinel back over the stored value, matching the
treatment `user_auth` extras and server-level extras already get; extras a PUT
omits carry over as well, while the declared mapping still replaces verbatim so
a round trip can remove an entry. `extra="allow"` plus name-based sensitivity
detection means the usual casualty is a name-valued key such as `tokenHeader`,
not only a credential.

The existing override test seeded the static header onto `request.headers`,
which production never does, so it modelled a merge that really happens one
layer down; the new tests drive a real adapter tool through a real connection
and assert on the headers the session is opened with, and the durable-submit
test runs through a real tool node with no runtime patching.

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

* fix(mcp): reject case-insensitive duplicate static header names

* fix(mcp): preserve omitted headers_from_context fields on partial updates

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 10:42:42 +08:00

97 lines
3.9 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.context_headers import build_context_headers_interceptor
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,
context_headers_builder: Any = build_context_headers_interceptor,
resolver: Any = resolve_variable,
target_logger: logging.Logger = logger,
) -> list[Any]:
"""Build OAuth, user-scoped auth, context headers, then 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)
# Last of the built-ins, by the same rule: a credential the caller chose for
# this one request is more specific than a configured per-user or per-server
# credential, so it must win the final header value for a server declaring
# more than one source.
context_headers_interceptor = context_headers_builder(extensions_config)
if context_headers_interceptor is not None:
interceptors.append(context_headers_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