fix: add lifespan context manager to StreamableHTTP mounting examples… · modelcontextprotocol/python-sdk@72a3400 · GitHub
Skip to content

Commit 72a3400

Browse files
TheMailmansTheMailmansKludex
authored
fix: add lifespan context manager to StreamableHTTP mounting examples (#1669)
Co-authored-by: TheMailmans <tyler@example.com> Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
1 parent 8e02fc1 commit 72a3400

4 files changed

Lines changed: 72 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 36 additions & 3 deletions

‎examples/snippets/servers/streamable_http_basic_mounting.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
uvicorn examples.snippets.servers.streamable_http_basic_mounting:app --reload
66
"""
77

8+
import contextlib
9+
810
from starlette.applications import Starlette
911
from starlette.routing import Mount
1012

@@ -20,9 +22,17 @@ def hello() -> str:
2022
return "Hello from MCP!"
2123

2224

25+
# Create a lifespan context manager to run the session manager
26+
@contextlib.asynccontextmanager
27+
async def lifespan(app: Starlette):
28+
async with mcp.session_manager.run():
29+
yield
30+
31+
2332
# Mount the StreamableHTTP server to the existing ASGI server
2433
app = Starlette(
2534
routes=[
2635
Mount("/", app=mcp.streamable_http_app()),
27-
]
36+
],
37+
lifespan=lifespan,
2838
)

‎examples/snippets/servers/streamable_http_host_mounting.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
uvicorn examples.snippets.servers.streamable_http_host_mounting:app --reload
66
"""
77

8+
import contextlib
9+
810
from starlette.applications import Starlette
911
from starlette.routing import Host
1012

@@ -20,9 +22,17 @@ def domain_info() -> str:
2022
return "This is served from mcp.acme.corp"
2123

2224

25+
# Create a lifespan context manager to run the session manager
26+
@contextlib.asynccontextmanager
27+
async def lifespan(app: Starlette):
28+
async with mcp.session_manager.run():
29+
yield
30+
31+
2332
# Mount using Host-based routing
2433
app = Starlette(
2534
routes=[
2635
Host("mcp.acme.corp", app=mcp.streamable_http_app()),
27-
]
36+
],
37+
lifespan=lifespan,
2838
)

‎examples/snippets/servers/streamable_http_multiple_servers.py‎

Lines changed: 14 additions & 1 deletion

0 commit comments

Comments
 (0)