API documentationAPI reference

Code examples

Ready-to-run Python and TypeScript for the Recruiting API, and calling the Torre MCP server from your own code. Each example uses an API key from API keys in TORRE_API_KEY. For curl, see Recipes. To connect an AI assistant instead, use Connect to Torre; assistants sign in with OAuth and need no key.

Commands that create, publish, move or message change real data. Run them only for records you manage.

Python client

A minimal client that depends only on requests, with cursor pagination, typed errors and safe retries (reads retry on 429 and gateway errors; writes are never retried, so a 429 on a write raises and you decide when to send it again).

"""Minimal client for the Torre Recruiting API (https://api.torre.ai/docs).

Only depends on `requests`. Copy this file into your project or use it as a reference.

    from torre import Torre
    torre = Torre()                      # reads TORRE_API_KEY
    print(torre.get("/account"))
    for opening in torre.paginate("/openings"):
        print(opening["id"], opening["objective"])
"""

from __future__ import annotations

import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import Any, Iterator

import requests

BASE_URL = os.environ.get("TORRE_API_BASE_URL", "https://api.torre.ai/v1")

# Only requests that change nothing are retried. Torre does not deduplicate
# writes, so a write is never retried automatically.
_SAFE_METHODS = {"GET", "HEAD"}


class TorreError(Exception):
    """An error response from the Torre API.

    Branch on `code` (for example `opening_incomplete` or `opening_not_aligned`),
    not on `message`. Include `request_id` when you contact support.
    """

    def __init__(self, status: int, code: str | None, message: str, request_id: str | None, details: Any = None):
        super().__init__(f"{status} {code or ''}: {message} (request_id={request_id})")
        self.status = status
        self.code = code
        self.message = message
        self.request_id = request_id
        self.details = details


class Torre:
    def __init__(self, api_key: str | None = None, base_url: str = BASE_URL, timeout: float = 30.0, max_retries: int = 3):
        api_key = api_key or os.environ.get("TORRE_API_KEY")
        if not api_key:
            raise SystemExit("Set TORRE_API_KEY. Create a key at https://torre.ai/developer/api-keys")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.max_retries = max_retries
        self.session = requests.Session()
        self.session.headers.update(
            {
                "Authorization": f"Bearer {api_key}",
                "Accept": "application/json",
                "User-Agent": "torre-api-examples/1.0",
            }
        )

    def request(self, method: str, path: str, *, params: dict | None = None, json: Any = None) -> Any:
        method = method.upper()
        url = f"{self.base_url}/{path.lstrip('/')}"
        for attempt in range(self.max_retries + 1):
            response = self.session.request(method, url, params=params, json=json, timeout=self.timeout)
            retryable = method in _SAFE_METHODS and (
                response.status_code in (429, 502, 503, 504)
            )
            if retryable and attempt < self.max_retries:
                time.sleep(_retry_delay(response.headers.get("Retry-After"), attempt))
                continue
            if response.status_code >= 400:
                raise _to_error(response)
            return response.json() if response.content else None
        raise RuntimeError("unreachable")

    def get(self, path: str, **params: Any) -> Any:
        return self.request("GET", path, params={k: v for k, v in params.items() if v is not None})

    def post(self, path: str, body: Any = None) -> Any:
        return self.request("POST", path, json=body)

    def patch(self, path: str, body: Any) -> Any:
        return self.request("PATCH", path, json=body)

    def paginate(self, path: str, **params: Any) -> Iterator[dict]:
        """Yield every item of a cursor-paginated list (openings, applicants, job matches)."""
        cursor = None
        while True:
            page = self.get(path, **params, cursor=cursor)
            yield from page.get("data", [])
            pagination = page.get("pagination") or {}
            cursor = pagination.get("next_cursor")
            if not pagination.get("has_more") or not cursor:
                return


def _retry_delay(retry_after: str | None, attempt: int) -> float:
    """Seconds to wait: Retry-After in seconds or as an HTTP date, else exponential backoff."""
    if retry_after:
        try:
            return max(0.0, float(retry_after))
        except ValueError:
            pass
        try:
            when = parsedate_to_datetime(retry_after)
            return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
        except (TypeError, ValueError):
            pass
    return float(2 ** attempt)


def _to_error(response: requests.Response) -> TorreError:
    try:
        payload = response.json()
    except ValueError:
        return TorreError(response.status_code, None, response.text[:200], None)
    error = payload.get("error") or {}
    return TorreError(
        response.status_code,
        error.get("code"),
        error.get("message", ""),
        payload.get("request_id"),
        error.get("details"),
    )

Find candidates for an aligned opening

"""Use case: find candidates who match an aligned opening.

    python find_candidates.py OPENING_ID --size 25 --pages 1

The opening must be aligned (criteria confirmed) first; Torre answers 409
`opening_not_aligned` otherwise. Search results are contact-free public profiles.
Searches can take several seconds; the client waits up to 60.
"""
import argparse

from torre import Torre, TorreError

parser = argparse.ArgumentParser()
parser.add_argument("opening_id")
parser.add_argument("--size", type=int, default=25, help="results per page (fixed for the search)")
parser.add_argument("--pages", type=int, default=1, help="how many pages to fetch")
args = parser.parse_args()

torre = Torre(timeout=60)


def show(results, start):
    for i, candidate in enumerate(results, start):
        name = candidate.get("name") or candidate.get("fullName") or ""
        headline = candidate.get("professionalHeadline") or candidate.get("headline") or ""
        print(f"{i:3}. {name}  {headline}  (candidateId {candidate.get('candidateId')})")


try:
    page = torre.post("/candidate-searches", {"openingId": args.opening_id, "size": args.size})
except TorreError as e:
    if e.code == "opening_not_aligned":
        raise SystemExit("Align this opening first (confirm its criteria), then search again.")
    raise

search_id = page.get("searchId")
results = page.get("data") or []
show(results, 1)
count = len(results)

external = (page.get("external") or {}).get("included", False)
page_number = 1
while page_number < args.pages:
    page_number += 1
    if external:
        # Searches that include external candidates use page numbers.
        page = torre.get(f"/candidate-searches/{search_id}", page=page_number, pageSize=args.size)
    else:
        # Torre-only searches use an opaque cursor. An empty page can still carry one.
        if not page.get("hasMore") or not page.get("nextCursor"):
            break
        page = torre.get(f"/candidate-searches/{search_id}", cursor=page["nextCursor"])
    results = page.get("data") or []
    show(results, count + 1)
    count += len(results)

print(f"\n{count} candidates. Open one with: GET /v1/people/{{candidateId}}")

Create a draft, confirm alignment and publish

"""Use case: create a job opening from a plain-text description, then publish it.

    python publish_job.py --organization-id 123 --file job.txt            # create only
    python publish_job.py --organization-id 123 --file job.txt --publish  # create and publish

Torre structures the text into an unpublished draft. Publishing needs the opening to be
aligned (criteria confirmed): review the draft first, then pass --confirm-alignment once the
hiring manager approves the criteria, or --skip-alignment. Skipping alignment does not
bypass completeness: if fields are missing, Torre answers 422 `opening_incomplete` and
lists them, and this script prints them. Publishing on Torre's job network is free.
"""
import argparse
import sys

from torre import Torre, TorreError

parser = argparse.ArgumentParser()
parser.add_argument("--organization-id", type=int, required=True, help="from `python account.py`")
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--file", help="text file with the job description")
source.add_argument("--text", help="the job description itself")
parser.add_argument("--publish", action="store_true", help="publish after creating")
parser.add_argument("--confirm-alignment", action="store_true", help="confirm the current criteria before publishing")
parser.add_argument("--skip-alignment", action="store_true", help="publish without confirming criteria first")
args = parser.parse_args()

text = open(args.file, encoding="utf-8").read() if args.file else args.text
torre = Torre()

opening = torre.post("/openings", {"organization_id": args.organization_id, "sourceText": text})
print(f"Created draft opening {opening['id']} (status={opening.get('status')})")
print(f"  {opening.get('url')}")

if not args.publish:
    print("Not published. Review it, then rerun with --publish.")
    sys.exit(0)

if args.confirm_alignment:
    torre.request("PUT", f"/openings/{opening['id']}/alignment")
    print("Alignment confirmed.")

try:
    published = torre.post(
        f"/openings/{opening['id']}/publish",
        {"published": True, "skipAlignment": args.skip_alignment},
    )
    print(f"Published: {published.get('url')}")
except TorreError as e:
    if e.code == "opening_incomplete":
        fields = (e.details or {}).get("fields")
        print(f"Torre needs more information before publishing: {fields}")
        print(f"Fill them with PATCH /openings/{opening['id']}, then publish again.")
    elif e.status == 409:
        print(f"Can't publish yet: {e.message}")
        print("Review the criteria, then rerun with --confirm-alignment, or use --skip-alignment.")
    else:
        raise

Review applicants ranked by match

"""Use case: review applicants ranked by match, and move the best ones forward.

    python review_applicants.py OPENING_ID                               # read-only list
    python review_applicants.py OPENING_ID --move-top 3 --stage STAGE_ID # preview the move
    python review_applicants.py OPENING_ID --move-top 3 --stage STAGE_ID --yes

Moving applicants changes their stage, so nothing is written without --yes.
"""
import argparse
import itertools

from torre import Torre

parser = argparse.ArgumentParser()
parser.add_argument("opening_id")
parser.add_argument("--limit", type=int, default=25)
parser.add_argument("--move-top", type=int, default=0, help="move the N best-ranked applicants")
parser.add_argument("--stage", help="stage id to move them to")
parser.add_argument("--yes", action="store_true", help="really make the change")
args = parser.parse_args()

torre = Torre()
applicants = list(
    itertools.islice(
        torre.paginate(f"/openings/{args.opening_id}/applicants", sort="match_rank", limit=min(args.limit, 100)),
        args.limit,
    )
)

for i, a in enumerate(applicants, 1):
    score = a.get("matchScore")
    score = f"{score:.2f}" if isinstance(score, (int, float)) else "-"
    print(f"{i:3}. {a.get('name')}  match={score}  stage={a.get('stageId')}  status={a.get('status')}")

if args.move_top:
    if not args.stage:
        raise SystemExit("--move-top needs --stage")
    for a in applicants[: args.move_top]:
        if not args.yes:
            print(f"Would move {a.get('name')} to {args.stage} (add --yes to do it)")
            continue
        torre.patch(f"/openings/{args.opening_id}/applicants/{a['candidateId']}", {"stageId": args.stage})
        print(f"Moved {a.get('name')} to {args.stage}")

Copy applicants into your ATS

Check Data privacy before storing applicant data in another system.

"""Use case: pull applicants from every opening into your own ATS or CRM.

    python sync_applicants_to_csv.py applicants.csv

Writes one row per applicant per opening. Swap the CSV writer for your ATS's API.
Contact details are left out unless you pass --include-contact. Check Torre's terms
(https://torre.ai/terms) before storing applicant data in another system.
"""
import argparse
import csv

from torre import Torre

parser = argparse.ArgumentParser()
parser.add_argument("output")
parser.add_argument("--include-contact", action="store_true")
args = parser.parse_args()

torre = Torre()
fields = ["openingId", "opening", "candidateId", "name", "professionalHeadline", "stageId",
          "status", "matchStatus", "matchScore", "appliedAt", "reviewedAt"]
if args.include_contact:
    fields += ["email", "phone"]

rows = 0
with open(args.output, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
    writer.writeheader()
    for opening in torre.paginate("/openings", limit=100):
        for applicant in torre.paginate(f"/openings/{opening['id']}/applicants", limit=100):
            row = {**applicant, "openingId": opening["id"], "opening": opening.get("objective")}
            if args.include_contact:
                contact = applicant.get("contactInfo") or {}
                row["email"], row["phone"] = contact.get("email"), contact.get("phone")
            writer.writerow(row)
            rows += 1

print(f"Wrote {rows} applicants to {args.output}")

Jobs that match your profile

"""Use case (job seekers): find jobs that match your Torre profile and see why.

    python job_matches.py               # jobs ranked against your Genome and preferences
    python job_matches.py --remote      # search open remote jobs instead
    python job_matches.py --explain JOB_ID

Uses the key owner's own Torre profile. Read-only and free.
"""
import argparse

from torre import Torre

parser = argparse.ArgumentParser()
parser.add_argument("--remote", action="store_true", help="search remote jobs")
parser.add_argument("--explain", metavar="JOB_ID", help="show the match factors for one job")
parser.add_argument("--limit", type=int, default=10, help="1 to 20")
args = parser.parse_args()

torre = Torre()

if args.explain:
    job = torre.get(f"/jobs/{args.explain}")
    match = torre.get(f"/jobs/{args.explain}/match")
    print(f"{job['title']} at {', '.join(job.get('organizations', []))}: score {match.get('score')}")
    for factor in match.get("factors", []):
        print(f"  {factor['code']}: {factor.get('score')}" + ("  (missing information)" if factor.get("missingInformation") else ""))
    for req in match.get("requirements", []):
        print(f"  requirement {req['code']}: {'passed' if req.get('passed') else 'not passed'}")
else:
    if args.remote:
        page = torre.post("/jobs/search", {"onlyRemote": True, "torreOnly": True, "limit": args.limit})
    else:
        page = torre.get("/candidates/me/job-matches", limit=args.limit)
    # Each item is {"job": {"id", "title", "url"}, "match": {"score", ...}}.
    for item in page.get("data", []):
        job, match = item.get("job") or {}, item.get("match") or {}
        print(f"{job.get('id')}  {job.get('title')}  score={match.get('score', '-')}  {job.get('url', '')}")

TypeScript client

No dependencies beyond Node 18+ fetch. Run files with npx tsx.

// Minimal client for the Torre Recruiting API (https://api.torre.ai/docs).
// No dependencies: uses the fetch built into Node 18+.

const BASE_URL = process.env.TORRE_API_BASE_URL ?? "https://api.torre.ai/v1";

export class TorreError extends Error {
  constructor(
    public status: number,
    public code: string | undefined,
    message: string,
    public requestId: string | undefined,
    public details?: unknown,
  ) {
    super(`${status} ${code ?? ""}: ${message}${requestId ? ` (request_id=${requestId})` : ""}`);
  }
}

type Query = Record<string, string | number | boolean | undefined>;

export class Torre {
  private apiKey: string;

  constructor(apiKey = process.env.TORRE_API_KEY, private maxRetries = 3) {
    if (!apiKey) throw new Error("Set TORRE_API_KEY. Create a key at https://torre.ai/developer/api-keys");
    this.apiKey = apiKey;
  }

  async request<T = any>(method: string, path: string, opts: { query?: Query; body?: unknown } = {}): Promise<T> {
    const url = new URL(`${BASE_URL}/${path.replace(/^\//, "")}`);
    for (const [k, v] of Object.entries(opts.query ?? {})) if (v !== undefined) url.searchParams.set(k, String(v));

    for (let attempt = 0; ; attempt++) {
      const res = await fetch(url, {
        method,
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
          Accept: "application/json",
          ...(opts.body !== undefined ? { "Content-Type": "application/json" } : {}),
        },
        body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
      });
      // Only reads are retried. Torre does not deduplicate writes, so a write is never retried.
      const retryable = method === "GET" && [429, 502, 503, 504].includes(res.status);
      if (retryable && attempt < this.maxRetries) {
        // Retry-After may be seconds or an HTTP date; otherwise back off exponentially.
        const header = res.headers.get("Retry-After");
        const seconds = header === null ? NaN : Number(header);
        const dateMs = header === null ? NaN : Date.parse(header);
        const wait = Number.isFinite(seconds)
          ? Math.max(0, seconds)
          : Number.isFinite(dateMs)
            ? Math.max(0, (dateMs - Date.now()) / 1000)
            : 2 ** attempt;
        await res.body?.cancel(); // Release the connection before retrying.
        // setTimeout overflows past ~24.8 days, so cap the wait at one hour.
        await new Promise((r) => setTimeout(r, Math.min(wait, 3600) * 1000));
        continue;
      }
      const text = await res.text();
      let payload: any;
      try {
        payload = text ? JSON.parse(text) : undefined;
      } catch {
        payload = undefined; // A non-JSON body, such as a proxy error page.
      }
      if (!res.ok) {
        const e = payload?.error ?? {};
        throw new TorreError(res.status, e.code, e.message ?? text.slice(0, 200), payload?.request_id, e.details);
      }
      return payload as T;
    }
  }

  post<T = any>(path: string, body?: unknown) {
    return this.request<T>("POST", path, { body });
  }
}

Find candidates

// Use case: find candidates that match an aligned opening.
//   npx tsx find-candidates.ts OPENING_ID [size]
import { Torre, TorreError } from "./torre.js";

const [openingId, size = "25"] = process.argv.slice(2);
if (!openingId) throw new Error("usage: find-candidates.ts OPENING_ID [size]");

try {
  const page = await new Torre().post("/candidate-searches", { openingId, size: Number(size) });
  const results: any[] = page.data ?? [];
  results.forEach((c, i) =>
    console.log(`${String(i + 1).padStart(3)}. ${c.name ?? ""}  ${c.professionalHeadline ?? ""}  (${c.candidateId})`),
  );
  console.log(`\nsearchId ${page.searchId}. Next page: GET /v1/candidate-searches/${page.searchId}?cursor=...`);
} catch (e) {
  if (e instanceof TorreError && e.code === "opening_not_aligned") {
    console.log("Align this opening first (confirm its criteria), then search again.");
  } else throw e;
}

Create and publish a job

// Use case: create a job opening from a plain-text description and publish it.
//   npx tsx publish-job.ts 123 job.txt            (create only)
//   npx tsx publish-job.ts 123 job.txt --publish  (create and publish)
import { readFileSync } from "node:fs";
import { Torre, TorreError } from "./torre.js";

const [orgId, file, flag] = process.argv.slice(2);
if (!orgId || !file) throw new Error("usage: publish-job.ts ORGANIZATION_ID FILE [--publish]");

const torre = new Torre();
const opening = await torre.post("/openings", {
  organization_id: Number(orgId),
  sourceText: readFileSync(file, "utf8"),
});
console.log(`Created draft opening ${opening.id} (status=${opening.status})\n  ${opening.url}`);

if (flag === "--publish") {
  try {
    const published = await torre.post(`/openings/${opening.id}/publish`, { published: true });
    console.log(`Published: ${published.url}`);
  } catch (e) {
    if (e instanceof TorreError && e.code === "opening_incomplete") {
      console.log("Torre needs more information:", (e.details as any)?.fields);
    } else if (e instanceof TorreError && e.status === 409) {
      console.log(`Can't publish yet: ${e.message}. Confirm its criteria (alignment) first, then run this again.`);
    } else throw e;
  }
}

Call Torre from the Claude API

The Claude API's MCP connector connects to Torre for you in one request.

Your Torre API key travels in the request to the model provider (Anthropic here, OpenAI below), which uses it to call Torre for you. The provider holds the key's full access: the tool allowlist limits what the model calls, not what the key can do. Use a key made only for this app, keep it in your server's secret store, and revoke it in API keys if it leaks.

"""Call Torre's MCP server from your own app with the Claude API (MCP connector).

    pip install anthropic
    export ANTHROPIC_API_KEY=... TORRE_API_KEY=...
    python claude_api_mcp.py "List my openings and tell me which ones are aligned."

Anthropic connects to https://torre.ai/mcp for you; your code makes one API call.
"""
import os
import sys

import anthropic

prompt = " ".join(sys.argv[1:]) or "List my openings and tell me which ones are aligned."
client = anthropic.Anthropic()

with client.beta.messages.stream(
    model="claude-opus-5-5",
    max_tokens=64000,
    betas=["mcp-client-2025-11-20", "server-side-fallback-2026-07-01"],
    fallbacks="default",
    mcp_servers=[
        {
            "type": "url",
            "url": "https://torre.ai/mcp",
            "name": "torre",
            "authorization_token": os.environ["TORRE_API_KEY"],
        }
    ],
    # Only read-only tools are enabled, so the model can't publish, message or spend.
    # Enable a write tool by name only where a person reviews the result.
    tools=[
        {
            "type": "mcp_toolset",
            "mcp_server_name": "torre",
            "default_config": {"enabled": False},
            "configs": {
                name: {"enabled": True}
                for name in ["getAccount", "listOpenings", "getOpening", "getAlignment", "listApplicants", "searchJobs"]
            },
        }
    ],
    messages=[{"role": "user", "content": prompt}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    message = stream.get_final_message()

print()
if message.stop_reason == "refusal":
    print("Claude declined this request.")

Call Torre from the OpenAI Responses API

"""Call Torre's MCP server from the OpenAI Responses API.

    pip install openai
    export OPENAI_API_KEY=... TORRE_API_KEY=...
    python openai_responses_mcp.py "Find remote jobs that fit my profile."

`allowed_tools` limits the model to read-only Torre tools, so it runs without
approval prompts. To let it make changes, add those tools and set
`require_approval="always"`, then approve each `mcp_approval_request` (see OpenAI's MCP docs).
"""
import os
import sys

from openai import OpenAI

prompt = " ".join(sys.argv[1:]) or "Find remote jobs on Torre that fit my profile."
client = OpenAI()

response = client.responses.create(
    model=os.environ.get("OPENAI_MODEL", "gpt-5"),
    tools=[
        {
            "type": "mcp",
            "server_label": "torre",
            "server_url": "https://torre.ai/mcp",
            "headers": {"Authorization": f"Bearer {os.environ['TORRE_API_KEY']}"},
            "allowed_tools": ["getAccount", "searchJobs", "listOpenings", "getOpening", "getAlignment", "listApplicants"],
            "require_approval": "never",
        }
    ],
    input=prompt,
)
print(response.output_text)

List the MCP tools your key can use

"""List the tools the Torre MCP server exposes to your API key.

    python mcp_list_tools.py

Calls the MCP endpoint directly with JSON-RPC, the same way an MCP client does.
"""
import json
import os

import requests

key = os.environ.get("TORRE_API_KEY") or exit("Set TORRE_API_KEY")
response = requests.post(
    "https://torre.ai/mcp",
    headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2025-06-18",
    },
    json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
    timeout=30,
)
response.raise_for_status()
text = response.text
if text.lstrip().startswith("event:") or text.lstrip().startswith("data:"):
    # Streamable HTTP may answer as server-sent events; take the JSON from the data line.
    text = next(line[5:] for line in text.splitlines() if line.startswith("data:"))
for tool in json.loads(text)["result"]["tools"]:
    annotations = tool.get("annotations") or {}
    hint = annotations.get("readOnlyHint")
    flag = "read-only" if hint is True else "writes" if hint is False else "unmarked"
    summary = (tool.get("description") or "").strip().split("\n")[0][:80]
    print(f"{tool['name']:32} {flag:9} {summary}")

Run a Torre skill on a schedule

The recruiting skills in torre-labs/skills can run unattended with the Claude API. Unattended runs can only use read-only Torre tools and list proposed changes instead of making them.

"""Run a Torre recruiting skill as an unattended agent, from a script, cron job or CI.

    git clone https://github.com/torre-labs/skills
    pip install anthropic
    export ANTHROPIC_API_KEY=... TORRE_API_KEY=...
    python run_skill.py torre-hiring-pipeline-report "Write this week's report." --skills-dir skills/skills

The skill's instructions become the system prompt, and Claude calls the Torre MCP
server through the Claude API's MCP connector. There is no human in the loop here, so
only read-only Torre tools are enabled and the agent lists changes instead of making
them. --allow-tools replaces the read-only list; add a write tool only where a person
reviews every run. An unattended run has no browser for OAuth sign-in, so it uses a
Torre API key.
"""
import argparse
import os
import pathlib
import sys

import anthropic

# Tools that only read. Every other Torre tool stays disabled unless you pass --allow-tools.
READ_ONLY_TOOLS = [
    "getAccount", "listOpenings", "getOpening", "getAlignment", "listStages",
    "listScreeningQuestions", "listApplicants", "getApplicant", "listConversationMessages",
    "listCandidateJobMatches", "searchJobs", "getBalance", "listUsage",
]

parser = argparse.ArgumentParser()
parser.add_argument("skill", help="skill folder name, for example torre-hiring-pipeline-report")
parser.add_argument("task", help="what you want done")
parser.add_argument(
    "--allow-tools",
    default=",".join(READ_ONLY_TOOLS),
    help="comma-separated Torre tool names to enable; all others are disabled (default: read-only tools)",
)
parser.add_argument("--skills-dir", default="skills/skills", help="folder that holds the skill folders")
args = parser.parse_args()
SKILLS = pathlib.Path(args.skills_dir)

skill_file = SKILLS / args.skill / "SKILL.md"
if not skill_file.exists():
    sys.exit(f"No skill named {args.skill}. Choose from: {', '.join(p.name for p in SKILLS.iterdir())}")

# Drop the YAML front matter; the body is the instructions.
instructions = skill_file.read_text(encoding="utf-8").split("---", 2)[-1].strip()
system = (
    instructions
    + "\n\nYou are running unattended: nobody can approve changes. Do not create, update, publish,"
    " review, move or message anything. Where the steps say to wait for approval, list the"
    " proposed changes in your answer instead."
)

toolset = {
    "type": "mcp_toolset",
    "mcp_server_name": "torre",
    "default_config": {"enabled": False},
    "configs": {name.strip(): {"enabled": True} for name in args.allow_tools.split(",") if name.strip()},
}

client = anthropic.Anthropic()
with client.beta.messages.stream(
    model="claude-opus-5-5",
    max_tokens=64000,
    betas=["mcp-client-2025-11-20", "server-side-fallback-2026-07-01"],
    fallbacks="default",
    output_config={"effort": "high"},
    system=system,
    mcp_servers=[
        {
            "type": "url",
            "url": "https://torre.ai/mcp",
            "name": "torre",
            "authorization_token": os.environ["TORRE_API_KEY"],
        }
    ],
    tools=[toolset],
    messages=[{"role": "user", "content": args.task}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    message = stream.get_final_message()

print()
if message.stop_reason == "refusal":
    sys.exit("Claude declined this request.")