|
| 1 | +"""Utilities for creating standardized httpx AsyncClient instances.""" |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import httpx |
| 6 | + |
| 7 | + |
| 8 | +def create_mcp_http_client( |
| 9 | + *, |
| 10 | + headers: dict[str, Any] | None = None, |
| 11 | + timeout: httpx.Timeout | float | None = None, |
| 12 | + **kwargs: Any, |
| 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 | + - Header will be merged |
| 20 | +
|
| 21 | + Args: |
| 22 | + headers: Optional headers to include with all requests. |
| 23 | + timeout: Request timeout in seconds (float) or httpx.Timeout object. |
| 24 | + Defaults to 30 seconds if not specified. |
| 25 | + **kwargs: Additional keyword arguments to pass to AsyncClient. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + Configured httpx.AsyncClient instance with MCP defaults. |
| 29 | +
|
| 30 | + Examples: |
| 31 | + # Basic usage with MCP defaults |
| 32 | + async with create_mcp_http_client() as client: |
| 33 | + response = await client.get("https://api.example.com") |
| 34 | +
|
| 35 | + # With custom headers |
| 36 | + headers = {"Authorization": "Bearer token"} |
| 37 | + async with create_mcp_http_client(headers=headers) as client: |
| 38 | + response = await client.get("/endpoint") |
| 39 | +
|
| 40 | + # With custom timeout |
| 41 | + timeout = httpx.Timeout(60.0, read=300.0) |
| 42 | + async with create_mcp_http_client(timeout=timeout) as client: |
| 43 | + response = await client.get("/long-request") |
| 44 | + """ |
| 45 | + # Set MCP defaults |
| 46 | + defaults: dict[str, Any] = { |
| 47 | + "follow_redirects": True, |
| 48 | + } |
| 49 | + |
| 50 | + # Handle timeout |
| 51 | + if timeout is None: |
| 52 | + defaults["timeout"] = httpx.Timeout(30.0) |
| 53 | + elif isinstance(timeout, int | float): |
| 54 | + defaults["timeout"] = httpx.Timeout(timeout) |
| 55 | + else: |
| 56 | + defaults["timeout"] = timeout |
| 57 | + |
| 58 | + # Handle headers |
| 59 | + if headers is not None: |
| 60 | + kwargs["headers"] = headers |
| 61 | + |
| 62 | + # Merge defaults with provided kwargs |
| 63 | + kwargs = {**defaults, **kwargs} |
| 64 | + |
| 65 | + return httpx.AsyncClient(**kwargs) |
0 commit comments