"""Knox MCP server: the tools a customer's coding agent uses to integrate an app with Knox in test mode (rdp-7dyt). Run it as a local stdio MCP server from the customer's repository. Python 3.10+, standard library only, so it can be downloaded from https://docs.knoxapi.com/agent-setup/tools/knox-mcp.py and run without installing anything: claude mcp add knox -- python3 /path/to/knox-mcp.py # Claude Code codex mcp add knox -- python3 /path/to/knox-mcp.py # Codex Decision D5 (rdp-rsak): the integration agent is the customer's existing coding agent with this MCP server and the knox-integrate skill. Knox runs no agent of its own. The server never edits the customer's code; the agent does. Tools (layout after juspay-mcp: one input schema and one handler per tool; preflight after its session_preflight, "ask, never guess"): - knox_request_test_keys / knox_poll_test_keys: the device-style key request (POST /knox/v1/agent/key_requests on the Meta host). The developer signs up (self-serve, test mode) or signs in and types the code. Keys are written to a git-ignored env file and never returned to the agent or printed. - knox_integration_spec: the prescribed integration for the detected day-1 stack (D4: Node/TypeScript with Express or Next.js, Python with FastAPI or Django), the template files and the anchored edits. - knox_preflight: which facts are still missing before the integration can be written, and who must supply them. - knox_register_webhook: registers the app's webhook endpoint and stores its signing secret in the env file. - knox_test_payment: a test PaymentIntent on the server key, or confirms an app-created one the way a browser does. - knox_integration_status: Knox's readiness checks, with what to do about each pending one. Configuration (environment of the MCP server process, all optional): KNOX_API_BASE Stripe-compatible API, default https://api.knoxapi.com KNOX_CONTROL_BASE Meta host for key requests and integration status, default https://meta.knoxapi.com KNOX_CONTROL_PREFIX prefix of the control API on that host, default /v1 (a local Knox serves /knox/v1) KNOX_DOCS_BASE docs host for templates and guides, default https://docs.knoxapi.com KNOX_ENV_FILE env file for keys, relative to the repository, default .env.knox KNOX_REPO repository root, default the current directory Secrets: no tool result contains a secret key, restricted key, webhook secret or client secret. Live keys are refused. Card numbers never pass through here; test payments use Knox test payment methods (pm_card_visa). """ from __future__ import annotations import itertools import json import os import re import subprocess import sys import time import urllib.error import urllib.parse import urllib.request from pathlib import Path SERVER_NAME = "knox" SERVER_VERSION = "0.1.0" PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") KEY_REQUEST_PATH = "/knox/v1/agent/key_requests" TEST_PAYMENT_METHODS = ("pm_card_visa", "pm_card_mastercard", "pm_card_chargeDeclined") ENV_NAMES = ("KNOX_SECRET_KEY", "KNOX_PUBLISHABLE_KEY", "KNOX_WEBHOOK_SECRET") LIVE = re.compile(r"^(sk|rk|pk)_live_") SERVER_KEY = re.compile(r"^(sk|rk)_test_[A-Za-z0-9_-]+$") PUBLISHABLE_KEY = re.compile(r"^pk_test_[A-Za-z0-9_-]+$") SECRETISH = re.compile(r"\b(?:sk|rk|pk)_(?:test|live)_[A-Za-z0-9_-]+|\bwhsec_[A-Za-z0-9_-]+|\b(?:pi|seti)_[A-Za-z0-9]+_secret_[A-Za-z0-9_-]+|\bakr_[A-Za-z0-9_-]+") INSTRUCTIONS = """Knox is a Stripe-compatible payments API. Use these tools with the knox-integrate skill (https://docs.knoxapi.com/agent-setup/skills/knox-integrate/SKILL.md) to integrate this repository in test mode. Order: knox_integration_spec -> knox_preflight (ask the developer for every missing fact; never guess amounts, currencies or account emails) -> knox_request_test_keys / knox_poll_test_keys -> apply the template on a branch -> knox_register_webhook -> run the app and pay through Knox's hosted card fields -> knox_integration_status. Keys are written to a git-ignored env file and never shown to you; do not ask the developer to paste keys into chat.""" class ToolError(Exception): """A refusal or failure the agent should read and act on (isError result), not a protocol error.""" def config() -> dict: env = os.environ return { "api_base": env.get("KNOX_API_BASE", "https://api.knoxapi.com").rstrip("/"), "control_base": env.get("KNOX_CONTROL_BASE", "https://meta.knoxapi.com").rstrip("/"), "control_prefix": "/" + env.get("KNOX_CONTROL_PREFIX", "/v1").strip("/"), "docs_base": env.get("KNOX_DOCS_BASE", "https://docs.knoxapi.com").rstrip("/"), "env_file": env.get("KNOX_ENV_FILE", ".env.knox"), "repo": env.get("KNOX_REPO", os.getcwd()), } def redact(text: str) -> str: return SECRETISH.sub(lambda m: m.group(0).split("_")[0] + "_[redacted]", text) # ---- HTTP --------------------------------------------------------------------------------------------------------- def _flatten(params: dict, prefix: str = "") -> list[tuple[str, str]]: out: list[tuple[str, str]] = [] for key, value in params.items(): name = f"{prefix}[{key}]" if prefix else str(key) if isinstance(value, dict): out.extend(_flatten(value, name)) elif isinstance(value, (list, tuple)): for i, item in enumerate(value): if isinstance(item, dict): out.extend(_flatten(item, f"{name}[{i}]")) else: out.append((f"{name}[{i}]", str(item))) elif isinstance(value, bool): out.append((name, "true" if value else "false")) elif value is not None: out.append((name, str(value))) return out def http(method: str, url: str, *, key: str | None = None, form: dict | None = None, body: dict | None = None, headers: dict | None = None, timeout: float = 30) -> tuple[int, dict]: data = None sent = {"User-Agent": f"knox-mcp/{SERVER_VERSION}", "Accept": "application/json"} if key: sent["Authorization"] = f"Bearer {key}" if form is not None: data = urllib.parse.urlencode(_flatten(form)).encode() sent["Content-Type"] = "application/x-www-form-urlencoded" elif body is not None: data = json.dumps(body).encode() sent["Content-Type"] = "application/json" sent.update(headers or {}) request = urllib.request.Request(url, data=data, method=method, headers=sent) try: with urllib.request.urlopen(request, timeout=timeout) as response: status, raw = response.status, response.read() except urllib.error.HTTPError as exc: status, raw = exc.code, exc.read() except (urllib.error.URLError, TimeoutError, OSError) as exc: raise ToolError(f"Could not reach {url.split('?')[0]}: {exc}") from None try: parsed = json.loads(raw.decode() or "{}") except ValueError: parsed = {"raw": raw.decode(errors="replace")[:500]} return status, parsed if isinstance(parsed, dict) else {"data": parsed} def _error_text(status: int, body: dict) -> str: error = body.get("error") if isinstance(body.get("error"), dict) else {} message = error.get("message") or body.get("raw") or json.dumps(body)[:300] code = error.get("code") return redact(f"HTTP {status}" + (f" ({code})" if code else "") + f": {message}") # ---- env file ----------------------------------------------------------------------------------------------------- def repo_root(arguments: dict) -> Path: root = Path(arguments.get("repo") or config()["repo"]).expanduser().resolve() if not root.is_dir(): raise ToolError(f"Repository directory {root} does not exist.") return root def env_path(arguments: dict) -> Path: root = repo_root(arguments) path = (root / (arguments.get("env_file") or config()["env_file"])).resolve() if root not in path.parents: raise ToolError("env_file must be inside the repository.") return path def read_env_file(path: Path) -> dict: values = {} if path.is_file(): for line in path.read_text().splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue name, _, value = line.partition("=") values[name.strip().removeprefix("export ").strip()] = value.strip().strip("'\"") return values def git_ignored(root: Path, path: Path) -> bool | None: """True or False inside a git work tree; None when the repository is not a git work tree.""" try: inside = subprocess.run(["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True, timeout=10) if inside.returncode != 0: return None result = subprocess.run(["git", "-C", str(root), "check-ignore", "-q", str(path)], capture_output=True, timeout=10) except (OSError, subprocess.SubprocessError): return None return result.returncode == 0 def write_env_values(arguments: dict, values: dict) -> str: """Merge values into the env file after proving git ignores it. Returns the file's repository-relative path.""" root, path = repo_root(arguments), env_path(arguments) ignored = git_ignored(root, path) if ignored is False: raise ToolError(f"{path.relative_to(root)} is not ignored by git. Add it to .gitignore (for example a line " f"'{path.name}'), confirm with `git check-ignore {path.relative_to(root)}`, then call this tool again. " "Nothing was written.") current = read_env_file(path) current.update(values) lines = [f"{name}={value}" for name, value in current.items()] path.parent.mkdir(parents=True, exist_ok=True) fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as handle: handle.write("# Knox test-mode credentials, written by the Knox MCP server. Never commit this file.\n") handle.write("\n".join(lines) + "\n") return str(path.relative_to(root)) def keys(arguments: dict) -> dict: """Process environment first, then the env file. Values stay inside this process.""" found = read_env_file(env_path(arguments)) for name in ENV_NAMES: if os.environ.get(name): found[name] = os.environ[name] for name in ENV_NAMES: if LIVE.match(found.get(name, "")): raise ToolError(f"{name} is a live key. This workflow is test mode only; use a test key.") return found def server_key(arguments: dict) -> str: key = keys(arguments).get("KNOX_SECRET_KEY", "") if not SERVER_KEY.match(key): raise ToolError("No Knox test server key (KNOX_SECRET_KEY, sk_test_ or rk_test_) in the environment or the env " "file. Call knox_request_test_keys first.") return key def publishable_key(arguments: dict) -> str: key = keys(arguments).get("KNOX_PUBLISHABLE_KEY", "") if not PUBLISHABLE_KEY.match(key): raise ToolError("No Knox test publishable key (KNOX_PUBLISHABLE_KEY, pk_test_). Call knox_request_test_keys first.") return key def mask(value: str) -> str: return value[:8] + "..." + value[-4:] if len(value) > 16 else "[set]" # ---- keys --------------------------------------------------------------------------------------------------------- PENDING: dict[str, dict] = {} # local handle -> {"id", "interval", "expires_at"}; the request id is a poll secret _HANDLES = itertools.count(1) def request_test_keys(arguments: dict) -> dict: email = str(arguments.get("email") or "").strip() if not email: raise ToolError("email is required. Ask the developer which email their Knox account uses (or should use for a " "new test-mode account). Do not guess it.") repo = repo_root(arguments) repository = str(arguments.get("repository") or repo.name) agent_name = str(arguments.get("agent_name") or "Coding agent") status, body = http("POST", config()["control_base"] + KEY_REQUEST_PATH, body={"email": email, "agent_name": agent_name, "repository": repository}) if status != 201: raise ToolError(_error_text(status, body) + ". Tell the developer; do not retry on your own.") handle = f"knox-key-request-{next(_HANDLES)}" # never reuses a handle, even after earlier ones are popped PENDING[handle] = {"id": body["id"], "interval": int(body.get("interval") or 5), "expires_at": body.get("expires_at"), "last_poll": 0.0} dashboard = body["verification_url"].split("/agents/approve")[0] return { "handle": handle, "user_code": body["user_code"], "verification_url": body["verification_url"], "expires_at": body.get("expires_at"), "interval": int(body.get("interval") or 5), "show_the_developer": (f"Open {body['verification_url']} signed in as {email}, type the code {body['user_code']} " "and click Approve. " f"No Knox account yet? Create a free test-mode account at {dashboard}/register with that " "email first (the approval email links there too)."), "next_action": "Show the developer user_code and verification_url exactly as returned, then call " "knox_poll_test_keys with this handle until it reports approved, denied or expired.", } def poll_test_keys(arguments: dict) -> dict: handle = str(arguments.get("handle") or "") pending = PENDING.get(handle) if pending is None: raise ToolError("Unknown handle. Start again with knox_request_test_keys.") wait = float(arguments.get("wait_seconds") if arguments.get("wait_seconds") is not None else 0) deadline = time.monotonic() + max(0.0, min(wait, 600.0)) while True: sleep = pending["last_poll"] + pending["interval"] + 0.2 - time.monotonic() if sleep > 0: time.sleep(sleep) pending["last_poll"] = time.monotonic() status, body = http("GET", f"{config()['control_base']}{KEY_REQUEST_PATH}/{urllib.parse.quote(pending['id'])}") if status == 429 and (body.get("error") or {}).get("code") == "slow_down": pending["interval"] += 5 elif status == 404: PENDING.pop(handle, None) raise ToolError("The key request is gone (expired more than a day ago or unknown). Tell the developer.") elif status != 200: raise ToolError(_error_text(status, body)) elif body.get("status") == "approved" and body.get("secret_key"): secret, publishable = body["secret_key"], body.get("publishable_key") or "" if LIVE.match(secret) or LIVE.match(publishable): raise ToolError("Knox returned a live key; refusing to store it. Tell the developer.") written = write_env_values(arguments, { "KNOX_SECRET_KEY": secret, "KNOX_PUBLISHABLE_KEY": publishable, "KNOX_API_BASE": config()["api_base"]}) PENDING.pop(handle, None) return {"status": "approved", "key_id": body.get("key_id"), "env_file": written, "server_key_kind": "restricted" if secret.startswith("rk_") else "secret", "stored": ["KNOX_SECRET_KEY", "KNOX_PUBLISHABLE_KEY", "KNOX_API_BASE"], "next_action": f"Keys are in {written} (git-ignored, mode 600). Load them from the environment in " "the app; never print or commit them."} elif body.get("status") == "approved": PENDING.pop(handle, None) raise ToolError("The request was approved but its keys were already delivered to an earlier poll. Start a " "new request if they were not saved.") elif body.get("status") in ("denied", "expired"): PENDING.pop(handle, None) return {"status": body["status"], "next_action": "Stop and tell the developer. Do not retry on your own."} if time.monotonic() >= deadline: return {"status": "pending", "next_action": "Still waiting for the developer to approve. Call again."} # ---- spec and preflight --------------------------------------------------------------------------------------------- # Day-1 stacks (D4, rdp-vz29). Each has a prescribed template on the docs host and an unmodified Stripe reference app # (knoxapi/agent/reference_apps/) that the acceptance run integrates with that template (rdp-6n6r). STACKS = { "express": {"language": "node", "framework": "Express", "template": "express", "reference_app": "express-stripe"}, "nextjs": {"language": "node", "framework": "Next.js", "template": "nextjs", "reference_app": "nextjs-stripe"}, "fastapi": {"language": "python", "framework": "FastAPI", "template": "fastapi", "reference_app": "fastapi-stripe"}, "django": {"language": "python", "framework": "Django", "template": "django", "reference_app": "django-stripe"}, } REFERENCE_APPS = "knoxapi/agent/reference_apps" SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "dist", "build", ".next", "__pycache__"} def _read(path: Path) -> str: try: return path.read_text() if path.stat().st_size < 1_000_000 else "" except (OSError, UnicodeError): return "" # Incumbents other than Stripe, by their SDK name or API hosts and endpoints (rdp-4kk3: an NMI app was read as fresh). OTHER_PROVIDERS = ( ("braintree", r"\bbraintree\b"), ("adyen", r"\badyen\b"), ("paypal", r"paypal\.com|@paypal/"), ("nmi", r"secure\.networkmerchants\.com|(?:secure|sandbox)\.nmi\.com|api/transact\.php|api/v2/three-step"), ("paysafe", r"api\.(?:test\.)?paysafe\.com|hosted\.(?:test\.)?paysafe\.com|paysafe\.(?:js|checkout)\b"), ("authorize_net", r"authorizenet|api(?:test)?\.authorize\.net"), ("checkout_com", r"api\.(?:sandbox\.)?checkout\.com"), ) def detect(root: Path) -> dict: """Stack and incumbent provider signals from manifests and imports. Heuristic; the agent confirms by reading code.""" stacks, providers, files = set(), set(), [] package = root / "package.json" if package.is_file(): try: manifest = json.loads(_read(package) or "{}") except ValueError: manifest = {} deps = {**manifest.get("dependencies", {}), **manifest.get("devDependencies", {})} if "next" in deps: stacks.add("nextjs") if "express" in deps: stacks.add("express") if "stripe" in deps or "@stripe/stripe-js" in deps: providers.add("stripe") python_manifests = " ".join(_read(root / name).lower() for name in ("requirements.txt", "pyproject.toml", "Pipfile")) if re.search(r"\bfastapi\b", python_manifests): stacks.add("fastapi") if re.search(r"\bdjango\b", python_manifests): stacks.add("django") if re.search(r"\bstripe\b", python_manifests): providers.add("stripe") for directory, folders, names in os.walk(root): folders[:] = [f for f in folders if f not in SKIP_DIRS and not f.startswith(".")] for name in names: if Path(name).suffix not in (".js", ".cjs", ".mjs", ".jsx", ".ts", ".tsx", ".py", ".html"): continue text = _read(Path(directory) / name) if re.search(r"js\.stripe\.com|require\(['\"]stripe['\"]\)|from ['\"](?:@stripe/stripe-js|stripe)['\"]|^\s*import stripe\b", text, re.M): providers.add("stripe") files.append(str((Path(directory) / name).relative_to(root))) for other, pattern in OTHER_PROVIDERS: if re.search(pattern, text, re.I): providers.add(other) workflow = ("fresh" if not providers else "stripe_to_knox" if providers == {"stripe"} else "processor_to_contract") return {"stacks": sorted(stacks), "providers": sorted(providers), "stripe_files": sorted(files), "workflow": workflow} def integration_spec(arguments: dict) -> dict: root = repo_root(arguments) found = detect(root) stack = arguments.get("stack") or (found["stacks"][0] if len(found["stacks"]) == 1 else None) cfg = config() spec = { "repository": str(root), "detected": found, "stack": stack, "api_base": cfg["api_base"], "browser_sdk": f"{cfg['api_base']}/js/v1/knox.js", "integration_status": f"{cfg['control_base']}{cfg['control_prefix']}/integration_status", "docs": {"llms_txt": f"{cfg['docs_base']}/llms.txt", "openapi": f"{cfg['docs_base']}/openapi/knox.json", "skill": f"{cfg['docs_base']}/agent-setup/skills/knox-integrate/SKILL.md", "stripe_migration": f"{cfg['docs_base']}/agent-setup/stripe-to-knox.md"}, "env": {"KNOX_SECRET_KEY": "server key, sk_test_ or rk_test_", "KNOX_PUBLISHABLE_KEY": "pk_test_", "KNOX_WEBHOOK_SECRET": "whsec_ from knox_register_webhook", "KNOX_API_BASE": cfg["api_base"], "PAYMENTS_PROVIDER": "'knox' selects the Knox arm; anything else keeps the incumbent"}, "rules": [ "Work on a new branch; open a pull request at the end. Change only what the integration needs.", "Keep the incumbent Stripe SDK, imports and configuration; Knox is added as an arm selected by PAYMENTS_PROVIDER.", "Keys only from the environment. Never write keys, webhook secrets or card numbers into code, tests or logs.", "Card data only inside Knox's hosted card fields (knox.js); never build card inputs on the merchant's page.", "Amounts are computed on the server from the stored order, in minor units; never trust the browser's amount.", "Fulfil only from a verified payment_intent.succeeded webhook, once per order.", "Unknown business facts (amount source, currency, account email): ask. Never guess.", ], "required_checks": ["secret_key_used", "publishable_key_used", "test_payment_succeeded", "payment_confirmed_client_side", "webhook_endpoint_enabled", "webhook_payment_succeeded_delivered", "card_fields_mounted"], } if stack is None: spec["next_action"] = ("Could not pick one day-1 stack from the manifests (found: " f"{', '.join(found['stacks']) or 'none'}). Read the app, then call again with stack set to " f"one of {', '.join(STACKS)}. If it is none of them, tell the developer it is not a day-1 stack.") return spec if stack not in STACKS: raise ToolError(f"Unsupported stack {stack!r}. Day-1 stacks: {', '.join(STACKS)}.") info = STACKS[stack] spec["stack_info"] = {k: v for k, v in info.items() if k != "template"} base = f"{cfg['docs_base']}/agent-setup/templates/{info['template']}" status, body = http("GET", f"{base}/template.json") if status != 200: raise ToolError(f"Template for {stack} unavailable from {base}/template.json: " + _error_text(status, body)) files = {} for name in body.get("files", []): request = urllib.request.Request(f"{base}/{name}", headers={"User-Agent": f"knox-mcp/{SERVER_VERSION}"}) try: with urllib.request.urlopen(request, timeout=30) as response: files[name] = response.read().decode() except (urllib.error.URLError, OSError) as exc: raise ToolError(f"Could not download template file {name}: {exc}") from None spec["template"] = {**body, "base_url": base, "file_contents": files} spec["reference_app"] = { "name": info["reference_app"], "source": f"{REFERENCE_APPS}/{info['reference_app']}", "about": f"The unmodified Stripe {info['framework']} app this template is verified against: Knox's acceptance run " "applies template.edits to it with no human edits and pays through Knox's hosted card fields.", } spec["next_action"] = ("Call knox_preflight with the facts you established from the code; ask the developer for the " "ones only they know. Then apply template.edits on a branch.") return spec FACTS = { # name: (who supplies it, description) "account_email": ("developer", "Email of the developer's Knox account (new test-mode accounts are self-serve)."), "checkout_handler": ("repository", "File and route/function where the server starts a payment (creates the PaymentIntent)."), "amount_source": ("repository", "Server-side expression for the order total in minor units (for example order.amount_cents). " "If the code does not make it unambiguous, ask the developer."), "currency": ("developer", "ISO currency of the orders, or the field it comes from. Ask; never default to usd."), "order_id_source": ("repository", "Stable order or payment-attempt id used for metadata[order_id] and the Idempotency-Key."), "fulfillment_handler": ("repository", "Function that marks the order paid. Webhook fulfillment must call it once per order."), "webhook_url": ("developer", "URL Knox can POST events to (https and public for api.knoxapi.com; local URL for a local Knox)."), } def preflight(arguments: dict) -> dict: facts = arguments.get("facts") or {} if not isinstance(facts, dict): raise ToolError("facts must be an object.") missing, satisfied = [], [] for name, (source, description) in FACTS.items(): value = facts.get(name) if value is None or (isinstance(value, str) and not value.strip()): missing.append({"field": name, "source": source, "description": description}) else: satisfied.append(name) found = {} try: found = keys(arguments) except ToolError as exc: missing.append({"field": "test_keys", "source": "developer", "description": str(exc)}) environment = { "server_key": bool(SERVER_KEY.match(found.get("KNOX_SECRET_KEY", ""))), "publishable_key": bool(PUBLISHABLE_KEY.match(found.get("KNOX_PUBLISHABLE_KEY", ""))), "webhook_secret": found.get("KNOX_WEBHOOK_SECRET", "").startswith("whsec_"), } root, path = repo_root(arguments), env_path(arguments) environment["env_file"] = str(path.relative_to(root)) environment["env_file_git_ignored"] = git_ignored(root, path) if not (environment["server_key"] and environment["publishable_key"]): missing.append({"field": "test_keys", "source": "knox_request_test_keys", "description": "Knox test keys are not available yet. Ask for the account email, then call knox_request_test_keys."}) if environment["env_file_git_ignored"] is False: missing.append({"field": "env_file_ignored", "source": "repository", "description": f"{environment['env_file']} must be listed in .gitignore before keys are written."}) url = str(facts.get("webhook_url") or "") if url and "knoxapi.com" in config()["api_base"] and (not url.startswith("https://") or re.search(r"//(localhost|127\.|0\.0\.0\.0|\[::1\])", url)): missing.append({"field": "webhook_url", "source": "developer", "description": "api.knoxapi.com cannot deliver to a local or plain-http URL. Ask the developer for a public https URL (a deployed preview or a tunnel)."}) by_source = {} for item in missing: by_source.setdefault(item["source"], []).append(item["field"]) if not missing: next_action = "All required facts are present. Apply the template edits, then call knox_register_webhook." else: parts = [] if by_source.get("repository"): parts.append("Determine from the code: " + ", ".join(by_source["repository"]) + " (if the code is ambiguous, ask)") if by_source.get("developer"): parts.append("Ask the developer for: " + ", ".join(by_source["developer"])) if by_source.get("knox_request_test_keys"): parts.append("Then get keys with knox_request_test_keys") next_action = ("Do NOT write the integration yet, and do NOT guess, default or invent values. " + "; ".join(parts) + ". Call knox_preflight again when you have them.") return {"ready": not missing, "missing": missing, "satisfied": satisfied, "environment": environment, "next_action": next_action} # ---- webhook, payment, status --------------------------------------------------------------------------------------- def register_webhook(arguments: dict) -> dict: url = str(arguments.get("url") or "").strip() if not re.match(r"^https?://", url): raise ToolError("url (the app's webhook route, http(s)://...) is required.") key = server_key(arguments) events = arguments.get("enabled_events") or ["payment_intent.succeeded", "payment_intent.payment_failed"] status, body = http("POST", f"{config()['api_base']}/v1/webhook_endpoints", key=key, form={"url": url, "enabled_events": list(events)}) if status != 200: raise ToolError(_error_text(status, body)) secret = body.get("secret") or "" if not secret.startswith("whsec_"): raise ToolError("Knox did not return a signing secret for the endpoint.") written = write_env_values(arguments, {"KNOX_WEBHOOK_SECRET": secret}) return {"webhook_endpoint": body.get("id"), "url": body.get("url"), "status": body.get("status"), "enabled_events": body.get("enabled_events"), "env_file": written, "stored": ["KNOX_WEBHOOK_SECRET"], "next_action": "Verify Stripe-Signature with KNOX_WEBHOOK_SECRET from the environment (restart the app so it " "reads the new value)."} def test_payment(arguments: dict) -> dict: method = str(arguments.get("payment_method") or "pm_card_visa") if method not in TEST_PAYMENT_METHODS: raise ToolError(f"payment_method must be one of {', '.join(TEST_PAYMENT_METHODS)}. Never pass card numbers.") api = config()["api_base"] intent_id = arguments.get("payment_intent") if intent_id: client_secret = str(arguments.get("client_secret") or "") if not client_secret.startswith(f"{intent_id}_secret_"): raise ToolError("client_secret must belong to payment_intent.") status, body = http("POST", f"{api}/v1/payment_intents/{urllib.parse.quote(intent_id)}/confirm", key=publishable_key(arguments), form={"client_secret": client_secret, "payment_method": method}) mode = "confirmed_with_publishable_key" else: amount, currency = arguments.get("amount"), arguments.get("currency") if not isinstance(amount, int) or amount <= 0 or not currency: raise ToolError("amount (integer, minor units) and currency are required. For a standalone check use a small " "amount in the app's currency; ask the developer if you do not know it.") form = {"amount": amount, "currency": str(currency).lower(), "payment_method": method, "confirm": True, "automatic_payment_methods": {"enabled": True, "allow_redirects": "never"}, "metadata": {"source": "knox-mcp test payment"}} status, body = http("POST", f"{api}/v1/payment_intents", key=server_key(arguments), form=form, headers={"Idempotency-Key": f"knox-mcp-{time.time_ns()}"}) mode = "server" error = body.get("error") if isinstance(body.get("error"), dict) else {} if status == 402 and error.get("type") == "card_error" and isinstance(error.get("payment_intent"), dict): body = error["payment_intent"] # a decline is a result, not a tool failure elif status != 200: raise ToolError(_error_text(status, body)) error = body.get("last_payment_error") or error or {} return {"payment_intent": body.get("id"), "status": body.get("status"), "livemode": body.get("livemode"), "amount": body.get("amount"), "currency": body.get("currency"), "mode": mode, "decline_code": error.get("decline_code") or error.get("code"), "note": ("A server-side test payment proves the server key and processor path, not the app's checkout. " "Finish with a payment through the app's own page and Knox's card fields.")} CHECK_HINTS = { "secret_key_used": "Call Knox from the server with KNOX_SECRET_KEY (any API call).", "publishable_key_used": "Load the checkout page so knox.js calls Knox with KNOX_PUBLISHABLE_KEY.", "test_payment_succeeded": "Complete a test payment (the app's checkout, or knox_test_payment).", "payment_confirmed_client_side": "Pay through the app's page: knox.confirmCardPayment(client_secret) in the browser.", "webhook_endpoint_enabled": "Register the app's webhook route with knox_register_webhook.", "webhook_payment_succeeded_delivered": "Knox must deliver payment_intent.succeeded to the webhook URL and get a 2xx; check the route verifies with KNOX_WEBHOOK_SECRET and that Knox can reach the URL.", "card_fields_mounted": "Open the checkout page so Knox's hosted card fields mount.", } def integration_status(arguments: dict) -> dict: cfg = config() status, body = http("GET", f"{cfg['control_base']}{cfg['control_prefix']}/integration_status", key=server_key(arguments)) if status != 200: raise ToolError(_error_text(status, body)) checks = body.get("checks") or [] pending = [{"id": c["id"], "status": c["status"], "do": CHECK_HINTS.get(c["id"], c.get("detail", ""))} for c in checks if c.get("status") != "passed" and c.get("status") != "not_available"] return {"ready": bool(body.get("ready")), "livemode": body.get("livemode"), "checks": [{"id": c.get("id"), "status": c.get("status"), "evidence": c.get("evidence")} for c in checks], "pending": pending, "next_action": ("Integration status is ready. Also confirm this app's own order was fulfilled; workspace " "evidence alone does not prove the new integration." if body.get("ready") else "Not ready. Work through 'pending' in order, then call again.")} # ---- MCP plumbing --------------------------------------------------------------------------------------------------- def _schema(properties: dict, required: tuple = ()) -> dict: return {"type": "object", "properties": properties, "required": list(required), "additionalProperties": False} REPO = {"repo": {"type": "string", "description": "Repository root. Default: the server's working directory."}, "env_file": {"type": "string", "description": "Env file for keys, relative to the repository. Default .env.knox."}} TOOLS = { "knox_request_test_keys": (request_test_keys, "Ask Knox for test-mode keys for this repository. Returns a code and " "link to show the developer, who signs up (self-serve, test mode) or signs in and approves. Needs the developer's " "account email: ask for it, never guess.", _schema({ "email": {"type": "string", "description": "The developer's Knox account email, as they gave it."}, "agent_name": {"type": "string", "description": "Your product name, e.g. 'Claude Code'."}, "repository": {"type": "string", "description": "owner/name or the directory name (not a URL)."}, **REPO}, ("email",))), "knox_poll_test_keys": (poll_test_keys, "Wait for the developer's approval of a key request. On approval the keys " "are written to the git-ignored env file; they are never returned to you.", _schema({ "handle": {"type": "string"}, "wait_seconds": {"type": "number", "description": "Keep polling up to this long (max 600)."}, **REPO}, ("handle",))), "knox_integration_spec": (integration_spec, "Detect the app's stack and incumbent provider and return Knox's " "prescribed integration for it: base URLs, env names, rules, template files and anchored edits.", _schema({ "stack": {"type": "string", "enum": list(STACKS)}, **REPO})), "knox_preflight": (preflight, "Report which facts are still missing before writing the integration, and who must " "supply each (the repository or the developer). Never guess the missing ones.", _schema({ "facts": {"type": "object", "description": "Facts established so far: " + ", ".join(FACTS)}, **REPO})), "knox_register_webhook": (register_webhook, "Register the app's webhook URL with Knox and store the signing " "secret in the env file (never returned).", _schema({ "url": {"type": "string"}, "enabled_events": {"type": "array", "items": {"type": "string"}}, **REPO}, ("url",))), "knox_test_payment": (test_payment, "Make a test payment with a Knox test payment method. Without payment_intent: " "create and confirm one on the server key. With payment_intent and client_secret: confirm an app-created " "PaymentIntent with the publishable key, as the browser would.", _schema({ "amount": {"type": "integer"}, "currency": {"type": "string"}, "payment_method": {"type": "string", "enum": list(TEST_PAYMENT_METHODS)}, "payment_intent": {"type": "string"}, "client_secret": {"type": "string"}, **REPO})), "knox_integration_status": (integration_status, "Knox's integration readiness for these test keys, with what to do " "about each pending check.", _schema(dict(REPO))), } def call_tool(name: str, arguments: dict) -> dict: if name not in TOOLS: return {"content": [{"type": "text", "text": f"Unknown tool {name}"}], "isError": True} try: result = TOOLS[name][0](arguments or {}) text = json.dumps(result, indent=2) if SECRETISH.search(text): # defence in depth: no tool may return a secret raise ToolError("Internal error: a result contained a secret and was withheld.") return {"content": [{"type": "text", "text": text}], "structuredContent": result, "isError": False} except ToolError as exc: return {"content": [{"type": "text", "text": redact(str(exc))}], "isError": True} except Exception as exc: # report, never crash the server return {"content": [{"type": "text", "text": redact(f"{type(exc).__name__}: {exc}")}], "isError": True} def handle(message: dict) -> dict | None: method, msg_id = message.get("method"), message.get("id") if msg_id is None: # a notification return None params = message.get("params") or {} if method == "initialize": asked = params.get("protocolVersion") result = {"protocolVersion": asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION}, "instructions": INSTRUCTIONS} elif method == "ping": result = {} elif method == "tools/list": result = {"tools": [{"name": name, "description": description, "inputSchema": schema} for name, (_, description, schema) in TOOLS.items()]} elif method == "tools/call": result = call_tool(params.get("name"), params.get("arguments") or {}) else: return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method not found: {method}"}} return {"jsonrpc": "2.0", "id": msg_id, "result": result} def main() -> int: for line in sys.stdin: line = line.strip() if not line: continue try: message = json.loads(line) except ValueError: reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} else: reply = handle(message) if isinstance(message, dict) else { "jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid request"}} if reply is not None: sys.stdout.write(json.dumps(reply) + "\n") sys.stdout.flush() return 0 if __name__ == "__main__": sys.exit(main())