|
| 1 | +"""Utilities for creating standardized httpx AsyncClient instances.""" |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import httpx |
| 6 | + |
| 7 | +__all__ = ["create_mcp_http_client"] |
| 8 | + |
| 9 | + |
| 10 | +def create_mcp_http_client( |
| 11 | + headers: dict[str, str] | None = None, |
| 12 | + timeout: httpx.Timeout | None = None, |
| 13 | +) -> httpx.AsyncClient: |
| 14 | + """Create a standardized httpx AsyncClient with MCP defaults. |
| 15 | +
|
| 16 | + This function provides common defaults used throughout the MCP codebase: |
| 17 | + - follow_redirects=True (always enabled) |
| 18 | + - Default timeout of 30 seconds if not specified |
| 19 | +
|
| 20 | + Args: |
| 21 | + headers: Optional headers to include with all requests. |
| 22 | + timeout: Request timeout as httpx.Timeout object. |
| 23 | + Defaults to 30 seconds if not specified. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + Configured httpx.AsyncClient instance with MCP defaults. |
| 27 | +
|
| 28 | + Note: |
| 29 | + The returned AsyncClient must be used as a context manager to ensure |
| 30 | + proper cleanup of connections. |
| 31 | +
|
| 32 | + Examples: |
| 33 | + # Basic usage with MCP defaults |
| 34 | + async with create_mcp_http_client() as client: |
| 35 | + response = await client.get("https://api.example.com") |
| 36 | +
|
| 37 | + # With custom headers |
| 38 | + headers = {"Authorization": "Bearer token"} |
| 39 | + async with create_mcp_http_client(headers) as client: |
| 40 | + response = await client.get("/endpoint") |
| 41 | +
|
| 42 | + # With both custom headers and timeout |
| 43 | + timeout = httpx.Timeout(60.0, read=300.0) |
| 44 | + async with create_mcp_http_client(headers, timeout) as client: |
| 45 | + response = await client.get("/long-request") |
| 46 | + """ |
| 47 | + # Set MCP defaults |
| 48 | + kwargs: dict[str, Any] = { |
| 49 | + "follow_redirects": True, |
| 50 | + } |
| 51 | + |
| 52 | + # Handle timeout |
| 53 | + if timeout is None: |
| 54 | + kwargs["timeout"] = httpx.Timeout(30.0) |
| 55 | + else: |
| 56 | + kwargs["timeout"] = timeout |
| 57 | + |
| 58 | + # Handle headers |
| 59 | + if headers is not None: |
| 60 | + kwargs["headers"] = headers |
| 61 | + |
| 62 | + return httpx.AsyncClient(**kwargs) |
0 commit comments