#!/usr/bin/env python3 """tft - the TheFantasyTool command line. A thin, read-only client for TheFantasyTool's MCP server (https://thefantasytool.com/api/mcp). Every tool the server offers becomes a command: `tft best-transfers --game ...`. There is no business logic here - the server decides what the tools are, what they take and what they return. Python 3.9+, standard library only. Docs: https://thefantasytool.com/cli/README.md Exit codes: 0 ok 1 usage / validation error, or the server refused the request (tool error) 2 runtime, network or server error 3 not signed in, or the sign-in expired (run `tft login`) """ import argparse import base64 import hashlib from http.server import BaseHTTPRequestHandler, HTTPServer import json import os import re import secrets import socket import stat import sys import tempfile import textwrap import threading import time import urllib.error import urllib.parse import urllib.request import webbrowser VERSION = "1.0.0" DEFAULT_MCP_URL = "https://thefantasytool.com/api/mcp" CLIENT_ID = "https://thefantasytool.com/cli/client.json" SCOPE = "openid profile email offline_access" # Used only when discovery fails AND the target is the default production server. FALLBACK_AS = { "issuer": "https://clerk.thefantasytool.com", "authorization_endpoint": "https://clerk.thefantasytool.com/oauth/authorize", "token_endpoint": "https://clerk.thefantasytool.com/oauth/token", "revocation_endpoint": "https://clerk.thefantasytool.com/oauth/token/revoke", "device_authorization_endpoint": "https://clerk.thefantasytool.com/oauth/device_authorization", "authorization_response_iss_parameter_supported": True, } MCP_PROTOCOL_VERSION = "2025-06-18" TOOLS_CACHE_TTL_S = 3600 LOGIN_WAIT_S = 300 MAX_RETRY_AFTER_S = 30 DEFAULT_TIMEOUT_S = 120.0 USER_AGENT = "tft-cli/%s" % VERSION EXIT_OK, EXIT_USAGE, EXIT_RUNTIME, EXIT_AUTH = 0, 1, 2, 3 EXIT_CODES_TEXT = """exit codes: 0 ok 1 usage/validation error, or the server refused the request (tool error) 2 runtime, network or server error 3 not signed in, or the sign-in expired - run `tft login`""" BUILTINS = ("login", "logout", "status", "tools", "call", "mcp-config", "version") GLOBAL_VALUE_FLAGS = ("--timeout", "--mcp-url") GLOBAL_FLAG_NAMES = ("json", "quiet", "timeout", "mcp-url", "mcp_url", "help", "h") # Nicer --help examples for the tools we know. Unknown tools get one derived from the schema. STATIC_EXAMPLES = { "list_games": ["tft list-games", "tft list-games --json"], "search_players": ['tft search-players --game "Fantasy Premier League 2026/2027" ' '--position MID --max-price 8 --rounds 3 --sort total', 'tft search-players --game "Fantasy Premier League 2026/2027" --query salah'], "my_team": ['tft my-team --game "Fantasy Premier League 2026/2027" --rounds 3', 'tft my-team --game "Fantasy Premier League 2026/2027" --team-id 1234567'], "captain_options": ['tft captain-options --game "Fantasy Premier League 2026/2027" --scope squad', 'tft captain-options --game "Fantasy Premier League 2026/2027" ' '--scope all --limit 10'], "best_transfers": ['tft best-transfers --game "Fantasy Premier League 2026/2027" --rounds 4', 'tft best-transfers --game "Fantasy Premier League 2026/2027" ' '--position FWD --max-results 3 --json'], "build_squad": ['tft build-squad --game "Fantasy Premier League 2026/2027" --mode wildcard ' '--rounds 5 --keep "Haaland" --avoid "Player A,Player B"'], "team_fixtures": ['tft team-fixtures --game "Fantasy Premier League 2026/2027" ' '--clubs Arsenal --clubs Chelsea --rounds 4'], } _QUIET = False _DEBUG = os.environ.get("TFT_DEBUG", "").strip() not in ("", "0", "false", "no") # ====================================================================================== # Errors and output # ====================================================================================== class CliError(Exception): """An error with an exit code and an actionable message for the user.""" def __init__(self, message, code=EXIT_RUNTIME, hint=None, payload=None): super().__init__(message) self.message = message self.code = code self.hint = hint self.payload = payload def log(msg): """Progress / informational line -> stderr (suppressed by --quiet).""" if not _QUIET: print(msg, file=sys.stderr, flush=True) def warn(msg): """Warnings always reach stderr, even with --quiet.""" print("tft: " + msg, file=sys.stderr, flush=True) _SECRET_KEYS = ("access_token", "refresh_token", "id_token", "code", "code_verifier", "device_code", "token", "client_secret") def redact(text): """Remove bearer tokens and OAuth secrets from a string meant for a log.""" s = str(text) s = re.sub(r"(?i)(bearer\s+)[^\s\"',]+", r"\1***", s) for k in _SECRET_KEYS: s = re.sub(r'("%s"\s*:\s*")[^"]*(")' % k, r"\1***\2", s) s = re.sub(r"(? 0: cols = cols[:_MAX_COLS] cells = [[_cell(r.get(c)) if c in r else "" for c in cols] for r in rows] def fit(s): s = s.replace("\n", " ") return s if len(s) <= max_width else s[:max_width - 3] + "..." cells = [[fit(c) for c in row] for row in cells] widths = [max([len(str(c))] + [len(row[i]) for row in cells]) for i, c in enumerate(cols)] pad = " " * indent out = [pad + " ".join(str(c).ljust(widths[i]) for i, c in enumerate(cols)).rstrip(), pad + " ".join("-" * widths[i] for i in range(len(cols)))] for row in cells: out.append(pad + " ".join(row[i].ljust(widths[i]) for i in range(len(cols))).rstrip()) if extra > 0: out.append(pad + "(+%d more fields - use --json for everything)" % extra) return out def render(value, indent=0): """Readable text lines for any JSON value: tables for flat lists of dicts, blocks for nested.""" pad = " " * indent if _is_table(value): return _table(value, indent) if isinstance(value, list): if not value: return [pad + "(none)"] out = [] for i, x in enumerate(value): if isinstance(x, (dict, list)) and x: out.append(pad + "-") out.extend(render(x, indent + 2)) else: out.append(pad + "- " + _scalar(x)) return out if isinstance(value, dict): out = [] for k, v in value.items(): if _is_table(v): out.append("%s%s:" % (pad, k)) out.extend(_table(v, indent + 2)) elif isinstance(v, list) and not v: out.append("%s%s: (none)" % (pad, k)) elif v and isinstance(v, (dict, list)) and not _is_flat(v): out.append("%s%s:" % (pad, k)) out.extend(render(v, indent + 2)) elif isinstance(v, dict) and v: out.append("%s%s:" % (pad, k)) out.extend(render(v, indent + 2)) elif isinstance(v, (dict, list)): out.append("%s%s: %s" % (pad, k, _cell(v) if v else "-")) else: out.append("%s%s: %s" % (pad, k, _scalar(v))) return out return [pad + _scalar(value)] def print_result(value, as_json): if as_json: emit_json(value) return lines = render(value) sys.stdout.write("\n".join(lines) + ("\n" if lines else "")) sys.stdout.flush() # ====================================================================================== # Configuration # ====================================================================================== def config_dir(): env = os.environ.get("TFT_CONFIG_DIR") if env: return os.path.abspath(os.path.expanduser(env)) if os.name == "nt": base = os.environ.get("APPDATA") or os.path.expanduser("~\\AppData\\Roaming") return os.path.join(base, "thefantasytool") base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") return os.path.join(base, "thefantasytool") def _path(name): return os.path.join(config_dir(), name) def _ensure_dir(): d = config_dir() if not os.path.isdir(d): os.makedirs(d, mode=0o700, exist_ok=True) try: os.chmod(d, 0o700) except OSError: pass return d def read_json_file(path): try: with open(path, encoding="utf-8") as f: return json.load(f) except (OSError, ValueError): return None def write_private_json(path, data): """Write JSON readable only by the current user (0600; best effort on Windows).""" _ensure_dir() fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=os.path.dirname(path)) try: try: os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR) except OSError: pass with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(data, f, indent=2) os.replace(tmp, path) except BaseException: try: os.unlink(tmp) except OSError: pass raise try: os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) except OSError: pass def check_mcp_url(url): """Refuse anything that would send a token in clear text to a remote host.""" try: u = urllib.parse.urlsplit(url) except ValueError: raise CliError("Invalid server URL: %r" % url, EXIT_USAGE) host = (u.hostname or "").lower() if u.scheme == "https" and host: return url if u.scheme == "http" and host in ("localhost", "127.0.0.1", "::1"): return url raise CliError("Refusing server URL %r: it must be https:// (plain http:// is only allowed " "for localhost / 127.0.0.1)." % url, EXIT_USAGE, hint="Fix --mcp-url / TFT_MCP_URL / mcp_url in config.json, or unset it to use " + DEFAULT_MCP_URL) def resolve_mcp_url(flag_value): """flags > env > config file > default.""" if flag_value: return check_mcp_url(flag_value) if os.environ.get("TFT_MCP_URL"): return check_mcp_url(os.environ["TFT_MCP_URL"]) cfg = read_json_file(_path("config.json")) or {} if isinstance(cfg, dict) and cfg.get("mcp_url"): return check_mcp_url(str(cfg["mcp_url"])) return DEFAULT_MCP_URL def resolve_timeout(flag_value): if flag_value is not None: return flag_value cfg = read_json_file(_path("config.json")) or {} try: return float(cfg.get("timeout")) if isinstance(cfg, dict) and cfg.get("timeout") else DEFAULT_TIMEOUT_S except (TypeError, ValueError): return DEFAULT_TIMEOUT_S # ====================================================================================== # HTTP # ====================================================================================== class _NoRedirect(urllib.request.HTTPRedirectHandler): """Never follow a redirect: a token must only ever go to the URL we were given.""" def redirect_request(self, req, fp, code, msg, headers, newurl): return None _OPENER = urllib.request.build_opener(_NoRedirect) def http(method, url, timeout, body=None, headers=None, token=None, form=None): """(status, headers dict lower-cased, body bytes). Network failure -> CliError(2).""" hdrs = {"User-Agent": USER_AGENT, "Accept": "application/json"} hdrs.update(headers or {}) data = None if form is not None: data = urllib.parse.urlencode(form).encode() hdrs["Content-Type"] = "application/x-www-form-urlencoded" elif body is not None: data = json.dumps(body).encode() hdrs["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, method=method, headers=hdrs) if token: # Unredirected: never copied onto a redirect, whatever the handler does. req.add_unredirected_header("Authorization", "Bearer " + token) debug("%s %s headers=%s body=%s" % (method, url, {k: v for k, v in hdrs.items()}, (data or b"")[:400].decode("utf-8", "replace"))) try: resp = _OPENER.open(req, timeout=timeout) status, rh, raw = resp.status, resp.headers, resp.read() except urllib.error.HTTPError as exc: status, rh, raw = exc.code, exc.headers, exc.read() if exc.fp else b"" except (urllib.error.URLError, socket.timeout, ConnectionError, OSError) as exc: reason = getattr(exc, "reason", exc) host = urllib.parse.urlsplit(url).netloc raise CliError("Could not reach %s: %s" % (host, reason), EXIT_RUNTIME, hint="Check your internet connection, or raise --timeout (now %ss)." % timeout) rhl = {k.lower(): v for k, v in (rh.items() if rh else [])} debug("-> %s %s" % (status, raw[:400].decode("utf-8", "replace"))) if 300 <= status < 400: raise CliError("%s redirected to %s - refusing to follow it with your credentials." % (url, rhl.get("location", "?")), EXIT_RUNTIME, hint="Check the server URL (--mcp-url / TFT_MCP_URL).") return status, rhl, raw def parse_json(raw, what): try: return json.loads(raw.decode("utf-8")) if raw else {} except (ValueError, UnicodeDecodeError): raise CliError("The %s returned something that is not JSON." % what, EXIT_RUNTIME) def _retry_after(headers): v = (headers or {}).get("retry-after") try: return max(0.0, float(v)) except (TypeError, ValueError): return None # ====================================================================================== # OAuth (Clerk) - discovery, login, refresh, logout # ====================================================================================== def _origin(url): u = urllib.parse.urlsplit(url) return "%s://%s" % (u.scheme, u.netloc) def discover(mcp_url, timeout): """Authorization-server metadata for this MCP server (RFC 9728 -> RFC 8414).""" issuer = None try: st, _, raw = http("GET", _origin(mcp_url) + "/.well-known/oauth-protected-resource", timeout) if st == 200: servers = parse_json(raw, "server").get("authorization_servers") or [] issuer = servers[0].rstrip("/") if servers else None if issuer: check_mcp_url(issuer) st, _, raw = http("GET", issuer + "/.well-known/oauth-authorization-server", timeout) if st == 200: meta = parse_json(raw, "sign-in server") if meta.get("token_endpoint") and meta.get("authorization_endpoint"): if meta.get("issuer", "").rstrip("/") != issuer: raise CliError("Sign-in server metadata names a different issuer (%s, " "expected %s)." % (meta.get("issuer"), issuer), EXIT_RUNTIME) return meta except CliError as exc: if mcp_url != DEFAULT_MCP_URL: raise debug("discovery failed, using built-in endpoints: %s" % exc.message) if mcp_url == DEFAULT_MCP_URL: return dict(FALLBACK_AS) raise CliError("Could not discover the sign-in server for %s." % mcp_url, EXIT_RUNTIME, hint="Check --mcp-url / TFT_MCP_URL.") def _b64url(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def _token_record(tok, meta, mcp_url, previous=None): if not tok.get("access_token"): raise CliError("The sign-in server did not return an access token.", EXIT_RUNTIME) now = time.time() rec = { "mcp_url": mcp_url, "client_id": CLIENT_ID, "issuer": meta.get("issuer"), "token_endpoint": meta.get("token_endpoint"), "revocation_endpoint": meta.get("revocation_endpoint"), "access_token": tok["access_token"], "refresh_token": tok.get("refresh_token") or (previous or {}).get("refresh_token"), "token_type": tok.get("token_type", "Bearer"), "scope": tok.get("scope", SCOPE), "obtained_at": int(now), "expires_at": int(now + float(tok["expires_in"])) if tok.get("expires_in") else None, } return rec def _token_post(meta, form, timeout, what="sign-in"): st, _, raw = http("POST", meta["token_endpoint"], timeout, form=form) data = parse_json(raw, "sign-in server") return st, data def _oauth_error(data, step): err = data.get("error") or "unknown_error" desc = data.get("error_description") or "" return "%s failed: %s%s" % (step, err, (" - " + desc) if desc else "") class _CallbackHandler(BaseHTTPRequestHandler): result = None def do_GET(self): u = urllib.parse.urlsplit(self.path) if u.path != "/callback": self.send_response(404) self.end_headers() return got = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True)) expected = getattr(self.server, "expected_state", None) if expected and not secrets.compare_digest(str(got.get("state", "")), expected): # A stray local request, not our sign-in: ignore it and keep waiting. self.send_response(400) self.end_headers() return self.server.result = got ok = "code" in self.server.result and "error" not in self.server.result msg = ("Signed in to TheFantasyTool. You can close this tab and return to the terminal." if ok else "Sign-in did not complete. Return to the terminal for details.") page = ("TheFantasyTool CLI" "

%s

" % msg).encode() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(page))) self.end_headers() self.wfile.write(page) def log_message(self, *args): pass class _LoopbackServer(HTTPServer): allow_reuse_address = False result = None def login_browser(mcp_url, meta, timeout, open_browser=True): verifier = _b64url(secrets.token_bytes(48)) challenge = _b64url(hashlib.sha256(verifier.encode()).digest()) state = _b64url(secrets.token_bytes(24)) server = _LoopbackServer(("127.0.0.1", 0), _CallbackHandler) server.expected_state = state try: port = server.server_address[1] redirect_uri = "http://127.0.0.1:%d/callback" % port params = {"response_type": "code", "client_id": CLIENT_ID, "redirect_uri": redirect_uri, "scope": SCOPE, "state": state, "code_challenge": challenge, "code_challenge_method": "S256", "resource": mcp_url} url = meta["authorization_endpoint"] + "?" + urllib.parse.urlencode(params) if open_browser: log("Opening your browser to sign in to TheFantasyTool. If it does not open, visit:") else: log("Open this URL in your browser to sign in to TheFantasyTool:") print(" " + url, file=sys.stderr, flush=True) if open_browser: try: webbrowser.open(url, new=1) except Exception: pass log("Waiting for the sign-in to finish (up to %d minutes)..." % (LOGIN_WAIT_S // 60)) deadline = time.time() + LOGIN_WAIT_S while server.result is None: left = deadline - time.time() if left <= 0: raise CliError("Timed out waiting for the browser sign-in.", EXIT_AUTH, hint="Run `tft login` again. On a machine without a browser, " "`tft login --no-browser` prints the sign-in URL to open in " "a browser on this same machine.") server.timeout = min(left, 1.0) server.handle_request() res = server.result finally: server.server_close() if "error" in res: raise CliError(_oauth_error(res, "Sign-in at the authorize step"), EXIT_AUTH, hint="Run `tft login` again.") if not secrets.compare_digest(str(res.get("state", "")), state): raise CliError("Sign-in response did not match this login attempt (state mismatch) - " "ignored it for your safety.", EXIT_USAGE, hint="Run `tft login` again.") iss = res.get("iss") expected_iss = (meta.get("issuer") or "").rstrip("/") if iss is not None and iss.rstrip("/") != expected_iss: raise CliError("Sign-in response came from an unexpected issuer (%s) - ignored it." % iss, EXIT_USAGE, hint="Run `tft login` again.") if iss is None and meta.get("authorization_response_iss_parameter_supported"): raise CliError("Sign-in response is missing the issuer (iss) parameter - ignored it.", EXIT_USAGE, hint="Run `tft login` again.") if not res.get("code"): raise CliError("Sign-in response carried no authorization code.", EXIT_AUTH, hint="Run `tft login` again.") st, data = _token_post(meta, { "grant_type": "authorization_code", "code": res["code"], "redirect_uri": redirect_uri, "client_id": CLIENT_ID, "code_verifier": verifier, "resource": mcp_url}, timeout) if st != 200: raise CliError(_oauth_error(data, "Exchanging the sign-in code"), EXIT_AUTH, hint="Run `tft login` again.") return data def login_device(mcp_url, meta, timeout): ep = meta.get("device_authorization_endpoint") if not ep: raise CliError("The sign-in server does not support device sign-in.", EXIT_RUNTIME, hint="Use `tft login` (browser) instead.") st, _, raw = http("POST", ep, timeout, form={"client_id": CLIENT_ID, "scope": SCOPE, "resource": mcp_url}) data = parse_json(raw, "sign-in server") if isinstance(data, dict) and data.get("error") == "invalid_client": raise CliError("Device sign-in is not enabled for this server.", EXIT_AUTH, hint="Use `tft login` (browser sign-in) instead.") if st != 200 or not data.get("device_code"): raise CliError(_oauth_error(data, "Starting device sign-in"), EXIT_AUTH, hint="Use `tft login` (browser sign-in) instead.") uri = data.get("verification_uri_complete") or data.get("verification_uri") print("To sign in, open: %s" % data.get("verification_uri", uri), file=sys.stderr, flush=True) print("and enter the code: %s" % data.get("user_code", "?"), file=sys.stderr, flush=True) if data.get("verification_uri_complete"): print("(or open %s directly)" % data["verification_uri_complete"], file=sys.stderr, flush=True) interval = float(data.get("interval", 5)) deadline = time.time() + float(data.get("expires_in", 600)) log("Waiting for you to approve the sign-in...") while time.time() < deadline: time.sleep(interval) st, tok = _token_post(meta, { "grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": data["device_code"], "client_id": CLIENT_ID, "resource": mcp_url}, timeout) if st == 200 and tok.get("access_token"): return tok err = tok.get("error") if err == "authorization_pending": continue if err == "slow_down": interval += 5 continue if err == "access_denied": raise CliError("Sign-in was declined.", EXIT_AUTH, hint="Run `tft login` again.") if err == "expired_token": break raise CliError(_oauth_error(tok, "Device sign-in"), EXIT_AUTH, hint="Run `tft login` again.") raise CliError("The device code expired before the sign-in was approved.", EXIT_AUTH, hint="Run `tft login` again.") def refresh_tokens(rec, timeout): """New token record from the refresh token, or None when that is not possible.""" if not rec.get("refresh_token"): return None meta = {"token_endpoint": rec.get("token_endpoint"), "issuer": rec.get("issuer"), "revocation_endpoint": rec.get("revocation_endpoint")} if not meta["token_endpoint"]: meta = discover(rec["mcp_url"], timeout) log("Refreshing your sign-in...") st, data = _token_post(meta, {"grant_type": "refresh_token", "refresh_token": rec["refresh_token"], "client_id": CLIENT_ID, "resource": rec["mcp_url"]}, timeout) if st != 200 or not data.get("access_token"): debug(_oauth_error(data, "refresh")) return None new = _token_record(data, meta, rec["mcp_url"], previous=rec) write_private_json(_path("token.json"), new) return new # ====================================================================================== # Credentials + MCP client # ====================================================================================== NOT_SIGNED_IN_HINT = ("Run `tft login`. On a machine without a browser, `tft login --no-browser` " "prints the sign-in URL to open in a browser on this same machine.") class Session: def __init__(self, mcp_url, timeout): self.mcp_url = mcp_url self.timeout = timeout self._id = 0 self._rec = None self._env = os.environ.get("TFT_TOKEN", "").strip() or None self.last_error = None # ---- credentials ---- def stored(self): rec = read_json_file(_path("token.json")) if not isinstance(rec, dict) or not rec.get("access_token"): return None return rec def credentials(self): """Token record for this MCP URL, or CliError(3).""" if self._env: return {"access_token": self._env, "source": "TFT_TOKEN", "mcp_url": self.mcp_url} if self._rec is None: rec = self.stored() if rec is None: raise CliError("You are not signed in to TheFantasyTool.", EXIT_AUTH, hint=NOT_SIGNED_IN_HINT) if rec.get("mcp_url") != self.mcp_url: raise CliError("You are signed in for %s, not %s." % (rec.get("mcp_url"), self.mcp_url), EXIT_AUTH, hint="Run `tft login` to sign in for this server.") self._rec = rec exp = self._rec.get("expires_at") if exp and exp - 30 <= time.time() and self._rec.get("refresh_token"): new = refresh_tokens(self._rec, self.timeout) if new is None: raise CliError("Your TheFantasyTool sign-in has expired.", EXIT_AUTH, hint=NOT_SIGNED_IN_HINT) self._rec = new return self._rec # ---- JSON-RPC ---- def rpc(self, method, params=None): creds = self.credentials() self._id += 1 msg = {"jsonrpc": "2.0", "id": self._id, "method": method, "params": params or {}} headers = {"Accept": "application/json, text/event-stream", "MCP-Protocol-Version": MCP_PROTOCOL_VERSION} refreshed = retried_429 = False while True: st, rh, raw = http("POST", self.mcp_url, self.timeout, body=msg, headers=headers, token=creds["access_token"]) if st == 401: if not refreshed and creds.get("source") != "TFT_TOKEN": refreshed = True new = refresh_tokens(creds, self.timeout) if new is not None: self._rec = creds = new continue if creds.get("source") == "TFT_TOKEN": raise CliError("The server rejected the token in TFT_TOKEN.", EXIT_AUTH, hint="Set a fresh TFT_TOKEN, or unset it and run `tft login`.") raise CliError("Your TheFantasyTool sign-in has expired or was revoked.", EXIT_AUTH, hint=NOT_SIGNED_IN_HINT) if st == 429: wait = _retry_after(rh) if not retried_429 and wait is not None and wait <= MAX_RETRY_AFTER_S: retried_429 = True log("Rate limited by the server - retrying once in %ds..." % int(wait + 0.999)) time.sleep(wait) continue raise CliError("Rate limited by TheFantasyTool (too many requests).", EXIT_RUNTIME, hint="Wait %s and try again." % ( ("%d seconds" % int(wait)) if wait is not None else "a minute")) if st == 503: raise CliError("TheFantasyTool is temporarily unavailable (503).", EXIT_RUNTIME, hint="Try again in a minute.") if st >= 400: raise CliError("The server answered HTTP %s." % st, EXIT_RUNTIME, hint="Try again later; if it persists, check `tft status`.") break data = self._decode(rh, raw) if isinstance(data, dict) and data.get("error"): err = data["error"] code = EXIT_USAGE if err.get("code") in (-32601, -32602) else EXIT_RUNTIME raise CliError("Server error: %s" % err.get("message", err), code) if not isinstance(data, dict) or "result" not in data: raise CliError("Unexpected response from the server.", EXIT_RUNTIME) return data["result"] def _decode(self, rh, raw): ctype = (rh.get("content-type") or "").lower() if "text/event-stream" in ctype: found = None for line in raw.decode("utf-8", "replace").splitlines(): if line.startswith("data:"): try: obj = json.loads(line[5:].strip()) except ValueError: continue if isinstance(obj, dict) and obj.get("id") == self._id: found = obj if found is None: raise CliError("Unexpected streamed response from the server.", EXIT_RUNTIME) return found return parse_json(raw, "server") # ---- tools ---- def list_tools(self): tools = self.rpc("tools/list").get("tools") if not isinstance(tools, list): raise CliError("The server returned no tool list.", EXIT_RUNTIME) save_tools_cache(self.mcp_url, tools) return tools def call_tool(self, name, arguments): res = self.rpc("tools/call", {"name": name, "arguments": arguments}) data = res.get("structuredContent") if data is None: texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] joined = "\n".join(texts) try: data = json.loads(joined) except ValueError: data = {"text": joined} return data, bool(res.get("isError")) # ---- tools cache ---------------------------------------------------------------------- def load_tools_cache(mcp_url, allow_stale=False): c = read_json_file(_path("tools.json")) if not isinstance(c, dict) or c.get("mcp_url") != mcp_url or not isinstance(c.get("tools"), list): return None if not allow_stale and time.time() - float(c.get("fetched_at", 0)) > TOOLS_CACHE_TTL_S: return None return c["tools"] def save_tools_cache(mcp_url, tools): try: _ensure_dir() p = _path("tools.json") tmp = p + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump({"mcp_url": mcp_url, "fetched_at": time.time(), "tools": tools}, f) os.replace(tmp, p) except OSError as exc: debug("could not write tools cache: %s" % exc) def get_tools(session, refresh=False, required=False): """Tools from the fresh cache, else the server, else the stale cache. required=False -> never raises (returns [] or a stale list, with a note on stderr).""" if not refresh: cached = load_tools_cache(session.mcp_url) if cached is not None: return cached try: return session.list_tools() except CliError as exc: session.last_error = exc stale = load_tools_cache(session.mcp_url, allow_stale=True) if required or (refresh and stale is None): raise if stale is not None: debug("using stale tools cache: %s" % exc.message) return stale debug("no tools available: %s" % exc.message) return [] # ====================================================================================== # Argument parsing # ====================================================================================== class Parser(argparse.ArgumentParser): def error(self, message): self.print_usage(sys.stderr) hint = "" if "invalid choice" in message and self.prog.split()[-1] in ("tft", "tft.py"): hint = ("\nhint: tool commands come from the server - run `tft tools --refresh` " "(needs `tft login`) to see them.") sys.stderr.write("%s: error: %s%s\n" % (self.prog, message, hint)) sys.exit(EXIT_USAGE) FORMATTER = argparse.RawDescriptionHelpFormatter def _global_parent(): p = argparse.ArgumentParser(add_help=False) g = p.add_argument_group("global options") g.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="machine output: JSON on stdout (logs stay on stderr)") g.add_argument("--quiet", "-q", action="store_true", default=argparse.SUPPRESS, help="no progress messages on stderr") g.add_argument("--timeout", type=float, default=argparse.SUPPRESS, metavar="SECONDS", help="HTTP timeout per request (default %d)" % DEFAULT_TIMEOUT_S) g.add_argument("--mcp-url", default=argparse.SUPPRESS, metavar="URL", help="MCP server (default %s; env TFT_MCP_URL)" % DEFAULT_MCP_URL) return p def cli_name(tool_name): return tool_name.replace("_", "-") def _first_sentence(text, limit=90): t = " ".join(str(text or "").split()) m = re.match(r"(.+?[.!?])(\s|$)", t) s = m.group(1) if m else t return s if len(s) <= limit else s[:limit - 3] + "..." def _example_value(name, prop): if prop.get("enum"): return str(prop["enum"][0]) m = re.search(r"e\.g\.\s*'([^']+)'", prop.get("description", "")) if m: return m.group(1) m = re.search(r"e\.g\.\s*([A-Za-z0-9][A-Za-z0-9 /.-]*?)(?:[,.;)]|$)", prop.get("description", "")) if m and prop.get("type") in ("string", "array"): return m.group(1).strip() t = prop.get("type") if t == "integer": return "3" if t == "number": return "7.5" if t == "boolean": return None return name.upper().replace("_", "-") def _quote(v): return '"%s"' % v if re.search(r"[\s/;&|]", v) else v def derive_example(tool): schema = tool.get("inputSchema") or {} props = schema.get("properties") or {} req = list(schema.get("required") or []) parts = ["tft", cli_name(tool["name"])] for name in req: p = props.get(name, {}) flag = "--" + cli_name(name) v = _example_value(name, p) if p.get("type") == "boolean": parts.append(flag) else: parts += [flag, _quote(v)] return " ".join(parts) def tool_examples(tool): return STATIC_EXAMPLES.get(tool["name"]) or [derive_example(tool), derive_example(tool) + " --json"] def _split_values(raw, conv): out = [] for part in raw.split(","): part = part.strip() if part: out.append(conv(part)) return out def _json_value(s): try: return json.loads(s) except ValueError: raise argparse.ArgumentTypeError("not valid JSON: %r" % s) def _bool_value(s): v = str(s).strip().lower() if v in ("1", "true", "yes", "y", "on"): return True if v in ("0", "false", "no", "n", "off"): return False raise argparse.ArgumentTypeError("expected true/false, got %r" % s) _CONVERTERS = {"string": str, "integer": int, "number": float, "boolean": _bool_value} def _type_label(prop): t = prop.get("type") if t == "array": it = (prop.get("items") or {}).get("type", "string") return "%s, repeatable or comma-separated" % it return t or "json" def add_tool_parser(sub, tool, parent): name = tool["name"] schema = tool.get("inputSchema") or {} props = schema.get("properties") or {} required = set(schema.get("required") or []) examples = tool_examples(tool) desc = "%s\n\n%s" % (tool.get("title") or name, textwrap.fill(" ".join( str(tool.get("description") or "").split()), 88)) epilog = "examples:\n" + "\n".join(" " + e for e in examples) + "\n\n" + EXIT_CODES_TEXT aliases = [name] if cli_name(name) != name else [] p = sub.add_parser(cli_name(name), aliases=aliases, help=_first_sentence(tool.get("description")), description=desc, epilog=epilog, formatter_class=FORMATTER, parents=[parent]) p.set_defaults(_tool=name, _props=props) for pname, prop in props.items(): if not isinstance(prop, dict): prop = {} hy = cli_name(pname) if hy in GLOBAL_FLAG_NAMES or pname in GLOBAL_FLAG_NAMES: flags = ["--arg-" + hy] # never shadow a global flag else: flags = ["--" + hy] + (["--" + pname] if pname != hy else []) dest = "tool__" + pname t = prop.get("type") helptxt = " ".join(str(prop.get("description") or "").split()) helptxt = ("%s [%s%s]" % (helptxt, _type_label(prop), ", required" if pname in required else "")).strip() helptxt = helptxt.replace("%", "%%") if t == "array": items = prop.get("items") or {} conv = _CONVERTERS.get(items.get("type"), _json_value if items.get("type") in ("object", "array") else str) choices = items.get("enum") def make(conv=conv, choices=choices, pname=pname): def f(raw): vals = [raw] if conv is _json_value else _split_values(raw, conv) if choices: bad = [v for v in vals if v not in choices] if bad: raise argparse.ArgumentTypeError( "invalid value %r for %s (choose from %s)" % (bad[0], pname, ", ".join(map(str, choices)))) return vals return f p.add_argument(*flags, dest=dest, action="append", type=make(), metavar="VALUE", required=pname in required, help=helptxt) elif t == "boolean": p.add_argument(*flags, dest=dest, action=argparse.BooleanOptionalAction, default=None, help=helptxt) else: conv = _CONVERTERS.get(t, _json_value) kw = {"dest": dest, "type": conv, "required": pname in required, "help": helptxt, "metavar": pname.upper()} if prop.get("enum"): kw["choices"] = [conv(v) if conv is not _json_value else v for v in prop["enum"]] kw.pop("metavar") p.add_argument(*flags, **kw) return p def build_parser(tools): parent = _global_parent() tool_lines = "" if tools: tool_lines = "\n".join(" %-18s %s" % (cli_name(t["name"]), _first_sentence(t.get("description"), 70)) for t in tools if cli_name(t["name"]) not in BUILTINS) else: tool_lines = (" (not loaded - run `tft login`, then `tft tools` to load the tool commands " "from the server)") description = ( "tft - TheFantasyTool on the command line (read-only).\n\n" "Ask TheFantasyTool's predictions about your fantasy team: captain picks, transfers,\n" "players and fixtures. Requires a TheFantasyTool subscription that includes the game.\n\n" "Tool commands (from the server; `tft --help` for flags):\n" + tool_lines) epilog = ("examples:\n" " tft login\n" " tft list-games\n" " tft my-team --game \"Fantasy Premier League 2026/2027\"\n" " tft captain-options --game \"Fantasy Premier League 2026/2027\" --scope squad --json\n" " tft call best_transfers --args '{\"game\": \"Fantasy Premier League 2026/2027\"}'\n\n" "environment: TFT_MCP_URL, TFT_CONFIG_DIR, TFT_TOKEN (CI), TFT_DEBUG=1\n" "config dir: %s\n\n%s" % (config_dir(), EXIT_CODES_TEXT)) parser = Parser(prog="tft", description=description, epilog=epilog, formatter_class=FORMATTER, parents=[parent]) sub = parser.add_subparsers(dest="command", metavar="", title="commands") def builtin(name, help_, desc, examples): return sub.add_parser(name, help=help_, description=desc, parents=[parent], formatter_class=FORMATTER, epilog="examples:\n" + "\n".join(" " + e for e in examples) + "\n\n" + EXIT_CODES_TEXT) p = builtin("login", "sign in (opens your browser)", "Sign in to TheFantasyTool. Opens your browser (OAuth with PKCE, answer comes back to\n" "a one-shot listener on 127.0.0.1). Without a browser, --no-browser prints the URL to open yourself.", ["tft login", "tft login --no-browser"]) p.add_argument("--device", action="store_true", help="device-code sign-in; only works if the sign-in server enables it " "(thefantasytool.com does not yet)") p.add_argument("--no-browser", action="store_true", help="print the sign-in URL instead of opening a browser") builtin("logout", "sign out and revoke the saved token", "Revoke the saved sign-in at TheFantasyTool's sign-in server and delete the token file.", ["tft logout"]) builtin("status", "sign-in, server and account status", "Show whether you are signed in, when the sign-in expires, whether the server is\n" "reachable, how many tools it offers and which games your account includes.\n" "Never prints the token. Checking games uses one of the day's lookups.", ["tft status", "tft status --json"]) p = builtin("tools", "list the server's tools", "List the tools the server offers (cached for 1 hour in the config dir).", ["tft tools", "tft tools --refresh", "tft tools --json"]) p.add_argument("--refresh", action="store_true", help="ignore the cache and ask the server") p = builtin("call", "call any tool with raw JSON arguments", "Raw escape hatch: call a tool by name with a JSON object of arguments, from --args,\n" "--args-file or stdin (`-`). Output is the tool's result.", ["tft call list_games", "tft call best_transfers --args '{\"game\": \"Fantasy Premier League 2026/2027\", \"rounds\": 3}'", "tft call my_team --args-file args.json", "echo '{\"game\": \"Fantasy Premier League 2026/2027\"}' | tft call my_team -"]) p.add_argument("tool", help="tool name, e.g. best_transfers") p.add_argument("stdin", nargs="?", choices=["-"], help="read the JSON arguments from stdin") p.add_argument("--args", dest="call_args", metavar="JSON", help="arguments as a JSON object") p.add_argument("--args-file", metavar="PATH", help="file holding the JSON arguments ('-' = stdin)") p = builtin("mcp-config", "print config to connect an AI client to the MCP server", "Print the snippet that connects an AI client straight to TheFantasyTool's MCP server.\n" "The client does its own sign-in; your CLI token is never put in a config.", ["tft mcp-config", "tft mcp-config claude-code", "tft mcp-config cursor --json"]) p.add_argument("client", nargs="?", choices=list(MCP_CLIENTS), help="which client (default: all)") builtin("version", "print the version", "Print the CLI version and the server it talks to.", ["tft version"]) seen = set(BUILTINS) for t in tools: if not isinstance(t, dict) or not t.get("name"): continue n = cli_name(t["name"]) if n in seen or t["name"] in seen: debug("tool %s collides with a built-in command; use `tft call %s`" % (t["name"], t["name"])) continue seen.update({n, t["name"]}) add_tool_parser(sub, t, parent) return parser def prescan(argv): """(command, global flag values) from argv without a full parse.""" vals = {} cmd = None i = 0 while i < len(argv): a = argv[i] if a == "--": break if a.startswith("-"): key = a.split("=", 1)[0] if key in GLOBAL_VALUE_FLAGS: if "=" in a: vals[key] = a.split("=", 1)[1] elif i + 1 < len(argv): vals[key] = argv[i + 1] i += 1 elif key in ("--json", "--quiet", "-q"): vals[key] = True elif key in ("-h", "--help"): vals["help"] = True elif cmd is None: cmd = a i += 1 return cmd, vals # ====================================================================================== # Commands # ====================================================================================== MCP_CLIENTS = ("claude-code", "claude-desktop", "cursor", "vscode") def mcp_snippets(url): return { "claude-code": { "how": "Run in a terminal, then type /mcp inside Claude Code to sign in:", "command": "claude mcp add --transport http thefantasytool %s" % url, }, "claude-desktop": { "how": ("Settings > Connectors > Add custom connector: name TheFantasyTool, URL below. " "Claude signs you in when you first use it."), "url": url, }, "cursor": { "how": "Add to ~/.cursor/mcp.json (or .cursor/mcp.json in a project):", "json": {"mcpServers": {"thefantasytool": {"url": url}}}, }, "vscode": { "how": "Add to .vscode/mcp.json (VS Code with GitHub Copilot agent mode):", "json": {"servers": {"thefantasytool": {"type": "http", "url": url}}}, }, } def cmd_mcp_config(args, ctx): snips = mcp_snippets(ctx.mcp_url) chosen = [args.client] if args.client else list(MCP_CLIENTS) if ctx.json: emit_json({c: snips[c] for c in chosen}) return EXIT_OK out = [] for c in chosen: s = snips[c] out.append("# %s" % c) out.append("# " + s["how"]) if "command" in s: out.append(s["command"]) if "url" in s: out.append(s["url"]) if "json" in s: out.append(json.dumps(s["json"], indent=2)) out.append("") sys.stdout.write("\n".join(out)) return EXIT_OK def cmd_version(args, ctx): if ctx.json: emit_json({"name": "tft-cli", "version": VERSION, "mcp_url": ctx.mcp_url}) else: print("tft-cli %s (%s)" % (VERSION, ctx.mcp_url)) return EXIT_OK def cmd_login(args, ctx): if os.environ.get("TFT_TOKEN"): warn("TFT_TOKEN is set and will keep overriding the saved sign-in until you unset it.") meta = discover(ctx.mcp_url, ctx.timeout) if args.device: tok = login_device(ctx.mcp_url, meta, ctx.timeout) else: tok = login_browser(ctx.mcp_url, meta, ctx.timeout, open_browser=not args.no_browser) rec = _token_record(tok, meta, ctx.mcp_url) write_private_json(_path("token.json"), rec) log("Signed in. Token saved to %s" % _path("token.json")) if not rec.get("refresh_token"): warn("no refresh token was issued - you will need to `tft login` again when this one expires.") try: n = len(Session(ctx.mcp_url, ctx.timeout).list_tools()) log("%d tools available - run `tft tools` or `tft --help`." % n) except CliError as exc: warn("signed in, but loading the tool list failed: %s" % exc.message) if ctx.json: emit_json({"signed_in": True, "expires_at": rec.get("expires_at"), "token_file": _path("token.json")}) return EXIT_OK def cmd_logout(args, ctx): p = _path("token.json") rec = read_json_file(p) revoked = [] if isinstance(rec, dict) and rec.get("access_token"): ep = rec.get("revocation_endpoint") if not ep: try: ep = discover(rec.get("mcp_url") or ctx.mcp_url, ctx.timeout).get("revocation_endpoint") except CliError: ep = None if ep: for kind in ("refresh_token", "access_token"): if not rec.get(kind): continue try: st, _, _ = http("POST", ep, ctx.timeout, form={ "token": rec[kind], "token_type_hint": kind, "client_id": CLIENT_ID}) if st == 200: revoked.append(kind) else: warn("could not revoke the %s (HTTP %s); deleting it locally anyway." % (kind.replace("_", " "), st)) except CliError as exc: warn("could not revoke the %s (%s); deleting it locally anyway." % (kind.replace("_", " "), exc.message)) else: warn("no revocation endpoint known; deleting the token locally only.") existed = os.path.exists(p) if existed: os.remove(p) if os.environ.get("TFT_TOKEN"): warn("TFT_TOKEN is still set in your environment; unset it yourself.") msg = "Signed out." if existed else "You were not signed in." if ctx.json: emit_json({"signed_out": True, "was_signed_in": existed, "revoked": revoked}) else: log(msg) return EXIT_OK def _fmt_time(ts): if not ts: return None left = ts - time.time() when = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) if left <= 0: return "%s (expired - renews automatically on next use)" % when if left < 3600: return "%s (in %d min)" % (when, left // 60) if left < 172800: return "%s (in %.1f h)" % (when, left / 3600) return "%s (in %d days)" % (when, left // 86400) def cmd_status(args, ctx): s = Session(ctx.mcp_url, ctx.timeout) out = {"server": ctx.mcp_url, "cli_version": VERSION} code = EXIT_OK # reachability: the public resource metadata needs no sign-in try: st, _, _ = http("GET", _origin(ctx.mcp_url) + "/.well-known/oauth-protected-resource", ctx.timeout) out["server_reachable"] = st == 200 except CliError: out["server_reachable"] = False rec = s.stored() if os.environ.get("TFT_TOKEN"): out["signed_in"] = True out["credentials"] = "TFT_TOKEN environment variable" elif rec and rec.get("mcp_url") == ctx.mcp_url: out["signed_in"] = True out["credentials"] = _path("token.json") out["token_expires"] = _fmt_time(rec.get("expires_at")) or "unknown" out["refresh_token"] = "yes" if rec.get("refresh_token") else "no" else: out["signed_in"] = False out["hint"] = NOT_SIGNED_IN_HINT code = EXIT_AUTH if out["signed_in"]: try: out["tools"] = len(s.list_tools()) data, is_err = s.call_tool("list_games", {}) games = data.get("games") if isinstance(data, dict) else None if isinstance(games, list): out["games_included"] = [g.get("game") for g in games if g.get("included_in_account")] if not out["games_included"]: out["account_note"] = data.get("note") or "This account includes no games." if is_err: out["account_note"] = data.get("error") if isinstance(data, dict) else str(data) except CliError as exc: out["error"] = exc.message if exc.hint: out["hint"] = exc.hint code = exc.code # the calls above may have refreshed the token: report the CURRENT expiry cur = s._rec if (s._rec and not os.environ.get("TFT_TOKEN")) else None if cur and "token_expires" in out: out["token_expires"] = _fmt_time(cur.get("expires_at")) or "unknown" out["refresh_token"] = "yes" if cur.get("refresh_token") else "no" print_result(out, ctx.json) return code def cmd_tools(args, ctx): s = Session(ctx.mcp_url, ctx.timeout) tools = get_tools(s, refresh=args.refresh, required=True) if ctx.json: emit_json(tools) return EXIT_OK rows = [] for t in tools: schema = t.get("inputSchema") or {} rows.append({"command": cli_name(t["name"]), "tool": t["name"], "required": ", ".join("--" + cli_name(r) for r in schema.get("required") or []) or "-", "description": _first_sentence(t.get("description"), 60)}) print_result(rows, False) return EXIT_OK def _read_args_json(text, source): try: val = json.loads(text) if text.strip() else {} except ValueError as exc: raise CliError("Arguments from %s are not valid JSON: %s" % (source, exc), EXIT_USAGE, hint="Pass a JSON object, e.g. --args '{\"game\": \"...\"}'.") if not isinstance(val, dict): raise CliError("Arguments from %s must be a JSON object, got %s." % (source, type(val).__name__), EXIT_USAGE) return val def cmd_call(args, ctx): sources = [x for x in (args.call_args is not None, args.args_file is not None, args.stdin == "-") if x] if len(sources) > 1: raise CliError("Give the arguments once: --args, --args-file or - (stdin).", EXIT_USAGE) if args.call_args is not None: arguments = _read_args_json(args.call_args, "--args") elif args.args_file is not None: if args.args_file == "-": arguments = _read_args_json(sys.stdin.read(), "stdin") else: try: with open(args.args_file, encoding="utf-8") as f: arguments = _read_args_json(f.read(), args.args_file) except OSError as exc: raise CliError("Cannot read %s: %s" % (args.args_file, exc.strerror), EXIT_USAGE) elif args.stdin == "-": arguments = _read_args_json(sys.stdin.read(), "stdin") else: arguments = {} s = Session(ctx.mcp_url, ctx.timeout) name = args.tool known = {t.get("name") for t in get_tools(s)} if known and name not in known and name.replace("-", "_") in known: name = name.replace("-", "_") return run_tool(s, ctx, name, arguments) def _tool_hint(text): t = str(text) if "list_games" in t or "Which game" in t: return "Run `tft list-games` for the exact game names." return None def run_tool(session, ctx, name, arguments): debug("call %s %s" % (name, json.dumps(arguments, ensure_ascii=False))) data, is_error = session.call_tool(name, arguments) if is_error: msg = data.get("error") if isinstance(data, dict) and data.get("error") else ( data.get("text") if isinstance(data, dict) else str(data)) if ctx.json: emit_json(data) print("tft: %s" % msg, file=sys.stderr, flush=True) hint = _tool_hint(msg) if hint: print("hint: %s" % hint, file=sys.stderr, flush=True) return EXIT_USAGE print_result(data, ctx.json) return EXIT_OK def cmd_tool(args, ctx): arguments = {} for pname in args._props: v = getattr(args, "tool__" + pname, None) if v is None: continue prop = args._props[pname] if isinstance(args._props[pname], dict) else {} if prop.get("type") == "array": flat = [] for chunk in v: flat.extend(chunk) v = flat arguments[pname] = v return run_tool(Session(ctx.mcp_url, ctx.timeout), ctx, args._tool, arguments) COMMANDS = {"login": cmd_login, "logout": cmd_logout, "status": cmd_status, "tools": cmd_tools, "call": cmd_call, "mcp-config": cmd_mcp_config, "version": cmd_version} class Context: pass def main(argv=None): global _QUIET argv = list(sys.argv[1:] if argv is None else argv) if not sys.stdout.isatty(): try: sys.stdout.reconfigure(encoding="utf-8") except (AttributeError, ValueError): pass cmd, pre = prescan(argv) _QUIET = bool(pre.get("--quiet") or pre.get("-q")) want_json = bool(pre.get("--json")) ctx = Context() ctx.json = want_json try: try: ctx.timeout = float(pre["--timeout"]) if "--timeout" in pre else resolve_timeout(None) except ValueError: ctx.timeout = DEFAULT_TIMEOUT_S # argparse reports the bad value below ctx.mcp_url = resolve_mcp_url(pre.get("--mcp-url")) # Tool commands come from the server; built-ins never need it. tools = [] if cmd is None or cmd not in BUILTINS: session = Session(ctx.mcp_url, ctx.timeout) tools = get_tools(session, required=False) names = {n for t in tools if isinstance(t, dict) for n in (t.get("name"), cli_name(t.get("name") or ""))} if cmd is not None and cmd not in names and session.last_error is not None: # `tft my-team ...` while signed out: say THAT, not "invalid choice". raise session.last_error parser = build_parser(tools) args = parser.parse_args(argv) ctx.json = bool(getattr(args, "json", False)) _QUIET = bool(getattr(args, "quiet", False)) if getattr(args, "timeout", None) is not None: ctx.timeout = args.timeout if getattr(args, "mcp_url", None): ctx.mcp_url = check_mcp_url(args.mcp_url) if ctx.timeout <= 0: raise CliError("--timeout must be positive.", EXIT_USAGE) if args.command is None: parser.print_help(sys.stderr) return EXIT_USAGE if hasattr(args, "_tool"): return cmd_tool(args, ctx) return COMMANDS[args.command](args, ctx) except CliError as exc: print("tft: %s" % exc.message, file=sys.stderr, flush=True) if exc.hint: print("hint: %s" % exc.hint, file=sys.stderr, flush=True) if ctx.json: emit_json({"error": exc.message, "hint": exc.hint, "exit_code": exc.code}) return exc.code except KeyboardInterrupt: print("tft: cancelled", file=sys.stderr) return 130 if __name__ == "__main__": sys.exit(main())