mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-21 04:54:17 +02:00
Merge pull request #917 from jlowin/http
This commit is contained in:
commit
c64554c4e7
30 changed files with 133 additions and 68 deletions
|
|
@ -32,4 +32,5 @@ async with Client(transport=StreamableHttpTransport(server_url)) as client:
|
|||
## Development Workflow
|
||||
|
||||
- You must always run pre-commit if you open a PR, because it is run as part of a required check.
|
||||
- When opening PRs, apply labels appropriately for bugs/breaking changes/enhancements/features. Generally, improvements are enhancements (not features) unless told otherwise.
|
||||
- When opening PRs, apply labels appropriately for bugs/breaking changes/enhancements/features. Generally, improvements are enhancements (not features) unless told otherwise.
|
||||
- NEVER modify files in docs/python-sdk/**, as they are auto-generated.
|
||||
|
|
|
|||
|
|
@ -349,7 +349,7 @@ mcp.run(transport="stdio") # Default, so transport argument is optional
|
|||
**Streamable HTTP**: Recommended for web deployments.
|
||||
|
||||
```python
|
||||
mcp.run(transport="streamable-http", host="127.0.0.1", port=8000, path="/mcp")
|
||||
mcp.run(transport="http", host="127.0.0.1", port=8000, path="/mcp")
|
||||
```
|
||||
|
||||
**SSE**: For compatibility with existing SSE clients.
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ config = {
|
|||
"mcpServers": {
|
||||
"server_name": {
|
||||
# Remote HTTP/SSE server
|
||||
"transport": "streamable-http", # or "sse"
|
||||
"transport": "http", # or "sse"
|
||||
"url": "https://api.example.com/mcp",
|
||||
"headers": {"Authorization": "Bearer token"},
|
||||
"auth": "oauth" # or bearer token string
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ Streamable HTTP is the recommended transport for web-based deployments, providin
|
|||
|
||||
- **Class:** `fastmcp.client.transports.StreamableHttpTransport`
|
||||
- **Inferred From:** URLs starting with `http://` or `https://` (default for HTTP URLs since v2.3.0) that do not contain `/sse/` in the path
|
||||
- **Server Compatibility:** Works with FastMCP servers running in `streamable-http` mode
|
||||
- **Server Compatibility:** Works with FastMCP servers running in `http` mode
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
|
|
@ -150,7 +150,7 @@ client = Client(transport)
|
|||
- **Use Streamable HTTP when:**
|
||||
- Setting up new deployments (recommended default)
|
||||
- You need bidirectional streaming
|
||||
- You're connecting to FastMCP servers running in `streamable-http` mode
|
||||
- You're connecting to FastMCP servers running in `http` mode
|
||||
|
||||
- **Use SSE when:**
|
||||
- Connecting to legacy FastMCP servers running in `sse` mode
|
||||
|
|
@ -397,7 +397,7 @@ config = {
|
|||
# Remote HTTP server
|
||||
"weather": {
|
||||
"url": "https://weather-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
},
|
||||
# Local stdio server
|
||||
"assistant": {
|
||||
|
|
@ -408,7 +408,7 @@ config = {
|
|||
# Another remote server
|
||||
"calendar": {
|
||||
"url": "https://calendar-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ When using Stdio transport, you will typically *not* run the server yourself as
|
|||
|
||||
Streamable HTTP is a modern, efficient transport for exposing your MCP server via HTTP. It is the recommended transport for web-based deployments.
|
||||
|
||||
To run a server using Streamable HTTP, you can use the `run()` method with the `transport` argument set to `"streamable-http"`. This will start a Uvicorn server on the default host (`127.0.0.1`), port (`8000`), and path (`/mcp/`).
|
||||
To run a server using Streamable HTTP, you can use the `run()` method with the `transport` argument set to `"http"`. This will start a Uvicorn server on the default host (`127.0.0.1`), port (`8000`), and path (`/mcp/`).
|
||||
<CodeGroup>
|
||||
```python {6} server.py
|
||||
from fastmcp import FastMCP
|
||||
|
|
@ -113,7 +113,7 @@ from fastmcp import FastMCP
|
|||
mcp = FastMCP()
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http")
|
||||
mcp.run(transport="http")
|
||||
```
|
||||
```python {5} client.py
|
||||
import asyncio
|
||||
|
|
@ -128,6 +128,10 @@ if __name__ == "__main__":
|
|||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Tip>
|
||||
For backward compatibility, wherever `"http"` is accepted as a transport name, you can also pass `"streamable-http"` as a fully supported alias. This is particularly useful when upgrading from FastMCP 1.x in the official Python SDK and FastMCP \<= 2.9, where `"streamable-http"` was the standard name.
|
||||
</Tip>
|
||||
|
||||
To customize the host, port, path, or log level, provide appropriate keyword arguments to the `run()` method.
|
||||
|
||||
<CodeGroup>
|
||||
|
|
@ -138,7 +142,7 @@ mcp = FastMCP()
|
|||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(
|
||||
transport="streamable-http",
|
||||
transport="http",
|
||||
host="127.0.0.1",
|
||||
port=4200,
|
||||
path="/my-custom-path",
|
||||
|
|
@ -158,7 +162,6 @@ if __name__ == "__main__":
|
|||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
### SSE
|
||||
|
||||
<Warning>
|
||||
|
|
@ -250,7 +253,7 @@ def hello(name: str) -> str:
|
|||
|
||||
async def main():
|
||||
# Use run_async() in async contexts
|
||||
await mcp.run_async(transport="streamable-http")
|
||||
await mcp.run_async(transport="http")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ FastMCP root path: ~/Developer/fastmcp
|
|||
Upgrading from the official MCP SDK's FastMCP 1.0 to FastMCP 2.0 is generally straightforward. The core server API is highly compatible, and in many cases, changing your import statement from `from mcp.server.fastmcp import FastMCP` to `from fastmcp import FastMCP` will be sufficient.
|
||||
|
||||
|
||||
```python {1-5}
|
||||
```python {5}
|
||||
# Before
|
||||
# from mcp.server.fastmcp import FastMCP
|
||||
|
||||
|
|
@ -56,8 +56,9 @@ from fastmcp import FastMCP
|
|||
|
||||
mcp = FastMCP("My MCP Server")
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Prior to `fastmcp==2.3.0` and `mcp==1.8.0`, the 2.x API always mirrored the 1.0 API. However, as the projects diverge, this can not be guaranteed. You may see deprecation warnings if you attempt to use 1.0 APIs in FastMCP 2.x. Please refer to this documentation for details on new capabilities.
|
||||
Prior to `fastmcp==2.3.0` and `mcp==1.8.0`, the 2.x API always mirrored the official 1.0 API. However, as the projects diverge, this can not be guaranteed. You may see deprecation warnings if you attempt to use 1.0 APIs in FastMCP 2.x. Please refer to this documentation for details on new capabilities.
|
||||
</Warning>
|
||||
|
||||
## Versioning and Breaking Changes
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ def roll_dice(n_dice: int) -> list[int]:
|
|||
return [random.randint(1, 6) for _ in range(n_dice)]
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
## Deploy the Server
|
||||
|
|
@ -175,7 +175,7 @@ def roll_dice(n_dice: int) -> list[int]:
|
|||
|
||||
if __name__ == "__main__":
|
||||
print(f"\n---\n\n🔑 Dice Roller access token:\n\n{access_token}\n\n---\n")
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
### Client Authentication
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ def create_server(
|
|||
|
||||
if __name__ == "__main__":
|
||||
mcp = create_server("path/to/records.json")
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
### Deploy the Server
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ def roll_dice(n_dice: int) -> list[int]:
|
|||
return [random.randint(1, 6) for _ in range(n_dice)]
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
## Connect to Claude Code
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ def roll_dice(n_dice: int) -> list[int]:
|
|||
return [random.randint(1, 6) for _ in range(n_dice)]
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
### Deploy the Server
|
||||
|
|
@ -172,7 +172,7 @@ def roll_dice(n_dice: int) -> list[int]:
|
|||
|
||||
if __name__ == "__main__":
|
||||
print(f"\n---\n\n🔑 Dice Roller access token:\n\n{access_token}\n\n---\n")
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
#### Client Authentication
|
||||
|
|
|
|||
|
|
@ -42,11 +42,12 @@ This command runs the server directly in your current Python environment. You ar
|
|||
|
||||
| Option | Flag | Description |
|
||||
| ------ | ---- | ----------- |
|
||||
| Transport | `--transport`, `-t` | Transport protocol to use (`stdio`, `streamable-http`, or `sse`) |
|
||||
| Transport | `--transport`, `-t` | Transport protocol to use (`stdio`, `http`, or `sse`) |
|
||||
| Host | `--host` | Host to bind to when using http transport (default: 127.0.0.1) |
|
||||
| Port | `--port`, `-p` | Port to bind to when using http transport (default: 8000) |
|
||||
| Log Level | `--log-level`, `-l` | Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
|
||||
|
||||
|
||||
#### Server Specification
|
||||
<VersionBadge version="2.3.5" />
|
||||
|
||||
|
|
@ -79,14 +80,14 @@ if __name__ == "__main__":
|
|||
You can run it with Streamable HTTP transport regardless of what's in the `__main__` block:
|
||||
|
||||
```bash
|
||||
fastmcp run server.py --transport streamable-http --port 8000
|
||||
fastmcp run server.py --transport http --port 8000
|
||||
```
|
||||
|
||||
**Examples**
|
||||
|
||||
```bash
|
||||
# Run a local server with Streamable HTTP transport on a custom port
|
||||
fastmcp run server.py --transport streamable-http --port 8000
|
||||
fastmcp run server.py --transport http --port 8000
|
||||
|
||||
# Connect to a remote server and proxy as a stdio server
|
||||
fastmcp run https://example.com/mcp-server
|
||||
|
|
@ -112,14 +113,14 @@ The `dev` command is a shortcut for testing a server over STDIO only. When the I
|
|||
1. Select "STDIO" from the transport dropdown
|
||||
2. Connect manually
|
||||
|
||||
This command does not support HTTP testing. To test a server over HTTP:
|
||||
1. Start your server manually with HTTP transport using either:
|
||||
This command does not support HTTP testing. To test a server over Streamable HTTP or SSE:
|
||||
1. Start your server manually with the appropriate transport using either the command line:
|
||||
```bash
|
||||
fastmcp run server.py --transport streamable-http
|
||||
fastmcp run server.py --transport http
|
||||
```
|
||||
or
|
||||
or by setting the transport in your code:
|
||||
```bash
|
||||
python server.py # Assuming your __main__ block sets HTTP transport
|
||||
python server.py # Assuming your __main__ block sets Streamable HTTP transport
|
||||
```
|
||||
2. Open the MCP Inspector separately and connect to your running server
|
||||
</Warning>
|
||||
|
|
|
|||
|
|
@ -168,11 +168,11 @@ Transport for connecting to one or more MCP servers defined in an MCPConfig.
|
|||
"mcpServers": {
|
||||
"weather": {
|
||||
"url": "https://weather-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
},
|
||||
"calendar": {
|
||||
"url": "https://calendar-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ The [MCP specification](https://modelcontextprotocol.io/specification/2025-03-26
|
|||
|
||||
Bearer Token authentication is a common way to secure HTTP-based APIs. In this model, the client sends a token (usually a JSON Web Token or JWT) in the `Authorization` header with the "Bearer" scheme. The server then validates this token to grant or deny access.
|
||||
|
||||
FastMCP supports Bearer Token authentication for its HTTP-based transports (`streamable-http` and `sse`), allowing you to protect your server from unauthorized access.
|
||||
FastMCP supports Bearer Token authentication for its HTTP-based transports (`http` and `sse`), allowing you to protect your server from unauthorized access.
|
||||
|
||||
## Authentication Strategy
|
||||
|
||||
|
|
|
|||
|
|
@ -118,7 +118,7 @@ config = {
|
|||
"mcpServers": {
|
||||
"default": { # For single server configs, 'default' is commonly used
|
||||
"url": "https://example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -145,11 +145,11 @@ config = {
|
|||
"mcpServers": {
|
||||
"weather": {
|
||||
"url": "https://weather-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
},
|
||||
"calendar": {
|
||||
"url": "https://calendar-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -158,8 +158,8 @@ if __name__ == "__main__":
|
|||
# This runs the server, defaulting to STDIO transport
|
||||
mcp.run()
|
||||
|
||||
# To use a different transport, e.g., HTTP:
|
||||
# mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
|
||||
# To use a different transport, e.g., Streamable HTTP:
|
||||
# mcp.run(transport="http", host="127.0.0.1", port=9000)
|
||||
```
|
||||
|
||||
FastMCP supports several transport options:
|
||||
|
|
@ -260,7 +260,7 @@ Transport settings are provided when running the server and control network beha
|
|||
```python
|
||||
# Configure transport when running
|
||||
mcp.run(
|
||||
transport="streamable-http",
|
||||
transport="http",
|
||||
host="0.0.0.0", # Bind to all interfaces
|
||||
port=9000, # Custom port
|
||||
log_level="DEBUG", # Override global log level
|
||||
|
|
@ -268,7 +268,7 @@ mcp.run(
|
|||
|
||||
# Or for async usage
|
||||
await mcp.run_async(
|
||||
transport="streamable-http",
|
||||
transport="http",
|
||||
host="127.0.0.1",
|
||||
port=8080,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ mcp = FastMCP.from_openapi(
|
|||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
|
||||
And that's it! With just a few lines of code, you've created an MCP server that exposes the entire JSONPlaceholder API as a collection of tools.
|
||||
|
|
@ -195,7 +195,7 @@ mcp = FastMCP.from_openapi(
|
|||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable-http", port=8000)
|
||||
mcp.run(transport="http", port=8000)
|
||||
```
|
||||
With this configuration:
|
||||
- `GET /users/{id}` becomes a `ResourceTemplate`.
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ img="https://www.jlowin.dev/_image?href=%2F_astro%2Fhero.M_hv6gEB.png&w=1000&h=5
|
|||
cta="Read more"
|
||||
>
|
||||
|
||||
FastMCP 2.3 introduces full support for Streamable HTTP, a modern alternative to SSE that simplifies MCP deployments over the web. It’s efficient, reliable, and now the default HTTP transport. Just run your server with transport="streamable-http" and connect clients via a standard URL—FastMCP handles the rest. No special setup required. This release makes deploying MCP servers easier and more portable than ever.
|
||||
FastMCP 2.3 introduces full support for Streamable HTTP, a modern alternative to SSE that simplifies MCP deployments over the web. It’s efficient, reliable, and now the default HTTP transport. Just run your server with transport="http" and connect clients via a standard URL—FastMCP handles the rest. No special setup required. This release makes deploying MCP servers easier and more portable than ever.
|
||||
|
||||
</Card>
|
||||
</Update>
|
||||
|
|
|
|||
|
|
@ -235,7 +235,7 @@ def run(
|
|||
typer.Option(
|
||||
"--transport",
|
||||
"-t",
|
||||
help="Transport protocol to use (stdio, streamable-http, or sse)",
|
||||
help="Transport protocol to use (stdio, http, or sse)",
|
||||
),
|
||||
] = None,
|
||||
host: Annotated[
|
||||
|
|
|
|||
|
|
@ -4,14 +4,12 @@ import importlib.util
|
|||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from typing import Any
|
||||
|
||||
from fastmcp.utilities.logging import get_logger
|
||||
|
||||
logger = get_logger("cli.run")
|
||||
|
||||
TransportType = Literal["stdio", "streamable-http", "sse"]
|
||||
|
||||
|
||||
def is_url(path: str) -> bool:
|
||||
"""Check if a string is a URL."""
|
||||
|
|
|
|||
|
|
@ -736,11 +736,11 @@ class MCPConfigTransport(ClientTransport):
|
|||
"mcpServers": {
|
||||
"weather": {
|
||||
"url": "https://weather-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
},
|
||||
"calendar": {
|
||||
"url": "https://calendar-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
"transport": "http"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ if TYPE_CHECKING:
|
|||
logger = get_logger(__name__)
|
||||
|
||||
DuplicateBehavior = Literal["warn", "error", "replace", "ignore"]
|
||||
Transport = Literal["stdio", "http", "sse", "streamable-http"]
|
||||
|
||||
# Compiled URI parsing regex to split a URI into protocol and path components
|
||||
URI_PATTERN = re.compile(r"^([^:]+://)(.*?)$")
|
||||
|
|
@ -280,7 +281,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
|
||||
async def run_async(
|
||||
self,
|
||||
transport: Literal["stdio", "streamable-http", "sse"] | None = None,
|
||||
transport: Transport | None = None,
|
||||
**transport_kwargs: Any,
|
||||
) -> None:
|
||||
"""Run the FastMCP server asynchronously.
|
||||
|
|
@ -290,19 +291,19 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
"""
|
||||
if transport is None:
|
||||
transport = "stdio"
|
||||
if transport not in {"stdio", "streamable-http", "sse"}:
|
||||
if transport not in {"stdio", "http", "sse", "streamable-http"}:
|
||||
raise ValueError(f"Unknown transport: {transport}")
|
||||
|
||||
if transport == "stdio":
|
||||
await self.run_stdio_async(**transport_kwargs)
|
||||
elif transport in {"streamable-http", "sse"}:
|
||||
elif transport in {"http", "sse", "streamable-http"}:
|
||||
await self.run_http_async(transport=transport, **transport_kwargs)
|
||||
else:
|
||||
raise ValueError(f"Unknown transport: {transport}")
|
||||
|
||||
def run(
|
||||
self,
|
||||
transport: Literal["stdio", "streamable-http", "sse"] | None = None,
|
||||
transport: Transport | None = None,
|
||||
**transport_kwargs: Any,
|
||||
) -> None:
|
||||
"""Run the FastMCP server. Note this is a synchronous function.
|
||||
|
|
@ -1253,7 +1254,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
|
||||
async def run_http_async(
|
||||
self,
|
||||
transport: Literal["streamable-http", "sse"] = "streamable-http",
|
||||
transport: Literal["http", "streamable-http", "sse"] = "http",
|
||||
host: str | None = None,
|
||||
port: int | None = None,
|
||||
log_level: str | None = None,
|
||||
|
|
@ -1384,7 +1385,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
middleware: list[ASGIMiddleware] | None = None,
|
||||
json_response: bool | None = None,
|
||||
stateless_http: bool | None = None,
|
||||
transport: Literal["streamable-http", "sse"] = "streamable-http",
|
||||
transport: Literal["http", "streamable-http", "sse"] = "http",
|
||||
) -> StarletteWithLifespan:
|
||||
"""Create a Starlette app using the specified HTTP transport.
|
||||
|
||||
|
|
@ -1397,7 +1398,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
A Starlette application configured with the specified transport
|
||||
"""
|
||||
|
||||
if transport == "streamable-http":
|
||||
if transport in ("streamable-http", "http"):
|
||||
return create_streamable_http_app(
|
||||
server=self,
|
||||
streamable_http_path=path
|
||||
|
|
@ -1444,7 +1445,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
stacklevel=2,
|
||||
)
|
||||
await self.run_http_async(
|
||||
transport="streamable-http",
|
||||
transport="http",
|
||||
host=host,
|
||||
port=port,
|
||||
log_level=log_level,
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ if TYPE_CHECKING:
|
|||
|
||||
def infer_transport_type_from_url(
|
||||
url: str | AnyUrl,
|
||||
) -> Literal["streamable-http", "sse"]:
|
||||
) -> Literal["http", "sse"]:
|
||||
"""
|
||||
Infer the appropriate transport type from the given URL.
|
||||
"""
|
||||
|
|
@ -34,7 +34,7 @@ def infer_transport_type_from_url(
|
|||
if re.search(r"/sse(/|\?|&|$)", path):
|
||||
return "sse"
|
||||
else:
|
||||
return "streamable-http"
|
||||
return "http"
|
||||
|
||||
|
||||
class StdioMCPServer(FastMCPBaseModel):
|
||||
|
|
@ -58,7 +58,7 @@ class StdioMCPServer(FastMCPBaseModel):
|
|||
class RemoteMCPServer(FastMCPBaseModel):
|
||||
url: str
|
||||
headers: dict[str, str] = Field(default_factory=dict)
|
||||
transport: Literal["streamable-http", "sse"] | None = None
|
||||
transport: Literal["http", "streamable-http", "sse"] | None = None
|
||||
auth: Annotated[
|
||||
str | Literal["oauth"] | httpx.Auth | None,
|
||||
Field(
|
||||
|
|
@ -79,6 +79,7 @@ class RemoteMCPServer(FastMCPBaseModel):
|
|||
if transport == "sse":
|
||||
return SSETransport(self.url, headers=self.headers, auth=self.auth)
|
||||
else:
|
||||
# Both "http" and "streamable-http" map to StreamableHttpTransport
|
||||
return StreamableHttpTransport(
|
||||
self.url, headers=self.headers, auth=self.auth
|
||||
)
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ def mcp_server_url(rsa_key_pair: RSAKeyPair) -> Generator[str]:
|
|||
with run_server_in_process(
|
||||
run_mcp_server,
|
||||
public_key=rsa_key_pair.public_key,
|
||||
run_kwargs=dict(transport="streamable-http"),
|
||||
run_kwargs=dict(transport="http"),
|
||||
) as url:
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
|
@ -696,7 +696,7 @@ class TestFastMCPBearerAuth:
|
|||
run_mcp_server,
|
||||
public_key=rsa_key_pair.public_key,
|
||||
auth_kwargs=dict(required_scopes=["read", "write"]),
|
||||
run_kwargs=dict(transport="streamable-http"),
|
||||
run_kwargs=dict(transport="http"),
|
||||
) as url:
|
||||
mcp_server_url = f"{url}/mcp/"
|
||||
with pytest.raises(httpx.HTTPStatusError) as exc_info:
|
||||
|
|
@ -719,7 +719,7 @@ class TestFastMCPBearerAuth:
|
|||
run_mcp_server,
|
||||
public_key=rsa_key_pair.public_key,
|
||||
auth_kwargs=dict(required_scopes=["read", "write"]),
|
||||
run_kwargs=dict(transport="streamable-http"),
|
||||
run_kwargs=dict(transport="http"),
|
||||
) as url:
|
||||
mcp_server_url = f"{url}/mcp/"
|
||||
async with Client(mcp_server_url, auth=BearerAuth(token)) as client:
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ def run_server(host: str, port: int, **kwargs) -> None:
|
|||
|
||||
@pytest.fixture(scope="module")
|
||||
def streamable_http_server() -> Generator[str, None, None]:
|
||||
with run_server_in_process(run_server, transport="streamable-http") as url:
|
||||
with run_server_in_process(run_server, transport="http") as url:
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -328,6 +328,41 @@ class TestRunCommand:
|
|||
assert result.exit_code == 0
|
||||
mock_server.run.assert_called_once_with(transport="sse")
|
||||
|
||||
def test_run_command_with_http_transports(self, temp_python_file):
|
||||
"""Test run command with both http and streamable-http transport options."""
|
||||
# Test "http" transport
|
||||
with (
|
||||
patch("fastmcp.cli.run.parse_file_path") as mock_parse,
|
||||
patch("fastmcp.cli.run.import_server") as mock_import,
|
||||
):
|
||||
mock_parse.return_value = (temp_python_file, None)
|
||||
mock_server = MagicMock()
|
||||
mock_server.name = "test_server"
|
||||
mock_import.return_value = mock_server
|
||||
|
||||
result = runner.invoke(
|
||||
cli.app, ["run", str(temp_python_file), "--transport", "http"]
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
mock_server.run.assert_called_once_with(transport="http")
|
||||
|
||||
# Test "streamable-http" transport (alias for http)
|
||||
with (
|
||||
patch("fastmcp.cli.run.parse_file_path") as mock_parse,
|
||||
patch("fastmcp.cli.run.import_server") as mock_import,
|
||||
):
|
||||
mock_parse.return_value = (temp_python_file, None)
|
||||
mock_server = MagicMock()
|
||||
mock_server.name = "test_server"
|
||||
mock_import.return_value = mock_server
|
||||
|
||||
result = runner.invoke(
|
||||
cli.app,
|
||||
["run", str(temp_python_file), "--transport", "streamable-http"],
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
mock_server.run.assert_called_once_with(transport="streamable-http")
|
||||
|
||||
def test_run_command_with_host(self, temp_python_file):
|
||||
"""Test run command with host option."""
|
||||
with (
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ def run_proxy_server(host: str, port: int, shttp_url: str, **kwargs) -> None:
|
|||
class TestClientHeaders:
|
||||
@pytest.fixture(scope="class")
|
||||
def shttp_server(self) -> Generator[str, None, None]:
|
||||
with run_server_in_process(run_server, transport="streamable-http") as url:
|
||||
with run_server_in_process(run_server, transport="http") as url:
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
@pytest.fixture(scope="class")
|
||||
|
|
@ -69,7 +69,7 @@ class TestClientHeaders:
|
|||
with run_server_in_process(
|
||||
run_proxy_server,
|
||||
shttp_url=shttp_server,
|
||||
transport="streamable-http",
|
||||
transport="http",
|
||||
) as url:
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
|
|
|||
|
|
@ -103,13 +103,24 @@ async def streamable_http_server(
|
|||
stateless_http: bool = False,
|
||||
) -> AsyncGenerator[str, None]:
|
||||
with run_server_in_process(
|
||||
run_server, stateless_http=stateless_http, transport="streamable-http"
|
||||
run_server, stateless_http=stateless_http, transport="http"
|
||||
) as url:
|
||||
async with Client(transport=StreamableHttpTransport(f"{url}/mcp/")) as client:
|
||||
assert await client.ping()
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
async def streamable_http_server_with_streamable_http_alias() -> AsyncGenerator[
|
||||
str, None
|
||||
]:
|
||||
"""Test that the "streamable-http" transport alias works."""
|
||||
with run_server_in_process(run_server, transport="streamable-http") as url:
|
||||
async with Client(transport=StreamableHttpTransport(f"{url}/mcp/")) as client:
|
||||
assert await client.ping()
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
||||
async def test_ping(streamable_http_server: str):
|
||||
"""Test pinging the server."""
|
||||
async with Client(
|
||||
|
|
@ -119,6 +130,19 @@ async def test_ping(streamable_http_server: str):
|
|||
assert result is True
|
||||
|
||||
|
||||
async def test_ping_with_streamable_http_alias(
|
||||
streamable_http_server_with_streamable_http_alias: str,
|
||||
):
|
||||
"""Test pinging the server."""
|
||||
async with Client(
|
||||
transport=StreamableHttpTransport(
|
||||
streamable_http_server_with_streamable_http_alias
|
||||
)
|
||||
) as client:
|
||||
result = await client.ping()
|
||||
assert result is True
|
||||
|
||||
|
||||
async def test_http_headers(streamable_http_server: str):
|
||||
"""Test getting HTTP headers from the server."""
|
||||
async with Client(
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ async def test_run_streamable_http_async_deprecation_warning():
|
|||
# Verify the mock was called with the right transport
|
||||
mock_run.assert_called_once()
|
||||
call_kwargs = mock_run.call_args.kwargs
|
||||
assert call_kwargs.get("transport") == "streamable-http"
|
||||
assert call_kwargs.get("transport") == "http"
|
||||
|
||||
|
||||
def test_http_app_with_sse_transport():
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ def run_server(host: str, port: int, **kwargs) -> None:
|
|||
|
||||
@pytest.fixture(autouse=True, scope="module")
|
||||
def shttp_server() -> Generator[str, None, None]:
|
||||
with run_server_in_process(run_server, transport="streamable-http") as url:
|
||||
with run_server_in_process(run_server, transport="http") as url:
|
||||
yield f"{url}/mcp/"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ async def test_streamable_http_app_with_custom_middleware():
|
|||
server._additional_http_routes = routes
|
||||
|
||||
# Create the app with custom middleware
|
||||
app = server.http_app(transport="streamable-http", middleware=custom_middleware)
|
||||
app = server.http_app(transport="http", middleware=custom_middleware)
|
||||
|
||||
# Create a test client
|
||||
transport = ASGITransport(app=app)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue