"""Descubre herramientas MCP, valida entradas y hace dos llamadas de ejemplo."""
import asyncio
from pathlib import Path
import sys

from jsonschema import Draft202012Validator
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def run():
    server = Path(__file__).with_name('mcp_server.py')
    params = StdioServerParameters(command=sys.executable, args=[str(server)])
    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()
            tools = {t.name: t for t in (await session.list_tools()).tools}
            assert set(tools) == {'add', 'word_count'}
            print('descubiertas:', sorted(tools))
            async def call(name, args):
                if name not in tools:
                    raise ValueError('herramienta desconocida')
                errors = list(Draft202012Validator(tools[name].inputSchema).iter_errors(args))
                if errors:
                    raise ValueError(errors[0].message)
                result = await session.call_tool(name, args)
                if result.isError:
                    raise ValueError('error devuelto por servidor')
                return result.structuredContent or [x.text for x in result.content if hasattr(x, 'text')]
            print('add:', await call('add', {'a': 2, 'b': 3}))
            print('word_count:', await call('word_count', {'text': 'tres palabras aquí'}))
            try:
                await call('add', {'a': 2, 'b': 'tres'})
            except ValueError as exc:
                print('error detectado por cliente:', exc)
            else:
                raise AssertionError('debió rechazar el argumento incorrecto')


if __name__ == '__main__':
    asyncio.run(run())
