|
| 1 | +# Copyright 2026 Google LLC. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +""" |
| 15 | +Client for interacting with the Data Commons Agent API. |
| 16 | +""" |
| 17 | + |
| 18 | +import logging |
| 19 | +import time |
| 20 | +from collections.abc import Callable |
| 21 | +from functools import wraps |
| 22 | +from typing import Any # noqa: ANN401 |
| 23 | + |
| 24 | +import httpx |
| 25 | + |
| 26 | +from datacommons_mcp.exceptions import AgentAPIError |
| 27 | +from datacommons_mcp.version import __version__ |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +def log_api_call(func: Callable[..., Any]) -> Callable[..., Any]: # noqa: ANN401 |
| 33 | + """Decorator to log URL, request payload, execution time, and errors for Agent API calls.""" |
| 34 | + |
| 35 | + @wraps(func) |
| 36 | + async def wrapper( |
| 37 | + self: "AgentAPIClient", |
| 38 | + endpoint: str, |
| 39 | + payload: dict, |
| 40 | + *args: object, |
| 41 | + **kwargs: object, |
| 42 | + ) -> Any: # noqa: ANN401 |
| 43 | + url = f"{self.api_root}/{endpoint}" |
| 44 | + logger.info("AgentAPIClient POST request URL: %s, payload: %s", url, payload) |
| 45 | + start_time = time.perf_counter() |
| 46 | + try: |
| 47 | + result = await func(self, endpoint, payload, *args, **kwargs) |
| 48 | + elapsed_time = time.perf_counter() - start_time |
| 49 | + logger.info( |
| 50 | + "AgentAPIClient POST request to %s completed in %.3f seconds", |
| 51 | + url, |
| 52 | + elapsed_time, |
| 53 | + ) |
| 54 | + return result |
| 55 | + except Exception as e: |
| 56 | + elapsed_time = time.perf_counter() - start_time |
| 57 | + logger.error( |
| 58 | + "AgentAPIClient POST request to %s failed after %.3f seconds with error: %s", |
| 59 | + url, |
| 60 | + elapsed_time, |
| 61 | + e, |
| 62 | + ) |
| 63 | + raise |
| 64 | + |
| 65 | + return wrapper |
| 66 | + |
| 67 | + |
| 68 | +class AgentAPIClient: |
| 69 | + """Async client for interacting with Data Commons agent endpoints.""" |
| 70 | + |
| 71 | + def __init__(self, api_root: str, api_key: str | None = None) -> None: |
| 72 | + """Initialize the AgentAPIClient. |
| 73 | +
|
| 74 | + Args: |
| 75 | + api_root: The base API root URL (e.g. 'https://api.datacommons.org/v2'). |
| 76 | + api_key: Optional API key for authentication. |
| 77 | + """ |
| 78 | + self.api_root = api_root.rstrip("/") |
| 79 | + self.api_key = api_key |
| 80 | + self.headers = { |
| 81 | + "Content-Type": "application/json", |
| 82 | + "x-surface": f"mcp-{__version__}", |
| 83 | + } |
| 84 | + if api_key: |
| 85 | + self.headers["X-API-Key"] = api_key |
| 86 | + self.timeout = 30.0 # 30 seconds default timeout |
| 87 | + self._client = None |
| 88 | + |
| 89 | + @property |
| 90 | + def client(self) -> httpx.AsyncClient: |
| 91 | + """Lazily initialize the AsyncClient under the active event loop.""" |
| 92 | + if self._client is None: |
| 93 | + self._client = httpx.AsyncClient(headers=self.headers, timeout=self.timeout) |
| 94 | + return self._client |
| 95 | + |
| 96 | + @log_api_call |
| 97 | + async def post(self, endpoint: str, payload: dict) -> dict: |
| 98 | + """Perform an asynchronous POST request to the specified endpoint. |
| 99 | +
|
| 100 | + Args: |
| 101 | + endpoint: The API endpoint (e.g. 'agent/get_observations'). |
| 102 | + payload: The dictionary to send as JSON payload. |
| 103 | +
|
| 104 | + Returns: |
| 105 | + The parsed JSON response as a dictionary. |
| 106 | + """ |
| 107 | + url = f"{self.api_root}/{endpoint}" |
| 108 | + try: |
| 109 | + response = await self.client.post(url, json=payload) |
| 110 | + response.raise_for_status() |
| 111 | + return response.json() |
| 112 | + except httpx.HTTPStatusError as e: |
| 113 | + error_msg = f"Agent API call to {endpoint} failed with status {e.response.status_code}" |
| 114 | + raise AgentAPIError( |
| 115 | + error_msg, e.response.status_code, e.response.text |
| 116 | + ) from e |
| 117 | + |
| 118 | + async def close(self) -> None: |
| 119 | + """Close the underlying HTTP client if it was initialized.""" |
| 120 | + if self._client is not None: |
| 121 | + await self._client.aclose() |
| 122 | + self._client = None |
0 commit comments