import asyncio
import os
from dotenv import load_dotenv
from apexagents import Agent, MCPServerClient

load_dotenv()

async def main():
    """
    Task: Initializes an MCP Client, connects to a public stdio server, wraps the tools natively, and runs the LLM execution over the MCP boundary.
    
    Input Parameters: None
        
    Output Parameters / Returns: None
    
    Raises: None
    """
    # 1. Connect to an external MCP server dynamically
    # We will use the standard mcp-server-fetch publicly available via uvx.
    print("Connecting to MCP Server (mcp-server-fetch)...")
    mcp_client = MCPServerClient(command="uvx", args=["mcp-server-fetch"])
    
    await mcp_client.connect()
    print("MCP Connected!")
    
    # 2. Get the tools dynamically from the server
    # The MCP protocol translates these into standard apexagents.Tool instances!
    mcp_tools = await mcp_client.get_tools()
    print(f"Loaded {len(mcp_tools)} tools from MCP:")
    for tool in mcp_tools:
        print(f" - {tool.name}: {tool.description}")

    # 3. Spin up an Agent equipped with the external MCP tools
    agent = Agent(
        name="WebFetcher",
        model=f"azure/{os.environ.get('DEPLOYMENT_NAME', 'gpt-4o-mini')}",
        instructions="You are a helpful assistant equipped with a web-fetching tool over MCP. When asked about a website, fetch it.",
        tools=mcp_tools
    )
    
    print("\n-----------------------------------")
    print("Agent prompt: Fetch the website https://example.com and tell me what the main header is.")
    print("-----------------------------------")

    response = await agent.arun("Fetch the website https://example.com and tell me what the main header is.")
    
    print("\n-----------------------------------")
    print("Final Agent Response:")
    print("-----------------------------------")
    print(response)

    # 4. Cleanup
    await mcp_client.close()

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