Skip to content

Commit 43ded92

Browse files
authored
add auth client sse (#760)
1 parent 5a9340a commit 43ded92

File tree

3 files changed

+64
-33
lines changed

3 files changed

+64
-33
lines changed

examples/clients/simple-auth-client/README.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
# Simple Auth Client Example
22

3-
A demonstration of how to use the MCP Python SDK with OAuth authentication over streamable HTTP transport.
3+
A demonstration of how to use the MCP Python SDK with OAuth authentication over streamable HTTP or SSE transport.
44

55
## Features
66

77
- OAuth 2.0 authentication with PKCE
8-
- Streamable HTTP transport
8+
- Support for both StreamableHTTP and SSE transports
99
- Interactive command-line interface
1010

1111
## Installation
@@ -31,7 +31,10 @@ uv run mcp-simple-auth --transport streamable-http --port 3001
3131
uv run mcp-simple-auth-client
3232

3333
# Or with custom server URL
34-
MCP_SERVER_URL=http://localhost:3001 uv run mcp-simple-auth-client
34+
MCP_SERVER_PORT=3001 uv run mcp-simple-auth-client
35+
36+
# Use SSE transport
37+
MCP_TRANSPORT_TYPE=sse uv run mcp-simple-auth-client
3538
```
3639

3740
### 3. Complete OAuth flow
@@ -67,4 +70,5 @@ mcp> quit
6770

6871
## Configuration
6972

70-
- `MCP_SERVER_URL` - Server URL (default: http://localhost:3001)
73+
- `MCP_SERVER_PORT` - Server URL (default: 8000)
74+
- `MCP_TRANSPORT_TYPE` - Transport type: `streamable_http` (default) or `sse`

examples/clients/simple-auth-client/mcp_simple_auth_client/main.py

Lines changed: 47 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
from mcp.client.auth import OAuthClientProvider, TokenStorage
2020
from mcp.client.session import ClientSession
21+
from mcp.client.sse import sse_client
2122
from mcp.client.streamable_http import streamablehttp_client
2223
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
2324

@@ -149,8 +150,9 @@ def get_state(self):
149150
class SimpleAuthClient:
150151
"""Simple MCP client with auth support."""
151152

152-
def __init__(self, server_url: str):
153+
def __init__(self, server_url: str, transport_type: str = "streamable_http"):
153154
self.server_url = server_url
155+
self.transport_type = transport_type
154156
self.session: ClientSession | None = None
155157

156158
async def connect(self):
@@ -195,38 +197,48 @@ async def _default_redirect_handler(authorization_url: str) -> None:
195197
callback_handler=callback_handler,
196198
)
197199

198-
# Create streamable HTTP transport with auth handler
199-
stream_context = streamablehttp_client(
200-
url=self.server_url,
201-
auth=oauth_auth,
202-
timeout=timedelta(seconds=60),
203-
)
204-
205-
print(
206-
"📡 Opening transport connection (HTTPX handles auth automatically)..."
207-
)
208-
async with stream_context as (read_stream, write_stream, get_session_id):
209-
print("🤝 Initializing MCP session...")
210-
async with ClientSession(read_stream, write_stream) as session:
211-
self.session = session
212-
print("⚡ Starting session initialization...")
213-
await session.initialize()
214-
print("✨ Session initialization complete!")
215-
216-
print(f"\n✅ Connected to MCP server at {self.server_url}")
217-
session_id = get_session_id()
218-
if session_id:
219-
print(f"Session ID: {session_id}")
220-
221-
# Run interactive loop
222-
await self.interactive_loop()
200+
# Create transport with auth handler based on transport type
201+
if self.transport_type == "sse":
202+
print("📡 Opening SSE transport connection with auth...")
203+
async with sse_client(
204+
url=self.server_url,
205+
auth=oauth_auth,
206+
timeout=60,
207+
) as (read_stream, write_stream):
208+
await self._run_session(read_stream, write_stream, None)
209+
else:
210+
print("📡 Opening StreamableHTTP transport connection with auth...")
211+
async with streamablehttp_client(
212+
url=self.server_url,
213+
auth=oauth_auth,
214+
timeout=timedelta(seconds=60),
215+
) as (read_stream, write_stream, get_session_id):
216+
await self._run_session(read_stream, write_stream, get_session_id)
223217

224218
except Exception as e:
225219
print(f"❌ Failed to connect: {e}")
226220
import traceback
227221

228222
traceback.print_exc()
229223

224+
async def _run_session(self, read_stream, write_stream, get_session_id):
225+
"""Run the MCP session with the given streams."""
226+
print("🤝 Initializing MCP session...")
227+
async with ClientSession(read_stream, write_stream) as session:
228+
self.session = session
229+
print("⚡ Starting session initialization...")
230+
await session.initialize()
231+
print("✨ Session initialization complete!")
232+
233+
print(f"\n✅ Connected to MCP server at {self.server_url}")
234+
if get_session_id:
235+
session_id = get_session_id()
236+
if session_id:
237+
print(f"Session ID: {session_id}")
238+
239+
# Run interactive loop
240+
await self.interactive_loop()
241+
230242
async def list_tools(self):
231243
"""List available tools from the server."""
232244
if not self.session:
@@ -326,13 +338,20 @@ async def main():
326338
"""Main entry point."""
327339
# Default server URL - can be overridden with environment variable
328340
# Most MCP streamable HTTP servers use /mcp as the endpoint
329-
server_url = os.getenv("MCP_SERVER_URL", "http://localhost:8000/mcp")
341+
server_url = os.getenv("MCP_SERVER_PORT", 8000)
342+
transport_type = os.getenv("MCP_TRANSPORT_TYPE", "streamable_http")
343+
server_url = (
344+
f"http://localhost:{server_url}/mcp"
345+
if transport_type == "streamable_http"
346+
else f"http://localhost:{server_url}/sse"
347+
)
330348

331349
print("🚀 Simple MCP Auth Client")
332350
print(f"Connecting to: {server_url}")
351+
print(f"Transport type: {transport_type}")
333352

334353
# Start connection flow - OAuth will be handled automatically
335-
client = SimpleAuthClient(server_url)
354+
client = SimpleAuthClient(server_url, transport_type)
336355
await client.connect()
337356

338357

src/mcp/client/sse.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,20 @@ async def sse_client(
2626
headers: dict[str, Any] | None = None,
2727
timeout: float = 5,
2828
sse_read_timeout: float = 60 * 5,
29+
auth: httpx.Auth | None = None,
2930
):
3031
"""
3132
Client transport for SSE.
3233
3334
`sse_read_timeout` determines how long (in seconds) the client will wait for a new
3435
event before disconnecting. All other HTTP operations are controlled by `timeout`.
36+
37+
Args:
38+
url: The SSE endpoint URL.
39+
headers: Optional headers to include in requests.
40+
timeout: HTTP timeout for regular operations.
41+
sse_read_timeout: Timeout for SSE read operations.
42+
auth: Optional HTTPX authentication handler.
3543
"""
3644
read_stream: MemoryObjectReceiveStream[SessionMessage | Exception]
3745
read_stream_writer: MemoryObjectSendStream[SessionMessage | Exception]
@@ -45,7 +53,7 @@ async def sse_client(
4553
async with anyio.create_task_group() as tg:
4654
try:
4755
logger.info(f"Connecting to SSE endpoint: {remove_request_params(url)}")
48-
async with create_mcp_http_client(headers=headers) as client:
56+
async with create_mcp_http_client(headers=headers, auth=auth) as client:
4957
async with aconnect_sse(
5058
client,
5159
"GET",

0 commit comments

Comments
 (0)