Skip to content

Building AI agents, atomically

#134 initial commit to enable http stream for mcp server, including mcp http stream test examples for client and server

jon fox67a962f36d44
diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
index a63b211..2d4194c 100644
--- a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
+++ b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
@@ -32,6 +32,7 @@ class MCPToolFactory:
self,
mcp_endpoint: Optional[str] = None,
use_stdio: bool = False,
+ use_http_stream: bool = False,
client_session: Optional[ClientSession] = None,
event_loop: Optional[asyncio.AbstractEventLoop] = None,
working_directory: Optional[str] = None,
@@ -42,18 +43,22 @@ class MCPToolFactory:
Args:
mcp_endpoint: URL of the MCP server (for SSE) or the full command to run the server (for STDIO)
use_stdio: If True, use STDIO transport instead of SSE
+ use_http_stream: If True, use HTTP streaming transport (preferred) instead of SSE (deprecated)
client_session: Optional pre-initialized ClientSession for reuse
event_loop: Optional event loop for running asynchronous operations
working_directory: Optional working directory to use when running STDIO commands
"""
self.mcp_endpoint = mcp_endpoint
self.use_stdio = use_stdio
+ self.use_http_stream = use_http_stream
self.client_session = client_session
self.event_loop = event_loop
self.schema_transformer = SchemaTransformer()
self.working_directory = working_directory
# Validate configuration
+ if self.use_stdio and self.use_http_stream:
+ raise ValueError("Cannot use both STDIO and HTTP stream transports at once.")
if client_session is not None and event_loop is None:
raise ValueError("When `client_session` is provided an `event_loop` must also be supplied.")
if not mcp_endpoint and client_session is None:
@@ -87,7 +92,12 @@ class MCPToolFactory:
return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover
else:
# Create new connection
- service = ToolDefinitionService(self.mcp_endpoint, self.use_stdio, self.working_directory)
+ service = ToolDefinitionService(
+ self.mcp_endpoint,
+ self.use_stdio,
+ self.use_http_stream,
+ self.working_directory,
+ )
return asyncio.run(service.fetch_definitions())
def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:
@@ -126,6 +136,7 @@ class MCPToolFactory:
bound_tool_name = self.mcp_tool_name
bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session
bound_use_stdio = self.use_stdio
+ bound_use_http_stream = self.use_http_stream
persistent_session: Optional[ClientSession] = getattr(self, "_client_session", None)
loop: Optional[asyncio.AbstractEventLoop] = getattr(self, "_event_loop", None)
bound_working_directory = getattr(self, "working_directory", None)
@@ -149,6 +160,12 @@ class MCPToolFactory:
)
stdio_transport = await stack.enter_async_context(stdio_client(server_params))
read_stream, write_stream = stdio_transport
+ elif bound_use_http_stream:
+ # HTTP streaming transport (preferred)
+ http_endpoint = f"{bound_mcp_endpoint}/mcp"
+ logger.debug(f"Executing tool '{bound_tool_name}' via HTTP stream: endpoint={http_endpoint}")
+ stream_transport = await stack.enter_async_context(sse_client(http_endpoint))
+ read_stream, write_stream = stream_transport
else:
sse_endpoint = f"{bound_mcp_endpoint}/sse"
logger.debug(f"Executing tool '{bound_tool_name}' via SSE: endpoint={sse_endpoint}")
@@ -201,6 +218,7 @@ class MCPToolFactory:
"mcp_tool_name": tool_name,
"mcp_endpoint": self.mcp_endpoint,
"use_stdio": self.use_stdio,
+ "use_http_stream": self.use_http_stream,
"_client_session": self.client_session,
"_event_loop": self.event_loop,
"working_directory": self.working_directory,
@@ -264,24 +282,26 @@ class MCPToolFactory:
def fetch_mcp_tools(
mcp_endpoint: Optional[str] = None,
use_stdio: bool = False,
+ use_http_stream: bool = False,
*,
client_session: Optional[ClientSession] = None,
event_loop: Optional[asyncio.AbstractEventLoop] = None,
working_directory: Optional[str] = None,
) -> List[Type[BaseTool]]:
"""
- Connects to an MCP server via SSE or STDIO, discovers tool definitions, and dynamically generates
+ Connects to an MCP server via SSE, Http Stream or STDIO, discovers tool definitions, and dynamically generates
synchronous Atomic Agents compatible BaseTool subclasses for each tool.
Each generated tool will establish its own connection when its `run` method is called.
Args:
- mcp_endpoint: URL of the MCP server (for SSE) or the full command string to run the server (for STDIO).
- use_stdio: If True, use STDIO transport instead of SSE.
+ mcp_endpoint: URL of the MCP server or command for STDIO.
+ use_stdio: If True, use STDIO transport.
+ use_http_stream: If True, use HTTP streaming transport.
client_session: Optional pre-initialized ClientSession for reuse.
event_loop: Optional event loop for running asynchronous operations.
- working_directory: Optional working directory to use when running STDIO commands.
+ working_directory: Optional working directory for STDIO.
"""
- factory = MCPToolFactory(mcp_endpoint, use_stdio, client_session, event_loop, working_directory)
+ factory = MCPToolFactory(mcp_endpoint, use_stdio, use_http_stream, client_session, event_loop, working_directory)
return factory.create_tools()
@@ -303,6 +323,7 @@ def create_mcp_orchestrator_schema(tools: List[Type[BaseTool]]) -> Optional[Type
def fetch_mcp_tools_with_schema(
mcp_endpoint: Optional[str] = None,
use_stdio: bool = False,
+ use_http_stream: bool = False,
*,
client_session: Optional[ClientSession] = None,
event_loop: Optional[asyncio.AbstractEventLoop] = None,
@@ -312,18 +333,19 @@ def fetch_mcp_tools_with_schema(
Fetches MCP tools and creates an orchestrator schema for them. Returns both as a tuple.
Args:
- mcp_endpoint: URL of the MCP server (for SSE) or the full command string to run the server (for STDIO).
- use_stdio: If True, use STDIO transport instead of SSE.
+ mcp_endpoint: URL of the MCP server or command for STDIO.
+ use_stdio: If True, use STDIO transport.
+ use_http_stream: If True, use HTTP streaming transport.
client_session: Optional pre-initialized ClientSession for reuse.
event_loop: Optional event loop for running asynchronous operations.
- working_directory: Optional working directory to use when running STDIO commands.
+ working_directory: Optional working directory for STDIO.
Returns:
A tuple containing:
- List of dynamically generated tool classes
- Orchestrator output schema with Union of tool input schemas, or None if no tools found.
"""
- factory = MCPToolFactory(mcp_endpoint, use_stdio, client_session, event_loop, working_directory)
+ factory = MCPToolFactory(mcp_endpoint, use_stdio, use_http_stream, client_session, event_loop, working_directory)
tools = factory.create_tools()
if not tools:
return [], None
diff --git a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
index d3c78ff..223db56 100644
--- a/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
+++ b/atomic-agents/atomic_agents/lib/factories/tool_definition_service.py
@@ -23,17 +23,19 @@ class MCPToolDefinition(NamedTuple):
class ToolDefinitionService:
"""Service for fetching tool definitions from MCP endpoints."""
- def __init__(self, endpoint: Optional[str] = None, use_stdio: bool = False, working_directory: Optional[str] = None):
+ def __init__(self, endpoint: Optional[str] = None, use_stdio: bool = False, use_http_stream: bool = False, working_directory: Optional[str] = None):
"""
Initialize the service.
Args:
- endpoint: URL of the MCP server (for SSE) or command string (for STDIO)
+ endpoint: URL of the MCP server (for SSE/HTTP stream) or command string (for STDIO)
use_stdio: Whether to use STDIO transport
+ use_http_stream: Whether to use HTTP stream transport (no '/sse')
working_directory: Optional working directory to use when running STDIO commands
"""
self.endpoint = endpoint
self.use_stdio = use_stdio
+ self.use_http_stream = use_http_stream
self.working_directory = working_directory
async def fetch_definitions(self) -> List[MCPToolDefinition]:
@@ -55,7 +57,7 @@ class ToolDefinitionService:
stack = AsyncExitStack()
try:
if self.use_stdio:
- # Split the command string into the command and its arguments
+ # STDIO transport
command_parts = shlex.split(self.endpoint)
if not command_parts:
raise ValueError("STDIO command string cannot be empty.")
@@ -65,11 +67,18 @@ class ToolDefinitionService:
server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)
stdio_transport = await stack.enter_async_context(stdio_client(server_params))
read_stream, write_stream = stdio_transport
+ elif self.use_http_stream:
+ # HTTP Stream transport
+ transport_endpoint = f"{self.endpoint}/mcp"
+ logger.info(f"Attempting HTTP Stream connection to {transport_endpoint}")
+ transport = await stack.enter_async_context(sse_client(transport_endpoint))
+ read_stream, write_stream = transport
else:
- sse_endpoint = f"{self.endpoint}/sse"
- logger.info(f"Attempting SSE connection to {sse_endpoint}")
- sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))
- read_stream, write_stream = sse_transport
+ # Default to SSE transport (deprecated)
+ transport_endpoint = f"{self.endpoint}/sse"
+ logger.info(f"Attempting SSE connection to {transport_endpoint}")
+ transport = await stack.enter_async_context(sse_client(transport_endpoint))
+ read_stream, write_stream = transport
session = await stack.enter_async_context(ClientSession(read_stream, write_stream))
definitions = await self.fetch_definitions_from_session(session)
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main.py b/atomic-examples/mcp-agent/example-client/example_client/main.py
index fbc83ab..1a88af2 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main.py
@@ -13,9 +13,9 @@ def main():
parser = argparse.ArgumentParser(description="MCP Agent example client")
parser.add_argument(
"--transport",
- choices=["stdio", "sse"],
+ choices=["stdio", "sse", "http"],
default="stdio",
- help="Transport method to use for MCP communication (stdio or sse)",
+ help="Transport method to use for MCP communication (stdio, sse, or http)",
)
args = parser.parse_args()
@@ -28,7 +28,7 @@ def main():
except ImportError as e:
print(f"Failed to import STDIO implementation: {e}")
sys.exit(1)
- else:
+ elif args.transport == "sse":
# Import and run SSE implementation
try:
from example_client.main_sse import main as sse_main
@@ -37,6 +37,18 @@ def main():
except ImportError as e:
print(f"Failed to import SSE implementation: {e}")
sys.exit(1)
+ elif args.transport == "http":
+ # Import and run HTTP implementation
+ try:
+ from example_client.main_http import main as http_main
+
+ http_main()
+ except ImportError as e:
+ print(f"Failed to import HTTP implementation: {e}")
+ sys.exit(1)
+ else:
+ print(f"Unknown transport: {args.transport}")
+ sys.exit(1)
if __name__ == "__main__":
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_http.py b/atomic-examples/mcp-agent/example-client/example_client/main_http.py
new file mode 100644
index 0000000..1256e55
--- /dev/null
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_http.py
@@ -0,0 +1,159 @@
+"""
+HTTP Stream transport client for MCP Agent example.
+Communicates with the server_http.py `/mcp` endpoint using HTTP GET/POST/DELETE for JSON-RPC streams.
+"""
+import sys
+from atomic_agents.lib.factories.mcp_tool_factory import fetch_mcp_tools
+from rich.console import Console
+from rich.table import Table
+from rich.markdown import Markdown
+from pydantic import Field
+from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+from atomic_agents.lib.components.chat_history import ChatHistory
+import openai, os, instructor
+from typing import Union, Type, Dict
+from dataclasses import dataclass
+import re
+
+
+@dataclass
+class MCPConfig:
+ """Configuration for the MCP Agent system using HTTP Stream transport."""
+ mcp_server_url: str = "http://localhost:6969"
+ openai_model: str = "gpt-4o"
+ openai_api_key: str = os.getenv("OPENAI_API_KEY")
+
+ def __post_init__(self):
+ if not self.openai_api_key:
+ raise ValueError("OPENAI_API_KEY environment variable is not set")
+
+
+def main():
+ # Use default HTTP transport settings from MCPConfig
+ config = MCPConfig()
+ console = Console()
+ client = instructor.from_openai(openai.OpenAI(api_key=config.openai_api_key))
+
+ console.print("[bold green]Initializing MCP Agent System (HTTP Stream mode)...[/bold green]")
+ tools = fetch_mcp_tools(mcp_endpoint=config.mcp_server_url, use_stdio=False, use_http_stream=True)
+ if not tools:
+ console.print(f"[bold red]No MCP tools found at {config.mcp_server_url}[/bold red]")
+ sys.exit(1)
+
+ # Display available tools
+ table = Table(title="Available MCP Tools", box=None)
+ table.add_column("Tool Name", style="cyan")
+ table.add_column("Input Schema", style="yellow")
+ table.add_column("Description", style="magenta")
+ for ToolClass in tools:
+ schema_name = getattr(ToolClass.input_schema, '__name__', 'N/A')
+ table.add_row(ToolClass.mcp_tool_name, schema_name, ToolClass.__doc__ or "")
+ console.print(table)
+
+ # Build orchestrator
+ class MCPOrchestratorInputSchema(BaseIOSchema):
+ """Input schema for the MCP orchestrator that processes user queries."""
+ query: str = Field(...)
+
+ class FinalResponseSchema(BaseIOSchema):
+ """Schema for the final response to the user."""
+ response_text: str = Field(...)
+
+ # Map schemas and define ActionUnion
+ tool_schema_map: Dict[Type[BaseIOSchema], Type] = {
+ ToolClass.input_schema: ToolClass for ToolClass in tools if hasattr(ToolClass, 'input_schema')
+ }
+ available_schemas = tuple(tool_schema_map.keys()) + (FinalResponseSchema,)
+ ActionUnion = Union[available_schemas]
+
+ class OrchestratorOutputSchema(BaseIOSchema):
+ """Output schema for the MCP orchestrator containing reasoning and selected action."""
+ reasoning: str
+ action: ActionUnion
+
+ history = ChatHistory()
+ orchestrator = BaseAgent[
+ MCPOrchestratorInputSchema, OrchestratorOutputSchema
+ ](
+ BaseAgentConfig(
+ client=client,
+ model=config.openai_model,
+ history=history,
+ system_prompt_generator=SystemPromptGenerator(
+ background=['You are an MCP orchestrator via HTTP.'],
+ steps=['Decide and invoke tools over HTTP stream.'],
+ output_instructions=['Provide reasoning and a single action schema.'],
+ ),
+ )
+ )
+
+ console.print("[bold green]HTTP Stream client ready. Type 'exit' to quit.[/bold green]")
+ while True:
+ query = console.input("[bold yellow]You:[/bold yellow] ").strip()
+ if query.lower() in {'exit', 'quit'}:
+ break
+ if not query:
+ continue
+
+ try:
+ # Initial run with user query
+ orchestrator_output = orchestrator.run(MCPOrchestratorInputSchema(query=query))
+
+ # Handle the output similar to SSE version
+ if hasattr(orchestrator_output, "chat_message") and not hasattr(orchestrator_output, "action"):
+ # Convert BaseAgentOutputSchema to FinalResponseSchema
+ action_instance = FinalResponseSchema(response_text=orchestrator_output.chat_message)
+ reasoning = "Response generated directly from chat model"
+ elif hasattr(orchestrator_output, "action"):
+ action_instance = orchestrator_output.action
+ reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, "reasoning") else "No reasoning provided"
+ else:
+ console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
+ continue
+
+ console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
+
+ # Keep executing until we get a final response
+ while not isinstance(action_instance, FinalResponseSchema):
+ # Find the matching tool class
+ tool_class = tool_schema_map.get(type(action_instance))
+ if not tool_class:
+ console.print(f"[red]Error: No tool found for schema {type(action_instance)}[/red]")
+ action_instance = FinalResponseSchema(response_text="I encountered an internal error. Could not find the appropriate tool.")
+ break
+
+ # Execute the tool
+ console.print(f"[blue]Executing {tool_class.mcp_tool_name}...[/blue]")
+ tool_instance = tool_class()
+ try:
+ result = tool_instance.run(action_instance)
+ console.print(f"[green]Tool result:[/green] {result}")
+
+ # Ask orchestrator what to do next with the result
+ next_query = f"Based on the tool result: {result}, please provide the final response to the user's original query: {query}"
+ next_output = orchestrator.run(MCPOrchestratorInputSchema(query=next_query))
+
+ if hasattr(next_output, "action"):
+ action_instance = next_output.action
+ else:
+ # If no action, treat as final response
+ action_instance = FinalResponseSchema(response_text=next_output.chat_message)
+
+ except Exception as e:
+ console.print(f"[red]Error executing tool: {e}[/red]")
+ action_instance = FinalResponseSchema(response_text=f"I encountered an error while executing the tool: {str(e)}")
+ break
+
+ # Display final response
+ if isinstance(action_instance, FinalResponseSchema):
+ console.print(f"[bold green]Assistant:[/bold green] {action_instance.response_text}")
+ else:
+ console.print("[red]Error: Expected final response but got something else[/red]")
+
+ except Exception as e:
+ console.print(f"[red]Error: {e}[/red]")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/atomic-examples/mcp-agent/example-mcp-server/README.md b/atomic-examples/mcp-agent/example-mcp-server/README.md
index 122cc84..fc55c41 100644
--- a/atomic-examples/mcp-agent/example-mcp-server/README.md
+++ b/atomic-examples/mcp-agent/example-mcp-server/README.md
@@ -11,6 +11,7 @@ This project is an MCP (Model Context Protocol) server that provides tools and r
│ ├── server.py # Unified server entry point with mode selection
│ ├── server_stdio.py # Implementation for stdio transport
│ ├── server_sse.py # Implementation for SSE transport (HTTP)
+│ ├── server_http.py # Implementation for HTTP Stream transport
│ ├── interfaces/ # Base classes/interfaces for tools and resources
│ │ ├── __init__.py
│ │ ├── resource.py
@@ -44,7 +45,7 @@ This project is an MCP (Model Context Protocol) server that provides tools and r
## Running the Server
-The server can run in two modes: `stdio` (standard input/output) or `sse` (HTTP Server-Sent Events). You must specify the desired mode using the `--mode` parameter.
+The server can run in three modes: `stdio` (standard input/output), `sse` (HTTP Server-Sent Events), or `http` (HTTP Stream Transport). You must specify the desired mode using the `--mode` parameter.
### Using the Command Line Script
@@ -62,6 +63,15 @@ poetry run example-mcp-server --mode=sse --host 127.0.0.1 --port 8000
# Run in SSE mode with auto-reload for development
poetry run example-mcp-server --mode=sse --reload
+
+# Run in HTTP Stream mode (default http://0.0.0.0:6969/mcp)
+poetry run example-mcp-server --mode=http
+
+# Run in HTTP Stream mode with custom host/port
+poetry run example-mcp-server --mode=http --host 127.0.0.1 --port 8000
+
+# Run in HTTP Stream mode with auto-reload
+poetry run example-mcp-server --mode=http --reload
```
### Using Python Module
@@ -72,10 +82,12 @@ Alternatively, you can run the server as a Python module:
# Using the unified server script
poetry run python -m example_mcp_server.server --mode=stdio
poetry run python -m example_mcp_server.server --mode=sse
+poetry run python -m example_mcp_server.server --mode=http
# Or call the specific implementations directly
poetry run python -m example_mcp_server.server_stdio
poetry run python -m example_mcp_server.server_sse
+poetry run python -m example_mcp_server.server_http
```
## Client Integration
@@ -84,6 +96,7 @@ This server is designed to work with the companion MCP client in the `example-cl
1. **STDIO Transport**: The client launches this server as a subprocess and communicates through standard input/output
2. **SSE Transport**: The client connects to this server running as an HTTP service
+3. **HTTP Stream Transport**: The client connects to the `/mcp` endpoint for a streaming RPC-like interface
### STDIO Mode Connection
@@ -105,6 +118,16 @@ mcp_server_url: str = "http://localhost:6969"
This mode is better for production deployments, sharing tools across multiple clients, or when the server needs to run on a different machine.
+### HTTP Stream Mode Connection
+
+In HTTP Stream mode, the client connects to the server's `/mcp` endpoint:
+
+```python
+mcp_server_url: str = "http://localhost:6969/mcp"
+```
+
+This mode supports a streaming RPC-like interaction over HTTP, where the client can negotiate a session, send JSON-RPC calls, and terminate the session.
+
## Developing Your Server
### Development Mode with Auto-Reload
diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py
index b35ccc8..f69127c 100644
--- a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py
+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server.py
@@ -11,8 +11,8 @@ def main():
"--mode",
type=str,
required=True,
- choices=["stdio", "sse"],
- help="Server mode: stdio for standard I/O or sse for HTTP Server-Sent Events",
+ choices=["stdio", "sse", "http"],
+ help="Server mode: stdio for standard I/O, sse for Server-Sent Events, or http for HTTP Stream Transport",
)
# SSE specific arguments
@@ -35,6 +35,14 @@ def main():
if args.reload:
sys.argv.append("--reload")
sse_main()
+ elif args.mode == "http":
+ # Import and run the HTTP Stream Transport server
+ from example_mcp_server.server_http import main as http_main
+
+ sys.argv = [sys.argv[0], "--host", args.host, "--port", str(args.port)]
+ if args.reload:
+ sys.argv.append("--reload")
+ http_main()
else:
parser.print_help()
sys.exit(1)
diff --git a/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py
new file mode 100644
index 0000000..001307e
--- /dev/null
+++ b/atomic-examples/mcp-agent/example-mcp-server/example_mcp_server/server_http.py
@@ -0,0 +1,141 @@
+"""example-mcp-server MCP Server HTTP Stream Transport."""
+
+from mcp.server.fastmcp import FastMCP
+from starlette.applications import Starlette
+from starlette.routing import Route, Mount
+from starlette.requests import Request
+from starlette.responses import JSONResponse
+from starlette.middleware import Middleware
+from starlette.middleware.cors import CORSMiddleware
+from mcp.server import Server
+from mcp.server.sse import SseServerTransport
+import uvicorn
+from typing import List
+import json
+
+from example_mcp_server.services.tool_service import ToolService
+from example_mcp_server.services.resource_service import ResourceService
+from example_mcp_server.interfaces.tool import Tool
+from example_mcp_server.interfaces.resource import Resource
+from example_mcp_server.tools import AddNumbersTool, SubtractNumbersTool, MultiplyNumbersTool, DivideNumbersTool
+
+
+def get_available_tools() -> List[Tool]:
+ """Get list of all available tools."""
+ return [
+ AddNumbersTool(),
+ SubtractNumbersTool(),
+ MultiplyNumbersTool(),
+ DivideNumbersTool(),
+ ]
+
+
+def get_available_resources() -> List[Resource]:
+ """Get list of all available resources."""
+ return []
+
+
+def create_http_app(mcp_server: Server) -> Starlette:
+ """Create a Starlette app supporting HTTP Stream Transport."""
+
+ # Create SSE transport for handling the connection
+ sse = SseServerTransport("/messages/")
+
+ async def handle_mcp(request: Request):
+ """Handle MCP requests over HTTP Stream - accepts GET for connection."""
+ try:
+ # Use SSE transport pattern for HTTP stream
+ async with sse.connect_sse(
+ request.scope,
+ request.receive,
+ request._send,
+ ) as (read_stream, write_stream):
+ await mcp_server.run(
+ read_stream,
+ write_stream,
+ mcp_server.create_initialization_options(),
+ )
+
+ except Exception as e:
+ error_response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {
+ "code": -32603,
+ "message": f"Internal error: {str(e)}"
+ }
+ }
+ return JSONResponse(error_response, status_code=500)
+
+ middleware = [
+ Middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ allow_credentials=True,
+ )
+ ]
+
+ return Starlette(
+ routes=[
+ Route("/mcp", handle_mcp, methods=["GET", "POST"]),
+ Mount("/messages/", app=sse.handle_post_message),
+ ],
+ middleware=middleware,
+ )
+
+
+# Initialize FastMCP server with HTTP transport - same as SSE
+mcp = FastMCP("example-mcp-server")
+tool_service = ToolService()
+resource_service = ResourceService()
+
+# Register all tools and their MCP handlers - same as SSE
+tool_service.register_tools(get_available_tools())
+tool_service.register_mcp_handlers(mcp)
+
+# Register all resources and their MCP handlers - same as SSE
+resource_service.register_resources(get_available_resources())
+resource_service.register_mcp_handlers(mcp)
+
+# Get the MCP server - same as SSE
+mcp_server = mcp._mcp_server # noqa: WPS437
+
+# Create the Starlette app
+app = create_http_app(mcp_server)
+
+# Export the app
+__all__ = ["app"]
+
+
+def main():
+ """Entry point for the HTTP Stream Transport server."""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Run MCP HTTP Stream server")
+ parser.add_argument(
+ "--host", default="0.0.0.0", help="Host to bind to"
+ )
+ parser.add_argument(
+ "--port", type=int, default=6969, help="Port to listen on"
+ )
+ parser.add_argument(
+ "--reload", action="store_true", help="Enable auto-reload for development"
+ )
+ args = parser.parse_args()
+
+ print(f"MCP HTTP Stream Server starting on {args.host}:{args.port}")
+
+ uvicorn.run(
+ "example_mcp_server.server_http:app",
+ host=args.host,
+ port=args.port,
+ reload=args.reload,
+ reload_dirs=["example_mcp_server"],
+ timeout_graceful_shutdown=5,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/examples/mcp_agent.md b/docs/examples/mcp_agent.md
index a06a4d5..80a1f2c 100644
--- a/docs/examples/mcp_agent.md
+++ b/docs/examples/mcp_agent.md
@@ -4,7 +4,7 @@ This guide provides a detailed overview of the Model Context Protocol (MCP) serv
## Overview
-The MCP example demonstrates how to build an intelligent agent system using the Model Context Protocol, showcasing both server and client implementations. The example supports two transport methods: STDIO and Server-Sent Events (SSE).
+The MCP example demonstrates how to build an intelligent agent system using the Model Context Protocol, showcasing both server and client implementations. The example supports three transport methods: STDIO, Server-Sent Events (SSE), and HTTP Stream.
## Architecture
@@ -19,6 +19,7 @@ Key components:
1. **Transport Layers**:
- `server_stdio.py`: Implements STDIO-based communication
- `server_sse.py`: Implements SSE-based HTTP communication
+ - `server_http.py`: Implements unified HTTP streaming transport
2. **Tools Service**:
- Manages registration and execution of MCP tools
@@ -56,7 +57,7 @@ The client component (`example-client`) is an intelligent agent that:
### Server Implementation
-The server supports two transport methods:
+The server supports three transport methods:
1. **SSE Transport** (`server_sse.py`):
```python
@@ -76,6 +77,10 @@ app = create_starlette_app(mcp_server)
- Communicates through standard input/output
- Ideal for local development
+3. **HTTP Stream Transport** (`server_http.py`):
+- Single `/mcp` endpoint for JSON-RPC and SSE-style streaming
+- Handles session via `Mcp-Session-Id` header; allows resumable and cancelable streams
+
### Client Implementation
The client uses a sophisticated orchestration system: