"""MCP server connection via stdio and SSE."""

from __future__ import annotations

import asyncio

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.client.sse import sse_client


async def fetch_tools_stdio(command: str, args: list[str]) -> list:
    """Connect to an MCP server via stdio and return its tool list."""
    params = StdioServerParameters(command=command, args=args)
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.list_tools()
            return list(result.tools)


async def fetch_tools_sse(url: str) -> list:
    """Connect to an MCP server via SSE and return its tool list."""
    async with sse_client(url) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.list_tools()
            return list(result.tools)


def get_tools_stdio(command: str, args: list[str]) -> list:
    """Synchronous wrapper for fetch_tools_stdio."""
    return asyncio.run(fetch_tools_stdio(command, args))


def get_tools_sse(url: str) -> list:
    """Synchronous wrapper for fetch_tools_sse."""
    return asyncio.run(fetch_tools_sse(url))
