chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# MCP Simple StreamableHttp Stateless Server Example
|
||||
|
||||
A stateless MCP server example demonstrating the StreamableHttp transport without maintaining session state. This example is ideal for understanding how to deploy MCP servers in multi-node environments where requests can be routed to any instance.
|
||||
|
||||
## Features
|
||||
|
||||
- Uses the StreamableHTTP transport in stateless mode (mcp_session_id=None)
|
||||
- Each request creates a new ephemeral connection
|
||||
- No session state maintained between requests
|
||||
- Suitable for deployment in multi-node environments
|
||||
|
||||
## Usage
|
||||
|
||||
Start the server:
|
||||
|
||||
```bash
|
||||
# Using default port 3000
|
||||
uv run mcp-simple-streamablehttp-stateless
|
||||
|
||||
# Using custom port
|
||||
uv run mcp-simple-streamablehttp-stateless --port 3000
|
||||
|
||||
# Custom logging level
|
||||
uv run mcp-simple-streamablehttp-stateless --log-level DEBUG
|
||||
|
||||
# Enable JSON responses instead of SSE streams
|
||||
uv run mcp-simple-streamablehttp-stateless --json-response
|
||||
```
|
||||
|
||||
The server exposes a tool named "start-notification-stream" that accepts three arguments:
|
||||
|
||||
- `interval`: Time between notifications in seconds (e.g., 1.0)
|
||||
- `count`: Number of notifications to send (e.g., 5)
|
||||
- `caller`: Identifier string for the caller
|
||||
|
||||
## Client
|
||||
|
||||
You can connect to this server using an HTTP client. For now, only the TypeScript SDK has streamable HTTP client examples, or you can use [Inspector](https://github.com/modelcontextprotocol/inspector) for testing.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
from .server import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Click will handle CLI arguments
|
||||
import sys
|
||||
|
||||
sys.exit(main()) # type: ignore[call-arg]
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import logging
|
||||
|
||||
import anyio
|
||||
import click
|
||||
import mcp_types as types
|
||||
import uvicorn
|
||||
from mcp.server import Server, ServerRequestContext
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def handle_list_tools(
|
||||
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
return types.ListToolsResult(
|
||||
tools=[
|
||||
types.Tool(
|
||||
name="start-notification-stream",
|
||||
description=("Sends a stream of notifications with configurable count and interval"),
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"required": ["interval", "count", "caller"],
|
||||
"properties": {
|
||||
"interval": {
|
||||
"type": "number",
|
||||
"description": "Interval between notifications in seconds",
|
||||
},
|
||||
"count": {
|
||||
"type": "number",
|
||||
"description": "Number of notifications to send",
|
||||
},
|
||||
"caller": {
|
||||
"type": "string",
|
||||
"description": ("Identifier of the caller to include in notifications"),
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
arguments = params.arguments or {}
|
||||
interval = arguments.get("interval", 1.0)
|
||||
count = arguments.get("count", 5)
|
||||
caller = arguments.get("caller", "unknown")
|
||||
|
||||
# Send the specified number of notifications with the given interval
|
||||
for i in range(count):
|
||||
await ctx.session.send_log_message( # pyright: ignore[reportDeprecated]
|
||||
level="info",
|
||||
data=f"Notification {i + 1}/{count} from caller: {caller}",
|
||||
logger="notification_stream",
|
||||
related_request_id=ctx.request_id,
|
||||
)
|
||||
if i < count - 1: # Don't wait after the last notification
|
||||
await anyio.sleep(interval)
|
||||
|
||||
return types.CallToolResult(
|
||||
content=[
|
||||
types.TextContent(
|
||||
type="text",
|
||||
text=(f"Sent {count} notifications with {interval}s interval for caller: {caller}"),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option("--port", default=3000, help="Port to listen on for HTTP")
|
||||
@click.option(
|
||||
"--log-level",
|
||||
default="INFO",
|
||||
help="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)",
|
||||
)
|
||||
@click.option(
|
||||
"--json-response",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Enable JSON responses instead of SSE streams",
|
||||
)
|
||||
def main(
|
||||
port: int,
|
||||
log_level: str,
|
||||
json_response: bool,
|
||||
) -> None:
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, log_level.upper()),
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
|
||||
app = Server(
|
||||
"mcp-streamable-http-stateless-demo",
|
||||
on_list_tools=handle_list_tools,
|
||||
on_call_tool=handle_call_tool,
|
||||
)
|
||||
|
||||
starlette_app = app.streamable_http_app(
|
||||
stateless_http=True,
|
||||
json_response=json_response,
|
||||
debug=True,
|
||||
)
|
||||
|
||||
# Wrap ASGI application with CORS middleware to expose Mcp-Session-Id header
|
||||
# for browser-based clients (ensures 500 errors get proper CORS headers)
|
||||
starlette_app = CORSMiddleware(
|
||||
starlette_app,
|
||||
allow_origins=["*"], # Note: streamable_http_app() enforces localhost-only Origin by default
|
||||
allow_methods=["GET", "POST", "DELETE"], # MCP streamable HTTP methods
|
||||
expose_headers=["Mcp-Session-Id"],
|
||||
)
|
||||
|
||||
uvicorn.run(starlette_app, host="127.0.0.1", port=port)
|
||||
@@ -0,0 +1,36 @@
|
||||
[project]
|
||||
name = "mcp-simple-streamablehttp-stateless"
|
||||
version = "0.1.0"
|
||||
description = "A simple MCP server exposing a StreamableHttp transport in stateless mode"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
authors = [{ name = "Model Context Protocol a Series of LF Projects, LLC." }]
|
||||
keywords = ["mcp", "llm", "automation", "web", "fetch", "http", "streamable", "stateless"]
|
||||
license = { text = "MIT" }
|
||||
dependencies = ["anyio>=4.5", "click>=8.2.0", "httpx>=0.27", "mcp", "starlette", "uvicorn"]
|
||||
|
||||
[project.scripts]
|
||||
mcp-simple-streamablehttp-stateless = "mcp_simple_streamablehttp_stateless.server:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["mcp_simple_streamablehttp_stateless"]
|
||||
|
||||
[tool.pyright]
|
||||
include = ["mcp_simple_streamablehttp_stateless"]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I"]
|
||||
ignore = []
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py310"
|
||||
|
||||
[dependency-groups]
|
||||
dev = ["pyright>=1.1.378", "pytest>=8.3.3", "ruff>=0.6.9"]
|
||||
Reference in New Issue
Block a user