"""Tool synchronization between Python Agent and Go backend.""" import asyncio import logging from typing import Any import aiohttp logger = logging.getLogger(__name__) class ToolSyncClient: """Client for syncing tools to Go backend.""" def __init__(self, base_url: str, agent_id: str = "default"): """Initialize tool sync client. Args: base_url: Go backend base URL agent_id: Agent ID """ self.base_url = base_url.rstrip("/") self.agent_id = agent_id self._session = None async def _get_session(self) -> aiohttp.ClientSession: """Get or create aiohttp session.""" if self._session is None or self._session.closed: self._session = aiohttp.ClientSession() return self._session async def close(self) -> None: """Close the session.""" if self._session and not self._session.closed: await self._session.close() async def sync_tools( self, tools: list[dict[str, Any]], ) -> tuple[int, str]: """Sync tools to Go backend. Args: tools: List of tool definitions Returns: Tuple of (synced_count, message) """ url = f"{self.base_url}/tool/sync-from-python" # Transform tools to match Go backend format python_tools = [] for tool in tools: func = tool.get("function", {}) python_tools.append({ "name": func.get("name"), "description": func.get("description"), "parameters": func.get("parameters", "{}"), "category": "python", # Default category for Python tools }) payload = {"tools": python_tools} try: session = await self._get_session() async with session.post(url, json=payload) as response: if response.status == 200: result = await response.json() count = result.get("synced_count", 0) return count, f"Synced {count} tools successfully" else: text = await response.text() return 0, f"Failed to sync tools: {response.status} - {text}" except Exception as e: logger.error(f"Error syncing tools: {e}") return 0, f"Error syncing tools: {e}" async def sync_registry_tools( registry, base_url: str, agent_id: str = "default", ) -> tuple[int, str]: """Sync tools from a ToolRegistry to Go backend. Args: registry: ToolRegistry instance base_url: Go backend base URL agent_id: Agent ID Returns: Tuple of (synced_count, message) """ client = ToolSyncClient(base_url, agent_id) try: # Get all tool definitions tools = registry.get_definitions() if not tools: return 0, "No tools to sync" # Sync tools count, message = await client.sync_tools(tools) return count, message finally: await client.close()