mirror of
https://github.com/aljazceru/mcp-python-sdk.git
synced 2025-12-24 09:14:21 +01:00
Add OAuth authentication client for HTTPX (#751)
Co-authored-by: Paul Carleton <paulc@anthropic.com>
This commit is contained in:
54
README.md
54
README.md
@@ -796,6 +796,60 @@ async def main():
|
||||
tool_result = await session.call_tool("echo", {"message": "hello"})
|
||||
```
|
||||
|
||||
### OAuth Authentication for Clients
|
||||
|
||||
The SDK includes [authorization support](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for connecting to protected MCP servers:
|
||||
|
||||
```python
|
||||
from mcp.client.auth import OAuthClientProvider, TokenStorage
|
||||
from mcp.client.session import ClientSession
|
||||
from mcp.client.streamable_http import streamablehttp_client
|
||||
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
|
||||
|
||||
|
||||
class CustomTokenStorage(TokenStorage):
|
||||
"""Simple in-memory token storage implementation."""
|
||||
|
||||
async def get_tokens(self) -> OAuthToken | None:
|
||||
pass
|
||||
|
||||
async def set_tokens(self, tokens: OAuthToken) -> None:
|
||||
pass
|
||||
|
||||
async def get_client_info(self) -> OAuthClientInformationFull | None:
|
||||
pass
|
||||
|
||||
async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
|
||||
pass
|
||||
|
||||
|
||||
async def main():
|
||||
# Set up OAuth authentication
|
||||
oauth_auth = OAuthClientProvider(
|
||||
server_url="https://api.example.com",
|
||||
client_metadata=OAuthClientMetadata(
|
||||
client_name="My Client",
|
||||
redirect_uris=["http://localhost:3000/callback"],
|
||||
grant_types=["authorization_code", "refresh_token"],
|
||||
response_types=["code"],
|
||||
),
|
||||
storage=CustomTokenStorage(),
|
||||
redirect_handler=lambda url: print(f"Visit: {url}"),
|
||||
callback_handler=lambda: ("auth_code", None),
|
||||
)
|
||||
|
||||
# Use with streamable HTTP client
|
||||
async with streamablehttp_client(
|
||||
"https://api.example.com/mcp", auth=oauth_auth
|
||||
) as (read, write, _):
|
||||
async with ClientSession(read, write) as session:
|
||||
await session.initialize()
|
||||
# Authenticated session ready
|
||||
```
|
||||
|
||||
For a complete working example, see [`examples/clients/simple-auth-client/`](examples/clients/simple-auth-client/).
|
||||
|
||||
|
||||
### MCP Primitives
|
||||
|
||||
The MCP protocol defines three core primitives that servers can implement:
|
||||
|
||||
Reference in New Issue
Block a user