"""pip install mcp==2.3.0; python mcp_roundtrip.py <explicit local/staging /mcp URL>"""
import asyncio
import os
import sys
from urllib.parse import urlsplit
import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client


async def run(url):
    if urlsplit(url).scheme not in ('http', 'https') or not urlsplit(url).netloc:
        raise ValueError('Provide an explicit MCP server URL.')
    headers = {'X-SetGet-Token':os.environ['SETGET_TOKEN']} if os.environ.get('SETGET_TOKEN') else {}
    async with httpx2.AsyncClient(headers=headers, timeout=40) as http:
        async with Client(streamable_http_client(url, http_client=http)) as client:
            created = await client.call_tool('create_key', {'value':'agent demo', 'ttl_seconds':3600})
            if created.is_error:
                raise RuntimeError('Creation failed; inspect state before retrying.')
            key = created.structured_content['body']['id']
            try:
                read = await client.call_tool('get_key', {'key':key})
                if read.is_error or read.structured_content['body']['value'] != 'agent demo':
                    raise RuntimeError('Read verification failed.')
                print('Created and read a public one-hour key successfully.')
            finally:
                deleted = await client.call_tool('delete_key', {'key':key})
                if deleted.is_error:
                    raise RuntimeError('Cleanup failed; inspect the temporary key.')


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python mcp_roundtrip.py <explicit local/staging /mcp URL>')
    asyncio.run(run(sys.argv[1]))
