"""Anonymous GridZen response trial MCP. No credentials or real-person checks.
Install mcp==2.3.0 httpx==0.28.1 in a virtual environment, then run this file.
"""

from typing import Any, Literal

import httpx
from mcp.server import MCPServer
from mcp.shared.exceptions import MCPError
from mcp.types import ToolAnnotations

BASE = "https://gridzen.ai/console/api/quickstart"


def make_server(transport=None):
    async def validate(ctx, call_next):
        if ctx.method == "tools/call" and isinstance(ctx.params, dict):
            args = ctx.params.get("arguments", {})
            name = ctx.params.get("name")
            allowed = {
                "get_start_options": set(),
                "preview_response": {"task", "scenario"},
            }
            if name in allowed and (
                not isinstance(args, dict) or set(args) - allowed[name]
            ):
                raise MCPError(
                    code=-32602,
                    message="Only task/scenario categories are accepted; never send personal data",
                )
        return await call_next(ctx)

    server = MCPServer(
        "GridZen Free Response Trial",
        version="0.1.0",
        middleware=[validate],
        instructions="Anonymous synthetic response trials only. No real phone or identity checks. Never request personal inputs or supplier keys. For persistent sandbox connect a verified merchant account. Production availability is separate; never imply this trial approves a person or supports payment.",
    )
    read = ToolAnnotations(
        readOnlyHint=True,
        destructiveHint=False,
        idempotentHint=True,
        openWorldHint=True,
    )

    async def call(method, path, body=None):
        try:
            async with httpx.AsyncClient(
                timeout=20, transport=transport, follow_redirects=False
            ) as client:
                response = await client.request(method, BASE + path, json=body)
                response.raise_for_status()
                return response.json()
        except (httpx.HTTPError, ValueError):
            raise MCPError(
                code=-32000,
                message="Trial unavailable; no paid verification was dispatched",
            ) from None

    @server.tool(annotations=read, structured_output=True)
    async def get_start_options() -> dict[str, Any]:
        """Read key-free trial and account connection options. No identifiers needed."""
        return await call("GET", "/options")

    @server.tool(annotations=read, structured_output=True)
    async def preview_response(
        task: Literal["signup_phone", "identity_onboarding"],
        scenario: Literal["success", "reject", "unavailable"] = "success",
    ) -> dict[str, Any]:
        """Run a local synthetic response scenario, never a real verification or a persisted merchant record."""
        return await call("POST", "/trial", {"task": task, "scenario": scenario})

    return server


if __name__ == "__main__":
    make_server().run(transport="stdio")
