"""How many tokens does one tool result add to the context? On the same real pages:
- Playwright MCP's browser_navigate: the reply, and the page snapshot it saves to a file
  instead of returning (what the reply would cost if the snapshot were inline);
- the Fetch server's fetch tool: its default reply (max_length 5,000 characters) and the
  whole page as Markdown.
Run on October 12, 2026, from Mumbai.
Run with: uv run --with mcp --with tiktoken python results_cost.py"""
import asyncio
import json
import re
from pathlib import Path

import tiktoken
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

enc = tiktoken.get_encoding("o200k_base")
PAGES = [
    "https://en.wikipedia.org/wiki/Web_scraping",
    "https://news.ycombinator.com/",
    "https://www.allbirds.com/products/womens-allbirds-flip-flop-dusty-pink",
]


def tokens(text):
    return len(enc.encode(text))


def text_of(result):
    return "\n".join(c.text for c in result.content if getattr(c, "text", None))


async def session(cmd, args):
    return stdio_client(StdioServerParameters(command=cmd, args=args))


async def main():
    out = {}
    async with stdio_client(StdioServerParameters(command="npx", args=["-y", "@playwright/mcp@0.0.83", "--headless"])) as (r, w):
        async with ClientSession(r, w) as s:
            await s.initialize()
            for url in PAGES:
                reply = text_of(await s.call_tool("browser_navigate", {"url": url}))
                snap = re.search(r"\((\.playwright-mcp/[^)]+\.yml)\)", reply)
                snapshot = Path(snap.group(1)).read_text() if snap else ""
                out.setdefault(url, {})["playwright_reply"] = tokens(reply)
                out[url]["playwright_snapshot_file"] = tokens(snapshot)
    async with stdio_client(StdioServerParameters(command="uvx", args=["mcp-server-fetch"])) as (r, w):
        async with ClientSession(r, w) as s:
            await s.initialize()
            for url in PAGES:
                out[url]["fetch_default"] = tokens(text_of(await s.call_tool("fetch", {"url": url})))
                out[url]["fetch_whole_page"] = tokens(text_of(await s.call_tool("fetch", {"url": url, "max_length": 999999})))
    json.dump(out, open("results_cost.json", "w"), indent=1)
    for url, v in out.items():
        print(url, v)


asyncio.run(main())
