Skip to content

Commit 1bae08b

Browse files
Add cleaned SSE client-server test
1 parent 09988a5 commit 1bae08b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import asyncio
2+
from typing import AsyncGenerator, List
3+
4+
from fastapi import FastAPI
5+
from starlette.responses import StreamingResponse
6+
import uvicorn
7+
from threading import Thread
8+
import httpx
9+
from mcp.client.sse import aconnect_sse
10+
11+
# Required packages: fastapi, uvicorn, httpx, httpx-sse, sse-starlette, anyio
12+
13+
app = FastAPI()
14+
15+
@app.get("/sse")
16+
async def sse_endpoint() -> StreamingResponse:
17+
async def event_stream() -> AsyncGenerator[str, None]:
18+
for i in range(3):
19+
yield f"data: Hello {i+1}\n\n"
20+
await asyncio.sleep(0.1)
21+
return StreamingResponse(event_stream(), media_type="text/event-stream")
22+
23+
def run_mock_server() -> None:
24+
uvicorn.run(app, host="127.0.0.1", port=8012, log_level="warning")
25+
26+
async def test_aconnect_sse_server_response() -> None:
27+
server_thread = Thread(target=run_mock_server, daemon=True)
28+
server_thread.start()
29+
await asyncio.sleep(1)
30+
31+
messages: List[str] = []
32+
33+
async with httpx.AsyncClient() as client:
34+
async with aconnect_sse(client, "GET", "http://127.0.0.1:8012/sse") as event_source:
35+
async for event in event_source.aiter_sse():
36+
if event.data:
37+
print("Event received:", event.data)
38+
messages.append(event.data)
39+
if len(messages) == 3:
40+
break
41+
42+
assert messages == ["Hello 1", "Hello 2", "Hello 3"]
43+
print("\n✅ Test passed! SSE connection via aconnect_sse worked correctly.")

0 commit comments

Comments
 (0)