"""MCPTool - 通过 MCP Client 调用远程工具"""

import json
import logging
from typing import Any

from agentkit.tools.base import Tool

logger = logging.getLogger(__name__)


class MCPTool(Tool):
    """MCP 工具 - 通过 MCP Client 调用远程工具

    将外部 MCP Server 上的工具包装为本地 Tool 对象，
    通过 MCPClient 发起 HTTP 调用。
    """

    def __init__(
        self,
        name: str,
        description: str,
        client: Any,
        input_schema: dict[str, Any] | None = None,
        output_schema: dict[str, Any] | None = None,
        version: str = "1.0.0",
        tags: list[str] | None = None,
    ):
        super().__init__(
            name=name,
            description=description,
            input_schema=input_schema,
            output_schema=output_schema,
            version=version,
            tags=tags or ["mcp"],
        )
        self._client = client

    async def execute(self, **kwargs) -> dict:
        """通过 MCP Client 调用远程工具"""
        result = await self._client.call_tool(self.name, kwargs)

        # 解析 MCP 响应格式
        if "content" in result:
            for item in result["content"]:
                if item.get("type") == "text":
                    try:
                        return json.loads(item["text"])
                    except json.JSONDecodeError:
                        return {"result": item["text"]}
        return result
