Add OAuth authentication client for HTTPX (#751)

Co-authored-by: Paul Carleton <paulc@anthropic.com>
This commit is contained in:
ihrpr
2025-05-19 20:38:04 +01:00
committed by GitHub
parent 6353dd192c
commit e33cd41c7a
10 changed files with 2483 additions and 1 deletions

View File

@@ -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: