#!/usr/bin/env python3 """Official zero-dependency MCP server for the TESI Agent API (stdio JSON-RPC 2.0). Exposes TESI discovery, pre-spend credit quoting, Work starter shortlisting, recoverable Stripe Checkout / promotional key claiming, paid Ask and Work execution on an isolated TESI computer, and crash-safe turn receipt recovery. Requirements: Python 3.10+ standard library only (Linux or macOS). """ from __future__ import annotations import argparse from datetime import datetime, timezone import hashlib import http.client import json import os from pathlib import Path import re import secrets import stat import sys import time from typing import Any from urllib.parse import urlencode, urlsplit SERVER_NAME = "tesi-agent-mcp" SERVER_VERSION = "1.0.0" SUPPORTED_PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") DEFAULT_PROTOCOL = "2025-03-26" DEFAULT_ORIGIN = "https://toolsenabled.ai" PRODUCTION_ORIGINS = frozenset({"https://toolsenabled.ai", "https://toolsenabled.ai"}) API_PREFIX = "/api/v1/agents" MAX_RPC_BYTES = 2 * 1024 * 1024 MAX_REQUEST_BYTES = 1024 * 1024 MAX_OFFER_BYTES = 256 * 1024 MAX_RECEIPT_BYTES = 32 * 1024 * 1024 MAX_PROMPT_BYTES = 500_000 TURN_ID_RE = re.compile(r"mw_[a-f0-9]{32}") PURCHASE_ID_RE = re.compile(r"[a-f0-9]{64}") ORDER_ID_RE = re.compile(r"ago_[a-f0-9]{32}") SESSION_ID_RE = re.compile(r"cs_(?:live|test)_[A-Za-z0-9]{8,240}") KEY_RE = re.compile(r"tesi_ak_[A-Za-z0-9_-]{20,80}") KEY_SCRUB_RE = re.compile(r"tesi_ak_[A-Za-z0-9_-]{20,80}") KEY_ID_RE = re.compile(r"agk_[a-f0-9]{24}") WORKSPACE_ID_RE = re.compile(r"ws_[a-f0-9]{24}") HOST_HEADER_RE = re.compile(r"[a-z0-9.-]{1,253}(?::[0-9]{1,5})?") STARTER_ID_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,63}") SAFE_FILENAME_RE = re.compile(r"[A-Za-z0-9._-]{1,120}") USAGE_CURSOR_RE = re.compile(r"[A-Za-z0-9_-]{1,64}") PACK_SKIP_DIRS = frozenset({".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", ".pytest_cache", "tesi-purchase"}) PACK_SECRET_NAMES = frozenset({".env", "key.json", "purchase.json", "session.json", "confirmation.json", "credentials.json"}) PACK_SECRET_PATTERNS = re.compile( r"(?:tesi_ak_[A-Za-z0-9_-]{20,80}|sk_(?:live|test)_[A-Za-z0-9]{16,}|rk_(?:live|test)_[A-Za-z0-9]{16,}|whsec_[A-Za-z0-9_+/=-]{16,}|-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----)" ) FENCED_FILE_RE = re.compile( r"^```[A-Za-z0-9_+.-]*[ \t]+(?:path|file)=([^\s`]+)[ \t]*\r?\n(.*?)^```[ \t]*$", re.MULTILINE | re.DOTALL, ) EFFORTS = ("auto", "auto-fast", "auto-ultrafast", "low", "medium", "high", "xhigh", "max", "ultra") ECMASCRIPT_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff" PICO_PER_CENT = 10_000_000_000 PICO_PER_CREDIT = 1_000_000_000_000 TEMPORARY_HTTP_STATUSES = (408, 500, 502, 503, 504) class McpToolError(Exception): def __init__(self, code: str, message: str, **details: Any) -> None: super().__init__(message) self.payload = {"status": "error", "error": code, "message": message, **details} def scrub_secrets(value: Any) -> Any: if isinstance(value, str): return KEY_SCRUB_RE.sub("tesi_ak_[REDACTED]", value) if isinstance(value, list): return [scrub_secrets(item) for item in value] if isinstance(value, tuple): return [scrub_secrets(item) for item in value] if isinstance(value, dict): return {str(k): scrub_secrets(v) for k, v in value.items()} return value def format_credits(pico_str: str) -> str: digits = str(int(pico_str)).zfill(13) whole = digits[:-12] frac = digits[-12:].rstrip("0") or "00" if len(frac) == 1: frac += "0" return f"{whole}.{frac}" def parse_credits_to_pico(value: str) -> str: if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,13}(?:\.[0-9]{1,12})?", value.strip()): raise McpToolError("invalid_budget_credits", "Use nonnegative decimal TESI credits with up to 12 decimal places.") whole, _, fraction = value.strip().partition(".") return str(int(whole + fraction.ljust(12, "0"))) def body_fingerprint(mode: str, effort: str | None, trimmed_message: str) -> str: normalized = json.dumps([mode, effort, trimmed_message], ensure_ascii=False, separators=(",", ":")).encode("utf-8") return hashlib.sha256(normalized).hexdigest() def _is_secret_filename(name: str) -> bool: lower = name.lower() return ( lower in PACK_SECRET_NAMES or lower.startswith(".env.") or lower.endswith((".pem", ".key", ".p12", ".pfx")) or lower.startswith(("id_rsa", "id_ed25519")) ) def _validate_rel_posix(raw_path: Any) -> str | None: if ( not isinstance(raw_path, str) or not (1 <= len(raw_path) <= 200) or raw_path.startswith("/") or "\\" in raw_path or ":" in raw_path or any(ord(ch) < 32 for ch in raw_path) ): return None parts = raw_path.split("/") if any(part in ("", ".", "..") or part in PACK_SKIP_DIRS for part in parts): return None if _is_secret_filename(parts[-1]): return None return "/".join(parts) def pack_project_sources( source_dir_raw: str, prompt_text: str, include_paths_raw: list[str] | None = None, ) -> tuple[str, dict[str, Any]]: src_path = Path(source_dir_raw) if src_path.is_symlink() or not src_path.is_dir(): raise McpToolError("project_dir_unavailable", "sourceDir must be an existing non-symlink directory.") root = src_path.resolve() selected: list[tuple[str, Path]] = [] if include_paths_raw is not None: if not isinstance(include_paths_raw, list) or not include_paths_raw: raise McpToolError("invalid_include_paths", "includePaths must be a non-empty list of relative POSIX file paths.") seen_inc: set[str] = set() for raw_rel in include_paths_raw: clean_rel = _validate_rel_posix(raw_rel) if clean_rel is None: raise McpToolError("unsafe_source_path_refused", f"Unsafe or secret relative path refused: {raw_rel!r}") if clean_rel in seen_inc: continue seen_inc.add(clean_rel) candidate = root.joinpath(*clean_rel.split("/")) # Check no intermediate symlink escapes root cur = root for part in clean_rel.split("/"): cur = cur / part if cur.is_symlink(): raise McpToolError("unsafe_symlink_refused", f"Symlink refused in sourceDir: {clean_rel}") if not candidate.is_file(): raise McpToolError("source_file_missing", f"Included file does not exist: {clean_rel}") selected.append((clean_rel, candidate)) else: for current, dirs, filenames in os.walk(root, topdown=True, followlinks=False): cur_path = Path(current) if cur_path.is_symlink(): raise McpToolError("unsafe_symlink_refused", f"Symlink directory refused: {cur_path.relative_to(root)}") dirs[:] = sorted(d for d in dirs if d not in PACK_SKIP_DIRS and not d.startswith(".tesi")) for fname in sorted(filenames): if fname.endswith((".pyc", ".pyo")) or fname == ".DS_Store" or fname.startswith(".tesi"): continue full = cur_path / fname rel = full.relative_to(root).as_posix() if full.is_symlink(): raise McpToolError("unsafe_symlink_refused", f"Symlink file refused: {rel}") if _is_secret_filename(fname): raise McpToolError("secret_file_refused", f"Refusing to pack credential or secret file: {rel}") selected.append((rel, full)) if not selected: raise McpToolError("empty_project_dir", "No packable UTF-8 source files found in sourceDir.") manifest: list[dict[str, Any]] = [] sections: list[str] = [] total_bytes = 0 for rel, full in selected: try: data = full.read_bytes() except OSError as exc: raise McpToolError("project_file_unreadable", f"Could not read {rel}: {type(exc).__name__}") from None if len(data) > MAX_PROMPT_BYTES or b"\x00" in data: raise McpToolError("binary_or_oversize_file_refused", f"Binary or oversize file refused: {rel}") try: text = data.decode("utf-8") except UnicodeDecodeError: raise McpToolError("binary_or_oversize_file_refused", f"Non-UTF-8 file refused: {rel}") from None if PACK_SECRET_PATTERNS.search(text): raise McpToolError("secret_content_refused", f"Secret or credential token pattern detected in {rel}; refusing to transmit.") if "```" in text: raise McpToolError("triple_backtick_in_source_unsupported", f"Triple backticks in {rel} conflict with fenced transport.") total_bytes += len(data) digest = hashlib.sha256(data).hexdigest() manifest.append({"path": rel, "bytes": len(data), "sha256": digest}) ext = full.suffix.lstrip(".") or "text" body = text if text.endswith("\n") else text + "\n" sections.append(f"```{ext} path={rel}\n{body}```") header_lines = [ prompt_text.strip(ECMASCRIPT_SPACE), "", "Return every created or modified file in full as a fenced code block whose opening fence includes path= (for example: ```python path=app.py), followed by the exact test command and observed results.", "", f"Supplied project files ({len(manifest)} files, {total_bytes} UTF-8 bytes):", ] for item in manifest: header_lines.append(f"- {item['path']} ({item['bytes']} bytes, sha256={item['sha256']})") combined = "\n".join(header_lines) + "\n\n" + "\n\n".join(sections) return combined, {"fileCount": len(manifest), "sourceBytes": total_bytes, "files": manifest} def extract_fenced_files(reply_text: str, dest_dir_raw: str, request_id: str, reply_sha256: str) -> dict[str, Any]: if not isinstance(dest_dir_raw, str) or not dest_dir_raw.strip(): raise McpToolError("invalid_extract_dir", "extractFilesTo must be a non-empty directory path.") matches = list(FENCED_FILE_RE.finditer(reply_text)) if not matches: raise McpToolError("no_fenced_files_found", "Reply did not contain any ```lang path= fenced files.", requestId=request_id) planned: list[tuple[str, bytes, str]] = [] seen: set[str] = set() for match in matches: clean_rel = _validate_rel_posix(match.group(1)) if clean_rel is None or clean_rel == "TESI-DELIVERY-MANIFEST.json": raise McpToolError("unsafe_extract_path_refused", f"Refusing unsafe or reserved relative path in reply: {match.group(1)!r}") if clean_rel in seen: raise McpToolError("duplicate_extract_path_refused", f"Duplicate file path in reply: {clean_rel}") seen.add(clean_rel) raw_bytes = match.group(2).encode("utf-8") planned.append((clean_rel, raw_bytes, hashlib.sha256(raw_bytes).hexdigest())) dest_root = Path(dest_dir_raw).resolve() if dest_root.exists(): if dest_root.is_symlink() or not dest_root.is_dir() or any(dest_root.iterdir()): raise McpToolError("extract_destination_not_empty", f"Destination {dest_dir_raw} must be a new or empty directory.") else: dest_root.mkdir(parents=True, mode=0o700, exist_ok=False) manifest_rows: list[dict[str, Any]] = [] for rel_path, raw_bytes, file_sha in planned: out_file = dest_root.joinpath(*rel_path.split("/")) out_file.parent.mkdir(parents=True, mode=0o700, exist_ok=True) fd = os.open(out_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "wb") as stream: stream.write(raw_bytes) stream.flush() os.fsync(stream.fileno()) manifest_rows.append({"path": rel_path, "bytes": len(raw_bytes), "sha256": file_sha}) manifest_doc = { "schema": "tesi-extracted-delivery/v1", "requestId": request_id, "replySha256": reply_sha256, "fileCount": len(manifest_rows), "files": manifest_rows, } manifest_bytes = (json.dumps(manifest_doc, indent=2, sort_keys=True) + "\n").encode("utf-8") m_fd = os.open(dest_root / "TESI-DELIVERY-MANIFEST.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(m_fd, "wb") as stream: stream.write(manifest_bytes) stream.flush() os.fsync(stream.fileno()) return { "destinationDir": str(dest_root), "fileCount": len(manifest_rows), "files": manifest_rows, "manifestFile": str(dest_root / "TESI-DELIVERY-MANIFEST.json"), } def normalize_turn(mode: str, message: Any, effort: Any = None, request_id: Any = None) -> dict[str, Any]: if mode not in ("ask", "work"): raise McpToolError("invalid_mode", "mode must be 'ask' or 'work'.") if not isinstance(message, str): raise McpToolError("invalid_message", "message must be a UTF-8 string.") trimmed = message.strip(ECMASCRIPT_SPACE) prompt_bytes = len(trimmed.encode("utf-8")) if prompt_bytes < 1 or prompt_bytes > MAX_PROMPT_BYTES: raise McpToolError("invalid_message", f"Trimmed message must be 1 to {MAX_PROMPT_BYTES} UTF-8 bytes.") norm_effort: str | None = None if effort is not None: if not isinstance(effort, str) or effort not in EFFORTS: raise McpToolError("invalid_effort", f"effort must be one of {', '.join(EFFORTS)}.") norm_effort = effort if request_id is None: norm_id = "mw_" + secrets.token_hex(16) else: if not isinstance(request_id, str) or not TURN_ID_RE.fullmatch(request_id): raise McpToolError("invalid_request_id", "requestId must match mw_ followed by 32 lowercase hex digits.") norm_id = request_id digest = body_fingerprint(mode, norm_effort, trimmed) body: dict[str, Any] = {"requestId": norm_id, "mode": mode, "message": trimmed} if norm_effort is not None: body["effort"] = norm_effort raw_bytes = json.dumps(body, ensure_ascii=False).encode("utf-8") if len(raw_bytes) > MAX_REQUEST_BYTES: raise McpToolError("request_too_large", "Serialized JSON request exceeds 1 MiB.") return { "requestId": norm_id, "mode": mode, "effort": norm_effort, "trimmedMessage": trimmed, "promptBytes": prompt_bytes, "requestBodySha256": digest, "checkedHeader": f"{norm_id}.{digest}", "body": body, } class EndpointConfig: def __init__(self, raw_origin: str) -> None: parsed = urlsplit(raw_origin) if parsed.username or parsed.password or parsed.path not in ("", "/") or parsed.query or parsed.fragment: raise ValueError("Origin must be a bare scheme://host[:port] URL without path, query, or credentials.") normalized = f"{parsed.scheme}://{parsed.netloc}" allow_loopback = os.environ.get("TESI_ALLOW_LOOPBACK_ORIGIN") == "1" if normalized in PRODUCTION_ORIGINS: self.scheme = "https" self.connect_host = parsed.hostname or "toolsenabled.ai" self.connect_port = 443 self.host_header = self.connect_host self.public_origin = normalized self.expected_origins = set(PRODUCTION_ORIGINS) return if ( allow_loopback and parsed.scheme == "http" and parsed.hostname == "127.0.0.1" and parsed.port is not None and 1 <= parsed.port <= 65535 ): override_host = os.environ.get("TESI_HOST_HEADER", "").strip() if override_host and not HOST_HEADER_RE.fullmatch(override_host): raise ValueError("Invalid TESI_HOST_HEADER.") self.scheme = "http" self.connect_host = "127.0.0.1" self.connect_port = parsed.port self.host_header = override_host or f"127.0.0.1:{parsed.port}" public_scheme = "https" if override_host and ":" not in override_host else "http" self.public_origin = f"{public_scheme}://{self.host_header}" self.expected_origins = {self.public_origin, normalized} return raise ValueError( "Refusing untrusted TESI origin. Only https://toolsenabled.ai and https://toolsenabled.ai are allowed." ) def request( self, method: str, path: str, *, body: bytes | None = None, headers: dict[str, str] | None = None, timeout: float = 30.0, max_bytes: int = MAX_OFFER_BYTES, ) -> tuple[int, dict[str, str], bytes]: req_headers = {"Host": self.host_header, "Accept": "application/json", "Connection": "close"} if headers: req_headers.update(headers) if body is not None: req_headers.setdefault("Content-Type", "application/json") req_headers["Content-Length"] = str(len(body)) conn: http.client.HTTPConnection if self.scheme == "https": conn = http.client.HTTPSConnection(self.connect_host, self.connect_port, timeout=timeout) else: conn = http.client.HTTPConnection(self.connect_host, self.connect_port, timeout=timeout) try: conn.request(method, path, body=body, headers=req_headers) resp = conn.getresponse() resp_headers = {k.lower(): v for k, v in resp.getheaders()} data = resp.read(max_bytes + 1) if len(data) > max_bytes: raise McpToolError("response_too_large", f"Response from {path} exceeded {max_bytes} bytes.") return resp.status, resp_headers, data finally: conn.close() def request_json( self, method: str, path: str, *, payload: dict[str, Any] | None = None, headers: dict[str, str] | None = None, timeout: float = 30.0, max_bytes: int = MAX_OFFER_BYTES, ) -> tuple[int, dict[str, str], dict[str, Any]]: raw_body = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None status, resp_headers, data = self.request( method, path, body=raw_body, headers=headers, timeout=timeout, max_bytes=max_bytes ) ctype = resp_headers.get("content-type", "").split(";", 1)[0].strip().lower() if ctype != "application/json": raise McpToolError("unexpected_content_type", f"Expected application/json from {path}, got {ctype or 'empty'}.", httpStatus=status) try: parsed = json.loads(data.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError): raise McpToolError("invalid_json_response", f"Invalid JSON response from {path}.", httpStatus=status) from None if not isinstance(parsed, dict): raise McpToolError("invalid_json_response", f"Expected JSON object from {path}.", httpStatus=status) if status == 429: retry_raw = resp_headers.get("retry-after", "") retry_sec = int(retry_raw) if re.fullmatch(r"[0-9]{1,9}", retry_raw) else parsed.get("retryAfterSeconds") raise McpToolError("rate_limited", parsed.get("message", "Rate limit reached; wait before retrying."), httpStatus=429, retryAfterSeconds=retry_sec) return status, resp_headers, parsed class PrivateDir: """Private 0700 directory with atomic 0600 JSON files, compatible with tesi-buy.py.""" def __init__(self, path: Path, *, create: bool) -> None: if create: path.mkdir(mode=0o700, parents=True, exist_ok=True) flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0) try: self.fd = os.open(path, flags) except FileNotFoundError: raise McpToolError("directory_missing", f"Directory does not exist: {path}") from None except OSError as exc: raise McpToolError("directory_inaccessible", f"Could not open private directory {path}: {exc.strerror}") from None info = os.fstat(self.fd) if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700: os.close(self.fd) raise McpToolError("directory_must_be_private", f"Directory {path} must be owned by current user with mode 0700.") self.path = path def close(self) -> None: if getattr(self, "fd", None) is not None: os.close(self.fd) self.fd = None # type: ignore[assignment] def __enter__(self) -> "PrivateDir": return self def __exit__(self, *_: Any) -> None: self.close() def read_json(self, name: str, max_bytes: int = 16_384) -> dict[str, Any] | None: if not SAFE_FILENAME_RE.fullmatch(name): raise McpToolError("invalid_filename", "Unsafe state filename.") flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) try: fd = os.open(name, flags, dir_fd=self.fd) except FileNotFoundError: return None with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600: raise McpToolError("file_must_be_private", f"State file {name} must be a regular file with mode 0600.") raw = stream.read(max_bytes + 1) if len(raw) > max_bytes: raise McpToolError("invalid_state_file", f"State file {name} exceeds {max_bytes} bytes.") try: parsed = json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError): raise McpToolError("invalid_state_file", f"State file {name} is not valid JSON.") from None if not isinstance(parsed, dict): raise McpToolError("invalid_state_file", f"State file {name} must contain a JSON object.") return parsed def write_json(self, name: str, data: dict[str, Any], *, overwrite: bool = False) -> dict[str, Any]: if not SAFE_FILENAME_RE.fullmatch(name): raise McpToolError("invalid_filename", "Unsafe state filename.") temp_name = f".tmp-{secrets.token_hex(12)}" fd = os.open(temp_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=self.fd) try: with os.fdopen(fd, "wb") as stream: os.fchmod(stream.fileno(), 0o600) stream.write((json.dumps(data, sort_keys=True) + "\n").encode("utf-8")) stream.flush() os.fsync(stream.fileno()) if overwrite: os.replace(temp_name, name, src_dir_fd=self.fd, dst_dir_fd=self.fd) temp_name = "" else: try: os.link(temp_name, name, src_dir_fd=self.fd, dst_dir_fd=self.fd, follow_symlinks=False) except FileExistsError: pass finally: if temp_name: try: os.unlink(temp_name, dir_fd=self.fd) except FileNotFoundError: pass os.fsync(self.fd) saved = self.read_json(name) if saved is None: raise McpToolError("state_write_failed", f"Could not verify saved file {name}.") return saved def read_private_key_file(path: Path) -> str: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) try: fd = os.open(path, flags) except FileNotFoundError: raise McpToolError("key_file_missing", f"Key file not found: {path}") from None except OSError: raise McpToolError("key_file_must_be_private", f"Key file could not be opened safely: {path}") from None with os.fdopen(fd, "rb") as handle: info = os.fstat(handle.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600: raise McpToolError("key_file_must_be_private", f"Key file {path} must be owned by current user with mode 0600.") raw = handle.read(4097) if len(raw) > 4096: raise McpToolError("invalid_key_file", "Key file exceeds 4096 bytes.") text = raw.decode("utf-8", errors="strict").strip() if text.startswith("{"): try: obj = json.loads(text) except ValueError: raise McpToolError("invalid_key_file", "Key JSON file could not be parsed.") from None token = obj.get("apiKey") if isinstance(obj, dict) else None else: token = text if not isinstance(token, str) or not KEY_RE.fullmatch(token): raise McpToolError("invalid_api_key", "Key file does not contain a valid tesi_ak_... bearer key.") return token def resolve_bearer_key(configured_key_file: Path | None, *, required: bool = True) -> str | None: env_key_file = os.environ.get("TESI_KEY_FILE", "").strip() explicit_path = configured_key_file or (Path(env_key_file) if env_key_file else None) if explicit_path is not None: return read_private_key_file(explicit_path) env_key = os.environ.get("TESI_API_KEY", "").strip() if env_key: if not KEY_RE.fullmatch(env_key): raise McpToolError("invalid_api_key", "TESI_API_KEY does not match tesi_ak_... format.") return env_key default_file = Path("./tesi-purchase/key.json") if default_file.exists() or default_file.is_symlink(): return read_private_key_file(default_file) if required: raise McpToolError( "agent_key_required", "No TESI bearer key configured. Set TESI_API_KEY, pass --key-file ./tesi-purchase/key.json, or fund/claim a key with tesi_prepare_purchase and tesi_claim_key.", ) return None def state_root_dir() -> Path: override = os.environ.get("TESI_MCP_STATE_DIR", "").strip() if override: return Path(override) home = os.environ.get("HOME", "").strip() if home: return Path(home) / ".local" / "state" / "tesi-agent-mcp" return Path("./.tesi-mcp-state") def record_turn_journal(turn: dict[str, Any]) -> None: turns_dir = state_root_dir() / "turns" with PrivateDir(turns_dir, create=True) as store: filename = f"{turn['requestId']}.json" existing = store.read_json(filename) if existing is not None: if existing.get("requestBodySha256") != turn["requestBodySha256"] or existing.get("mode") != turn["mode"]: raise McpToolError( "local_request_id_conflict", "This requestId is already recorded locally for a different message, mode, or effort. Omit requestId to generate a fresh ID, or pass the original unchanged message to recover its receipt.", requestId=turn["requestId"], ) return store.write_json( filename, { "schema": 1, "requestId": turn["requestId"], "mode": turn["mode"], "effort": turn["effort"], "promptBytes": turn["promptBytes"], "requestBodySha256": turn["requestBodySha256"], "recordedAtMs": int(time.time() * 1000), }, ) def valid_checkout_url(url: Any) -> str: if not isinstance(url, str) or not url.startswith("https://checkout.stripe.com/"): raise McpToolError("invalid_checkout_url", "Server returned a non-Stripe Checkout URL.") parsed = urlsplit(url) if parsed.scheme != "https" or parsed.netloc != "checkout.stripe.com" or any(ch.isspace() for ch in url): raise McpToolError("invalid_checkout_url", "Server returned an invalid Stripe Checkout URL.") return url TOOLS: list[dict[str, Any]] = [ { "name": "tesi_discover", "description": "Read the free TESI Agent API offer, credit pack prices, rate limits, MCP/Skill metadata, and Work starters. Optionally verify public OpenAPI, MCP, Skill, and sample SHA-256 digests.", "annotations": { "title": "Discover TESI Offer & Starters", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "full": { "type": "boolean", "description": "Set true for the full /api/v1/agents catalog; false (default) reads compact /api/v1/agents/quickstart.", }, "verifyPublic": { "type": "boolean", "description": "Set true to also verify the OpenAPI spec, MCP server, Agent Skill, and newsletter sample SHA-256 checksums.", }, }, }, }, { "name": "tesi_quote", "description": "Quote exact minimum starting credit (and eligible USD packs) for a planned Ask or Work message without sending the prompt text over the network. Optionally price a reference token scenario and compare against your configured key balance.", "annotations": { "title": "Quote Starting Credit & Pack Coverage", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "message": { "type": "string", "description": "Draft Ask or Work message. Measured locally; only its UTF-8 byte count is sent for the quote.", }, "promptBytes": { "type": "integer", "minimum": 1, "maximum": MAX_PROMPT_BYTES, "description": "UTF-8 byte count when quoting without supplying a message.", }, "mode": {"type": "string", "enum": ["ask", "work"]}, "effort": {"type": "string", "enum": list(EFFORTS)}, "sourceDir": { "type": "string", "description": "Optional local directory of safe UTF-8 project files to pack and measure locally (only the resulting byte count is sent).", }, "includePaths": { "type": "array", "items": {"type": "string", "minLength": 1}, "description": "Optional relative POSIX file paths inside sourceDir to pack.", }, "inputTokens": {"type": "integer", "minimum": 0, "maximum": 1_000_000}, "outputTokens": {"type": "integer", "minimum": 0, "maximum": 1_000_000}, }, }, }, { "name": "tesi_shortlist_work", "description": "Compare public TESI Work starters (CSV cleanup, docs review, supplier merge spec, SQLite webhook service, clean-room download check, ledger reconciliation, responsive UI prototype) against a planned TESI credit budget or your configured bearer key's spendable balance.", "annotations": { "title": "Shortlist Work Starters by Budget", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "budgetCredits": { "type": "string", "description": "Optional decimal TESI credits (for example '0.001' or '10.00') to compare without an API key.", } }, }, }, { "name": "tesi_balance", "description": "Read the spendable prepaid TESI credit balance on your configured bearer key (reconciling up to 5 unsettled top-ups) and optionally read settled usage debits.", "annotations": { "title": "Read Key Balance & Settled Usage", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "includeUsage": { "type": "boolean", "description": "Set true to also list recent settled usage debits.", }, "windowHours": { "type": "integer", "minimum": 1, "maximum": 744, "description": "Optional rolling window (1-744 hours) to sum exact settled debits.", }, }, }, }, { "name": "tesi_usage", "description": "Inspect itemized settled debit charges (agc_... IDs, UTC settlement timestamps, and exact TESI credits) with cursor pagination, or compute rolling-window debit totals (1-744 hours) for per-job margin accounting.", "annotations": { "title": "Inspect Itemized Settled Usage Debits", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "limit": { "type": "integer", "minimum": 1, "maximum": 100, "description": "Number of settled debit charges to return (1-100, default 25).", }, "cursor": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$", "description": "nextCursor from a previous tesi_usage response.", }, "windowHours": { "type": "integer", "minimum": 1, "maximum": 744, "description": "Mutually exclusive with limit/cursor: sum settled debits over the last 1-744 hours.", }, }, }, }, { "name": "tesi_plan_topup", "description": "Read-only check comparing a planned message or byte count against your key's balance, held credits, and unsettled top-ups, returning the smallest recommended USD pack and purchaser review URL without opening Stripe Checkout.", "annotations": { "title": "Plan Same-Key Credit Top-Up", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "message": {"type": "string"}, "promptBytes": {"type": "integer", "minimum": 1, "maximum": MAX_PROMPT_BYTES}, }, }, }, { "name": "tesi_prepare_purchase", "description": "Review a USD credit pack or prepare/resume a recoverable Stripe Checkout session in a private 0700 directory (compatible with tesi-buy.py). Never charges without purchaser approval on Stripe.", "annotations": { "title": "Review or Prepare Credit Pack Purchase", "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "required": ["amountCents"], "properties": { "amountCents": { "type": "integer", "minimum": 100, "maximum": 1_000_000, "description": "Offered pack amount in USD cents (for example 1000 for $10).", }, "quoteOnly": { "type": "boolean", "description": "Set true to verify the pack and return a browser reviewUrl without creating a Stripe Checkout session.", }, "purchaseDir": { "type": "string", "description": "Private 0700 directory for this purchase (defaults to ./tesi-purchase).", }, }, }, }, { "name": "tesi_claim_key", "description": "Claim and save a funded TESI bearer key into a private 0600 key.json file (without exposing the raw secret in chat/logs), confirm saved delivery, or preview/redeem an issued promotional giftCode.", "annotations": { "title": "Claim or Redeem TESI Bearer Key", "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "purchaseDir": { "type": "string", "description": "Private 0700 directory holding purchase.json and session.json (defaults to ./tesi-purchase).", }, "confirmSaved": { "type": "boolean", "description": "Set true after claiming a Checkout key to confirm local custody and close the 48-hour recovery window.", }, "giftCode": { "type": "string", "minLength": 1, "description": "Optional promotional code to preview or redeem instead of a Checkout purchase.", }, "preview": { "type": "boolean", "description": "With giftCode, set true to check creditCents and redeemable without consuming the code.", }, }, }, }, { "name": "tesi_prepare_topup", "description": "Create or recover a Stripe Checkout top-up for your existing bearer key, read an existing open top-up link, or reconcile a paid top-up sessionId.", "annotations": { "title": "Prepare or Reconcile Same-Key Top-Up", "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "amountCents": {"type": "integer", "minimum": 100, "maximum": 1_000_000}, "sessionId": {"type": "string", "description": "Stripe Checkout cs_... session ID to reconcile after payment."}, "recoverOnly": { "type": "boolean", "description": "With amountCents, read an existing open top-up Checkout without creating a new session.", }, }, }, }, { "name": "tesi_ask", "description": "Run a paid read-only TESI Ask turn on your key's isolated TESI computer. Records a local crash-safe requestId before sending, sets TESI-Topup-Mode: manual by default, verifies replySha256, and automatically recovers via receipt if interrupted.", "annotations": { "title": "Ask TESI (Read-Only Paid Turn)", "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "required": ["message"], "properties": { "message": {"type": "string", "minLength": 1}, "effort": {"type": "string", "enum": list(EFFORTS)}, "requestId": { "type": "string", "pattern": "^mw_[a-f0-9]{32}$", "description": "Optional client requestId (mw_ + 32 lowercase hex) to make retries idempotent.", }, "waitSeconds": { "type": "integer", "minimum": 0, "maximum": 180, "description": "Seconds to poll the turn receipt if the initial HTTP connection drops or returns 409 recorded (default 60).", }, "allowAutoTopupCheckout": { "type": "boolean", "description": "Default false (sends TESI-Topup-Mode: manual so 402 never opens Checkout automatically).", }, }, }, }, { "name": "tesi_work", "description": "Commission a paid TESI Work deliverable on your key's isolated TESI computer (1 vCPU, 2 GB RAM, 4 GB disk). Supply a clear deliverable and acceptance checks. Uses crash-safe requestId journaling, verifies replySha256, and recovers interrupted turns via receipt.", "annotations": { "title": "Commission TESI Work Deliverable", "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "required": ["message"], "properties": { "message": { "type": "string", "minLength": 1, "description": "Work deliverable description (or complete brief).", }, "acceptanceChecks": { "type": "array", "items": {"type": "string", "minLength": 1}, "description": "Optional acceptance checks appended under 'Acceptance checks:' unless already included in message.", }, "effort": {"type": "string", "enum": list(EFFORTS)}, "requestId": { "type": "string", "pattern": "^mw_[a-f0-9]{32}$", "description": "Optional client requestId (mw_ + 32 lowercase hex) for idempotent submission and recovery.", }, "waitSeconds": { "type": "integer", "minimum": 0, "maximum": 180, "description": "Seconds to poll the turn receipt if the initial HTTP connection drops or returns 409 recorded (default 90).", }, "allowAutoTopupCheckout": { "type": "boolean", "description": "Default false (sends TESI-Topup-Mode: manual so 402 never opens Checkout automatically).", }, "sourceDir": { "type": "string", "description": "Optional local directory of UTF-8 project files to pack safely into the Work brief (refusing secrets, binaries, and symlinks).", }, "includePaths": { "type": "array", "items": {"type": "string", "minLength": 1}, "description": "Optional subset of relative POSIX file paths inside sourceDir to pack.", }, "extractFilesTo": { "type": "string", "description": "Optional new or empty local directory to extract ```lang path= fenced files from TESI's verified reply.", }, }, }, }, { "name": "tesi_receipt", "description": "Read a saved turn receipt by requestId (recovering verified replies without re-running or double-spending), optionally export the verified reply or extract fenced project files into a clean local directory, or list recent receipts for your key.", "annotations": { "title": "Read or List Turn Receipts", "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True, }, "inputSchema": { "type": "object", "additionalProperties": False, "properties": { "requestId": {"type": "string", "pattern": "^mw_[a-f0-9]{32}$"}, "expectedRequestBodySha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "waitSeconds": {"type": "integer", "minimum": 0, "maximum": 180}, "saveReplyTo": { "type": "string", "description": "Optional new file path to write the verified UTF-8 reply when status is result_ready.", }, "extractFilesTo": { "type": "string", "description": "Optional new or empty local directory to extract ```lang path= fenced files when status is result_ready.", }, "listReceipts": {"type": "boolean", "description": "Set true to list recent receipts instead of reading one requestId."}, "mode": {"type": "string", "enum": ["ask", "work"]}, "delivery": {"type": "string", "enum": ["ready", "unresolved"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "cursor": {"type": "string", "pattern": "^mw_[a-f0-9]{32}$"}, }, }, }, ] class TesiMcpRuntime: def __init__(self, endpoint: EndpointConfig, key_file: Path | None = None) -> None: self.endpoint = endpoint self.key_file = key_file def _reject_secret_args(self, args: dict[str, Any]) -> None: for forbidden in ("apiKey", "bearerKey", "authorization"): if forbidden in args: raise McpToolError( "secret_in_arguments_refused", f"Never pass {forbidden} in MCP tool arguments. Configure TESI_API_KEY or --key-file (mode 0600) instead.", ) def call_tool(self, name: str, raw_args: Any) -> dict[str, Any]: if raw_args is None: args: dict[str, Any] = {} elif isinstance(raw_args, dict): args = raw_args else: raise McpToolError("invalid_arguments", "Tool arguments must be a JSON object.") self._reject_secret_args(args) dispatch = { "tesi_discover": self._tool_discover, "tesi_quote": self._tool_quote, "tesi_shortlist_work": self._tool_shortlist_work, "tesi_balance": self._tool_balance, "tesi_usage": self._tool_usage, "tesi_plan_topup": self._tool_plan_topup, "tesi_prepare_purchase": self._tool_prepare_purchase, "tesi_claim_key": self._tool_claim_key, "tesi_prepare_topup": self._tool_prepare_topup, "tesi_ask": lambda a: self._tool_turn("ask", a), "tesi_work": lambda a: self._tool_turn("work", a), "tesi_receipt": self._tool_receipt, } handler = dispatch.get(name) if handler is None: raise KeyError(f"Unknown tool: {name}") return handler(args) def _verify_public_assets(self, full_offer: dict[str, Any]) -> list[dict[str, Any]]: checks: list[dict[str, Any]] = [] evidence = full_offer.get("buyerGuide", {}).get("publicEvidence", {}) mcp_meta = full_offer.get("buyerGuide", {}).get("mcpServer", {}) status, headers, raw_oa = self.endpoint.request( "GET", "/agents/openapi.yaml", headers={"Accept": "application/yaml"}, max_bytes=256 * 1024 ) if status != 200 or headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/yaml": raise McpToolError("public_check_failed", "OpenAPI document check failed.", failedCheck="openapi", httpStatus=status) oa_text = raw_oa.decode("utf-8") ver_match = re.search(r"^openapi: (3\.1\.[0-9]+)[ \t]*$", oa_text, re.MULTILINE) ops = set(re.findall(r"^[ \t]+operationId: ([A-Za-z]+)[ \t]*$", oa_text, re.MULTILINE)) req_ops = {"discoverAgentOffer", "askTESI", "commissionTESIWork", "readAgentTurnReceipt"} if not ver_match or not req_ops <= ops: raise McpToolError("public_check_failed", "OpenAPI version or required operations missing.", failedCheck="openapi") checks.append({"id": "openapi", "version": ver_match.group(1), "bytes": len(raw_oa)}) if isinstance(mcp_meta.get("sha256"), str): status, headers, raw_mcp = self.endpoint.request( "GET", "/agents/tesi-agent-mcp.py.txt", headers={"Accept": "text/plain"}, max_bytes=256 * 1024 ) digest = hashlib.sha256(raw_mcp).hexdigest() if status != 200 or digest != mcp_meta["sha256"]: raise McpToolError("public_check_failed", "MCP server SHA-256 mismatch.", failedCheck="mcp_server") checks.append({"id": "mcp_server", "sha256": digest, "bytes": len(raw_mcp)}) if isinstance(evidence.get("skillSha256"), str): status, headers, raw_skill = self.endpoint.request( "GET", "/agents/SKILL.md", headers={"Accept": "text/markdown"}, max_bytes=128 * 1024 ) digest = hashlib.sha256(raw_skill).hexdigest() if status != 200 or digest != evidence["skillSha256"]: raise McpToolError("public_check_failed", "SKILL.md SHA-256 mismatch.", failedCheck="skill") checks.append({"id": "skill", "sha256": digest, "bytes": len(raw_skill)}) sample_hash = evidence.get("sampleSha256") status, headers, raw_zip = self.endpoint.request( "GET", "/agents/examples/newsletter.zip", headers={"Accept": "application/zip"}, max_bytes=512 * 1024 ) zip_digest = hashlib.sha256(raw_zip).hexdigest() if status != 200 or zip_digest != sample_hash: raise McpToolError("public_check_failed", "Sample newsletter.zip SHA-256 mismatch.", failedCheck="sample") checks.append({"id": "sample", "sha256": zip_digest, "bytes": len(raw_zip)}) return checks def _tool_discover(self, args: dict[str, Any]) -> dict[str, Any]: full = bool(args.get("full", False)) verify_public = bool(args.get("verifyPublic", False)) path = API_PREFIX if (full or verify_public) else f"{API_PREFIX}/quickstart" status, _, data = self.endpoint.request_json("GET", path) if status != 200: raise McpToolError("discovery_unavailable", "Could not read TESI discovery endpoint.", httpStatus=status) result: dict[str, Any] = {"status": "offer_ready"} if verify_public: checks = self._verify_public_assets(data) if not full: _, _, compact = self.endpoint.request_json("GET", f"{API_PREFIX}/quickstart") result["offer"] = compact else: result["offer"] = data result["publicChecks"] = checks else: result["offer"] = data return result def _tool_quote(self, args: dict[str, Any]) -> dict[str, Any]: has_msg = "message" in args and args["message"] is not None has_src = "sourceDir" in args and args["sourceDir"] is not None has_bytes = "promptBytes" in args and args["promptBytes"] is not None if (has_msg or has_src) and has_bytes: raise McpToolError("invalid_arguments", "Supply either message/sourceDir or promptBytes, not both.") local_turn = None packed_meta = None if has_src: base_msg = args["message"] if has_msg else "Review and update the supplied project." packed_msg, packed_meta = pack_project_sources(args["sourceDir"], base_msg, args.get("includePaths")) mode = args.get("mode", "work") local_turn = normalize_turn(mode, packed_msg, args.get("effort")) prompt_bytes = local_turn["promptBytes"] elif has_msg: mode = args.get("mode", "work") local_turn = normalize_turn(mode, args["message"], args.get("effort")) prompt_bytes = local_turn["promptBytes"] elif has_bytes: prompt_bytes = args["promptBytes"] if type(prompt_bytes) is not int or not (1 <= prompt_bytes <= MAX_PROMPT_BYTES): raise McpToolError("invalid_prompt_bytes", f"promptBytes must be an integer from 1 to {MAX_PROMPT_BYTES}.") else: prompt_bytes = None out: dict[str, Any] = {"status": "quote_ready"} if packed_meta is not None: out["packedProject"] = packed_meta if prompt_bytes is not None: query = urlencode({"promptBytes": prompt_bytes, "includePacks": "1"}) status, _, quote = self.endpoint.request_json("GET", f"{API_PREFIX}/starting-credit?{query}") if status != 200: raise McpToolError("quote_failed", quote.get("message", "Could not read starting credit."), httpStatus=status) min_pico = quote["minimumAvailablePico"] smallest = quote.get("packOptions", {}).get("smallestEligibleAmountCents") out["startingCredit"] = { **quote, "minimumAvailableCredits": format_credits(min_pico), **( {"reviewUrl": f"{self.endpoint.public_origin}/agents/?agentPack={smallest}#agent-funding"} if smallest is not None else {} ), } if local_turn is not None: out["localValidation"] = { "mode": local_turn["mode"], "effort": local_turn["effort"], "promptBytes": local_turn["promptBytes"], "requestBodySha256": local_turn["requestBodySha256"], } key = resolve_bearer_key(self.key_file, required=False) if key is not None: b_status, _, bal = self.endpoint.request_json( "GET", f"{API_PREFIX}/balance", headers={"Authorization": f"Bearer {key}"} ) if b_status == 200: avail_pico = int(bal["availablePico"]) out["keyComparison"] = { "keyId": bal["keyId"], "availablePico": bal["availablePico"], "availableCredits": format_credits(bal["availablePico"]), "availableUsd": bal["availableUsd"], "meetsStartingCredit": avail_pico >= int(min_pico), } in_tok = args.get("inputTokens") out_tok = args.get("outputTokens") if in_tok is not None or out_tok is not None: if type(in_tok) is not int or type(out_tok) is not int or in_tok < 0 or out_tok < 0 or in_tok + out_tok == 0: raise McpToolError("invalid_tokens", "Provide nonnegative integer inputTokens and outputTokens with at least 1 token.") c_query = urlencode({"inputTokens": in_tok, "outputTokens": out_tok, "includePacks": "1"}) c_status, _, cost_ex = self.endpoint.request_json("GET", f"{API_PREFIX}/cost-example?{c_query}") if c_status != 200: raise McpToolError("cost_example_failed", cost_ex.get("message", "Could not read cost example."), httpStatus=c_status) out["referenceCallCost"] = { **cost_ex, "costCredits": format_credits(cost_ex["costPico"]), } if prompt_bytes is None and in_tok is None: raise McpToolError("invalid_arguments", "Provide message, promptBytes, or inputTokens + outputTokens.") return out def _tool_shortlist_work(self, args: dict[str, Any]) -> dict[str, Any]: status, _, offer = self.endpoint.request_json("GET", f"{API_PREFIX}/quickstart") if status != 200 or offer.get("available") is not True: raise McpToolError("catalog_unavailable", "TESI Work starter catalog is currently unavailable.", httpStatus=status) starters = offer.get("workStarters", []) budget_raw = args.get("budgetCredits") if budget_raw is not None: available_pico_str = parse_credits_to_pico(budget_raw) source = "planned_budget" else: key = resolve_bearer_key(self.key_file, required=False) if key is not None: b_status, _, bal = self.endpoint.request_json( "GET", f"{API_PREFIX}/balance", headers={"Authorization": f"Bearer {key}"} ) if b_status != 200: raise McpToolError("balance_unavailable", bal.get("message", "Could not read key balance."), httpStatus=b_status) available_pico_str = bal["availablePico"] source = "key_balance" else: available_pico_str = parse_credits_to_pico("10.00") source = "default_10_usd_pack_example" avail = int(available_pico_str) matches = [] nearest = None for row in starters: req_pico = int(row["minimumAvailablePico"]) gap = req_pico - avail item = { "id": row["id"], "title": row["title"], "expectedOutput": row["expectedOutput"], "suggestedEffort": row.get("suggestedEffort"), "minimumAvailablePico": row["minimumAvailablePico"], "minimumAvailableCredits": format_credits(row["minimumAvailablePico"]), "browserPreviewUrl": row["browserPreviewUrl"], "acceptanceChecks": row.get("acceptanceChecks", []), } for extra in ("referenceFiles", "referenceCheck", "acceptanceFixture", "offlineChecker", "sampleDeliverable"): if extra in row: item[extra] = row[extra] if gap <= 0: matches.append(item) elif nearest is None or gap < int(nearest["shortfallPico"]): nearest = {**item, "shortfallPico": str(gap), "shortfallCredits": format_credits(str(gap))} res: dict[str, Any] = { "status": "work_shortlist_ready", "balanceSource": source, "availablePico": available_pico_str, "availableCredits": format_credits(available_pico_str), "matches": matches, } if nearest is not None: res["nearestUnaffordableStarter"] = nearest if not matches and "sampleProject" in offer: res["sampleProject"] = offer["sampleProject"] return res def _tool_balance(self, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None auth = {"Authorization": f"Bearer {key}"} status, _, bal = self.endpoint.request_json("GET", f"{API_PREFIX}/balance", headers=auth) if status != 200: raise McpToolError(bal.get("error", "balance_failed"), bal.get("message", "Balance read failed."), httpStatus=status) result: dict[str, Any] = { "status": "balance_ready", "balance": {**bal, "availableCredits": format_credits(bal["availablePico"])}, } window_hours = args.get("windowHours") if window_hours is not None: if type(window_hours) is not int or not (1 <= window_hours <= 744): raise McpToolError("invalid_window_hours", "windowHours must be an integer from 1 to 744.") u_status, _, win = self.endpoint.request_json( "GET", f"{API_PREFIX}/usage?{urlencode({'windowHours': window_hours})}", headers=auth ) if u_status != 200: raise McpToolError(win.get("error", "usage_failed"), win.get("message", "Usage window read failed."), httpStatus=u_status) result["usageWindow"] = {**win, "debitCredits": format_credits(win["debitPico"])} elif args.get("includeUsage"): u_status, _, page = self.endpoint.request_json("GET", f"{API_PREFIX}/usage", headers=auth) if u_status != 200: raise McpToolError(page.get("error", "usage_failed"), page.get("message", "Usage read failed."), httpStatus=u_status) result["usage"] = {"charges": page.get("charges", []), "nextCursor": page.get("nextCursor")} return result def _tool_usage(self, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None auth = {"Authorization": f"Bearer {key}"} window_hours = args.get("windowHours") limit = args.get("limit") cursor = args.get("cursor") if window_hours is not None: if limit is not None or cursor is not None: raise McpToolError("invalid_arguments", "windowHours cannot be combined with limit or cursor.") if type(window_hours) is not int or not (1 <= window_hours <= 744): raise McpToolError("invalid_window_hours", "windowHours must be an integer from 1 to 744.") status, _, win = self.endpoint.request_json( "GET", f"{API_PREFIX}/usage?{urlencode({'windowHours': window_hours})}", headers=auth ) if status != 200: raise McpToolError(win.get("error", "usage_failed"), win.get("message", "Usage window read failed."), httpStatus=status) return { "status": "usage_window_ready", **win, "debitCredits": format_credits(win["debitPico"]), } params: dict[str, Any] = {} if limit is not None: if type(limit) is not int or not (1 <= limit <= 100): raise McpToolError("invalid_limit", "limit must be an integer from 1 to 100.") params["limit"] = limit if cursor is not None: if not isinstance(cursor, str) or not USAGE_CURSOR_RE.fullmatch(cursor): raise McpToolError("invalid_cursor", "Use nextCursor from a previous tesi_usage response.") params["cursor"] = cursor query = f"?{urlencode(params)}" if params else "" status, _, page = self.endpoint.request_json("GET", f"{API_PREFIX}/usage{query}", headers=auth) if status != 200: raise McpToolError(page.get("error", "usage_failed"), page.get("message", "Usage ledger read failed."), httpStatus=status) charges = [] for row in page.get("charges", []): settled_ms = row.get("settledAt") settled_utc = ( datetime.fromtimestamp(settled_ms / 1000.0, tz=timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") if isinstance(settled_ms, int) and settled_ms >= 0 else None ) charges.append( { **row, "debitCredits": format_credits(row["debitPico"]), **({"settledAtUtc": settled_utc} if settled_utc else {}), } ) bal = page.get("balance", {}) return { "status": "usage_ready", "creditUnit": page.get("creditUnit", "TESI credits"), "observedAt": page.get("observedAt"), "balance": { **bal, **({"availableCredits": format_credits(bal["availablePico"])} if "availablePico" in bal else {}), }, "charges": charges, "nextCursor": page.get("nextCursor"), } def _tool_plan_topup(self, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None if "message" in args and args["message"] is not None: prompt_bytes = normalize_turn("work", args["message"])["promptBytes"] elif type(args.get("promptBytes")) is int and 1 <= args["promptBytes"] <= MAX_PROMPT_BYTES: prompt_bytes = args["promptBytes"] else: raise McpToolError("invalid_arguments", "Supply message or promptBytes (1..500000).") status, _, plan = self.endpoint.request_json( "GET", f"{API_PREFIX}/topup?{urlencode({'promptBytes': prompt_bytes})}", headers={"Authorization": f"Bearer {key}"}, ) if status != 200: raise McpToolError(plan.get("error", "topup_plan_failed"), plan.get("message", "Could not read top-up plan."), httpStatus=status) rec = plan.get("recommendedAmountCents") return { "status": "topup_plan_ready", **plan, "availableCredits": format_credits(plan["availablePico"]), "minimumAvailableCredits": format_credits(plan["minimumAvailablePico"]), "shortfallCredits": format_credits(plan["shortfallPico"]), **( {"reviewUrl": f"{self.endpoint.public_origin}/agents/?agentPack={rec}#agent-funding"} if rec is not None else {} ), } def _tool_prepare_purchase(self, args: dict[str, Any]) -> dict[str, Any]: amount = args.get("amountCents") if type(amount) is not int or not (100 <= amount <= 1_000_000): raise McpToolError("invalid_amount_cents", "amountCents must be an integer from 100 to 1000000.") status, _, offer = self.endpoint.request_json("GET", API_PREFIX) if status != 200 or offer.get("available") is not True: raise McpToolError("offer_unavailable", "TESI Agent API is currently unavailable.", httpStatus=status) offered = offer.get("amountsCents", []) if amount not in offered: raise McpToolError("pack_unavailable", "Choose one of the currently offered amountsCents.", advertisedAmountsCents=offered) review_url = f"{self.endpoint.public_origin}/agents/?agentPack={amount}#agent-funding" if args.get("quoteOnly"): return { "status": "pack_review_ready", "amountCents": amount, "currency": "usd", "reviewUrl": review_url, } purchase_dir = Path(args.get("purchaseDir") or "./tesi-purchase") with PrivateDir(purchase_dir, create=True) as store: purchase = store.read_json("purchase.json") if purchase is None: purchase = store.write_json( "purchase.json", {"schema": 1, "amountCents": amount, "purchaseId": secrets.token_hex(32)}, ) if purchase.get("amountCents") != amount or not PURCHASE_ID_RE.fullmatch(str(purchase.get("purchaseId", ""))): raise McpToolError( "purchase_amount_already_fixed", f"Directory {purchase_dir} already tracks a purchase for {purchase.get('amountCents')} cents. Use a new purchaseDir for a different pack.", ) prior_session = store.read_json("session.json") p_status, _, data = self.endpoint.request_json( "POST", f"{API_PREFIX}/keys", payload={"amountCents": amount, "purchaseId": purchase["purchaseId"]}, ) if p_status not in (200, 402): raise McpToolError(data.get("error", "purchase_failed"), data.get("message", "Could not prepare Checkout."), httpStatus=p_status) order_id = data.get("orderId") if not isinstance(order_id, str) or not ORDER_ID_RE.fullmatch(order_id): raise McpToolError("unconfirmed_checkout", "Missing valid orderId in purchase response.") if prior_session and prior_session.get("orderId") != order_id: raise McpToolError("checkout_mismatch", "Order ID changed unexpectedly for saved purchase.") state = data.get("status") out: dict[str, Any] = { "status": state, "orderId": order_id, "amountCents": amount, "currency": "usd", "purchaseDir": str(purchase_dir), "reviewUrl": review_url, } if state in ("expired", "refunded"): return out if state == "claimed": return out session_id = data.get("sessionId") if not isinstance(session_id, str) or not SESSION_ID_RE.fullmatch(session_id): raise McpToolError("unconfirmed_checkout", "Missing valid Stripe sessionId.") store.write_json( "session.json", { "orderId": order_id, "purchaseDigest": hashlib.sha256(purchase["purchaseId"].encode("ascii")).hexdigest(), "sessionId": session_id, }, ) out["sessionId"] = session_id if state == "open": out["checkoutUrl"] = valid_checkout_url(data.get("checkoutUrl")) out["nextStep"] = "Present checkoutUrl to the human purchaser. After payment, call tesi_claim_key with the same purchaseDir." elif state == "paid": out["nextStep"] = "Payment settled. Call tesi_claim_key with the same purchaseDir to save the key privately." return out def _save_key_Target(self, purchase_dir: Path) -> Path: env_key_file = os.environ.get("TESI_KEY_FILE", "").strip() return self.key_file or (Path(env_key_file) if env_key_file else purchase_dir / "key.json") def _tool_claim_key(self, args: dict[str, Any]) -> dict[str, Any]: purchase_dir = Path(args.get("purchaseDir") or "./tesi-purchase") gift_code = args.get("giftCode") if gift_code is not None: if not isinstance(gift_code, str) or not gift_code.strip(): raise McpToolError("invalid_gift_code", "giftCode must be a non-empty string.") preview = bool(args.get("preview", False)) payload: dict[str, Any] = {"giftCode": gift_code.strip()} if preview: payload["preview"] = True status, _, data = self.endpoint.request_json("POST", f"{API_PREFIX}/keys", payload=payload) if preview: if status != 200: raise McpToolError(data.get("error", "gift_preview_failed"), data.get("message", "Could not preview giftCode."), httpStatus=status) return {"status": "gift_preview_ready", **data} if status != 201: raise McpToolError(data.get("error", "gift_claim_failed"), data.get("message", "Could not redeem giftCode."), httpStatus=status) api_key = data.get("apiKey") key_id = data.get("keyId") ws_id = data.get("workspaceId") if not (isinstance(api_key, str) and KEY_RE.fullmatch(api_key) and isinstance(key_id, str) and isinstance(ws_id, str)): raise McpToolError("unconfirmed_claim", "Key response lacked valid key fields.") target_file = self._save_key_Target(purchase_dir) with PrivateDir(target_file.parent, create=True) as store: store.write_json( target_file.name, {"apiKey": api_key, "funding": "promotional", "keyId": key_id, "workspaceId": ws_id}, overwrite=True, ) return { "status": "key_saved_locally", "funding": "promotional", "keyId": key_id, "keyPrefix": data.get("keyPrefix", api_key[:14]), "workspaceId": ws_id, "creditCents": data.get("creditCents"), "availablePico": data.get("availablePico"), "credentialFile": str(target_file), } with PrivateDir(purchase_dir, create=False) as store: purchase = store.read_json("purchase.json") session = store.read_json("session.json") if not purchase or not session: raise McpToolError("purchase_files_missing", f"Expected purchase.json and session.json in {purchase_dir}.") existing = store.read_json("key.json") body = {"sessionId": session["sessionId"], "purchaseId": purchase["purchaseId"]} if existing is None: status, _, data = self.endpoint.request_json("POST", f"{API_PREFIX}/keys", payload=body) if status == 402: return { "status": "payment_pending" if data.get("error") == "payment_required" else data.get("error", "unpaid"), "sessionId": session["sessionId"], "message": data.get("message", "Payment has not settled yet."), } if status not in (200, 201): raise McpToolError(data.get("error", "claim_failed"), data.get("message", "Key claim failed."), httpStatus=status) api_key = data.get("apiKey") key_id = data.get("keyId") ws_id = data.get("workspaceId") if not ( isinstance(api_key, str) and KEY_RE.fullmatch(api_key) and isinstance(key_id, str) and KEY_ID_RE.fullmatch(key_id) and isinstance(ws_id, str) and WORKSPACE_ID_RE.fullmatch(ws_id) ): raise McpToolError("unconfirmed_claim", "Claim response did not include valid key metadata.") existing = store.write_json( "key.json", {"orderId": session["orderId"], "apiKey": api_key, "keyId": key_id, "workspaceId": ws_id}, ) confirmed = False if args.get("confirmSaved"): marker = store.read_json("confirmation.json") if marker is None: c_status, _, c_data = self.endpoint.request_json( "POST", f"{API_PREFIX}/keys", payload={**body, "saved": True}, headers={"Authorization": f"Bearer {existing['apiKey']}"}, ) if c_status != 200 or c_data.get("status") != "saved": raise McpToolError("confirm_failed", "Could not confirm key delivery.", httpStatus=c_status) store.write_json("confirmation.json", {"status": "saved", "keyId": existing["keyId"]}) confirmed = True return { "status": "delivery_confirmed" if confirmed else "key_saved_locally", "keyId": existing["keyId"], "keyPrefix": existing["apiKey"][:14], "workspaceId": existing["workspaceId"], "credentialFile": str(purchase_dir / "key.json"), "deliveryConfirmed": confirmed, } def _tool_prepare_topup(self, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None auth = {"Authorization": f"Bearer {key}"} session_id = args.get("sessionId") amount = args.get("amountCents") recover_only = bool(args.get("recoverOnly", False)) if recover_only: if type(amount) is not int or not (100 <= amount <= 1_000_000): raise McpToolError("invalid_amount_cents", "Supply amountCents (100..1000000) with recoverOnly.") status, _, data = self.endpoint.request_json( "GET", f"{API_PREFIX}/topup/checkout?{urlencode({'amountCents': amount})}", headers=auth ) if status != 200: raise McpToolError(data.get("error", "topup_lookup_failed"), data.get("message", "No matching open top-up."), httpStatus=status) if "checkoutUrl" in data: valid_checkout_url(data["checkoutUrl"]) return data if session_id is not None: if not isinstance(session_id, str) or not SESSION_ID_RE.fullmatch(session_id): raise McpToolError("invalid_session_id", "sessionId must be a valid cs_... Stripe Checkout Session ID.") status, _, data = self.endpoint.request_json("POST", f"{API_PREFIX}/topup", payload={"sessionId": session_id}, headers=auth) if status not in (200, 402): raise McpToolError(data.get("error", "topup_reconcile_failed"), data.get("message", "Top-up reconciliation failed."), httpStatus=status) return data if type(amount) is not int or not (100 <= amount <= 1_000_000): raise McpToolError("invalid_amount_cents", "Supply amountCents or sessionId.") status, _, data = self.endpoint.request_json("POST", f"{API_PREFIX}/topup", payload={"amountCents": amount}, headers=auth) if status not in (200, 402): raise McpToolError(data.get("error", "topup_failed"), data.get("message", "Could not prepare top-up."), httpStatus=status) if "checkoutUrl" in data: valid_checkout_url(data["checkoutUrl"]) return data def _poll_receipt( self, key: str, request_id: str, expected_body_sha256: str | None, wait_seconds: int, ) -> dict[str, Any]: deadline = time.monotonic() + max(0, min(180, wait_seconds)) auth = {"Authorization": f"Bearer {key}"} last_receipt: dict[str, Any] | None = None while True: try: status, headers, data = self.endpoint.request_json( "GET", f"{API_PREFIX}/turns/{request_id}", headers=auth, timeout=15.0, max_bytes=MAX_RECEIPT_BYTES, ) except (OSError, http.client.HTTPException): status, headers, data = 503, {}, {} if status == 200: if expected_body_sha256 and data.get("requestBodySha256") != expected_body_sha256: raise McpToolError( "receipt_request_mismatch", "Server receipt requestBodySha256 differs from the expected local request fingerprint.", requestId=request_id, ) if data.get("status") == "result_ready": reply = data.get("reply") reply_sha = data.get("replySha256") if not isinstance(reply, str) or hashlib.sha256(reply.encode("utf-8")).hexdigest() != reply_sha: raise McpToolError("reply_checksum_mismatch", "Receipt replySha256 failed UTF-8 verification.", requestId=request_id) return data last_receipt = data elif status == 404: if time.monotonic() >= deadline: raise McpToolError("receipt_not_found", "No receipt recorded for this requestId and key.", requestId=request_id, httpStatus=404) elif status not in TEMPORARY_HTTP_STATUSES: raise McpToolError(data.get("error", "receipt_failed"), data.get("message", "Could not read turn receipt."), httpStatus=status) remaining = deadline - time.monotonic() if remaining <= 0: return last_receipt or {"status": "outcome_unknown", "requestId": request_id} time.sleep(min(2.0, remaining)) def _tool_turn(self, mode: str, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None message = args.get("message") checks = args.get("acceptanceChecks") if mode == "work" and checks is not None: if not isinstance(checks, list) or any(not isinstance(c, str) or not c.strip() for c in checks): raise McpToolError("invalid_acceptance_checks", "acceptanceChecks must be a list of non-empty strings.") if isinstance(message, str) and "Acceptance checks:" not in message and checks: bullet_block = "\n".join(f"- {c.strip()}" for c in checks) message = f"{message.rstrip()}\n\nAcceptance checks:\n{bullet_block}" packed_meta = None if mode == "work" and args.get("sourceDir") is not None: if not isinstance(message, str) or not message.strip(): raise McpToolError("invalid_message", "message is required when packing sourceDir.") message, packed_meta = pack_project_sources(args["sourceDir"], message, args.get("includePaths")) extract_to = args.get("extractFilesTo") if mode == "work" else None turn = normalize_turn(mode, message, args.get("effort"), args.get("requestId")) record_turn_journal(turn) def finalize_ready(payload: dict[str, Any], recovered_flag: bool) -> dict[str, Any]: out = {"status": "result_ready", "recoveredFromReceipt": recovered_flag, **payload} if packed_meta is not None: out["packedProject"] = packed_meta usage = payload.get("usage") if isinstance(usage, dict) and "costPico" in usage and "remainingPico" in usage: out["usageSummary"] = { "costPico": usage["costPico"], "costCredits": format_credits(usage["costPico"]), "remainingPico": usage["remainingPico"], "remainingCredits": format_credits(usage["remainingPico"]), "inputTokens": usage.get("inputTokens", 0), "outputTokens": usage.get("outputTokens", 0), "cachedInputTokens": usage.get("cachedInputTokens", 0), } if extract_to is not None: out["extractedFiles"] = extract_fenced_files( payload["reply"], extract_to, turn["requestId"], payload["replySha256"] ) return out wait_default = 90 if mode == "work" else 60 wait_seconds = args.get("waitSeconds", wait_default) if type(wait_seconds) is not int or not (0 <= wait_seconds <= 180): raise McpToolError("invalid_wait_seconds", "waitSeconds must be an integer from 0 to 180.") auto_topup = bool(args.get("allowAutoTopupCheckout", False)) headers = { "Authorization": f"Bearer {key}", "TESI-Checked-Request": turn["checkedHeader"], } if not auto_topup: headers["TESI-Topup-Mode"] = "manual" route = f"{API_PREFIX}/work" if mode == "work" else f"{API_PREFIX}/chat" try: status, _, data = self.endpoint.request_json( "POST", route, payload=turn["body"], headers=headers, timeout=max(30.0, float(wait_seconds or 30)), max_bytes=MAX_RECEIPT_BYTES, ) except (OSError, http.client.HTTPException, TimeoutError): recovered = self._poll_receipt(key, turn["requestId"], turn["requestBodySha256"], wait_seconds) if recovered.get("status") != "result_ready": raise McpToolError( "turn_interrupted_unresolved", "Connection interrupted; keep the same requestId and call tesi_receipt to recover the result.", requestId=turn["requestId"], receiptStatus=recovered.get("status"), ) from None return finalize_ready(recovered, True) if status == 200: reply = data.get("reply") if not isinstance(reply, str) or hashlib.sha256(reply.encode("utf-8")).hexdigest() != data.get("replySha256"): raise McpToolError("reply_checksum_mismatch", "Turn replySha256 failed UTF-8 verification.", requestId=turn["requestId"]) return finalize_ready(data, False) if status == 409 and data.get("error") == "agent_request_recorded": recovered = self._poll_receipt(key, turn["requestId"], turn["requestBodySha256"], wait_seconds) if recovered.get("status") != "result_ready": return { "status": recovered.get("status", "processing"), "recoveredFromReceipt": True, "requestId": turn["requestId"], "receipt": recovered, } return finalize_ready(recovered, True) if status == 402: raise McpToolError( data.get("error", "insufficient_credits"), data.get("message", "Insufficient prepaid TESI credits."), httpStatus=402, requestId=turn["requestId"], payment=data, ) if status in TEMPORARY_HTTP_STATUSES: recovered = self._poll_receipt(key, turn["requestId"], turn["requestBodySha256"], min(wait_seconds, 15)) if recovered.get("status") == "result_ready": return finalize_ready(recovered, True) raise McpToolError( data.get("error", "turn_failed"), data.get("message", f"TESI {mode} request failed."), httpStatus=status, requestId=turn["requestId"], ) def _tool_receipt(self, args: dict[str, Any]) -> dict[str, Any]: key = resolve_bearer_key(self.key_file, required=True) assert key is not None auth = {"Authorization": f"Bearer {key}"} if args.get("listReceipts"): params: dict[str, Any] = {} for field in ("mode", "delivery", "limit", "cursor"): if args.get(field) is not None: params[field] = args[field] query = f"?{urlencode(params)}" if params else "" status, _, page = self.endpoint.request_json("GET", f"{API_PREFIX}/turns{query}", headers=auth) if status != 200: raise McpToolError(page.get("error", "receipt_list_failed"), page.get("message", "Could not list receipts."), httpStatus=status) return {"status": "receipts_ready", **page} req_id = args.get("requestId") if not isinstance(req_id, str) or not TURN_ID_RE.fullmatch(req_id): raise McpToolError("invalid_request_id", "Provide requestId (mw_ + 32 lowercase hex) or set listReceipts: true.") expected_sha = args.get("expectedRequestBodySha256") if expected_sha is None: turns_dir = state_root_dir() / "turns" if turns_dir.is_dir(): try: with PrivateDir(turns_dir, create=False) as store: saved = store.read_json(f"{req_id}.json") if saved: expected_sha = saved.get("requestBodySha256") except McpToolError: pass wait_sec = args.get("waitSeconds", 0) if type(wait_sec) is not int or not (0 <= wait_sec <= 180): raise McpToolError("invalid_wait_seconds", "waitSeconds must be an integer from 0 to 180.") receipt = self._poll_receipt(key, req_id, expected_sha, wait_sec) save_to = args.get("saveReplyTo") extract_to = args.get("extractFilesTo") if save_to is not None and extract_to is not None: raise McpToolError("invalid_arguments", "Supply either saveReplyTo or extractFilesTo, not both.") if extract_to is not None: if receipt.get("status") != "result_ready": return receipt extracted = extract_fenced_files(receipt["reply"], extract_to, req_id, receipt["replySha256"]) return { "status": "files_extracted", "requestId": req_id, "replySha256": receipt["replySha256"], "requestBodySha256": receipt["requestBodySha256"], **extracted, } if save_to is not None: if not isinstance(save_to, str) or not save_to.strip(): raise McpToolError("invalid_save_path", "saveReplyTo must be a non-empty file path.") if receipt.get("status") != "result_ready": return receipt dest = Path(save_to) try: fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except FileExistsError: raise McpToolError("reply_file_exists", f"Refusing to overwrite existing file: {dest}") from None with os.fdopen(fd, "wb") as stream: reply_bytes = receipt["reply"].encode("utf-8") stream.write(reply_bytes) stream.flush() os.fsync(stream.fileno()) return { "status": "reply_saved", "requestId": req_id, "replyFile": str(dest), "replyBytes": len(reply_bytes), "replySha256": receipt["replySha256"], "requestBodySha256": receipt["requestBodySha256"], } return receipt RESOURCES: list[dict[str, Any]] = [ { "uri": "tesi://guide/decision-rubric", "name": "decision-rubric", "title": "TESI Delegation Fit & Mode Rubric", "description": "Concise decision rubric for when an agent should use TESI Ask vs. TESI Work, when NOT to delegate, and how to structure acceptance checks.", "mimeType": "text/markdown", }, { "uri": "tesi://status/local-custody", "name": "local-custody", "title": "Local Key & Turn Journal Status (Redacted)", "description": "Local bearer-key configuration status (never exposing raw secrets) and local crash-recovery journal directory status.", "mimeType": "application/json", }, { "uri": "tesi://catalog/quickstart", "name": "quickstart-catalog", "title": "Live TESI Agent API Quickstart Catalog", "description": "Live GET /api/v1/agents/quickstart JSON catalog with offered USD packs, starter templates, minimum starting credits, and SHA-256 artifact digests.", "mimeType": "application/json", }, { "uri": "tesi://guide/skill", "name": "agent-skill", "title": "TESI Agent Skill (SKILL.md)", "description": "Complete /agents/SKILL.md Markdown skill fetched from the configured TESI origin.", "mimeType": "text/markdown", }, ] PROMPTS: list[dict[str, Any]] = [ { "name": "commission-tested-project", "description": "Quote starting credit and commission a complete tested software deliverable on TESI Work.", "arguments": [ {"name": "deliverable", "description": "Concrete service, CLI tool, or responsive UI prototype to build.", "required": True}, {"name": "acceptanceChecks", "description": "Runnable tests or verification criteria TESI must execute before returning.", "required": True}, {"name": "effort", "description": "Optional effort level (low, medium, high).", "required": False}, ], }, { "name": "patch-local-codebase", "description": "Safely pack a local UTF-8 source directory (refusing secrets and symlinks), quote starting credit, commission a tested change, and extract delivered files.", "arguments": [ {"name": "sourceDir", "description": "Local UTF-8 project directory to pack safely.", "required": True}, {"name": "changeRequest", "description": "Requested feature, bugfix, or test suite.", "required": True}, {"name": "extractDir", "description": "Clean local output directory for extracted files (default ./tesi-delivered).", "required": False}, ], }, { "name": "verify-public-download", "description": "Run a clean-room TESI Work verification of a public artifact URL (HTTP status, Content-Type, byte count, SHA-256, and schema check).", "arguments": [ {"name": "targetUrl", "description": "Public HTTPS URL to verify from TESI's clean computer.", "required": True}, {"name": "expectedSha256", "description": "Optional expected 64-character lowercase hex SHA-256 digest.", "required": False}, ], }, { "name": "reconcile-csv-ledgers", "description": "Reconcile an orders CSV against a settlements CSV on TESI Work and verify the returned JSON report offline.", "arguments": [ {"name": "ordersPath", "description": "Local path or inline description of orders CSV.", "required": True}, {"name": "settlementsPath", "description": "Local path or inline description of settlements CSV.", "required": True}, ], }, ] DECISION_RUBRIC_MD = """# TESI Delegation Fit & Mode Rubric 1. **Choose `tesi_ask` (`POST /api/v1/agents/chat`)** for read-only analysis, code review, or second-opinion verification on your key's isolated computer. 2. **Choose `tesi_work` (`POST /api/v1/agents/work`)** when you can state a concrete deliverable AND runnable acceptance checks (for example: a stdlib Python/SQLite service with loopback tests, a responsive HTML/CSS/JS prototype verified at 390px/1280px, a deduplicated CSV with exact row counts, or an order-vs-settlement reconciliation JSON report). 3. **Always quote first (free, keyless):** Call `tesi_quote` (or `tesi_shortlist_work`) before spending credits. Only UTF-8 byte counts are sent over the network. 4. **Never pass secrets:** Configure `TESI_API_KEY` or a mode-`0600` `--key-file`. When packing local code with `sourceDir`, `.env*`, credentials, keys, binaries, and symlinks are refused automatically. 5. **Do NOT use TESI** for sub-100ms autocomplete streaming, private VPC databases without sanitized fixtures, or unattended card charging without human Stripe Checkout approval. """ def read_mcp_resource(runtime: TesiMcpRuntime, uri: str) -> dict[str, Any]: if uri == "tesi://guide/decision-rubric": return {"contents": [{"uri": uri, "mimeType": "text/markdown", "text": DECISION_RUBRIC_MD}]} if uri == "tesi://status/local-custody": key = resolve_bearer_key(runtime.key_file, required=False) turns_dir = state_root_dir() / "turns" recorded_turns = len(list(turns_dir.glob("mw_*.json"))) if turns_dir.is_dir() else 0 status_doc = { "origin": runtime.endpoint.public_origin, "keyConfigured": key is not None, "keyPrefix": (key[:14] + "...") if key else None, "configuredKeyFile": str(runtime.key_file) if runtime.key_file else "./tesi-purchase/key.json", "journalDirectory": str(turns_dir), "recordedTurnCount": recorded_turns, } return {"contents": [{"uri": uri, "mimeType": "application/json", "text": json.dumps(status_doc, indent=2, sort_keys=True)}]} if uri == "tesi://catalog/quickstart": data = runtime._tool_discover({}) return {"contents": [{"uri": uri, "mimeType": "application/json", "text": json.dumps(data["offer"], indent=2, sort_keys=True)}]} if uri == "tesi://guide/skill": status, _, body = runtime.endpoint.request( "GET", "/agents/SKILL.md", headers={"Accept": "text/markdown, text/plain, */*"} ) if status != 200: raise McpToolError("skill_unavailable", "Could not fetch /agents/SKILL.md from origin.", httpStatus=status) return {"contents": [{"uri": uri, "mimeType": "text/markdown", "text": body.decode("utf-8", errors="strict")}]} raise KeyError(f"Unknown resource URI: {uri}") def build_mcp_prompt(name: str, arguments: Any) -> dict[str, Any]: args = arguments if isinstance(arguments, dict) else {} if name == "commission-tested-project": deliverable = str(args.get("deliverable") or "").strip() checks = str(args.get("acceptanceChecks") or "").strip() effort = str(args.get("effort") or "medium").strip() text = ( f"Commission this tested project through the TESI MCP server:\n\n" f"Deliverable:\n{deliverable}\n\n" f"Acceptance checks:\n{checks}\n\n" f"Workflow:\n" f"1. Call `tesi_quote` with mode='work', effort='{effort}', and the full brief to verify starting credit and key balance.\n" f"2. If key balance is missing or low, prepare a review link with `tesi_prepare_purchase(amountCents=1000, quoteOnly=True)` or `tesi_plan_topup` and ask the human purchaser before opening Checkout.\n" f"3. Call `tesi_work` with explicit `acceptanceChecks`, effort='{effort}', and `extractFilesTo='./tesi-delivered'` if fenced files are expected.\n" f"4. Verify the extracted files locally and call `tesi_usage(limit=5)` to record settled credits." ) return {"description": PROMPTS[0]["description"], "messages": [{"role": "user", "content": {"type": "text", "text": text}}]} if name == "patch-local-codebase": src = str(args.get("sourceDir") or "./src").strip() change = str(args.get("changeRequest") or "").strip() dest = str(args.get("extractDir") or "./tesi-delivered").strip() text = ( f"Use TESI Work to implement and test a change against local UTF-8 directory `{src}`:\n\n" f"Change request:\n{change}\n\n" f"Workflow:\n" f"1. Call `tesi_quote(sourceDir='{src}', message=..., mode='work')` to confirm zero secret/binary files and check starting credit.\n" f"2. Call `tesi_work(sourceDir='{src}', extractFilesTo='{dest}', message=..., acceptanceChecks=['Return complete updated files in ```lang path= fences and test output.'])`.\n" f"3. Inspect `{dest}/TESI-DELIVERY-MANIFEST.json` and run local tests before applying changes." ) return {"description": PROMPTS[1]["description"], "messages": [{"role": "user", "content": {"type": "text", "text": text}}]} if name == "verify-public-download": url = str(args.get("targetUrl") or "https://toolsenabled.ai/agents/examples/newsletter-proof.json").strip() sha = str(args.get("expectedSha256") or "").strip() sha_line = f"- Confirm SHA-256 equals {sha}.\n" if sha else "- Report the exact SHA-256 hex digest.\n" text = ( f"Delegate a clean-room public download check to TESI Work:\n\n" f"Target URL: {url}\n" f"Acceptance checks:\n" f"- Fetch from TESI's clean computer with zero cookies or sign-in credentials.\n" f"- Report final URL, HTTP status, Content-Type, and exact byte count.\n" f"{sha_line}" f"Call `tesi_quote` first, then `tesi_work(effort='low', ...)`." ) return {"description": PROMPTS[2]["description"], "messages": [{"role": "user", "content": {"type": "text", "text": text}}]} if name == "reconcile-csv-ledgers": orders_p = str(args.get("ordersPath") or "orders.csv").strip() settle_p = str(args.get("settlementsPath") or "settlements.csv").strip() text = ( f"Reconcile `{orders_p}` against `{settle_p}` using TESI Work and verify deterministically:\n\n" f"1. Include both `id,amount_cents` CSV ledgers in the Work brief and require a JSON report with `ordersTotalCents`, `settlementsTotalCents`, `netDeltaCents`, `matchedCount`, `missingIds`, `unexpectedIds`, and `amountDifferences`.\n" f"2. Quote with `tesi_quote`, run `tesi_work(effort='medium', ...)`, and verify the returned JSON offline using `/agents/examples/check-reconciliation.py.txt`." ) return {"description": PROMPTS[3]["description"], "messages": [{"role": "user", "content": {"type": "text", "text": text}}]} raise KeyError(f"Unknown prompt: {name}") def read_stdio_message(stream: Any) -> tuple[str, dict[str, Any]] | None: """Read one JSON-RPC message supporting both newline JSON and Content-Length framing.""" while True: first_line = stream.readline(MAX_RPC_BYTES + 1) if not first_line: return None if len(first_line) > MAX_RPC_BYTES: raise ValueError("JSON-RPC frame exceeded maximum size.") if first_line in (b"\r\n", b"\n"): continue break stripped = first_line.lstrip() if stripped.lower().startswith(b"content-length:"): headers: dict[str, str] = {} line = first_line while line not in (b"\r\n", b"\n", b""): if b":" not in line: raise ValueError("Malformed header in Content-Length frame.") k, v = line.decode("ascii", errors="strict").split(":", 1) headers[k.strip().lower()] = v.strip() line = stream.readline(4096) if len(headers) > 16: raise ValueError("Too many frame headers.") length = int(headers["content-length"]) if length < 0 or length > MAX_RPC_BYTES: raise ValueError("Invalid Content-Length.") payload = b"" while len(payload) < length: chunk = stream.read(length - len(payload)) if not chunk: raise ValueError("Truncated Content-Length frame body.") payload += chunk parsed = json.loads(payload.decode("utf-8")) if not isinstance(parsed, dict): raise ValueError("JSON-RPC message must be a JSON object.") return "content-length", parsed parsed = json.loads(first_line.decode("utf-8")) if not isinstance(parsed, dict): raise ValueError("JSON-RPC message must be a JSON object.") return "line", parsed def write_stdio_message(stream: Any, framing: str, message: dict[str, Any]) -> None: safe_msg = scrub_secrets(message) encoded = json.dumps(safe_msg, ensure_ascii=False, separators=(",", ":")).encode("utf-8") if framing == "content-length": stream.write(f"Content-Length: {len(encoded)}\r\n\r\n".encode("ascii") + encoded) else: stream.write(encoded + b"\n") stream.flush() def handle_rpc(runtime: TesiMcpRuntime, msg: dict[str, Any]) -> dict[str, Any] | None: if msg.get("jsonrpc") != "2.0" or not isinstance(msg.get("method"), str): req_id = msg.get("id") if isinstance(msg.get("id"), (str, int, type(None))) else None return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32600, "message": "Invalid JSON-RPC 2.0 request."}} method = msg["method"] has_id = "id" in msg req_id = msg.get("id") if not has_id: return None if method == "initialize": params = msg.get("params") if isinstance(msg.get("params"), dict) else {} requested = params.get("protocolVersion") negotiated = requested if requested in SUPPORTED_PROTOCOLS else DEFAULT_PROTOCOL return { "jsonrpc": "2.0", "id": req_id, "result": { "protocolVersion": negotiated, "capabilities": { "tools": {"listChanged": False}, "resources": {"listChanged": False}, "prompts": {"listChanged": False}, }, "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION}, "instructions": ( "Use tesi_discover and tesi_quote or tesi_shortlist_work for free before spending credits. " "Never pass raw bearer keys in tool arguments; configure TESI_API_KEY or a 0600 --key-file. " "Require explicit human purchaser approval before opening Stripe Checkout URLs. " "Include clear acceptanceChecks on tesi_work and verify returned deliverables locally." ), }, } if method == "ping": return {"jsonrpc": "2.0", "id": req_id, "result": {}} if method == "tools/list": return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}} if method == "resources/list": return {"jsonrpc": "2.0", "id": req_id, "result": {"resources": RESOURCES}} if method == "resources/read": params = msg.get("params") uri = params.get("uri") if isinstance(params, dict) else None if not isinstance(uri, str) or not uri: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "resources/read requires params.uri."}} try: return {"jsonrpc": "2.0", "id": req_id, "result": scrub_secrets(read_mcp_resource(runtime, uri))} except KeyError as exc: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": str(exc)}} except McpToolError as err: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": err.payload.get("message", "Resource read failed.")}} if method == "prompts/list": return {"jsonrpc": "2.0", "id": req_id, "result": {"prompts": PROMPTS}} if method == "prompts/get": params = msg.get("params") pname = params.get("name") if isinstance(params, dict) else None if not isinstance(pname, str) or not pname: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "prompts/get requires params.name."}} try: return {"jsonrpc": "2.0", "id": req_id, "result": build_mcp_prompt(pname, params.get("arguments"))} except KeyError as exc: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": str(exc)}} if method == "tools/call": params = msg.get("params") if not isinstance(params, dict) or not isinstance(params.get("name"), str): return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "tools/call requires params.name."}} tool_name = params["name"] try: payload = scrub_secrets(runtime.call_tool(tool_name, params.get("arguments"))) text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) return { "jsonrpc": "2.0", "id": req_id, "result": { "content": [{"type": "text", "text": text}], "structuredContent": payload, "isError": False, }, } except KeyError: return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}} except McpToolError as err: payload = scrub_secrets(err.payload) text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) return { "jsonrpc": "2.0", "id": req_id, "result": { "content": [{"type": "text", "text": text}], "structuredContent": payload, "isError": True, }, } except (OSError, http.client.HTTPException) as exc: payload = {"status": "error", "error": "network_unavailable", "message": f"Network or file error: {type(exc).__name__}"} text = json.dumps(payload, indent=2, sort_keys=True) return { "jsonrpc": "2.0", "id": req_id, "result": { "content": [{"type": "text", "text": text}], "structuredContent": payload, "isError": True, }, } return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}} def build_config_snippet(script_path: Path, key_file: Path | None) -> dict[str, Any]: resolved_script = str(script_path.resolve()) args = ["-I", resolved_script] if key_file is not None: args.extend(["--key-file", str(key_file)]) return { "mcpServers": { "tesi": { "command": "python3", "args": args, } }, "claudeCodeCommand": ["claude", "mcp", "add", "--transport", "stdio", "tesi", "--", "python3", *args], "codexCliCommand": ["codex", "mcp", "add", "tesi", "--", "python3", *args], } def main(argv: list[str] | None = None) -> int: os.umask(0o077) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--origin", default=os.environ.get("TESI_ORIGIN", DEFAULT_ORIGIN), help="Trusted TESI origin (defaults to https://toolsenabled.ai).", ) parser.add_argument( "--key-file", type=Path, default=None, help="Optional mode-0600 key.json file (defaults to TESI_KEY_FILE, TESI_API_KEY, or ./tesi-purchase/key.json).", ) parser.add_argument("--self-check", action="store_true", help="Verify local MCP server configuration and tool schemas offline.") parser.add_argument("--print-config", action="store_true", help="Print ready-to-use MCP client configuration JSON without reading secrets.") args = parser.parse_args(argv) try: endpoint = EndpointConfig(args.origin) except ValueError as exc: print(json.dumps({"status": "invalid_origin", "message": str(exc)}, sort_keys=True), file=sys.stderr) return 2 if args.self_check: tool_names = [t["name"] for t in TOOLS] assert len(tool_names) == len(set(tool_names)) == 12 assert len(RESOURCES) == 4 and len(PROMPTS) == 4 print( json.dumps( { "status": "mcp_server_ready", "server": SERVER_NAME, "version": SERVER_VERSION, "origin": endpoint.public_origin, "protocolVersions": list(SUPPORTED_PROTOCOLS), "toolCount": len(TOOLS), "tools": tool_names, "resourceCount": len(RESOURCES), "resources": [r["uri"] for r in RESOURCES], "promptCount": len(PROMPTS), "prompts": [p["name"] for p in PROMPTS], }, sort_keys=True, ) ) return 0 if args.print_config: print(json.dumps(build_config_snippet(Path(__file__), args.key_file), indent=2, sort_keys=True)) return 0 runtime = TesiMcpRuntime(endpoint, key_file=args.key_file) last_framing = "line" while True: try: item = read_stdio_message(sys.stdin.buffer) except ValueError as exc: write_stdio_message( sys.stdout.buffer, last_framing, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}, ) return 1 if item is None: return 0 framing, msg = item last_framing = framing reply = handle_rpc(runtime, msg) if reply is not None: write_stdio_message(sys.stdout.buffer, framing, reply) if __name__ == "__main__": raise SystemExit(main())