"""Async MCP client helpers for the filesystem (MinIO) server."""

from __future__ import annotations

import os

from mcp import ClientSession
from mcp.client.sse import sse_client
from mcp.types import TextContent


async def fetch_text_via_mcp(object_key: str) -> str:
    url = os.environ["MCP_FS_SSE_URL"]
    async with sse_client(url) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()
            result = await session.call_tool("get_object_text", {"key": object_key})
            if result.isError:
                raise RuntimeError(result.content)
            parts: list[str] = []
            for block in result.content:
                if isinstance(block, TextContent):
                    parts.append(block.text)
            return "".join(parts)
