Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Merge branch 'main' into oauthclient

Jeremiah Lowin0c8469ea4c60
diff --cc src/fastmcp/client/transports.py
index fc33af335,b1938e10c..c9988da03
--- a/src/fastmcp/client/transports.py
+++ b/src/fastmcp/client/transports.py
@@@ -2,39 -5,94 +5,103 @@@ import datetim
import os
import shutil
import sys
-import warnings
from collections.abc import AsyncIterator
from pathlib import Path
- from typing import Any
+ from typing import TYPE_CHECKING, Any, TypedDict, TypeVar, cast, overload
from mcp import ClientSession, StdioServerParameters
-from mcp.client.session import (
- ListRootsFnT,
- LoggingFnT,
- MessageHandlerFnT,
- SamplingFnT,
-)
-from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
-from mcp.client.streamable_http import streamablehttp_client
from mcp.client.websocket import websocket_client
+ from mcp.server.fastmcp import FastMCP as FastMCP1Server
from mcp.shared.memory import create_connected_server_and_client_session
from pydantic import AnyUrl
from typing_extensions import Unpack
+from fastmcp.client.client import ClientTransport, SessionKwargs
+from fastmcp.client.sse import SSETransport
+from fastmcp.client.streamable_http import StreamableHttpTransport
from fastmcp.server import FastMCP as FastMCPServer
+ from fastmcp.server.dependencies import get_http_headers
+ from fastmcp.server.server import FastMCP
+ from fastmcp.utilities.logging import get_logger
+ from fastmcp.utilities.mcp_config import MCPConfig, infer_transport_type_from_url
+
+ if TYPE_CHECKING:
+ from fastmcp.utilities.mcp_config import MCPConfig
+
+ logger = get_logger(__name__)
+
+ # TypeVar for preserving specific ClientTransport subclass types
+ ClientTransportT = TypeVar("ClientTransportT", bound="ClientTransport")
+__all__ = [
+ "ClientTransport",
+ "SSETransport",
+ "StreamableHttpTransport",
+ "FastMCPServer",
- "WSTransport",
+ "StdioTransport",
+ "PythonStdioTransport",
+ "FastMCPStdioTransport",
+ "NodeStdioTransport",
+ "UvxStdioTransport",
+ "NpxStdioTransport",
+ "FastMCPTransport",
+ "infer_transport",
+]
+
+ class SessionKwargs(TypedDict, total=False):
+ """Keyword arguments for the MCP ClientSession constructor."""
+
+ sampling_callback: SamplingFnT | None
+ list_roots_callback: ListRootsFnT | None
+ logging_callback: LoggingFnT | None
+ message_handler: MessageHandlerFnT | None
+ read_timeout_seconds: datetime.timedelta | None
+
+
+ class ClientTransport(abc.ABC):
+ """
+ Abstract base class for different MCP client transport mechanisms.
+
+ A Transport is responsible for establishing and managing connections
+ to an MCP server, and providing a ClientSession within an async context.
+
+ """
+
+ @abc.abstractmethod
+ @contextlib.asynccontextmanager
+ async def connect_session(
+ self, **session_kwargs: Unpack[SessionKwargs]
+ ) -> AsyncIterator[ClientSession]:
+ """
+ Establishes a connection and yields an active ClientSession.
+
+ The ClientSession is *not* expected to be initialized in this context manager.
+
+ The session is guaranteed to be valid only within the scope of the
+ async context manager. Connection setup and teardown are handled
+ within this context.
+
+ Args:
+ **session_kwargs: Keyword arguments to pass to the ClientSession
+ constructor (e.g., callbacks, timeouts).
+
+ Yields:
+ A mcp.ClientSession instance.
+ """
+ raise NotImplementedError
+ yield # type: ignore
+
+ def __repr__(self) -> str:
+ # Basic representation for subclasses
+ return f"<{self.__class__.__name__}>"
+
+ async def close(self):
+ """Close the transport."""
+ pass
+
+
class WSTransport(ClientTransport):
"""Transport implementation that connects to an MCP server via WebSockets."""
diff --cc src/fastmcp/settings.py
index 104550025,c872ecb2a..1a9e5be2f
--- a/src/fastmcp/settings.py
+++ b/src/fastmcp/settings.py
@@@ -28,10 -27,19 +28,21 @@@ class Settings(BaseSettings)
nested_model_default_partial_update=True,
)
+ home: Path = Path.home() / ".fastmcp"
+
test_mode: bool = False
log_level: LOG_LEVEL = "INFO"
+ enable_rich_tracebacks: Annotated[
+ bool,
+ Field(
+ description=inspect.cleandoc(
+ """
+ If True, will use rich tracebacks for logging.
+ """
+ )
+ ),
+ ] = True
+
client_raise_first_exceptiongroup_error: Annotated[
bool,
Field(