"""AgentWeb stdio bridge. Install: pip install "mcp>=1.12,<2" httpx

Set AGENTWEB_API_KEY. Tools and results come from hosted MCP; no copied catalog.
"""
import asyncio
import os

from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from mcp.server import Server
from mcp.server.stdio import stdio_server

URL = "https://api.agentweb.live/mcp"
server = Server("agentweb")


def headers():
    return {header: os.environ[env] for header, env in (
        ("X-API-Key", "AGENTWEB_API_KEY"),
        ("X-AgentWeb-Workspace", "AGENTWEB_WORKSPACE"),
        ("X-AgentWeb-User", "AGENTWEB_USER"),
    ) if os.environ.get(env)}


async def remote(method, **kwargs):
    async with streamablehttp_client(URL, headers=headers()) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            return await getattr(session, method)(**kwargs)


@server.list_tools()
async def list_tools():
    return (await remote("list_tools")).tools


@server.call_tool()
async def call_tool(name: str, arguments: dict):
    # Keep isError, structuredContent and every content block intact.
    return await remote("call_tool", name=name, arguments=arguments)


async def main():
    async with stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())


if __name__ == "__main__":
    asyncio.run(main())
