Skip to content

Feat/sse server parameters client #300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/mcp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from .client.session import ClientSession
from .client.stdio import StdioServerParameters, stdio_client
from .client.sse import SseServerParameters, sse_client
from .server.session import ServerSession
from .server.stdio import stdio_server
from .shared.exceptions import McpError
@@ -101,14 +102,16 @@
"ServerResult",
"ServerSession",
"SetLevelRequest",
"SseServerParameters",
"StdioServerParameters",
"StopReason",
"SubscribeRequest",
"Tool",
"ToolsCapability",
"UnsubscribeRequest",
"sse_client",
"stdio_client",
"stdio_server",
"CompleteRequest",
"JSONRPCResponse",
]
]
26 changes: 21 additions & 5 deletions src/mcp/client/sse.py
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@
from anyio.abc import TaskStatus
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from httpx_sse import aconnect_sse
from pydantic import BaseModel

import mcp.types as types

@@ -18,19 +19,34 @@ def remove_request_params(url: str) -> str:
return urljoin(url, urlparse(url).path)


class SseServerParameters(BaseModel):
url: str
"""The URL to connect to for SSE events."""

headers: dict[str, Any] | None = None
"""Headers to include in the HTTP requests."""

timeout: float = 5
"""Timeout in seconds for HTTP operations."""

sse_read_timeout: float = 60 * 5
"""
How long (in seconds) the client will wait for a new event before disconnecting.
"""


@asynccontextmanager
async def sse_client(
url: str,
headers: dict[str, Any] | None = None,
timeout: float = 5,
sse_read_timeout: float = 60 * 5,
server: SseServerParameters,
):
"""
Client transport for SSE.
`sse_read_timeout` determines how long (in seconds) the client will wait for a new
event before disconnecting. All other HTTP operations are controlled by `timeout`.
"""
url, headers, timeout, sse_read_timeout = server.url, server.headers, server.timeout, server.sse_read_timeout

read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception]
read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception]

@@ -143,4 +159,4 @@ async def post_writer(endpoint_url: str):
tg.cancel_scope.cancel()
finally:
await read_stream_writer.aclose()
await write_stream.aclose()
await write_stream.aclose()