Skip to content

Commit c90a507

Browse files
committed
sse explored
1 parent 9ff3a85 commit c90a507

5 files changed

Lines changed: 796 additions & 0 deletions

File tree

fastapi_sse/app/__init__.py

Whitespace-only changes.

fastapi_sse/app/main.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from fastapi import FastAPI
2+
from app.sse import create_sse_server
3+
from mcp.server.fastmcp import FastMCP
4+
5+
app = FastAPI()
6+
mcp = FastMCP("Echo")
7+
8+
# Mount the Starlette SSE server onto the FastAPI app
9+
app.mount("/", create_sse_server(mcp))
10+
# this mounting allows the sse server to
11+
# handle the reqs to /sse and /message path
12+
13+
14+
@app.get("/")
15+
def read_root():
16+
return {"Hello": "World"}
17+
18+
19+
# Add MCP functionality with decorators
20+
@mcp.resource("echo://{message}")
21+
def echo_resource(message: str) -> str:
22+
"""Echo a message as a resource"""
23+
return f"Resource echo: {message}"
24+
25+
26+
@mcp.tool()
27+
def echo_tool(message: str) -> str:
28+
"""Echo a message as a tool"""
29+
return f"Tool echo: {message}"
30+
31+
32+
@mcp.prompt()
33+
def echo_prompt(message: str) -> str:
34+
"""Create an echo prompt"""
35+
return f"Please process this message: {message}"

fastapi_sse/app/sse.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from mcp.server.fastmcp import FastMCP
2+
from mcp.server.sse import SseServerTransport
3+
from starlette.applications import Starlette
4+
from starlette.routing import Mount, Route
5+
6+
7+
def create_sse_server(mcp: FastMCP):
8+
"""Create a Starlette app that handles SSE connections and message handling"""
9+
transport = SseServerTransport("/messages/")
10+
# this takes care of the event streaming
11+
12+
# Define handler functions
13+
async def handle_sse(request):
14+
# estab connect
15+
async with transport.connect_sse(
16+
request.scope, request.receive, request._send
17+
) as streams:
18+
# bi directional stream of conn
19+
await mcp._mcp_server.run(
20+
streams[0], streams[1], mcp._mcp_server.create_initialization_options()
21+
)
22+
23+
# Create Starlette routes for SSE and message handling
24+
routes = [
25+
Route("/sse/", endpoint=handle_sse),
26+
Mount("/messages/", app=transport.handle_post_message),
27+
]
28+
29+
# Create a Starlette app
30+
return Starlette(routes=routes)

fastapi_sse/pyproject.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[project]
2+
name = "fastapi-sse"
3+
version = "0.1.0"
4+
requires-python = ">=3.11"
5+
dependencies = [
6+
"fastapi[standard]>=0.115.12",
7+
"mcp>=1.6.0",
8+
]

0 commit comments

Comments
 (0)