"""mcp_client.py, M16: connect to an MCP server, discover its tools, and call them.

This is the other half of MCP: a client that launches/connects to a server, asks "what tools
do you have?", and calls them, the exact handshake an MCP-aware app (Claude Desktop, an
agent) does for you. No API key, no network, it talks to the local server over stdio.

Setup:  pip install mcp
Run:    python mcp_client.py        # it starts mcp_server.py and uses its tools
"""

import sys
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def main():
    # Tell the client how to start the server (same Python interpreter, our server file).
    params = StdioServerParameters(command=sys.executable, args=["mcp_server.py"])

    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()                      # MCP handshake

            # 1. DISCOVER, ask the server what it offers (this is MCP's superpower).
            tools = await session.list_tools()
            print("Tools the server offers:")
            for t in tools.tools:
                print(f"  - {t.name}: {t.description}")

            # 2. CALL, invoke tools by name with arguments.
            r1 = await session.call_tool("calculate", {"expression": "245 * 18 / 100"})
            print("\ncalculate('245 * 18 / 100') ->", r1.content[0].text)

            r2 = await session.call_tool("lookup_ioc", {"indicator": "185.220.101.45"})
            print("lookup_ioc('185.220.101.45') ->", r2.content[0].text)


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