mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* test(mcp): add red /mcp contract for an upstream -32042 URL elicitation error A tools/call that the upstream answers with -32042 must reach the /mcp client as a JSON-RPC error with code and data.elicitations intact. The stub provider moves to a shared factory so the existing REST case and the new /mcp case script the same peer. * fix(mcp): return an upstream -32042 URL elicitation error from /mcp as a JSON-RPC error An upstream tools/call answered with JSON-RPC error -32042 was flattened into an isError text result, so the client never saw data.elicitations[].url. The four catches that built that result now re-raise it and the MCP SDK serializes it with code, message and data intact. /mcp-rest/tools/call keeps its HTTP 200 isError text result, and every other error keeps its current path. Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): keep the REST virtual mcp_tool_call result for an upstream -32042 The virtual mcp_tool_call branch of /mcp-rest/tools/call had no guard, so the re-raised -32042 became an HTTP 500. Both REST branches now share one guard that renders it as the HTTP 200 isError text result, while /mcp still relays it as a JSON-RPC error on its virtual path. The MCP client also re-raises -32042 before its error-level log, since it is an expected consent signal. Co-Authored-By: bot_apk <apk@cognition.ai> * test(mcp): add integration cells for upstream -32042 URL elicitation across entry points, auth paths and chaos Covers every /mcp entry point, the official SDK client, SDK-built upstreams over http, sse and stdio, token exchange, delegated and per-user OAuth servers, the REST error result, unusual error payloads, spend log rows, a two-proxy burst, a killed worker, an upstream outage and a held reply. The LLM auto-execute cell pins the tool result text and spend status that the merge base produces. * test(mcp): assert the auto-executed -32042 tool call hands the model the error and logs a failure Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): run post_mcp_call guardrails over a relayed -32042 URL elicitation's message text Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): keep the LLM auto-execute path unchanged for -32042 and drop the unmasked cause from the relayed error Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): let a during-call guardrail block outrank a relayed -32042 and run the post tool call hook on its messages Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): flatten a -32042 for REST before the shared post-call path so guardrails and the tool call hook run once Co-Authored-By: bot_apk <apk@cognition.ai> * fix(mcp): run the -32042 guardrails and tool call hook outside the except block so a block cannot chain the upstream error Co-Authored-By: bot_apk <apk@cognition.ai> * test(mcp): drive the -32042 relay unit test through a real post_mcp_call guardrail Co-Authored-By: bot_apk <apk@cognition.ai> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: bot_apk <apk@cognition.ai>
1886 lines
84 KiB
Python
1886 lines
84 KiB
Python
"""
|
|
LiteLLM Proxy uses this MCP Client to connnect to other MCP servers.
|
|
"""
|
|
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import os
|
|
import time
|
|
from collections.abc import AsyncIterator, Awaitable, Callable, Generator, Mapping, Sequence
|
|
from contextlib import AbstractAsyncContextManager, AsyncExitStack, nullcontext
|
|
from functools import partial
|
|
from importlib.metadata import version
|
|
from types import MappingProxyType
|
|
from typing import TYPE_CHECKING, Final, Literal, TypeAlias, TypeVar, cast, overload
|
|
|
|
import anyio
|
|
import httpx2
|
|
from httpx2._client import UseClientDefault
|
|
from httpx2._types import AuthTypes
|
|
from mcp import ClientSession, MCPError, ReadResourceResult, Resource, StdioServerParameters
|
|
from mcp.client._input_required import run_input_required_driver
|
|
from mcp.client.session import ClientRequestContext, ElicitationFnT, LoggingFnT, SamplingFnT
|
|
from mcp.client.sse import sse_client
|
|
from mcp.client.stdio import stdio_client
|
|
from mcp.client.streamable_http import streamable_http_client
|
|
from mcp.shared._stream_protocols import ReadStream, WriteStream
|
|
from mcp.shared.message import SessionMessage
|
|
from typing_extensions import ReadOnly, TypedDict, assert_never
|
|
|
|
_TransportStreams: TypeAlias = tuple[
|
|
ReadStream[SessionMessage | Exception],
|
|
WriteStream[SessionMessage],
|
|
]
|
|
_TransportContext: TypeAlias = AbstractAsyncContextManager[_TransportStreams]
|
|
_SessionCallbackName: TypeAlias = Literal["sampling_callback", "elicitation_callback", "logging_callback"]
|
|
|
|
|
|
SESSION_CLEANUP_TIMEOUT_MESSAGE: Final = "MCP session cleanup timed out"
|
|
|
|
|
|
class _SessionCallbackMap(TypedDict):
|
|
sampling_callback: ReadOnly[SamplingFnT | None]
|
|
elicitation_callback: ReadOnly[ElicitationFnT | None]
|
|
logging_callback: ReadOnly[LoggingFnT | None]
|
|
response_hooks: ReadOnly[tuple[Callable[[httpx2.Response], Awaitable[None]], ...]]
|
|
|
|
|
|
from mcp.types import (
|
|
CONNECTION_CLOSED,
|
|
METHOD_NOT_FOUND,
|
|
REQUEST_TIMEOUT,
|
|
CacheableResult,
|
|
ClientCapabilities,
|
|
CreateMessageRequestParams,
|
|
CreateMessageResult,
|
|
CreateMessageResultWithTools,
|
|
DiscoverResult,
|
|
ElicitationCapability,
|
|
ElicitRequestParams,
|
|
ElicitResult,
|
|
ErrorData,
|
|
FormElicitationCapability,
|
|
GetPromptRequestParams,
|
|
GetPromptResult,
|
|
Implementation,
|
|
InitializedNotification,
|
|
InitializeRequest,
|
|
InitializeRequestParams,
|
|
InitializeResult,
|
|
InputRequiredResult,
|
|
InputResponses,
|
|
ListPromptsRequest,
|
|
ListPromptsResult,
|
|
ListResourcesRequest,
|
|
ListResourcesResult,
|
|
ListResourceTemplatesResult,
|
|
ListToolsRequest,
|
|
ListToolsResult,
|
|
LoggingMessageNotificationParams,
|
|
PaginatedRequestParams,
|
|
Prompt,
|
|
ResourceTemplate,
|
|
SamplingCapability,
|
|
ServerNotification,
|
|
UrlElicitationCapability,
|
|
)
|
|
from mcp.types import CallToolRequestParams as MCPCallToolRequestParams
|
|
from mcp.types import CallToolResult as MCPCallToolResult
|
|
from mcp.types import Tool as MCPTool
|
|
from pydantic import AnyUrl, TypeAdapter
|
|
|
|
from litellm._logging import verbose_logger
|
|
from litellm.constants import (
|
|
MCP_CLIENT_TIMEOUT,
|
|
MCP_MAX_SSE_EVENT_SIZE_BYTES,
|
|
MCP_NPM_CACHE_DIR,
|
|
MCP_TOOL_LISTING_MAX_PAGES,
|
|
MCP_TOOL_LISTING_TIMEOUT,
|
|
)
|
|
from litellm.llms.custom_httpx.http_handler import get_ssl_configuration
|
|
from litellm.mcp_client.tools import list_tools_result_with_pagination, list_tools_with_pagination
|
|
from litellm.proxy.mcp_server.mcp_context import get_active_mcp_request_ctx
|
|
from litellm.proxy.mcp_server.mcp_debug import capture_upstream_error_response
|
|
from litellm.proxy.mcp_server.result_conversion import (
|
|
age_freshness,
|
|
aggregate_freshness,
|
|
error_text_result,
|
|
is_url_elicitation_required,
|
|
)
|
|
from litellm.types.llms.custom_http import VerifyTypes
|
|
from litellm.types.mcp import (
|
|
MCP_LEGACY_VERSIONS,
|
|
MCPAuth,
|
|
MCPAuthType,
|
|
MCPStdioConfig,
|
|
MCPTransport,
|
|
MCPTransportType,
|
|
MCPUpstreamProtocol,
|
|
credential_redirect_hook,
|
|
has_header,
|
|
validate_mcp_protocol_transport,
|
|
without_header,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from litellm.proxy.mcp_server.contracts import CatalogListRequest, CatalogListResult
|
|
from litellm.proxy.mcp_server.legacy_callbacks import ElicitationCallback
|
|
|
|
|
|
def _mcp_response_hooks() -> tuple[Callable[[httpx2.Response], Awaitable[None]], ...]:
|
|
if get_active_mcp_request_ctx() is None:
|
|
return (capture_upstream_error_response,)
|
|
from litellm.proxy.mcp_server.legacy_callbacks import (
|
|
get_scope_response,
|
|
record_upstream_tool_authorization,
|
|
)
|
|
|
|
return (
|
|
partial(record_upstream_tool_authorization, pending=get_scope_response()),
|
|
capture_upstream_error_response,
|
|
)
|
|
|
|
|
|
def to_basic_auth(auth_value: str) -> str:
|
|
"""Convert auth value to Basic Auth format."""
|
|
return base64.b64encode(auth_value.encode("utf-8")).decode()
|
|
|
|
|
|
def strip_auth_scheme(auth_value: str, scheme: str) -> str:
|
|
"""Return ``auth_value`` with a leading ``<scheme>`` and separator removed, or unchanged when absent.
|
|
|
|
Callers supply both a bare credential and a complete header value, so prefixing
|
|
unconditionally yields ``Bearer Bearer <jwt>``. Scheme names are case-insensitive per
|
|
RFC 7235. A credential is required after the scheme, so both a token that merely begins
|
|
with the scheme text and a scheme with nothing behind it are returned untouched.
|
|
Surrounding whitespace is left to ``_strip_header_whitespace`` at header-build time.
|
|
"""
|
|
parts: Final = auth_value.split(None, 1)
|
|
if len(parts) == 2 and parts[0].lower() == scheme.lower():
|
|
return parts[1]
|
|
return auth_value
|
|
|
|
|
|
def to_basic_credentials(auth_value: str) -> str:
|
|
"""Return the base64 credentials for a ``Basic`` header, encoding only when needed.
|
|
|
|
``Basic <credentials>`` carries credentials that are already encoded, so encoding the whole
|
|
value again would bury the scheme inside the payload. This has to run before
|
|
:func:`to_basic_auth` rather than at header-build time, where no prefix is left to find.
|
|
A schemed value whose remainder does not decode is the bare ``username:password`` shape with
|
|
the scheme written in front of it, and is encoded rather than forwarded as an invalid header;
|
|
a pair always contains ``:``, which is outside the base64 alphabet, so the two never collide.
|
|
"""
|
|
credentials: Final = strip_auth_scheme(auth_value, "Basic")
|
|
if credentials == auth_value:
|
|
return to_basic_auth(auth_value)
|
|
try:
|
|
base64.b64decode(credentials, validate=True)
|
|
except ValueError:
|
|
return to_basic_auth(credentials)
|
|
return credentials
|
|
|
|
|
|
def _strip_header_whitespace(headers: dict[str, str]) -> dict[str, str]:
|
|
return {
|
|
(key.strip() if isinstance(key, str) else key): (value.strip() if isinstance(value, str) else value)
|
|
for key, value in headers.items()
|
|
}
|
|
|
|
|
|
async def _receive_session_message(
|
|
message: ServerNotification | Exception,
|
|
*,
|
|
stream_error: asyncio.Future[Exception],
|
|
on_notification: Callable[[ServerNotification], Awaitable[None]] | None,
|
|
) -> None:
|
|
if not isinstance(message, Exception):
|
|
if on_notification is not None:
|
|
await on_notification(message)
|
|
return
|
|
if not isinstance(message, (ValueError, httpx2.HTTPError, OSError)):
|
|
return
|
|
if not stream_error.done():
|
|
stream_error.set_result(message)
|
|
raise RuntimeError("MCP response stream failed")
|
|
|
|
|
|
def _first_non_cancelled_cause(exc: BaseException, cleanup_errors: tuple[Exception, ...] = ()) -> BaseException | None:
|
|
queue: Final[list[BaseException]] = [exc]
|
|
while queue:
|
|
current = queue.pop(0)
|
|
nested = getattr(current, "exceptions", None)
|
|
if nested:
|
|
queue.extend(nested)
|
|
elif not isinstance(current, asyncio.CancelledError) and not any(current is error for error in cleanup_errors):
|
|
return current
|
|
return None
|
|
|
|
|
|
_SDK_READ_TIMEOUT_CODE: Final = REQUEST_TIMEOUT
|
|
"""The code the MCP SDK puts on its own elapsed read timeout."""
|
|
|
|
|
|
def as_mcp_read_timeout(exc: BaseException) -> TimeoutError | None:
|
|
"""Normalize an MCP SDK read timeout for client and gateway diagnostics, or return ``None``.
|
|
|
|
The SDK reports its own elapsed read timeout as ``MCPError`` carrying ``REQUEST_TIMEOUT`` in a
|
|
field that also carries relayed upstream JSON-RPC errors. The numeric code alone therefore
|
|
cannot separate the two, and an upstream answering with the same application code would be
|
|
reported as a gateway timeout it never caused. The SDK raises its own from inside an ``except TimeoutError``, so the elapsed timeout is
|
|
on the context chain, while a relayed error is built from a received message and has no such
|
|
chain; that is the discriminator.
|
|
"""
|
|
if not isinstance(exc, MCPError) or exc.error.code != _SDK_READ_TIMEOUT_CODE:
|
|
return None
|
|
if not isinstance(exc.__context__, TimeoutError):
|
|
return None
|
|
return TimeoutError(exc.error.message)
|
|
|
|
|
|
TSessionResult = TypeVar("TSessionResult")
|
|
_ListPage = TypeVar("_ListPage", ListPromptsResult, ListResourcesResult, ListResourceTemplatesResult)
|
|
_ListItem = TypeVar("_ListItem")
|
|
|
|
|
|
async def _run_bounded_cleanup(operation: Callable[[], Awaitable[TSessionResult]], deadline: float) -> TSessionResult:
|
|
async def run() -> TSessionResult:
|
|
with anyio.fail_after(max(0, deadline - anyio.current_time()), shield=True):
|
|
return await operation()
|
|
|
|
# A cancelled asyncio.gather repeatedly forwards Task.cancel, bypassing AnyIO shields.
|
|
# Isolate only cleanup, and drain it before propagating the caller's cancellation.
|
|
task: Final = asyncio.create_task(run())
|
|
interrupted: asyncio.CancelledError | None = None
|
|
with anyio.CancelScope(shield=True):
|
|
while not task.done():
|
|
try:
|
|
await asyncio.shield(task)
|
|
except asyncio.CancelledError as exc:
|
|
interrupted = exc
|
|
except Exception:
|
|
break
|
|
if interrupted is not None:
|
|
if not task.cancelled():
|
|
task.exception()
|
|
raise interrupted
|
|
return task.result()
|
|
|
|
|
|
class _MCPResponseStream(httpx2.AsyncByteStream):
|
|
def __init__(self, stream: httpx2.AsyncByteStream, record_error: Callable[[Exception], None]) -> None:
|
|
self._stream: Final = stream
|
|
self._record_error: Final = record_error
|
|
|
|
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
try:
|
|
async for chunk in self._stream:
|
|
yield chunk
|
|
except Exception as error:
|
|
self._record_error(error)
|
|
raise
|
|
|
|
async def aclose(self) -> None:
|
|
try:
|
|
await self._stream.aclose()
|
|
except Exception as error:
|
|
self._record_error(error)
|
|
raise
|
|
|
|
|
|
class _MCPHTTPClient(httpx2.AsyncClient):
|
|
cleanup_scope: anyio.CancelScope | None = None
|
|
cleanup_errors: tuple[Exception, ...] = ()
|
|
post_failure: asyncio.Future[Exception] | None = None
|
|
|
|
def _record_cleanup_error(self, error: Exception) -> None:
|
|
if self.cleanup_scope is not None and self.cleanup_scope.shield:
|
|
self.cleanup_errors += (error,)
|
|
|
|
async def send(
|
|
self,
|
|
request: httpx2.Request,
|
|
*,
|
|
stream: bool = False,
|
|
auth: AuthTypes | UseClientDefault | None = httpx2.USE_CLIENT_DEFAULT,
|
|
follow_redirects: bool | UseClientDefault = httpx2.USE_CLIENT_DEFAULT,
|
|
) -> httpx2.Response:
|
|
if request.method == "DELETE" and self.cleanup_scope is not None:
|
|
|
|
async def terminate() -> httpx2.Response:
|
|
termination: Final = await super(_MCPHTTPClient, self).send(
|
|
request, stream=stream, auth=auth, follow_redirects=follow_redirects
|
|
)
|
|
await termination.aread()
|
|
return termination
|
|
|
|
return await _run_bounded_cleanup(terminate, self.cleanup_scope.deadline)
|
|
try:
|
|
response: Final = await super().send(request, stream=stream, auth=auth, follow_redirects=follow_redirects)
|
|
if request.method == "POST" and response.is_error and response.status_code != 404:
|
|
await response.aclose()
|
|
try:
|
|
response.raise_for_status()
|
|
except httpx2.HTTPStatusError as error:
|
|
if self.post_failure is not None and not self.post_failure.done():
|
|
self.post_failure.set_result(error)
|
|
raise
|
|
if stream:
|
|
response.stream = _MCPResponseStream(
|
|
cast(httpx2.AsyncByteStream, response.stream), self._record_cleanup_error
|
|
)
|
|
return response
|
|
except Exception as error:
|
|
self._record_cleanup_error(error)
|
|
raise
|
|
|
|
|
|
class MCPSigV4Auth(httpx2.Auth):
|
|
"""
|
|
httpx2 Auth class that signs each request with AWS SigV4.
|
|
This is used for MCP servers that require AWS SigV4 authentication,
|
|
such as AWS Bedrock AgentCore MCP servers. httpx calls auth_flow()
|
|
for every outgoing request, enabling per-request signature computation.
|
|
"""
|
|
|
|
requires_request_body = True
|
|
|
|
def __init__(
|
|
self,
|
|
aws_access_key_id: str | None = None,
|
|
aws_secret_access_key: str | None = None,
|
|
aws_session_token: str | None = None,
|
|
aws_region_name: str | None = None,
|
|
aws_service_name: str | None = None,
|
|
aws_role_name: str | None = None,
|
|
aws_session_name: str | None = None,
|
|
):
|
|
try:
|
|
from botocore.credentials import Credentials
|
|
except ImportError:
|
|
raise ImportError("Missing botocore to use AWS SigV4 authentication. Run 'pip install boto3'.")
|
|
self.service_name = aws_service_name or "bedrock-agentcore"
|
|
self.region_name = aws_region_name or "us-east-1"
|
|
self.identity: Final[tuple[str, str, str | None, str | None]] = (
|
|
self.service_name,
|
|
self.region_name,
|
|
aws_role_name,
|
|
aws_access_key_id,
|
|
)
|
|
# Note: os.environ/ prefixed values are already resolved by
|
|
# ProxyConfig._check_for_os_environ_vars() at config load time.
|
|
# Values arrive here as plain strings.
|
|
if aws_role_name:
|
|
self.credentials = self._assume_role(
|
|
aws_role_name=aws_role_name,
|
|
aws_session_name=aws_session_name,
|
|
aws_access_key_id=aws_access_key_id,
|
|
aws_secret_access_key=aws_secret_access_key,
|
|
aws_session_token=aws_session_token,
|
|
aws_region_name=self.region_name,
|
|
)
|
|
elif aws_access_key_id and aws_secret_access_key:
|
|
self.credentials = Credentials(
|
|
access_key=aws_access_key_id,
|
|
secret_key=aws_secret_access_key,
|
|
token=aws_session_token,
|
|
)
|
|
else:
|
|
# Fall back to default boto3 credential chain
|
|
import botocore.session
|
|
|
|
session: Final = botocore.session.get_session()
|
|
self.credentials = session.get_credentials()
|
|
if self.credentials is None:
|
|
raise ValueError(
|
|
"No AWS credentials found. Provide aws_access_key_id and "
|
|
"aws_secret_access_key, or configure default credentials "
|
|
"(env vars, ~/.aws/credentials, instance profile)."
|
|
)
|
|
|
|
@staticmethod
|
|
def _assume_role(
|
|
aws_role_name: str,
|
|
aws_session_name: str | None,
|
|
aws_access_key_id: str | None,
|
|
aws_secret_access_key: str | None,
|
|
aws_session_token: str | None,
|
|
aws_region_name: str,
|
|
):
|
|
"""Call STS AssumeRole and return temporary credentials."""
|
|
import time
|
|
|
|
import boto3
|
|
from botocore.credentials import RefreshableCredentials
|
|
|
|
session_name: Final = aws_session_name or f"litellm-mcp-{int(time.time())}"
|
|
sts_kwargs: Final[dict] = {"region_name": aws_region_name}
|
|
if aws_access_key_id and aws_secret_access_key:
|
|
sts_kwargs["aws_access_key_id"] = aws_access_key_id
|
|
sts_kwargs["aws_secret_access_key"] = aws_secret_access_key
|
|
if aws_session_token:
|
|
sts_kwargs["aws_session_token"] = aws_session_token
|
|
sts_client: Final = boto3.client("sts", **sts_kwargs)
|
|
|
|
def assume() -> Mapping[str, str]:
|
|
sts_creds: Final = sts_client.assume_role(
|
|
RoleArn=aws_role_name,
|
|
RoleSessionName=session_name,
|
|
)["Credentials"]
|
|
return MappingProxyType(
|
|
{
|
|
"access_key": sts_creds["AccessKeyId"],
|
|
"secret_key": sts_creds["SecretAccessKey"],
|
|
"token": sts_creds["SessionToken"],
|
|
"expiry_time": sts_creds["Expiration"].isoformat(),
|
|
}
|
|
)
|
|
|
|
return RefreshableCredentials.create_from_metadata(
|
|
metadata=dict(assume()), refresh_using=assume, method="sts-assume-role"
|
|
)
|
|
|
|
def auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
|
|
from botocore.auth import SigV4Auth
|
|
from botocore.awsrequest import AWSRequest
|
|
|
|
# Build AWSRequest from the httpx Request.
|
|
# Pass all request headers so the canonical SigV4 signature covers them.
|
|
aws_request: Final = AWSRequest(
|
|
method=request.method,
|
|
url=str(request.url),
|
|
data=request.content,
|
|
headers=dict(request.headers),
|
|
)
|
|
# Sign the request — SigV4Auth.add_auth() adds Authorization,
|
|
# X-Amz-Date, and X-Amz-Security-Token (if session token present).
|
|
# Host header is derived automatically from the URL.
|
|
sigv4: Final = SigV4Auth(self.credentials, self.service_name, self.region_name)
|
|
sigv4.add_auth(aws_request)
|
|
# Copy SigV4 headers back to the httpx request
|
|
for header_name, header_value in aws_request.headers.items():
|
|
request.headers[header_name] = header_value
|
|
yield request
|
|
|
|
|
|
def _notify_stream_error(
|
|
callback: Callable[[asyncio.Future[Exception]], None] | None,
|
|
stream_error: asyncio.Future[Exception],
|
|
) -> None:
|
|
if callback is not None:
|
|
callback(stream_error)
|
|
|
|
|
|
def _notify_cleanup(callback: Callable[[], None] | None) -> None:
|
|
if callback is not None:
|
|
callback()
|
|
|
|
|
|
class _UnvalidatedClientSession(ClientSession):
|
|
"""Skips the SDK's output check, which lists the upstream's tools on a session with no schema cached."""
|
|
|
|
async def validate_tool_result(self, name: str, result: MCPCallToolResult) -> None:
|
|
return None
|
|
|
|
|
|
class MCPClient:
|
|
"""
|
|
MCP Client supporting:
|
|
SSE and HTTP transports
|
|
Authentication via Bearer token, Basic Auth, or API Key
|
|
Tool calling with error handling and result parsing
|
|
Sampling callbacks for upstream server LLM requests
|
|
Elicitation callbacks for upstream server user-input requests
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
server_url: str = "",
|
|
transport_type: MCPTransportType = MCPTransport.http,
|
|
auth_type: MCPAuthType = None,
|
|
auth_value: str | dict[str, str] | None = None,
|
|
auth_header_name: str | None = None,
|
|
timeout: float | None = None,
|
|
stdio_config: MCPStdioConfig | None = None,
|
|
extra_headers: dict[str, str] | None = None,
|
|
ssl_verify: VerifyTypes | None = None,
|
|
aws_auth: httpx2.Auth | None = None,
|
|
resolved_auth: httpx2.Auth | None = None,
|
|
sampling_callback: Callable | None = None,
|
|
elicitation_callback: "ElicitationCallback | None" = None,
|
|
logging_callback: Callable | None = None,
|
|
protocol_version: MCPUpstreamProtocol = "auto",
|
|
skip_tool_output_validation: bool = False,
|
|
upstream_transport: httpx2.AsyncBaseTransport | None = None,
|
|
):
|
|
self.protocol_version: MCPUpstreamProtocol = TypeAdapter[MCPUpstreamProtocol](
|
|
MCPUpstreamProtocol
|
|
).validate_python(protocol_version)
|
|
validate_mcp_protocol_transport(self.protocol_version, transport_type)
|
|
# 2026-07-28 lists tools before every call, so its output check adds no list
|
|
self.skip_tool_output_validation: Final = skip_tool_output_validation and self.protocol_version != "2026-07-28"
|
|
self.server_url: str = server_url
|
|
self.transport_type: MCPTransport = transport_type
|
|
self.auth_type: MCPAuthType = auth_type
|
|
self.timeout: float = timeout if timeout is not None else MCP_CLIENT_TIMEOUT
|
|
self._mcp_auth_value: str | dict[str, str] | None = None
|
|
# The one place this client decides which header its credential occupies: the operator's
|
|
# configured slot on the v1 path, or the slot the v2 resolver's auth object already owns.
|
|
# Every consumer reads this rather than re-deriving it, since each re-derivation so far
|
|
# picked up a different bug.
|
|
self._credential_slot: str | None = auth_header_name or getattr(resolved_auth, "header_name", None)
|
|
self.stdio_config: MCPStdioConfig | None = stdio_config
|
|
self.extra_headers: dict[str, str] | None = extra_headers
|
|
self.ssl_verify: VerifyTypes | None = ssl_verify
|
|
self._aws_auth: httpx2.Auth | None = aws_auth
|
|
# A pre-resolved httpx2.Auth (e.g. from the v2 credential resolver) attached to the
|
|
# upstream client's auth= slot, taking precedence over the SigV4 aws_auth.
|
|
self._resolved_auth: httpx2.Auth | None = resolved_auth
|
|
self._last_initialize_instructions: str | None = None
|
|
self._sampling_callback: Callable | None = sampling_callback
|
|
self._elicitation_callback: ElicitationCallback | None = elicitation_callback
|
|
self._logging_callback: Callable | None = logging_callback
|
|
self._upstream_transport: httpx2.AsyncBaseTransport | None = upstream_transport
|
|
self._session_callbacks_override: _SessionCallbackMap | None = None
|
|
# handle the basic auth value if provided
|
|
if auth_value:
|
|
self.update_auth_value(auth_value)
|
|
|
|
def session_callbacks(self) -> _SessionCallbackMap:
|
|
return {
|
|
"sampling_callback": self._sampling_callback,
|
|
"elicitation_callback": self._elicitation_callback,
|
|
"logging_callback": self._logging_callback,
|
|
"response_hooks": _mcp_response_hooks(),
|
|
}
|
|
|
|
def session_settings(self) -> tuple[MCPTransport, MCPUpstreamProtocol, float, bool, bool, bool, bool]:
|
|
callbacks: Final = self.session_callbacks()
|
|
return (
|
|
self.transport_type,
|
|
self.protocol_version,
|
|
self.timeout,
|
|
callbacks["sampling_callback"] is not None,
|
|
callbacks["elicitation_callback"] is not None,
|
|
callbacks["logging_callback"] is not None,
|
|
self.skip_tool_output_validation,
|
|
)
|
|
|
|
def route_session_callbacks(self, callbacks: _SessionCallbackMap) -> None:
|
|
self._session_callbacks_override = callbacks
|
|
|
|
async def discovery_auth_fingerprint(self) -> str:
|
|
return self._hash_discovery_auth(await self.prepare_request_auth(), self._aws_identity())
|
|
|
|
async def subscription_auth_fingerprint(self) -> str:
|
|
from litellm.proxy.mcp_server.outbound_credentials.client_credentials import (
|
|
ClientCredentialsBearerAuth,
|
|
)
|
|
|
|
request: Final = await self.prepare_request_auth()
|
|
auth: Final = self._resolved_auth
|
|
if isinstance(auth, ClientCredentialsBearerAuth) and auth.subscription_identity is not None:
|
|
request.headers[auth.header_name] = "managed-grant:" + auth.subscription_identity
|
|
return self._hash_discovery_auth(request, self._aws_identity())
|
|
|
|
def _aws_identity(self) -> tuple[str, str, str | None, str | None] | None:
|
|
return self._aws_auth.identity if isinstance(self._aws_auth, MCPSigV4Auth) else None
|
|
|
|
async def prepare_request_auth(self) -> httpx2.Request:
|
|
"""Preview the authenticated request without sending it, closing the auth flow afterwards."""
|
|
request: Final = httpx2.Request(
|
|
"POST", self.server_url or "http://localhost/", headers=self._get_auth_headers()
|
|
)
|
|
if self._resolved_auth is None:
|
|
return request
|
|
flow: Final = self._resolved_auth.async_auth_flow(request)
|
|
try:
|
|
authenticated: Final = await flow.__anext__()
|
|
return authenticated
|
|
finally:
|
|
await flow.aclose()
|
|
|
|
@staticmethod
|
|
def _hash_discovery_auth(
|
|
request: httpx2.Request, aws_identity: tuple[str, str, str | None, str | None] | None
|
|
) -> str:
|
|
material: Final = json.dumps((str(request.url), tuple(sorted(request.headers.multi_items())), aws_identity))
|
|
return hashlib.sha256(material.encode()).hexdigest()
|
|
|
|
def _create_transport_context(
|
|
self,
|
|
) -> tuple[_TransportContext, httpx2.AsyncClient | None]:
|
|
"""
|
|
Create the appropriate transport context based on transport type.
|
|
Returns:
|
|
Tuple of (transport_context, http_client).
|
|
http_client is only set for HTTP transport and needs cleanup.
|
|
"""
|
|
http_client: httpx2.AsyncClient | None = None
|
|
if self.transport_type == MCPTransport.stdio:
|
|
if not self.stdio_config:
|
|
raise ValueError("stdio_config is required for stdio transport")
|
|
server_params: Final = StdioServerParameters(
|
|
command=self.stdio_config.get("command", ""),
|
|
args=self.stdio_config.get("args", []),
|
|
env=self._get_safe_stdio_env(self.stdio_config.get("env")),
|
|
)
|
|
return stdio_client(server_params), None
|
|
if self.transport_type == MCPTransport.sse:
|
|
headers = self._get_auth_headers()
|
|
httpx_client_factory = (
|
|
self._create_httpx_client_factory()
|
|
if self._upstream_transport is None
|
|
else self._create_httpx_client_factory(transport=self._upstream_transport)
|
|
)
|
|
return (
|
|
sse_client(
|
|
url=self.server_url,
|
|
timeout=self.timeout,
|
|
headers=headers,
|
|
httpx_client_factory=httpx_client_factory,
|
|
),
|
|
None,
|
|
)
|
|
# HTTP transport (default)
|
|
headers = self._get_auth_headers()
|
|
httpx_client_factory = (
|
|
self._create_httpx_client_factory()
|
|
if self._upstream_transport is None
|
|
else self._create_httpx_client_factory(transport=self._upstream_transport)
|
|
)
|
|
verbose_logger.debug("litellm headers for streamable_http_client: %s", headers)
|
|
http_client = httpx_client_factory(
|
|
headers=headers,
|
|
timeout=httpx2.Timeout(self.timeout),
|
|
)
|
|
transport_ctx: Final = streamable_http_client(
|
|
url=self.server_url,
|
|
http_client=http_client,
|
|
max_sse_event_size=MCP_MAX_SSE_EVENT_SIZE_BYTES,
|
|
)
|
|
return transport_ctx, http_client
|
|
|
|
def _get_safe_stdio_env(self, provided_env: dict[str, str] | None) -> dict[str, str] | None:
|
|
"""
|
|
Return a safe environment for the stdio subprocess.
|
|
|
|
If provided_env is set, we use it as-is.
|
|
If provided_env is None, we return a minimal allowlist from the parent environment
|
|
to avoid leaking sensitive LiteLLM keys (OPENAI_API_KEY, etc.) to sub-processes.
|
|
"""
|
|
if provided_env is not None:
|
|
return provided_env
|
|
|
|
# Minimal allowlist of safe/standard environment variables
|
|
safe_keys: Final = {
|
|
"PATH",
|
|
"HOME",
|
|
"USER",
|
|
"LOGNAME",
|
|
"TMPDIR",
|
|
"TMP",
|
|
"TEMP",
|
|
"SHELL",
|
|
"LANG",
|
|
"LC_ALL",
|
|
# Node/Package manager caches
|
|
"NPM_CONFIG_CACHE",
|
|
"PNPM_HOME",
|
|
"XDG_CACHE_HOME",
|
|
"XDG_CONFIG_HOME",
|
|
"XDG_DATA_HOME",
|
|
# System info
|
|
"SYSTEMROOT",
|
|
"COMSPEC",
|
|
"PATHEXT",
|
|
"WINDIR",
|
|
}
|
|
|
|
safe_env: Final = {}
|
|
for key in safe_keys:
|
|
if key in os.environ:
|
|
safe_env[key] = os.environ[key]
|
|
|
|
if "NPM_CONFIG_CACHE" not in safe_env:
|
|
safe_env["NPM_CONFIG_CACHE"] = MCP_NPM_CACHE_DIR
|
|
|
|
return safe_env
|
|
|
|
async def _prepare_session(self, session: ClientSession) -> InitializeResult | DiscoverResult:
|
|
if self.protocol_version != "2026-07-28":
|
|
return await self._initialize_session(session)
|
|
discovery: Final = DiscoverResult.model_validate(await session.send_discover(self.protocol_version))
|
|
if self.protocol_version not in discovery.supported_versions:
|
|
raise MCPError(code=-32022, message="Upstream did not accept the configured MCP protocol version")
|
|
session.adopt(discovery)
|
|
if session.protocol_version != self.protocol_version:
|
|
raise MCPError(code=-32022, message="Upstream selected an unsupported MCP protocol version")
|
|
return discovery
|
|
|
|
async def _initialize_session(self, session: ClientSession) -> InitializeResult:
|
|
if self.protocol_version == "auto":
|
|
automatic: Final = await session.initialize()
|
|
if automatic.protocol_version not in MCP_LEGACY_VERSIONS:
|
|
raise MCPError(code=-32022, message="Upstream selected an unsupported MCP protocol version")
|
|
return automatic
|
|
result: Final = await session.send_request(
|
|
InitializeRequest(
|
|
params=InitializeRequestParams(
|
|
protocol_version=self.protocol_version,
|
|
client_info=Implementation(name="litellm", version=version("litellm")),
|
|
capabilities=ClientCapabilities(
|
|
sampling=SamplingCapability() if self._sampling_callback is not None else None,
|
|
elicitation=ElicitationCapability(
|
|
form=FormElicitationCapability(), url=UrlElicitationCapability()
|
|
)
|
|
if self._elicitation_callback is not None
|
|
else None,
|
|
),
|
|
)
|
|
),
|
|
InitializeResult,
|
|
)
|
|
if result.protocol_version != self.protocol_version:
|
|
raise MCPError(code=-32022, message="Upstream did not accept the configured MCP protocol version")
|
|
session.adopt(result)
|
|
await session.send_notification(InitializedNotification())
|
|
return result
|
|
|
|
async def _execute_session_operation(
|
|
self,
|
|
transport_ctx: _TransportContext,
|
|
operation: Callable[[ClientSession], Awaitable[TSessionResult]],
|
|
http_client: httpx2.AsyncClient | None = None,
|
|
*,
|
|
on_stream_error: Callable[[asyncio.Future[Exception]], None] | None = None,
|
|
on_cleanup: Callable[[], None] | None = None,
|
|
on_notification: Callable[[ServerNotification], Awaitable[None]] | None = None,
|
|
) -> TSessionResult:
|
|
"""
|
|
Execute an operation within a transport and session context.
|
|
Handles entering/exiting contexts and running the operation.
|
|
Passes sampling/elicitation/logging callbacks to the ClientSession
|
|
so that upstream MCP servers can request LLM inference (sampling),
|
|
user input (elicitation), or send log messages.
|
|
"""
|
|
in_flight_error: BaseException | None = None
|
|
with anyio.CancelScope() as cleanup_scope:
|
|
if isinstance(http_client, _MCPHTTPClient):
|
|
http_client.cleanup_scope = cleanup_scope
|
|
try:
|
|
transport: Final = await transport_ctx.__aenter__()
|
|
try:
|
|
read_stream: Final = transport[0]
|
|
write_stream: Final = transport[1]
|
|
stream_error: Final[asyncio.Future[Exception]] = asyncio.get_running_loop().create_future()
|
|
if isinstance(http_client, _MCPHTTPClient):
|
|
http_client.post_failure = stream_error # rebind-ok: operation-scoped stream error
|
|
_notify_stream_error(on_stream_error, stream_error)
|
|
|
|
session_kwargs: Final = (
|
|
self._session_callbacks_override
|
|
if self._session_callbacks_override is not None
|
|
else self.session_callbacks()
|
|
)
|
|
# The SDK drops a response stream that ends without a JSON-RPC reply, so nothing else
|
|
# ever fails the request.
|
|
session_type: Final = (
|
|
_UnvalidatedClientSession if self.skip_tool_output_validation else ClientSession
|
|
)
|
|
session_ctx: Final = session_type(
|
|
read_stream,
|
|
write_stream,
|
|
read_timeout_seconds=self.timeout,
|
|
message_handler=partial(
|
|
_receive_session_message, stream_error=stream_error, on_notification=on_notification
|
|
),
|
|
sampling_callback=session_kwargs["sampling_callback"],
|
|
elicitation_callback=session_kwargs["elicitation_callback"],
|
|
logging_callback=session_kwargs["logging_callback"],
|
|
)
|
|
session: Final = await session_ctx.__aenter__()
|
|
try:
|
|
init_result: Final = await self._prepare_session(session)
|
|
instructions: Final = getattr(init_result, "instructions", None)
|
|
self._last_initialize_instructions = (
|
|
instructions.strip() or None if isinstance(instructions, str) else None
|
|
)
|
|
result: Final = await operation(session)
|
|
except BaseException as operation_error:
|
|
in_flight_error = operation_error
|
|
if isinstance(operation_error, MCPError) and stream_error.done():
|
|
raise stream_error.result()
|
|
raise
|
|
finally:
|
|
_notify_cleanup(on_cleanup)
|
|
cleanup_scope.shield = True
|
|
cleanup_scope.deadline = anyio.current_time() + 5
|
|
try:
|
|
await session_ctx.__aexit__(None, None, None)
|
|
except (Exception, asyncio.CancelledError) as e:
|
|
verbose_logger.debug("Error during session context exit: %s", e)
|
|
if in_flight_error is None and isinstance(e, asyncio.CancelledError):
|
|
raise
|
|
except BaseException as e:
|
|
in_flight_error = e
|
|
raise
|
|
finally:
|
|
_notify_cleanup(on_cleanup)
|
|
cleanup_scope.shield = True
|
|
cleanup_scope.deadline = min(cleanup_scope.deadline, anyio.current_time() + 5)
|
|
try:
|
|
await transport_ctx.__aexit__(None, None, None)
|
|
except (Exception, asyncio.CancelledError) as exit_error:
|
|
verbose_logger.debug("Error during transport context exit: %s", exit_error)
|
|
if in_flight_error is None and isinstance(exit_error, asyncio.CancelledError):
|
|
raise
|
|
root_cause: Final = _first_non_cancelled_cause(
|
|
exit_error, http_client.cleanup_errors if isinstance(http_client, _MCPHTTPClient) else ()
|
|
)
|
|
if root_cause is not None and isinstance(in_flight_error, asyncio.CancelledError):
|
|
raise root_cause from in_flight_error
|
|
finally:
|
|
cleanup_scope.shield = False
|
|
if isinstance(http_client, _MCPHTTPClient):
|
|
http_client.cleanup_errors = ()
|
|
http_client.cleanup_scope = None
|
|
http_client.post_failure = None # rebind-ok: clear operation-scoped stream error
|
|
await anyio.lowlevel.checkpoint_if_cancelled()
|
|
if cleanup_scope.cancel_called:
|
|
raise (
|
|
in_flight_error
|
|
if in_flight_error is not None
|
|
else asyncio.CancelledError(SESSION_CLEANUP_TIMEOUT_MESSAGE)
|
|
)
|
|
return result
|
|
|
|
async def run_with_session(
|
|
self,
|
|
operation: Callable[[ClientSession], Awaitable[TSessionResult]],
|
|
*,
|
|
quiet_on_error: bool = False,
|
|
on_stream_error: Callable[[asyncio.Future[Exception]], None] | None = None,
|
|
on_cleanup: Callable[[], None] | None = None,
|
|
on_notification: Callable[[ServerNotification], Awaitable[None]] | None = None,
|
|
) -> TSessionResult:
|
|
"""Open a session, run the provided coroutine, and clean up.
|
|
|
|
quiet_on_error demotes the failure line to debug for callers that own the exception
|
|
(call_tool / list_tools under raise_on_error), so an expected pass-through re-auth does
|
|
not emit a warning per call; every other caller keeps the operator-visible warning."""
|
|
http_client: httpx2.AsyncClient | None = None
|
|
close_cancellation: asyncio.CancelledError | None = None
|
|
try:
|
|
self._last_initialize_instructions = None
|
|
transport_ctx, http_client = self._create_transport_context()
|
|
execution: Final = (
|
|
self._execute_session_operation(
|
|
transport_ctx,
|
|
operation,
|
|
http_client=http_client,
|
|
on_stream_error=on_stream_error,
|
|
on_cleanup=on_cleanup,
|
|
on_notification=on_notification,
|
|
)
|
|
if on_stream_error is not None or on_cleanup is not None or on_notification is not None
|
|
else self._execute_session_operation(transport_ctx, operation, http_client=http_client)
|
|
)
|
|
result: Final = await execution
|
|
except Exception as e:
|
|
read_timeout: Final = as_mcp_read_timeout(e)
|
|
if read_timeout is not None:
|
|
verbose_logger.warning(
|
|
"MCP client timed out after %ss waiting for a valid MCP response from %s",
|
|
self.timeout,
|
|
self.server_url or "stdio",
|
|
)
|
|
raise read_timeout from e
|
|
_log: Final = verbose_logger.debug if quiet_on_error else verbose_logger.warning
|
|
_log("MCP client run_with_session failed for %s", self.server_url or "stdio")
|
|
raise
|
|
finally:
|
|
if http_client is not None:
|
|
try:
|
|
await _run_bounded_cleanup(http_client.aclose, anyio.current_time() + 1)
|
|
except (Exception, asyncio.CancelledError) as e:
|
|
verbose_logger.debug("Error during http_client cleanup: %s", e)
|
|
if isinstance(e, asyncio.CancelledError):
|
|
close_cancellation = e
|
|
|
|
if close_cancellation is not None:
|
|
raise close_cancellation
|
|
await anyio.lowlevel.checkpoint_if_cancelled()
|
|
return result
|
|
|
|
def open_persistent_session(
|
|
self,
|
|
admission: Callable[[], AbstractAsyncContextManager[None]] | None = None,
|
|
) -> "PersistentMCPSession":
|
|
return PersistentMCPSession(self, admission)
|
|
|
|
def update_auth_value(self, mcp_auth_value: str | dict[str, str]) -> None:
|
|
"""
|
|
Set the authentication header for the MCP client.
|
|
"""
|
|
if isinstance(mcp_auth_value, dict):
|
|
self._mcp_auth_value = mcp_auth_value
|
|
elif self.auth_type == MCPAuth.basic:
|
|
self._mcp_auth_value = to_basic_credentials(mcp_auth_value)
|
|
else:
|
|
self._mcp_auth_value = mcp_auth_value
|
|
|
|
def _header_slot(self, default: str) -> str:
|
|
return self._credential_slot or default
|
|
|
|
def _get_auth_headers(self) -> dict:
|
|
"""Generate authentication headers based on auth type."""
|
|
headers: Final = {}
|
|
if self._mcp_auth_value:
|
|
if isinstance(self._mcp_auth_value, str):
|
|
if self.auth_type == MCPAuth.bearer_token:
|
|
static_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer")
|
|
headers[self._header_slot("Authorization")] = f"Bearer {static_bearer}"
|
|
elif self.auth_type == MCPAuth.basic:
|
|
headers[self._header_slot("Authorization")] = f"Basic {self._mcp_auth_value}"
|
|
elif self.auth_type == MCPAuth.api_key:
|
|
headers[self._header_slot("X-API-Key")] = self._mcp_auth_value
|
|
elif self.auth_type == MCPAuth.authorization:
|
|
# This auth type means the caller owns the whole header value.
|
|
headers[self._header_slot("Authorization")] = self._mcp_auth_value
|
|
elif self.auth_type == MCPAuth.oauth2:
|
|
oauth2_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer")
|
|
headers[self._header_slot("Authorization")] = f"Bearer {oauth2_bearer}"
|
|
elif self.auth_type == MCPAuth.token:
|
|
scheme_token: Final = strip_auth_scheme(self._mcp_auth_value, "token")
|
|
headers[self._header_slot("Authorization")] = f"token {scheme_token}"
|
|
elif self.auth_type == MCPAuth.oauth2_token_exchange:
|
|
exchanged_bearer: Final = strip_auth_scheme(self._mcp_auth_value, "Bearer")
|
|
headers[self._header_slot("Authorization")] = f"Bearer {exchanged_bearer}"
|
|
elif isinstance(self._mcp_auth_value, dict):
|
|
headers.update(self._mcp_auth_value)
|
|
# Note: aws_sigv4 auth is not handled here — SigV4 requires per-request
|
|
# signing (including the body hash), so it uses httpx2.Auth flow instead
|
|
# of static headers. See MCPSigV4Auth and _create_httpx_client_factory().
|
|
# update the headers with the extra headers
|
|
if self.extra_headers:
|
|
# Mirrors _resolve_v2_auth: when the operator named a slot for the credential the
|
|
# gateway resolved, no injected header may shadow it, case-insensitively, since HTTP
|
|
# header names are. Without a configured slot the old precedence stands unchanged.
|
|
slot: Final = self._credential_slot
|
|
injected: Final = (
|
|
without_header(self.extra_headers, slot) if slot and has_header(headers, slot) else self.extra_headers
|
|
)
|
|
headers.update(injected or {})
|
|
return _strip_header_whitespace(headers)
|
|
|
|
def _create_httpx_client_factory(
|
|
self, *, transport: httpx2.AsyncBaseTransport | None = None
|
|
) -> Callable[..., httpx2.AsyncClient]:
|
|
"""
|
|
Create a custom httpx2 client factory that uses LiteLLM's SSL configuration.
|
|
This factory follows the same CA bundle path logic as http_handler.py:
|
|
1. Check ssl_verify parameter (can be SSLContext, bool, or path to CA bundle)
|
|
2. Check SSL_VERIFY environment variable
|
|
3. Check SSL_CERT_FILE environment variable
|
|
4. Fall back to certifi CA bundle
|
|
"""
|
|
|
|
def factory(
|
|
*,
|
|
headers: dict[str, str] | None = None,
|
|
timeout: httpx2.Timeout | None = None,
|
|
auth: httpx2.Auth | None = None,
|
|
) -> httpx2.AsyncClient:
|
|
"""Create an httpx2.AsyncClient with LiteLLM's SSL configuration."""
|
|
# Get unified SSL configuration using the same logic as http_handler.py
|
|
ssl_config: Final = get_ssl_configuration(self.ssl_verify)
|
|
verbose_logger.debug("MCP client using SSL configuration: %s", type(ssl_config).__name__)
|
|
# The MCP SDK's sse_client and streamable_http_client call this factory without
|
|
# passing auth=, so the fallback is used: a v2-resolved auth if present, else the
|
|
# SigV4 aws_auth. Both are None for the common case — no behavior change.
|
|
fallback_auth: Final = self._resolved_auth if self._resolved_auth is not None else self._aws_auth
|
|
effective_auth: Final = auth if auth is not None else fallback_auth
|
|
guard: Final = credential_redirect_hook(self.server_url, self._credential_slot)
|
|
return _MCPHTTPClient(
|
|
transport=transport,
|
|
headers=headers,
|
|
timeout=timeout,
|
|
auth=effective_auth,
|
|
verify=ssl_config,
|
|
follow_redirects=True,
|
|
event_hooks=MappingProxyType(
|
|
{
|
|
"response": list(
|
|
self._session_callbacks_override["response_hooks"]
|
|
if self._session_callbacks_override is not None
|
|
else _mcp_response_hooks()
|
|
),
|
|
"request": [guard] if guard else [],
|
|
}
|
|
),
|
|
)
|
|
|
|
return factory
|
|
|
|
async def list_page(self, request: "CatalogListRequest") -> "CatalogListResult":
|
|
from mcp.types import INVALID_PARAMS
|
|
|
|
params: Final = request.params or PaginatedRequestParams()
|
|
if isinstance(request, ListToolsRequest):
|
|
return await self.list_tools_page(params)
|
|
|
|
async def fetch(session: ClientSession) -> "CatalogListResult":
|
|
capabilities: Final = session.server_capabilities
|
|
empty: Final = (
|
|
ListPromptsResult(prompts=[])
|
|
if isinstance(request, ListPromptsRequest)
|
|
else ListResourcesResult(resources=[])
|
|
if isinstance(request, ListResourcesRequest)
|
|
else ListResourceTemplatesResult(resource_templates=[])
|
|
)
|
|
supported: Final = capabilities is None or (
|
|
capabilities.prompts is not None
|
|
if isinstance(request, ListPromptsRequest)
|
|
else capabilities.resources is not None
|
|
)
|
|
if not supported:
|
|
if params.cursor is not None:
|
|
raise MCPError(
|
|
code=INVALID_PARAMS, message="Upstream catalog became unavailable; start a fresh listing"
|
|
)
|
|
return empty
|
|
try:
|
|
if isinstance(request, ListPromptsRequest):
|
|
return await session.list_prompts(params=params)
|
|
if isinstance(request, ListResourcesRequest):
|
|
return await session.list_resources(params=params)
|
|
return await session.list_resource_templates(params=params)
|
|
except MCPError as error:
|
|
if error.error.code == METHOD_NOT_FOUND and params.cursor is None:
|
|
return empty
|
|
raise
|
|
|
|
with anyio.fail_after(max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)):
|
|
return await self.run_with_session(fetch, quiet_on_error=True)
|
|
|
|
async def list_tools_page(self, params: PaginatedRequestParams) -> ListToolsResult:
|
|
with anyio.fail_after(max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)):
|
|
return await self.run_with_session(lambda session: session.list_tools(params=params), quiet_on_error=True)
|
|
|
|
async def list_tools(self, raise_on_error: bool = False) -> list[MCPTool]:
|
|
return (await self.list_tools_result(raise_on_error=raise_on_error)).tools
|
|
|
|
async def list_tools_result(self, raise_on_error: bool = False) -> ListToolsResult:
|
|
"""List available tools from the server.
|
|
|
|
Args:
|
|
raise_on_error: When True, re-raise exceptions instead of returning
|
|
an empty list. Used by the proxy's pass-through MCP flow so it
|
|
can surface upstream HTTP 401 responses as a proper 401 to the
|
|
MCP client (triggering the upstream OAuth flow) rather than
|
|
masking them as "connected, no tools".
|
|
"""
|
|
verbose_logger.debug("MCP client listing tools from %s", self.server_url or "stdio")
|
|
|
|
try:
|
|
# A per-server timeout above the global default extends the whole-walk deadline
|
|
listing_deadline: Final = max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)
|
|
listing: Final = await self.run_with_session(
|
|
partial(
|
|
list_tools_result_with_pagination,
|
|
listing_deadline=listing_deadline,
|
|
require_complete=raise_on_error,
|
|
),
|
|
quiet_on_error=raise_on_error,
|
|
)
|
|
tool_count: Final = len(listing.tools)
|
|
tool_names: Final = tuple(tool.name for tool in listing.tools)
|
|
verbose_logger.info(
|
|
"MCP client listed %s tools from %s: %s", tool_count, self.server_url or "stdio", tool_names
|
|
)
|
|
return listing
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client list_tools was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
error_type: Final = type(e).__name__
|
|
# Mirror call_tool: when the caller opted into raise_on_error it owns the exception and
|
|
# logs it at the fitting level (an expected pass-through re-auth 401 is info, not an
|
|
# error), so log at debug here to avoid an error-level line + traceback that would trip
|
|
# error-rate alerts on that expected signal. The swallow path still logs the full
|
|
# exception because nothing downstream will surface the failure.
|
|
_log: Final = verbose_logger.debug if raise_on_error else verbose_logger.exception
|
|
_log(
|
|
f"MCP client list_tools failed - "
|
|
f"Error Type: {error_type}, "
|
|
f"Error: {e}, "
|
|
f"Server: {self.server_url or 'stdio'}, "
|
|
f"Transport: {self.transport_type}"
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
_log_broken: Final = verbose_logger.debug if raise_on_error else verbose_logger.error
|
|
_log_broken(
|
|
"MCP client detected broken connection/stream during list_tools - "
|
|
"the MCP server may have crashed, disconnected, or timed out"
|
|
)
|
|
|
|
if raise_on_error:
|
|
raise
|
|
# Return empty list instead of raising to allow graceful degradation
|
|
return ListToolsResult(tools=[])
|
|
|
|
@staticmethod
|
|
def error_tool_result(exc: Exception) -> MCPCallToolResult:
|
|
"""The error result ``call_tool`` returns when it swallows a failure (no re-execution)."""
|
|
return error_text_result(exc)
|
|
|
|
async def _request_with_interaction(
|
|
self,
|
|
session: ClientSession,
|
|
request: Callable[[InputResponses | None, str | None], Awaitable[TSessionResult | InputRequiredResult]],
|
|
input_responses: InputResponses | None,
|
|
request_state: str | None,
|
|
allow_input_required: bool,
|
|
) -> TSessionResult | InputRequiredResult:
|
|
from litellm.proxy.mcp_server.contracts import ClientInteraction
|
|
from litellm.proxy.mcp_server.interactions import LegacyClientInteraction, ModernClientInteraction
|
|
|
|
with anyio.fail_after(self.timeout):
|
|
first: Final = await request(input_responses, request_state)
|
|
if allow_input_required:
|
|
return await ModernClientInteraction(
|
|
session, allow_elicitation=self._elicitation_callback is not None
|
|
).complete(first, request)
|
|
if not isinstance(first, InputRequiredResult):
|
|
return first
|
|
interaction: Final[ClientInteraction] = LegacyClientInteraction(session)
|
|
return await run_input_required_driver(first, dispatch=interaction.request, retry=request)
|
|
|
|
async def call_tool(
|
|
self,
|
|
call_tool_request_params: MCPCallToolRequestParams,
|
|
host_progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
raise_on_error: bool = False,
|
|
allow_input_required: bool = False,
|
|
persistent_session: "PersistentMCPSession | None" = None,
|
|
) -> MCPCallToolResult | InputRequiredResult:
|
|
"""
|
|
Call an MCP Tool.
|
|
|
|
persistent_session runs the call inside an already-open upstream session (one
|
|
upstream mcp-session-id shared by every call of a stateful gateway session) instead of
|
|
the per-call initialize + teardown that run_with_session performs.
|
|
|
|
Args:
|
|
raise_on_error: When True, re-raise the underlying exception instead of returning an
|
|
``isError=True`` result. The token-exchange (OBO) tool-call path uses this to detect
|
|
an upstream 401 so it can re-mint the exchanged token and retry once; every other
|
|
caller keeps the default and gets graceful ``isError`` degradation.
|
|
allow_input_required: When True, a 2026-07-28 upstream may answer with an interim
|
|
``InputRequiredResult`` and it is returned as is. The SDK rejects it otherwise, so
|
|
callers only opt in when the downstream side can carry it.
|
|
"""
|
|
verbose_logger.info("MCP client calling tool '%s'", call_tool_request_params.name)
|
|
|
|
async def on_progress(progress: float, total: float | None, message: str | None):
|
|
percentage: Final = (progress / total * 100) if total else 0
|
|
verbose_logger.info(
|
|
f"MCP Tool '{call_tool_request_params.name}' progress: "
|
|
f"{progress}/{total} ({percentage:.0f}%) - {message or ''}"
|
|
)
|
|
# Forward to Host if callback provided
|
|
if host_progress_callback:
|
|
try:
|
|
try:
|
|
inspect.signature(host_progress_callback).bind(progress, total, message)
|
|
except (TypeError, ValueError):
|
|
await host_progress_callback(progress, total)
|
|
else:
|
|
await host_progress_callback(progress, total, message)
|
|
except Exception as e:
|
|
verbose_logger.warning("Failed to forward to Host: %s", e)
|
|
|
|
async def _call_tool_operation(session: ClientSession):
|
|
verbose_logger.debug("MCP client sending tool call to session")
|
|
if self.protocol_version == "2026-07-28":
|
|
tools: Final = await list_tools_with_pagination(
|
|
session, listing_deadline=max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)
|
|
)
|
|
if not any(tool.name == call_tool_request_params.name for tool in tools):
|
|
raise MCPError(code=-32603, message="Tool schema is unavailable from the bounded upstream catalog")
|
|
|
|
async def request(
|
|
responses: InputResponses | None, state: str | None
|
|
) -> MCPCallToolResult | InputRequiredResult:
|
|
return await session.call_tool(
|
|
name=call_tool_request_params.name,
|
|
arguments=call_tool_request_params.arguments,
|
|
input_responses=responses,
|
|
request_state=state,
|
|
progress_callback=on_progress,
|
|
allow_input_required=True,
|
|
)
|
|
|
|
return await self._request_with_interaction(
|
|
session,
|
|
request,
|
|
call_tool_request_params.input_responses,
|
|
call_tool_request_params.request_state,
|
|
allow_input_required,
|
|
)
|
|
|
|
try:
|
|
tool_result: Final = (
|
|
await self.run_with_session(_call_tool_operation, quiet_on_error=raise_on_error)
|
|
if persistent_session is None
|
|
else await persistent_session.run(
|
|
_call_tool_operation,
|
|
quiet_on_error=raise_on_error,
|
|
callbacks=self.session_callbacks(),
|
|
)
|
|
)
|
|
verbose_logger.info("MCP client tool call '%s' completed successfully", call_tool_request_params.name)
|
|
return tool_result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client tool call timed out after %ss for %s", self.timeout, self.server_url)
|
|
raise
|
|
except Exception as e:
|
|
import traceback
|
|
|
|
error_trace: Final = traceback.format_exc()
|
|
verbose_logger.debug("MCP client tool call traceback:\n%s", error_trace)
|
|
# Log detailed error information
|
|
error_type: Final = type(e).__name__
|
|
if is_url_elicitation_required(e):
|
|
raise
|
|
# When the caller opted into raise_on_error it owns the exception and logs it at the
|
|
# level that fits (an expected pass-through re-auth 401 is info, not an operator-actionable
|
|
# error), so log at debug here to avoid an error-level line that would trip error-rate
|
|
# alerts on that expected signal. The swallow path (raise_on_error=False) still logs at
|
|
# error because nothing downstream will surface the failure.
|
|
_log: Final = verbose_logger.debug if raise_on_error else verbose_logger.error
|
|
_log(
|
|
f"MCP client call_tool failed - "
|
|
f"Error Type: {error_type}, "
|
|
f"Error: {e}, "
|
|
f"Tool: {call_tool_request_params.name}, "
|
|
f"Server: {self.server_url or 'stdio'}, "
|
|
f"Transport: {self.transport_type}"
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
_log(
|
|
"MCP client detected broken connection/stream - "
|
|
"the MCP server may have crashed, disconnected, or timed out."
|
|
)
|
|
if raise_on_error:
|
|
raise
|
|
# Return a default error result instead of raising
|
|
return self.error_tool_result(e)
|
|
|
|
async def _run_optional_discovery(self, operation: Callable[[ClientSession], Awaitable[_ListPage]]) -> _ListPage:
|
|
async def timed_operation(session: ClientSession) -> tuple[_ListPage, float]:
|
|
result: Final = await operation(session)
|
|
return result, time.monotonic()
|
|
|
|
result, received = await self.run_with_session(timed_operation)
|
|
return age_freshness(result, time.monotonic() - received)
|
|
|
|
async def _list_optional_pages(
|
|
self,
|
|
fetch_page: Callable[[PaginatedRequestParams | None], Awaitable[_ListPage]],
|
|
items_of: Callable[[_ListPage], Sequence[_ListItem]],
|
|
) -> tuple[list[_ListItem], CacheableResult]:
|
|
items: Final[list[_ListItem]] = [] # mutable-ok: bounded iterative page accumulation
|
|
pages: Final[list[tuple[CacheableResult, float]]] = [] # mutable-ok: bounded pagination evidence
|
|
cursors: Final[set[str]] = set() # mutable-ok: constant-time detection of cursor cycles
|
|
cursor: str | None = None # rebind-ok: iterative traversal avoids recursion at the existing page cap
|
|
with anyio.fail_after(max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)):
|
|
for page_index in range(MCP_TOOL_LISTING_MAX_PAGES):
|
|
try:
|
|
page = await fetch_page(None if cursor is None else PaginatedRequestParams(cursor=cursor))
|
|
except MCPError as error:
|
|
if page_index > 0 and error.error.code == METHOD_NOT_FOUND:
|
|
raise RuntimeError("MCP list operation became unavailable during pagination") from error
|
|
raise
|
|
pages.append((page, time.monotonic()))
|
|
items.extend(items_of(page))
|
|
if not page.next_cursor:
|
|
now: Final = time.monotonic()
|
|
return items, aggregate_freshness(
|
|
tuple(age_freshness(value, now - received) for value, received in pages)
|
|
)
|
|
if page.next_cursor in cursors:
|
|
raise RuntimeError("MCP list pagination repeated a cursor")
|
|
cursors.add(page.next_cursor)
|
|
cursor = page.next_cursor
|
|
raise RuntimeError(f"MCP list pagination exceeded {MCP_TOOL_LISTING_MAX_PAGES} pages")
|
|
|
|
async def list_prompts(self, *, raise_on_error: bool = False) -> list[Prompt]:
|
|
return (await self.list_prompts_result(raise_on_error=raise_on_error)).prompts
|
|
|
|
async def list_prompts_result(self, *, raise_on_error: bool = False) -> ListPromptsResult:
|
|
"""List available prompts from the server."""
|
|
verbose_logger.debug("MCP client listing tools from %s", self.server_url or "stdio")
|
|
|
|
async def _list_prompts_operation(session: ClientSession) -> ListPromptsResult:
|
|
capabilities: Final = session.server_capabilities
|
|
if capabilities is not None and capabilities.prompts is None:
|
|
return ListPromptsResult(prompts=[])
|
|
try:
|
|
items, freshness = await self._list_optional_pages(
|
|
lambda params: session.list_prompts(params=params), lambda page: page.prompts
|
|
)
|
|
return ListPromptsResult(prompts=items, ttl_ms=freshness.ttl_ms, cache_scope=freshness.cache_scope)
|
|
except MCPError as error:
|
|
if error.error.code != METHOD_NOT_FOUND:
|
|
raise
|
|
verbose_logger.debug(
|
|
"MCP client list_prompts is unsupported by %s: %s", self.server_url or "stdio", error
|
|
)
|
|
return ListPromptsResult(prompts=[])
|
|
|
|
try:
|
|
result: Final = await self._run_optional_discovery(_list_prompts_operation)
|
|
prompt_count: Final = len(result.prompts)
|
|
prompt_names: Final = [prompt.name for prompt in result.prompts]
|
|
verbose_logger.info(
|
|
"MCP client listed %s tools from %s: %s", prompt_count, self.server_url or "stdio", prompt_names
|
|
)
|
|
return result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client list_prompts was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
if raise_on_error:
|
|
raise
|
|
error_type: Final = type(e).__name__
|
|
verbose_logger.error(
|
|
"MCP client list_prompts failed - Error Type: %s, Error: %s, Server: %s, Transport: %s",
|
|
error_type,
|
|
e,
|
|
self.server_url or "stdio",
|
|
self.transport_type,
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
verbose_logger.error(
|
|
"MCP client detected broken connection/stream during list_tools - "
|
|
"the MCP server may have crashed, disconnected, or timed out"
|
|
)
|
|
# Return empty list instead of raising to allow graceful degradation
|
|
return ListPromptsResult(prompts=[])
|
|
|
|
async def get_prompt(
|
|
self, get_prompt_request_params: GetPromptRequestParams, *, allow_input_required: bool = False
|
|
) -> GetPromptResult | InputRequiredResult:
|
|
"""Fetch a prompt definition from the MCP server."""
|
|
verbose_logger.info("MCP client fetching prompt '%s'", get_prompt_request_params.name)
|
|
|
|
async def _get_prompt_operation(session: ClientSession):
|
|
verbose_logger.debug("MCP client sending get_prompt request to session")
|
|
|
|
async def request(
|
|
responses: InputResponses | None, state: str | None
|
|
) -> GetPromptResult | InputRequiredResult:
|
|
return await session.get_prompt(
|
|
name=get_prompt_request_params.name,
|
|
arguments=get_prompt_request_params.arguments,
|
|
input_responses=responses,
|
|
request_state=state,
|
|
allow_input_required=True,
|
|
)
|
|
|
|
return await self._request_with_interaction(
|
|
session,
|
|
request,
|
|
get_prompt_request_params.input_responses,
|
|
get_prompt_request_params.request_state,
|
|
allow_input_required,
|
|
)
|
|
|
|
try:
|
|
get_prompt_result: Final = await self.run_with_session(_get_prompt_operation)
|
|
verbose_logger.info("MCP client get_prompt '%s' completed successfully", get_prompt_request_params.name)
|
|
return get_prompt_result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client get_prompt was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
import traceback
|
|
|
|
error_trace: Final = traceback.format_exc()
|
|
verbose_logger.debug("MCP client get_prompt traceback:\n%s", error_trace)
|
|
# Log detailed error information
|
|
error_type: Final = type(e).__name__
|
|
verbose_logger.error(
|
|
"MCP client get_prompt failed - Error Type: %s, Error: %s, Prompt: %s, Server: %s, Transport: %s",
|
|
error_type,
|
|
e,
|
|
get_prompt_request_params.name,
|
|
self.server_url or "stdio",
|
|
self.transport_type,
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
verbose_logger.error(
|
|
"MCP client detected broken connection/stream during get_prompt - "
|
|
"the MCP server may have crashed, disconnected, or timed out."
|
|
)
|
|
raise
|
|
|
|
async def list_resources(self, *, raise_on_error: bool = False) -> list[Resource]:
|
|
return (await self.list_resources_result(raise_on_error=raise_on_error)).resources
|
|
|
|
async def list_resources_result(self, *, raise_on_error: bool = False) -> ListResourcesResult:
|
|
"""List available resources from the server."""
|
|
verbose_logger.debug("MCP client listing resources from %s", self.server_url or "stdio")
|
|
|
|
async def _list_resources_operation(session: ClientSession) -> ListResourcesResult:
|
|
capabilities: Final = session.server_capabilities
|
|
if capabilities is not None and capabilities.resources is None:
|
|
return ListResourcesResult(resources=[])
|
|
try:
|
|
items, freshness = await self._list_optional_pages(
|
|
lambda params: session.list_resources(params=params), lambda page: page.resources
|
|
)
|
|
return ListResourcesResult(resources=items, ttl_ms=freshness.ttl_ms, cache_scope=freshness.cache_scope)
|
|
except MCPError as error:
|
|
if error.error.code != METHOD_NOT_FOUND:
|
|
raise
|
|
verbose_logger.debug(
|
|
"MCP client list_resources is unsupported by %s: %s", self.server_url or "stdio", error
|
|
)
|
|
return ListResourcesResult(resources=[])
|
|
|
|
try:
|
|
result: Final = await self._run_optional_discovery(_list_resources_operation)
|
|
resource_count: Final = len(result.resources)
|
|
resource_names: Final = [resource.name for resource in result.resources]
|
|
verbose_logger.info(
|
|
"MCP client listed %s resources from %s: %s", resource_count, self.server_url or "stdio", resource_names
|
|
)
|
|
return result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client list_resources was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
if raise_on_error:
|
|
raise
|
|
error_type: Final = type(e).__name__
|
|
verbose_logger.error(
|
|
"MCP client list_resources failed - Error Type: %s, Error: %s, Server: %s, Transport: %s",
|
|
error_type,
|
|
e,
|
|
self.server_url or "stdio",
|
|
self.transport_type,
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
verbose_logger.error(
|
|
"MCP client detected broken connection/stream during list_resources - "
|
|
"the MCP server may have crashed, disconnected, or timed out"
|
|
)
|
|
# Return empty list instead of raising to allow graceful degradation
|
|
return ListResourcesResult(resources=[])
|
|
|
|
async def list_resource_templates(self, *, raise_on_error: bool = False) -> list[ResourceTemplate]:
|
|
return (await self.list_resource_templates_result(raise_on_error=raise_on_error)).resource_templates
|
|
|
|
async def list_resource_templates_result(self, *, raise_on_error: bool = False) -> ListResourceTemplatesResult:
|
|
"""List available resource templates from the server."""
|
|
verbose_logger.debug("MCP client listing resource templates from %s", self.server_url or "stdio")
|
|
|
|
async def _list_resource_templates_operation(session: ClientSession) -> ListResourceTemplatesResult:
|
|
capabilities: Final = session.server_capabilities
|
|
if capabilities is not None and capabilities.resources is None:
|
|
return ListResourceTemplatesResult(resource_templates=[])
|
|
try:
|
|
items, freshness = await self._list_optional_pages(
|
|
lambda params: session.list_resource_templates(params=params), lambda page: page.resource_templates
|
|
)
|
|
return ListResourceTemplatesResult(
|
|
resource_templates=items, ttl_ms=freshness.ttl_ms, cache_scope=freshness.cache_scope
|
|
)
|
|
except MCPError as error:
|
|
if error.error.code != METHOD_NOT_FOUND:
|
|
raise
|
|
verbose_logger.debug(
|
|
"MCP client list_resource_templates is unsupported by %s: %s", self.server_url or "stdio", error
|
|
)
|
|
return ListResourceTemplatesResult(resource_templates=[])
|
|
|
|
try:
|
|
result: Final = await self._run_optional_discovery(_list_resource_templates_operation)
|
|
resource_template_count: Final = len(result.resource_templates)
|
|
resource_template_names: Final = [resource_template.name for resource_template in result.resource_templates]
|
|
verbose_logger.info(
|
|
"MCP client listed %s resource templates from %s: %s",
|
|
resource_template_count,
|
|
self.server_url or "stdio",
|
|
resource_template_names,
|
|
)
|
|
return result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client list_resource_templates was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
if raise_on_error:
|
|
raise
|
|
error_type: Final = type(e).__name__
|
|
verbose_logger.error(
|
|
"MCP client list_resource_templates failed - Error Type: %s, Error: %s, Server: %s, Transport: %s",
|
|
error_type,
|
|
e,
|
|
self.server_url or "stdio",
|
|
self.transport_type,
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
verbose_logger.error(
|
|
"MCP client detected broken connection/stream during list_resource_templates - "
|
|
"the MCP server may have crashed, disconnected, or timed out"
|
|
)
|
|
# Return empty list instead of raising to allow graceful degradation
|
|
return ListResourceTemplatesResult(resource_templates=[])
|
|
|
|
async def read_resource(
|
|
self,
|
|
url: AnyUrl,
|
|
*,
|
|
input_responses: InputResponses | None = None,
|
|
request_state: str | None = None,
|
|
allow_input_required: bool = False,
|
|
) -> ReadResourceResult | InputRequiredResult:
|
|
"""Fetch resource contents from the MCP server."""
|
|
verbose_logger.info("MCP client fetching resource '%s'", url)
|
|
|
|
async def _read_resource_operation(session: ClientSession):
|
|
verbose_logger.debug("MCP client sending read_resource request to session")
|
|
|
|
async def request(
|
|
responses: InputResponses | None, state: str | None
|
|
) -> ReadResourceResult | InputRequiredResult:
|
|
return await session.read_resource(
|
|
str(url),
|
|
input_responses=responses,
|
|
request_state=state,
|
|
allow_input_required=True,
|
|
)
|
|
|
|
return await self._request_with_interaction(
|
|
session,
|
|
request,
|
|
input_responses,
|
|
request_state,
|
|
allow_input_required,
|
|
)
|
|
|
|
try:
|
|
read_resource_result: Final = await self.run_with_session(_read_resource_operation)
|
|
verbose_logger.info("MCP client read_resource '%s' completed successfully", url)
|
|
return read_resource_result
|
|
except asyncio.CancelledError:
|
|
verbose_logger.warning("MCP client read_resource was cancelled")
|
|
raise
|
|
except Exception as e:
|
|
import traceback
|
|
|
|
error_trace: Final = traceback.format_exc()
|
|
verbose_logger.debug("MCP client read_resource traceback:\n%s", error_trace)
|
|
# Log detailed error information
|
|
error_type: Final = type(e).__name__
|
|
verbose_logger.error(
|
|
"MCP client read_resource failed - Error Type: %s, Error: %s, Url: %s, Server: %s, Transport: %s",
|
|
error_type,
|
|
e,
|
|
url,
|
|
self.server_url or "stdio",
|
|
self.transport_type,
|
|
)
|
|
# Check if it's a stream/connection error
|
|
if "BrokenResourceError" in error_type or "Broken" in error_type:
|
|
verbose_logger.error(
|
|
"MCP client detected broken connection/stream during read_resource - "
|
|
"the MCP server may have crashed, disconnected, or timed out."
|
|
)
|
|
raise
|
|
|
|
|
|
_PendingOperation: TypeAlias = tuple[
|
|
Callable[[ClientSession], Awaitable[object]],
|
|
asyncio.Future[object],
|
|
_SessionCallbackMap | None,
|
|
]
|
|
_MAX_PENDING_OPERATIONS: Final = 64
|
|
|
|
|
|
def _ends_session(outcome: BaseException) -> bool:
|
|
if isinstance(
|
|
outcome,
|
|
(httpx2.HTTPError, OSError, anyio.BrokenResourceError, anyio.ClosedResourceError, anyio.EndOfStream),
|
|
):
|
|
return True
|
|
return isinstance(outcome, MCPError) and outcome.error.code == CONNECTION_CLOSED
|
|
|
|
|
|
def _deliver_persistent_outcome(
|
|
future: asyncio.Future[object],
|
|
outcome: object,
|
|
stream_error: asyncio.Future[Exception] | None,
|
|
) -> bool:
|
|
mapped_outcome: Final = (
|
|
stream_error.result()
|
|
if isinstance(outcome, MCPError) and stream_error is not None and stream_error.done()
|
|
else outcome
|
|
)
|
|
if not future.done():
|
|
if isinstance(mapped_outcome, Exception):
|
|
future.set_exception(mapped_outcome)
|
|
elif isinstance(mapped_outcome, BaseException):
|
|
future.set_exception(RuntimeError("upstream MCP operation was cancelled"))
|
|
else:
|
|
future.set_result(mapped_outcome)
|
|
return (
|
|
isinstance(outcome, BaseException)
|
|
and _ends_session(outcome)
|
|
or isinstance(mapped_outcome, BaseException)
|
|
and _ends_session(mapped_outcome)
|
|
or stream_error is not None
|
|
and stream_error.done()
|
|
)
|
|
|
|
|
|
async def _await_persistent_operation(operation: Awaitable[object], result: asyncio.Future[object]) -> object:
|
|
running: Final = asyncio.ensure_future(operation)
|
|
|
|
def cancel_operation(_: asyncio.Future[object]) -> None:
|
|
running.cancel()
|
|
|
|
result.add_done_callback(cancel_operation)
|
|
try:
|
|
(outcome,) = await asyncio.gather(running, return_exceptions=True)
|
|
return outcome
|
|
finally:
|
|
result.remove_done_callback(cancel_operation)
|
|
|
|
|
|
class UpstreamSessionClosedError(RuntimeError):
|
|
def __init__(self) -> None:
|
|
super().__init__("upstream MCP session closed")
|
|
|
|
|
|
class PersistentMCPSession:
|
|
"""One upstream MCP session kept open across operations.
|
|
|
|
The SDK transport owns anyio cancel scopes that must be entered and exited by the same
|
|
task, so a dedicated task holds the session open and serves queued operations in order.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
client: MCPClient,
|
|
admission: Callable[[], AbstractAsyncContextManager[None]] | None = None,
|
|
) -> None:
|
|
loop: Final = asyncio.get_running_loop()
|
|
self._client: Final = client
|
|
self._admission: Final = admission
|
|
self._queue: Final[asyncio.Queue[_PendingOperation]] = asyncio.Queue(maxsize=_MAX_PENDING_OPERATIONS)
|
|
self._ready: Final[asyncio.Future[None]] = loop.create_future()
|
|
self._active: asyncio.Future[object] | None = None
|
|
self._stream_error: asyncio.Future[Exception] | None = None
|
|
self._retiring: bool = False
|
|
self._ended: bool = False
|
|
self._initial_callbacks: Final[_SessionCallbackMap] = client.session_callbacks()
|
|
self._current_callbacks: _SessionCallbackMap = self._initial_callbacks
|
|
delegated_callbacks: Final[_SessionCallbackMap] = {
|
|
"response_hooks": (self._record_response,),
|
|
"sampling_callback": (
|
|
self._delegate("sampling_callback")
|
|
if self._initial_callbacks["sampling_callback"] is not None
|
|
else None
|
|
),
|
|
"elicitation_callback": (
|
|
self._delegate("elicitation_callback")
|
|
if self._initial_callbacks["elicitation_callback"] is not None
|
|
else None
|
|
),
|
|
"logging_callback": (
|
|
self._delegate("logging_callback") if self._initial_callbacks["logging_callback"] is not None else None
|
|
),
|
|
}
|
|
client.route_session_callbacks(delegated_callbacks)
|
|
self._task: Final = loop.create_task(self._serve())
|
|
|
|
async def _record_response(self, response: httpx2.Response) -> None:
|
|
for hook in self._current_callbacks["response_hooks"]:
|
|
await hook(response)
|
|
|
|
@overload
|
|
def _delegate(self, name: Literal["sampling_callback"]) -> SamplingFnT: ...
|
|
|
|
@overload
|
|
def _delegate(self, name: Literal["elicitation_callback"]) -> ElicitationFnT: ...
|
|
|
|
@overload
|
|
def _delegate(self, name: Literal["logging_callback"]) -> LoggingFnT: ...
|
|
|
|
def _delegate(self, name: _SessionCallbackName) -> SamplingFnT | ElicitationFnT | LoggingFnT:
|
|
match name:
|
|
case "sampling_callback":
|
|
|
|
async def sampling_callback(
|
|
context: ClientRequestContext, params: CreateMessageRequestParams
|
|
) -> CreateMessageResult | CreateMessageResultWithTools | ErrorData:
|
|
current_callback: Final = self._current_callbacks.get(name)
|
|
initial_callback: Final = self._initial_callbacks.get(name)
|
|
callback: Final = current_callback if current_callback is not None else initial_callback
|
|
if callback is None:
|
|
raise RuntimeError("sampling callback is unavailable")
|
|
return await callback(context, params)
|
|
|
|
return sampling_callback
|
|
case "elicitation_callback":
|
|
|
|
async def elicitation_callback(
|
|
context: ClientRequestContext, params: ElicitRequestParams
|
|
) -> ElicitResult | ErrorData:
|
|
current_callback: Final = self._current_callbacks.get(name)
|
|
initial_callback: Final = self._initial_callbacks.get(name)
|
|
callback: Final = current_callback if current_callback is not None else initial_callback
|
|
if callback is None:
|
|
raise RuntimeError("elicitation callback is unavailable")
|
|
return await callback(context, params)
|
|
|
|
return elicitation_callback
|
|
case "logging_callback":
|
|
|
|
async def logging_callback(params: LoggingMessageNotificationParams) -> None:
|
|
current_callback: Final = self._current_callbacks.get(name)
|
|
initial_callback: Final = self._initial_callbacks.get(name)
|
|
callback: Final = current_callback if current_callback is not None else initial_callback
|
|
if callback is None:
|
|
raise RuntimeError("logging callback is unavailable")
|
|
await callback(params)
|
|
|
|
return logging_callback
|
|
assert_never(name)
|
|
|
|
@property
|
|
def closed(self) -> bool:
|
|
return self._task.done()
|
|
|
|
@property
|
|
def reusable(self) -> bool:
|
|
return not self._ended and not self._retiring and not self._task.done()
|
|
|
|
def _record_stream_error(self, stream_error: asyncio.Future[Exception]) -> None:
|
|
self._stream_error = stream_error
|
|
|
|
def _mark_ended(self) -> None:
|
|
self._ended = True
|
|
|
|
async def _serve(self) -> None:
|
|
admission_stack: Final = AsyncExitStack()
|
|
|
|
async def drain(session: ClientSession) -> None:
|
|
await admission_stack.aclose()
|
|
self._ready.set_result(None)
|
|
while True:
|
|
operation, future, callbacks = await self._queue.get()
|
|
if not future.done():
|
|
self._active = future
|
|
if callbacks is not None:
|
|
self._current_callbacks = callbacks
|
|
async with self._admission() if self._admission is not None else nullcontext():
|
|
if not future.done() and _deliver_persistent_outcome(
|
|
future,
|
|
await _await_persistent_operation(operation(session), future),
|
|
self._stream_error,
|
|
):
|
|
self._active = None
|
|
self._ended = True
|
|
return
|
|
self._active = None
|
|
if self._retiring and self._queue.empty():
|
|
return
|
|
|
|
try:
|
|
if self._admission is not None:
|
|
await admission_stack.enter_async_context(self._admission())
|
|
(ended,) = await asyncio.gather(
|
|
self._client.run_with_session(
|
|
drain,
|
|
quiet_on_error=True,
|
|
on_stream_error=self._record_stream_error,
|
|
on_cleanup=self._mark_ended,
|
|
),
|
|
return_exceptions=True,
|
|
)
|
|
self._ended = True
|
|
except asyncio.CancelledError:
|
|
self._ended = True
|
|
self._fail_waiters(None)
|
|
raise
|
|
finally:
|
|
await admission_stack.aclose()
|
|
self._fail_waiters(ended if isinstance(ended, Exception) else None)
|
|
|
|
def _fail_waiters(self, cause: Exception | None) -> None:
|
|
pending: Final = (self._ready, self._active, *(future for _, future, _ in self._drained()))
|
|
for future in pending:
|
|
if future is not None and not future.done():
|
|
future.set_exception(UpstreamSessionClosedError() if cause is None else cause)
|
|
|
|
def _drained(self) -> tuple[_PendingOperation, ...]:
|
|
return tuple(self._queue.get_nowait() for _ in range(self._queue.qsize()))
|
|
|
|
async def run(
|
|
self,
|
|
operation: Callable[[ClientSession], Awaitable[TSessionResult]],
|
|
*,
|
|
quiet_on_error: bool = False,
|
|
callbacks: _SessionCallbackMap | None = None,
|
|
) -> TSessionResult:
|
|
if self.closed:
|
|
await asyncio.shield(self._ready)
|
|
raise UpstreamSessionClosedError()
|
|
future: Final[asyncio.Future[object]] = asyncio.get_running_loop().create_future()
|
|
await self._queue.put((operation, future, callbacks))
|
|
try:
|
|
_ = await asyncio.wait((future, self._task), return_when=asyncio.FIRST_COMPLETED)
|
|
except asyncio.CancelledError:
|
|
_ = future.cancel()
|
|
raise
|
|
if not future.done():
|
|
raise UpstreamSessionClosedError()
|
|
return cast(TSessionResult, future.result()) # cast-ok: one queue serves operations of every result type
|
|
|
|
def close(self) -> None:
|
|
_ = self._task.cancel()
|
|
|
|
def retire(self) -> None:
|
|
if self._retiring:
|
|
return
|
|
self._retiring = True
|
|
if self.closed:
|
|
return
|
|
|
|
async def retired_operation(_: ClientSession) -> None:
|
|
return None
|
|
|
|
loop: Final = asyncio.get_running_loop()
|
|
future: Final[asyncio.Future[object]] = loop.create_future()
|
|
future.set_result(None)
|
|
try:
|
|
self._queue.put_nowait((retired_operation, future, None))
|
|
except asyncio.QueueFull:
|
|
return
|
|
|
|
async def wait_closed(self) -> None:
|
|
await asyncio.gather(self._task, return_exceptions=True)
|