MCP over REST API (HTTP + SSE Transport)
By default, MCP uses stdio (standard input/output) for local communication. For remote or web-based integrations, MCP supports HTTP with Server-Sent Events (SSE) transport — allowing you to expose your MCP server as a REST API.
Why REST API Transport?
- Deploy MCP servers as web services accessible from anywhere
- Enable multiple clients to connect simultaneously
- Integrate with cloud-hosted AI applications
- Use behind load balancers and API gateways
MCP Server with SSE Transport
# rest_mcp_server.py
from mcp.server import Server
from mcp.server.sse import SseServerTransport
from mcp.types import Tool, TextContent
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.requests import Request
from starlette.responses import JSONResponse
import uvicorn
server = Server("rest-mcp-server")
sse = SseServerTransport("/messages/")
# Define tools
@server.list_tools()
async def list_tools():
return [
Tool(
name="get_user",
description="Get user details by ID",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "The user ID"}
},
"required": ["user_id"]
}
),
Tool(
name="create_order",
description="Create a new order for a user",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string"},
"product": {"type": "string"},
"quantity": {"type": "integer"}
},
"required": ["user_id", "product", "quantity"]
}
),
Tool(
name="search_products",
description="Search products by keyword",
inputSchema={
"type": "object",
"properties": {
"query": {"type": "string"},
"max_results": {"type": "integer", "default": 10}
},
"required": ["query"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_user":
# Simulate database lookup
user = {"id": arguments["user_id"], "name": "John Doe", "email": "john@example.com", "plan": "pro"}
return [TextContent(type="text", text=str(user))]
elif name == "create_order":
order_id = "ORD-12345"
return [TextContent(type="text",
text=f"Order {order_id} created: {arguments['quantity']}x {arguments['product']} for user {arguments['user_id']}")]
elif name == "search_products":
products = [
{"name": "Widget Pro", "price": 29.99},
{"name": "Widget Lite", "price": 9.99}
]
return [TextContent(type="text", text=str(products))]
# SSE endpoint for MCP clients
async def handle_sse(request: Request):
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
await server.run(streams[0], streams[1])
# Health check endpoint
async def health(request: Request):
return JSONResponse({"status": "ok", "server": "rest-mcp-server"})
# Create ASGI app
app = Starlette(
routes=[
Route("/health", health),
Route("/sse", handle_sse),
Mount("/messages/", app=sse.handle_post_message),
]
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Running the REST MCP Server
pip install mcp starlette uvicorn
python rest_mcp_server.py
# Server running at http://localhost:8000
# SSE endpoint: http://localhost:8000/sse
# Health check: http://localhost:8000/health
Connecting a Client to the REST MCP Server
# client.py
from mcp.client import ClientSession
from mcp.client.sse import sse_client
async def main():
async with sse_client("http://localhost:8000/sse") as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Available tools:")
for tool in tools.tools:
print(f" - {tool.name}: {tool.description}")
# Call a tool
result = await session.call_tool("get_user", {"user_id": "usr_001"})
print(f"\nUser info: {result.content[0].text}")
# Search products
result = await session.call_tool("search_products", {"query": "widget"})
print(f"Products: {result.content[0].text}")
if __name__ == "__main__":
import asyncio
asyncio.run(main())