Code

researcher.py

A Python script that publishes on Webloyt through the Claude API. Copy it, put ANTHROPIC_API_KEY and WEBLOYT_TOKEN in a .env file next to it (tokens come from the tokens page) and run it. The constants at the top are the only things to change.

"""Adventures in Finance: an agent finds an interesting paper, a writer explains it on a page, and the page
joins a site that grows by one paper per run.

The agent decides which paper, within a field (FIELD) and a small budget. Each run:
1. The script reads the site: which papers are already explained, and the site's stylesheet.
2. The researcher (Claude Opus, with web search and web fetch) chooses a paper not yet covered, reads it,
   and hands over notes: question, method, results with numbers, caveats, sources.
3. The writer (Claude Fable, no tools) turns the notes into a page in the site's look (or designs the look
   on the first run), and rewrites the index that lists every paper so far. The files are saved under
   researcher/<site>/ so you can read them, keep them or change them.
4. The script checks the photographs, has the writer fix what does not load, and uploads the page, the
   index, the stylesheet and the list of papers with the Webloyt tools.
The first time it runs it has no Webloyt token, so it asks for permission: it starts a pairing, prints
a link, and waits for you to open it and approve; the token is saved to .env and later runs do not ask.

Setup:   pip install anthropic fastmcp rich python-dotenv
         ANTHROPIC_API_KEY in the environment or in a .env file
Run:     python researcher.py
"""

import asyncio
import json
import os
import re
import time
import urllib.error
import urllib.request
from pathlib import Path

import anthropic
from dotenv import load_dotenv
from fastmcp import Client
from fastmcp.exceptions import ToolError
from rich.console import Console
from rich.table import Table

load_dotenv()

# ---- The site and the mandate ---------------------------------------------------------------
SITE = "adventures-in-finance"
SITE_TITLE = "Adventures in Finance"
FIELD = "finance or economics"       # the agent decides which paper; the budget is small
TASK = (f"Find an interesting recent paper in {FIELD}: one with a clear question, a result that would surprise "
        "a thoughtful non-specialist, and a method a reader can follow. Look at a few candidates, choose one, "
        "then read it, the abstract and the paper itself if it is open, and the discussion around it if any. "
        "Hand over everything a writer needs to explain it: the question, the data, the method in plain terms, "
        "the main numbers, the caveats the authors give, who the authors are, and where to find the paper.")
RESEARCHER_MODEL = "claude-opus-5-5"
WRITER_MODEL = "claude-fable-5-2"
SEARCHES = 8
FETCHES = 4                   # pages the researcher may read in full
OUT = Path("researcher") / SITE   # the pages are saved here too
WEBLOYT = "https://webloyt-mcp.iroiro.cloud"

PRICES = {  # (input, output, cache write, cache read), dollars per million tokens
    "claude-fable-5-2": (8.00, 40.00, 10.00, 0.20),
    "claude-opus-5-5": (4.00, 20.00, 5.00, 0.20),
    "claude-sonnet-5-5": (2.00, 10.00, 2.50, 0.10),
}
SEARCH_PRICE = 10.00  # dollars per thousand web searches

RESEARCHER = """You are a researcher with a small search budget, so choose searches that discriminate between
candidates and spend the reading on the paper you choose. Prefer the paper itself and the authors' own
words; keep every fact and number with its source; where you are unsure, say so. If a photograph fits
(an author's portrait, the thing the paper is about), give it as a Wikimedia Commons thumbnail address,
https://commons.wikimedia.org/wiki/Special:FilePath/<File name>?width=1280 (Wikimedia serves these widths:
500, 960, 1280, 1920), or an Unsplash or Pexels direct image address, with what it shows. When you are done,
hand over your notes in Markdown: the paper (title, authors, year, where published, link); why you chose
it, in two sentences; the question; the data and method in plain terms; the main results with the numbers;
the caveats; a mood for the page, in one sentence; any photographs; and a short list of the sources."""

WRITER = f"""You are a writer and a designer for "{SITE_TITLE}", a site that explains one paper per page to a
thoughtful non-specialist. From the researcher's notes, write the page: a title that makes a promise, an
opening that states the surprise, then the question, how they found out, what they found, what it means and
what it does not. Plain, exact prose; no filler; bullet points only where a list is the honest form; no
headings that sound like a manual. Use only facts and numbers from the notes, with the paper linked where it
is used, a short list of sources and a line saying when the page was researched. One figure: the paper's
main number or comparison drawn as inline SVG (a bar or a line, labelled, from numbers in the notes only).
Photographs from the notes, with captions, if there are any. Every page links to the index as index.html.

The site has one stylesheet, style.css. If you are given it, keep the site's look and reuse its classes,
adding rules only if the page needs them, and return the whole stylesheet. If you are not, design the look:
a mood that fits a site about money and evidence, a palette of two or three colours, one or two typefaces
from Google Fonts, generous space, a layout that reads well on a phone.

The index, index.html, lists every paper explained so far, newest first: for each, the title as a link to
its page, the one-line summary, and the date. It opens with the site's name, one sentence on what the site
is, and a line saying that an agent chose the papers.

Webloyt serves static HTML and CSS only: no JavaScript, no forms, no iframes except Google Maps embeds;
stylesheets only from Google Fonts or style.css. Every page needs a title, a meta description of 50-160
characters, a viewport tag, exactly one h1 and alt text on every image. Answer with these parts and nothing
else, each after its marker on a line of its own: ===SLUG=== the page's file name without .html (lowercase
letters, digits and hyphens), ===TITLE=== the page title, ===SUMMARY=== one line for the index,
===STYLE=== style.css, ===PAGE=== the page, ===INDEX=== index.html."""

# `rich` only colours the output and records it, so the run can be shared as an image.
console = Console(record=True)
client = anthropic.Anthropic()
usage = {}
searches = 0


# ---- Asking for permission ------------------------------------------------------------------

def pair():
    """Ask Webloyt for a token of this agent's own: print the link, wait for approval, save it."""
    request = urllib.request.Request(f"{WEBLOYT}/pair", data=json.dumps({"label": "researcher"}).encode(),
                                     headers={"Content-Type": "application/json"}, method="POST")
    with urllib.request.urlopen(request) as response:
        start = json.load(response)
    console.print(f"[bold]The agent wants to publish on Webloyt. Open this link and approve:[/]\n{start['pairing_url']}")
    poll = urllib.request.Request(start["poll_url"], data=json.dumps({"secret": start["poll_secret"]}).encode(),
                                  headers={"Content-Type": "application/json"}, method="POST")
    deadline = time.time() + start["expires_in"]
    while time.time() < deadline:
        time.sleep(start["interval"])
        try:
            with urllib.request.urlopen(poll) as response:
                if response.status == 200:
                    token = json.load(response)["token"]
                    break
        except urllib.error.HTTPError as error:
            raise SystemExit(f"Pairing refused: {error.read().decode()[:200]}")
    else:
        raise SystemExit("Nobody approved in time.")
    with open(".env", "a") as env:
        env.write(f"\nWEBLOYT_TOKEN={token}\n")
    os.environ["WEBLOYT_TOKEN"] = token
    console.print("[green]Approved. The token is saved in .env for the next runs.\n")


# ---- The models -----------------------------------------------------------------------------

def record(message):
    global searches
    totals = usage.setdefault(message.model, {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0})
    totals["input"] += message.usage.input_tokens
    totals["output"] += message.usage.output_tokens
    totals["cache_write"] += message.usage.cache_creation_input_tokens or 0
    totals["cache_read"] += message.usage.cache_read_input_tokens or 0
    if message.usage.server_tool_use:
        searches += message.usage.server_tool_use.web_search_requests or 0


def text_of(message):
    return " ".join(block.text for block in message.content if block.type == "text").strip()


def research(covered):
    """The researcher searches the web and hands over notes. A long turn comes back paused and is continued."""
    task = TASK + ("\nAlready explained on the site, so choose something else: " + "; ".join(covered) if covered else "")
    messages = [{"role": "user", "content": task}]
    while True:
        with client.beta.messages.stream(
            model=RESEARCHER_MODEL, max_tokens=32000, output_config={"effort": "high"},
            betas=["server-side-fallback-2026-07-01"], fallbacks="default",
            system=RESEARCHER,
            tools=[{"type": "web_search_20260209", "name": "web_search", "max_uses": SEARCHES},
                   {"type": "web_fetch_20260209", "name": "web_fetch", "max_uses": FETCHES}],
            messages=messages,
        ) as stream:
            message = stream.get_final_message()
        record(message)
        for block in message.content:
            if block.type == "server_tool_use":
                console.print(f"  [dim]{block.name}: {block.input.get('query') or block.input.get('url', '')}[/]")
        if message.stop_reason != "pause_turn":
            break
        messages.append({"role": "assistant", "content": message.content})
    if message.stop_reason != "end_turn":
        raise SystemExit(f"{RESEARCHER_MODEL} stopped early: {message.stop_reason}")
    return text_of(message)


def write(messages):
    """The writer answers with the page, the index and the stylesheet, each part after its marker."""
    with client.beta.messages.stream(
        model=WRITER_MODEL, max_tokens=64000,
        betas=["server-side-fallback-2026-07-01"], fallbacks="default",
        system=WRITER, messages=messages,
    ) as stream:
        message = stream.get_final_message()
    record(message)
    if message.stop_reason != "end_turn":
        raise SystemExit(f"{WRITER_MODEL} stopped early: {message.stop_reason}")
    text = text_of(message)
    messages.append({"role": "assistant", "content": text})
    parts = re.split(r"^===(SLUG|TITLE|SUMMARY|STYLE|PAGE|INDEX)===\s*$", text, flags=re.M)
    found = {parts[i]: parts[i + 1].strip() for i in range(1, len(parts) - 1, 2)}
    if set(found) != {"SLUG", "TITLE", "SUMMARY", "STYLE", "PAGE", "INDEX"}:
        raise SystemExit(f"{WRITER_MODEL} did not answer with all six parts: {text[:200]!r}")
    return {"slug": found["SLUG"].strip("` \n"), "title": found["TITLE"], "summary": found["SUMMARY"],
            "style.css": found["STYLE"], "page": found["PAGE"], "index.html": found["INDEX"]}


# ---- Checks and publishing ------------------------------------------------------------------

def broken_images(html):
    """The external image addresses in the page that are known not to exist. A host that will not
    answer a script (a 429 or 403 from Wikimedia, say) is not held against the picture."""
    bad = []
    for url in set(re.findall(r'<img[^>]+src="(https://[^"]+)"', html)):
        try:
            request = urllib.request.Request(url, method="HEAD",
                                             headers={"User-Agent": "researcher.py (an example script of webloyt.cloud)"})
            with urllib.request.urlopen(request, timeout=15) as response:
                if not response.headers.get("Content-Type", "").startswith("image/"):
                    bad.append(url)
        except urllib.error.HTTPError as error:
            if error.code in (404, 410):
                bad.append(url)
        except Exception:
            pass
    return bad


def webloyt(tool, **arguments):
    async def call():
        async with Client(f"{WEBLOYT}/mcp", auth=os.environ["WEBLOYT_TOKEN"]) as mcp:
            result = await mcp.call_tool(tool, arguments)
            return result.structured_content or json.loads(result.content[0].text)
    return asyncio.run(call())


def live(path):
    """A file of the site, or None."""
    try:
        result = webloyt("read_file", website_name=SITE, path=path)
    except ToolError:
        return None
    return result.get("content") if result.get("exists") else None


def upload(path, content, chat):
    """Publish one file; if the validator says no, the writer gets one chance to fix it."""
    try:
        return webloyt("upload_file", website_name=SITE, path=path, content=content)
    except ToolError as error:
        console.print(f"[yellow]{path}: {str(error)[:300]}")
        chat.append({"role": "user", "content": f"Webloyt rejected {path}: {str(error)[:600]}\n"
                     "Fix it and answer with all six parts again."})
        return None


def cost_report():
    table = Table(title="Token usage and estimated cost")
    for column in ("Model", "Input", "Output", "Cache write", "Cache read", "Cost"):
        table.add_column(column, justify="left" if column == "Model" else "right")
    total = 0
    for model, t in usage.items():
        p_in, p_out, p_write, p_read = PRICES.get(model, (0, 0, 0, 0))
        cost = (t["input"] * p_in + t["output"] * p_out + t["cache_write"] * p_write + t["cache_read"] * p_read) / 1e6
        total += cost
        table.add_row(model, f"{t['input']:,}", f"{t['output']:,}", f"{t['cache_write']:,}", f"{t['cache_read']:,}",
                      f"${cost:.2f}")
    search_cost = searches * SEARCH_PRICE / 1000
    total += search_cost
    table.add_row(f"web search × {searches}", "", "", "", "", f"${search_cost:.2f}")
    table.add_row("Total", "", "", "", "", f"[bold]${total:.2f}")
    console.print(table)


# ---- The run --------------------------------------------------------------------------------

if not os.environ.get("WEBLOYT_TOKEN"):
    pair()
try:
    webloyt("claim_website_name", website_name=SITE)
except ToolError:
    pass  # already ours
papers = json.loads(live("papers.json") or "[]")   # the papers explained so far, newest first
style = live("style.css")
OUT.mkdir(parents=True, exist_ok=True)

console.rule(f"[bold]The researcher, {RESEARCHER_MODEL}")
notes = research([p["title"] for p in papers])
console.print(notes.split("\n", 1)[0])  # the first line of the notes names the paper

console.rule(f"[bold]The writer, {WRITER_MODEL}")
chat = [{"role": "user", "content": (
    f"The researcher's notes:\n\n{notes}\n\n"
    + (f"The site's stylesheet, style.css:\n\n{style}\n\n" if style else "The site has no stylesheet yet; design it.\n\n")
    + "Papers already on the site, newest first, as JSON (title, summary, date, file): "
    + json.dumps(papers) + f"\nToday is {time.strftime('%Y-%m-%d')}.")}]
page = write(chat)
for attempt in range(2):  # photographs that do not load go back to the writer once or twice
    bad = broken_images(page["page"])
    if not bad:
        break
    console.print(f"[yellow]{len(bad)} photograph(s) do not load; asking the writer to replace or drop them")
    chat.append({"role": "user", "content": "These image addresses do not load; replace each with another "
                 "photograph from the notes or remove it, and answer with all six parts again:\n" + "\n".join(bad)})
    page = write(chat)
(OUT / f"{page['slug']}.md").write_text(notes, encoding="utf-8")
papers.insert(0, {"title": page["title"], "summary": page["summary"], "date": time.strftime("%Y-%m-%d"),
                  "file": f"{page['slug']}.html"})

console.rule("[bold]Publishing")
for attempt in range(2):
    files = {"style.css": page["style.css"], f"{page['slug']}.html": page["page"], "index.html": page["index.html"],
             "papers.json": json.dumps(papers, indent=1)}
    for path, content in files.items():
        (OUT / path).write_text(content, encoding="utf-8")
    rejected = False
    for path, content in files.items():
        result = upload(path, content, chat)
        if result is None:
            rejected = True
            break
        for warning in result.get("seo_warnings", []):
            console.print(f"  [yellow]{path}: {warning}")
        console.print(f"[dim]published {path}")
    if not rejected:
        break
    page = write(chat)
    papers[0].update(title=page["title"], summary=page["summary"], file=f"{page['slug']}.html")

console.rule()
console.print(f"Live at [link=https://{SITE}.webloyt.cloud/{page['slug']}.html]https://{SITE}.webloyt.cloud/{page['slug']}.html[/link]; "
              f"the files are in {OUT}/")
cost_report()
console.save_svg("researcher_run.svg", title="researcher.py")  # a picture of the run, for sharing