#!/usr/bin/env bash # Steps installer. The app fills in the origin and the lasting instruction before serving this file. # Fetch it from /connect.sh, or run this file with STEPS_URL set. # The token is read from STEPS_TOKEN or a hidden prompt. It is never printed # and never written into a rule or instruction file. set -euo pipefail if ! command -v python3 >/dev/null 2>&1; then echo "steps-connect: python3 is required to merge config files." >&2 exit 1 fi ORIGIN="${STEPS_URL:-https://usesteps.dev}" ORIGIN="${ORIGIN%/}" STEPS_INSTRUCTIONS=$(cat << 'STEPS_INSTRUCTIONS_END' Steps is the organization's library of step-by-step workflows: the source of truth for how work should be done. People author workflows in Steps; you follow them. Finding tools are read-only and already authenticated. Documenting needs a Can edit token. Publish, unpublish, activate_version, and visibility tools need a Can publish token. Whenever someone asks to write up, follow, recall, or change a process, procedure, checklist, or how-to, search Steps first. Do this without waiting for them to say "Steps". That includes onboarding, refunds, provisioning, access, deploys, resets, shipping a change, and anything else the organization might have documented. Before a multi-step task, search Steps for a matching workflow and follow it when one exists. Use Find, then follow the checklist on the first hit: 1. search_workflows with the user's own words. include_checklist defaults to true on this tool: the first hit's checklist field is the same markdown as export_diagram_markdown. Follow that checklist. Read why, fit_reasons, evidence, and confidence. diagram_id is the numeric id. next_step is a sentence of guidance, not an id and not a tool argument. ask_user is a question to show the human, not a tool. 2. If status is needs_more_info, ask the human the ask_user question and offer suggested_refinements, then call search_workflows again. Do not invent steps. Do not call a tool named ask_user. The checklist is omitted when the first hit's confidence is low. 3. get_workflow with the chosen id only when you need another hit, an older version, or the checklist field is absent. id may be a number or a string. Leave full false unless you need older versions or the step graph. full false still includes a versions array with only the active version, and modules[].diagrams without steps. full true lists every version with steps and transitions and keeps modules[].diagrams. 4. export_diagram_markdown with the numeric diagram_id when checklist is absent, or when you want a diagram other than the first hit. Do not pass next_step; it is a sentence and returns 404. Follow the markdown, including the Discussion under each step. Ask the human when a branch is ambiguous. Discussions come with the checklist, the export, and get_workflow. include_discussions defaults to true. Pass false only when you want the steps alone. get_discussions filters one workflow by step_id or by resolved status. A comment can hold the answer the step does not, including a contact someone typed in the thread. Documenting: Edits apply to the version you are changing. Edits to the current published version are live immediately and do not create a new draft. Edits to a draft are not live until someone makes it current (activate_version, needs Can publish). A new version is created only by create_version (POST /api/v1/modules/:id/versions). Historical versions cannot be edited until someone makes them current. Comments do not create a version. Leaving Can publish off does not stop Can edit from changing the current version. lock_version is optional on updates and deletes; always prefer sending lock_version from the last read so concurrent edits are not overwritten. Omitting lock_version applies the change to the latest row without that stale check. On stale_object, error.current has the latest lock_version and fields — re-apply your change on top of that content (merge conflicts; do not blindly overwrite), then retry with the new lock_version. When publish, unpublish, or activate_version is refused because of the current status, error.state has machine, status, attempted, allowed, and next — follow next instead of retrying the same call. Deletes require confirm_name that matches the title exactly — show the UI warning and ask the user to type the exact name; never invent confirm_name. Suite UI: Delete “{title}”? This cannot be undone. then Type the suite name to confirm. Workflow UI: Delete “{title}”? This cannot be undone. then Type the workflow name to confirm. create_workflow, create_module, add_step, create_transition, create_frame, upload_media, reply_comment, and the other documenting tools exist when the token can edit. publish_suite, unpublish_suite, publish_module, unpublish_module, and activate_version need Can publish. If none matches, and the task is repeatable or likely to come up again, ask the user once whether to turn it into a new Steps workflow. Offer a short draft: a title, a suggested suite (an existing one by name, or a new suite if none fits), and numbered steps. Then point them to https://usesteps.dev/authoring, or to that suite. If the token can edit, create_workflow saves that draft. Otherwise these tools cannot create it. After a task that deviated from an existing workflow, suggest a new version of that workflow instead of a duplicate. Ask at most once per task. Skip trivial one-off tasks. A no is final for that task. Do not ask the user to paste a token into chat. STEPS_INSTRUCTIONS_END ) export STEPS_ORIGIN="$ORIGIN" export STEPS_INSTRUCTIONS tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT cat > "$tmp" << 'PY' import getpass import json import os import re import shutil import subprocess import sys from datetime import datetime from pathlib import Path ORIGIN = os.environ.get("STEPS_ORIGIN", "").rstrip("/") INSTRUCTIONS = os.environ.get("STEPS_INSTRUCTIONS", "").strip("\n") BEGIN = "" END = "" HASH_BEGIN = "# BEGIN STEPS CONNECT" HASH_END = "# END STEPS CONNECT" HARNESSES = ( "cursor", "claude", "claude-desktop", "codex", "gemini", "opencode", "goose", ) changes = [] secret_files = [] secret_backups = [] deleted_backups = [] kept_failure_backups = [] restored = [] created_this_run = [] dry = False uninstall = False assume_yes = False store_token = False keep_backups = False project = None BACKUP_STAMP = re.compile(r"^\d{14}(?:\.\d+)?$") def die(message): print(f"steps-connect: {message}", file=sys.stderr) raise SystemExit(1) def record(action, path): changes.append(f" {action}: {path}") def home(): return Path(os.environ.get("HOME") or str(Path.home())).expanduser() def xdg_config(): raw = os.environ.get("XDG_CONFIG_HOME") return Path(raw).expanduser() if raw else home() / ".config" def codex_home(): raw = os.environ.get("CODEX_HOME") return Path(raw).expanduser() if raw else home() / ".codex" def rule_body(): return ( f"Use Steps ({ORIGIN}). Search before a multi-step task. " "If you would add a workflow or suite, ask the user once and send them to " f"{ORIGIN}/authoring.\n\n" f"{INSTRUCTIONS}\n\n" f"MCP at {ORIGIN}/mcp is read-only. It cannot create or edit a workflow. " f"Ask the user to open {ORIGIN}/authoring.\n" ) def marked(body): return f"{BEGIN}\n{body.rstrip()}\n{END}\n" def hash_marked(body): return f"{HASH_BEGIN}\n{body.rstrip()}\n{HASH_END}\n" def installer_backup_name(original_name, candidate_name): prefix = original_name + ".bak." if not candidate_name.startswith(prefix): return False return BACKUP_STAMP.fullmatch(candidate_name[len(prefix) :]) is not None def managed_paths(): paths = [ home() / ".cursor" / "mcp.json", home() / ".cursor" / "rules" / "steps.mdc", home() / ".claude.json", home() / ".claude" / "CLAUDE.md", codex_home() / "config.toml", codex_home() / "AGENTS.md", home() / ".gemini" / "settings.json", home() / ".gemini" / "GEMINI.md", xdg_config() / "opencode" / "opencode.jsonc", xdg_config() / "opencode" / "AGENTS.md", xdg_config() / "goose" / "config.yaml", xdg_config() / "goose" / "AGENTS.md", xdg_config() / "goose" / ".goosehints", ] if project: paths.extend( [ project / ".cursor" / "mcp.json", project / ".cursor" / "rules" / "steps.mdc", project / "AGENTS.md", project / ".mcp.json", project / "CLAUDE.md", project / "GEMINI.md", project / ".goosehints", ] ) return paths def remember_deleted(path): rendered = str(path) if rendered not in deleted_backups: deleted_backups.append(rendered) def note_secret_backup(copied: Path): secret = token_value() if copied is None or not secret or not copied.exists(): return try: body = copied.read_text(encoding="utf-8") except OSError: return if secret not in body: return try: os.chmod(copied, 0o600) except OSError: pass rendered = str(copied) if rendered not in secret_backups: secret_backups.append(rendered) def next_backup_path(path: Path): stamp = datetime.now().strftime("%Y%m%d%H%M%S") dest = Path(f"{path}.bak.{stamp}") n = 0 while dest.exists(): n += 1 dest = Path(f"{path}.bak.{stamp}.{n}") return dest def backup(path: Path): dest = next_backup_path(path) if dry: record("would-backup", dest) if uninstall: try: body = path.read_text(encoding="utf-8") if path.exists() else "" except OSError: body = "" if holds_token(body): record("would-chmod", f"600 {dest}") rendered = str(dest) if rendered not in secret_backups: secret_backups.append(rendered) if not keep_backups: record("would-delete-backup", dest) remember_deleted(dest) return None dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, dest) record("backup", dest) created_this_run.append(dest) note_secret_backup(dest) return dest def token_value(): return os.environ.get("STEPS_TOKEN", "") def holds_token(content): secret = token_value() return bool(secret) and secret in content def note_secret(path: Path): rendered = str(path) if rendered not in secret_files: secret_files.append(rendered) def restrict_private(path: Path): if dry or not path.exists(): record("would-chmod", f"600 {path}") return mode = path.stat().st_mode & 0o777 if mode != 0o600: os.chmod(path, 0o600) record("chmod", f"600 {path}") def write_text(path: Path, content: str, secret_ok=False): if not content.endswith("\n"): content += "\n" holds = holds_token(content) if holds and not secret_ok: die(f"refusing to store the token in {path}") if holds and secret_ok: note_secret(path) old = path.read_text(encoding="utf-8") if path.exists() else None if old == content: record("unchanged", path) if holds and secret_ok: restrict_private(path) return if dry: record("would-write" if old is None else "would-update", path) if holds and secret_ok: record("would-chmod", f"600 {path}") if uninstall and old is not None: backup(path) return path.parent.mkdir(parents=True, exist_ok=True) copied = None if old is not None: copied = backup(path) record("update", path) else: record("write", path) try: path.write_text(content, encoding="utf-8") except OSError as exc: if copied is not None: restore_from(path, copied) else: die(f"could not write {path}: {exc}") return if holds and secret_ok: restrict_private(path) finish_edit(path, copied) def delete_path(path: Path): if not path.exists(): record("unchanged", path) return if dry: record("would-delete", path) if uninstall: backup(path) return copied = backup(path) try: path.unlink() except OSError: if copied is not None: restore_from(path, copied) return record("delete", path) finish_edit(path, copied) def restore_from(path: Path, copied: Path): rendered = str(copied) if rendered not in kept_failure_backups: kept_failure_backups.append(rendered) try: path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(copied, path) except OSError as exc: record("restore-failed", path) restored.append(f"{path} (restore copy failed: {exc}; backup kept at {copied})") return record("restored", path) restored.append(f"{path} (backup kept at {copied})") def release_backup(copied: Path): if keep_backups or copied is None: return rendered = str(copied) if rendered in kept_failure_backups: return try: copied.unlink() except FileNotFoundError: return except OSError as exc: if rendered not in kept_failure_backups: kept_failure_backups.append(rendered) restored.append(f"{copied} (could not delete backup: {exc})") return remember_deleted(copied) record("removed-backup", copied) def finish_edit(path: Path, copied): if copied is None or not uninstall: return try: ok = parses(path) except Exception: ok = False if ok: release_backup(copied) else: restore_from(path, copied) def structured_config(path: Path): suffix = path.suffix.lower() return suffix in {".json", ".jsonc", ".toml", ".yaml", ".yml"} or path.name.lower().endswith(".jsonc") def delimiters_balanced(text): curly = 0 square = 0 in_str = False esc = False for c in text: if in_str: if esc: esc = False elif c == "\\": esc = True elif c == '"': in_str = False continue if c == '"': in_str = True continue if c == "{": curly += 1 elif c == "}": curly -= 1 if curly < 0: return False elif c == "[": square += 1 elif c == "]": square -= 1 if square < 0: return False return (not in_str) and curly == 0 and square == 0 def toml_ok(text): try: import tomllib except ImportError: return delimiters_balanced(text) try: tomllib.loads(text if text.strip() else "") return True except Exception: return False def yaml_ok(text): try: import yaml except ImportError: return delimiters_balanced(text) try: yaml.safe_load(text if text.strip() else None) return True except Exception: return False def parses(path: Path): if not path.exists(): return True text = path.read_text(encoding="utf-8") suffix = path.suffix.lower() if not structured_config(path): return True try: if suffix in {".json", ".jsonc"} or path.name.lower().endswith(".jsonc"): json.loads(strip_jsonc(text) if text.strip() else "{}") return True if suffix == ".toml": return toml_ok(text) if suffix in {".yaml", ".yml"}: return yaml_ok(text) return True except Exception: return False def sweep_old_backups(): if not uninstall: return seen = set(kept_failure_backups) candidates = [] for path in managed_paths(): parent = path.parent if not parent.is_dir(): continue try: children = list(parent.iterdir()) except OSError: continue for child in children: if child.is_file() and installer_backup_name(path.name, child.name): candidates.append(child) for child in created_this_run: if child.is_file() and child not in candidates: candidates.append(child) for child in candidates: rendered = str(child) if rendered in seen or not child.exists(): continue seen.add(rendered) if keep_backups: continue if dry: record("would-delete-backup", child) remember_deleted(child) continue release_backup(child) def strip_jsonc(text): out = [] i = 0 n = len(text) in_str = False esc = False while i < n: c = text[i] if in_str: out.append(c) if esc: esc = False elif c == "\\": esc = True elif c == '"': in_str = False i += 1 continue if c == '"': in_str = True out.append(c) i += 1 continue if c == "/" and i + 1 < n and text[i + 1] == "/": while i < n and text[i] != "\n": i += 1 continue if c == "/" and i + 1 < n and text[i + 1] == "*": i += 2 while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"): i += 1 i = min(n, i + 2) continue out.append(c) i += 1 return strip_trailing_commas("".join(out)) def strip_trailing_commas(text): out = [] i = 0 n = len(text) in_str = False esc = False while i < n: c = text[i] if in_str: out.append(c) if esc: esc = False elif c == "\\": esc = True elif c == '"': in_str = False i += 1 continue if c == '"': in_str = True out.append(c) i += 1 continue if c == ",": j = i + 1 while j < n and text[j] in " \t\r\n": j += 1 if j < n and text[j] in "}]": i += 1 continue out.append(c) i += 1 return "".join(out) def load_json(path: Path): if not path.exists(): return {} text = path.read_text(encoding="utf-8") if not text.strip(): return {} try: value = json.loads(text) except json.JSONDecodeError: try: value = json.loads(strip_jsonc(text)) except json.JSONDecodeError as exc: die(f"refusing to edit {path}: {exc}. The file was not changed.") if not isinstance(value, dict): die(f"refusing to edit {path}: the top level is not an object.") return value def json_text(data): return json.dumps(data, indent=2, ensure_ascii=False) + "\n" def save_json(path: Path, data, drop_if_only_schema=False, secret_ok=False): keys = set(data) populated = any(isinstance(data.get(k), dict) and data.get(k) for k in ("mcpServers", "mcp")) removable = keys <= {"$schema", "mcpServers", "mcp"} and not populated if uninstall and (data == {} or (drop_if_only_schema and removable)): if path.exists(): delete_path(path) else: record("unchanged", path) return write_text(path, json_text(data), secret_ok=secret_ok) def set_named(data, container, name, value): block = data.get(container) if not isinstance(block, dict): block = {} if uninstall: block.pop(name, None) if block: data[container] = block else: data.pop(container, None) else: block[name] = value data[container] = block return data def remove_named(data, container, name): block = data.get(container) if not isinstance(block, dict) or name not in block: return False block.pop(name, None) if block: data[container] = block else: data.pop(container, None) return True def install_project_server(path, container, server, create_missing): """Project MCP files stay free of the token so they can be committed.""" exists = path.exists() if store_token and not uninstall: if not exists: return data = load_json(path) if not remove_named(data, container, "steps"): record("unchanged", path) return if data == {}: delete_path(path) else: save_json(path, data, secret_ok=False) return if not exists and (uninstall or not create_missing): return data = load_json(path) set_named(data, container, "steps", server) save_json(path, data, secret_ok=False) def upsert_markers(path: Path, begin, end, block): block = block if block.endswith("\n") else block + "\n" if not path.exists(): if uninstall: record("unchanged", path) return write_text(path, block) return text = path.read_text(encoding="utf-8") start = text.find(begin) finish = text.find(end, start + len(begin)) if start >= 0 else -1 if start >= 0 and finish >= 0: after = finish + len(end) if text[after:after + 1] == "\n": after += 1 if uninstall: updated = text[:start] + text[after:] updated = re.sub(r"\n{3,}", "\n\n", updated).strip("\n") if not updated.strip(): delete_path(path) else: write_text(path, updated + "\n") return updated = text[:start] + block + text[after:] write_text(path, updated) return if uninstall: record("unchanged", path) return sep = "" if text.endswith("\n\n") or text == "" else ("\n" if text.endswith("\n") else "\n\n") write_text(path, text + sep + block) def replace_span(text, start, end, replacement): if replacement and not replacement.endswith("\n"): replacement += "\n" return text[:start] + replacement + text[end:] def find_toml_table(text, header): lines = text.splitlines(keepends=True) offset = 0 start = None for i, line in enumerate(lines): if line.strip() == header: start = offset break offset += len(line) if start is None: return None offset = start + len(lines[[ln.strip() for ln in lines].index(header)]) # recompute end from the line index index = [ln.strip() for ln in lines].index(header) end_index = len(lines) for j in range(index + 1, len(lines)): stripped = lines[j].lstrip() if stripped.startswith("[") and not stripped.startswith("[["): end_index = j break end = sum(len(lines[k]) for k in range(end_index)) return start, end def leftover_scaffold(text): stripped = text.strip() return stripped == "" or stripped == "extensions:" def upsert_hash_block(path: Path, block, table_header=None, yaml_key=None, secret_ok=False): def put(content): write_text(path, content, secret_ok=secret_ok) block = block if block.endswith("\n") else block + "\n" if not path.exists(): if uninstall: record("unchanged", path) return put(block) return text = path.read_text(encoding="utf-8") start = text.find(HASH_BEGIN) finish = text.find(HASH_END, start + len(HASH_BEGIN)) if start >= 0 else -1 if start >= 0 and finish >= 0: after = finish + len(HASH_END) if text[after:after + 1] == "\n": after += 1 updated = text[:start] + ("" if uninstall else block) + text[after:] if uninstall and leftover_scaffold(updated): delete_path(path) else: put(updated) return if uninstall: if table_header: span = find_toml_table(text, table_header) if span: updated = replace_span(text, span[0], span[1], "") if leftover_scaffold(updated): delete_path(path) else: put(updated) return record("unchanged", path) return if table_header: span = find_toml_table(text, table_header) if span: put(replace_span(text, span[0], span[1], block)) return if yaml_key and re.search(rf"(?m)^ {re.escape(yaml_key)}:\s*$", text): lines = text.splitlines(keepends=True) start_i = next(i for i, line in enumerate(lines) if line.startswith(f" {yaml_key}:")) end_i = len(lines) for j in range(start_i + 1, len(lines)): if re.match(r"^ [^ \n].*:\s*$", lines[j]) or lines[j].startswith(HASH_BEGIN): end_i = j break start_off = sum(len(lines[k]) for k in range(start_i)) end_off = sum(len(lines[k]) for k in range(end_i)) put(replace_span(text, start_off, end_off, block)) return if yaml_key and re.search(r"(?m)^extensions:\s*$", text): lines = text.splitlines(keepends=True) insert_at = next(i for i, line in enumerate(lines) if line.startswith("extensions:")) + 1 off = sum(len(lines[k]) for k in range(insert_at)) put(text[:off] + block + text[off:]) return sep = "" if text.endswith("\n\n") or text == "" else ("\n" if text.endswith("\n") else "\n\n") put(text + sep + block) def confirm(selected): if dry or assume_yes: return if not sys.stdin.isatty(): die("re-run with --yes to change files when input is not a terminal. Nothing was written.") names = ", ".join(selected) verb = "Remove Steps from" if uninstall else "Update Steps for" answer = input(f"{verb} {names}? [y/N] ") if answer.strip().lower() not in {"y", "yes"}: die("cancelled. Nothing was written.") def acceptable_token(token): # Real PATs are steps_pat_ plus hex and base64url. Rejecting anything else # keeps a pasted newline, quote, or shell metacharacter out of every writer. return ( isinstance(token, str) and len(token) >= 20 and token.startswith("steps_pat_") and all(char.isascii() and (char.isalnum() or char in "_-") for char in token) ) def require_token(): token = token_value() needs_value = (not dry and not uninstall) or store_token if not needs_value: if token and not token.startswith("steps_pat_"): die("STEPS_TOKEN must start with steps_pat_. The value was not printed.") return if not token: if sys.stdin.isatty() and not dry: token = getpass.getpass("Steps personal access token (input hidden): ") os.environ["STEPS_TOKEN"] = token else: die("STEPS_TOKEN is not set. Export it and run again. The token is not printed.") if not acceptable_token(token): die( "STEPS_TOKEN must be a personal access token starting with steps_pat_ " "and containing only letters, digits, underscore, and hyphen. " "The value was not printed." ) def ask_store_token(selected): global store_token if store_token or uninstall or dry or assume_yes or not sys.stdin.isatty(): return print("Apps opened from the Dock or Start menu cannot see STEPS_TOKEN from your shell.") print("Saving the token in the MCP config makes that launch work.") print("The value is not printed, and it is not written into rule files.") if "cursor" in selected: print("For Cursor, saving it is the default: an env-var reference stays empty in a desktop launch.") answer = input("Save the token in MCP config files? [Y/n] ") store_token = answer.strip().lower() in {"", "y", "yes"} else: answer = input("Save the token in MCP config files? [y/N] ") store_token = answer.strip().lower() in {"y", "yes"} def authorization_header(env_form, allow_secret=True): # Project files are often committed. The token stays in user-level config. if not allow_secret or not store_token or uninstall: return env_form token = token_value() if not acceptable_token(token): die( "STEPS_TOKEN must be a personal access token starting with steps_pat_ " "and containing only letters, digits, underscore, and hyphen. " "The value was not printed." ) return f"Bearer {token}" def toml_quote(value): # TOML basic string, also used for YAML double quotes. Tokens are rejected # before this runs; the escapes still cover a value that reaches a writer. out = ['"'] for char in value: if char == "\\": out.append("\\\\") elif char == '"': out.append('\\"') elif char == "\b": out.append("\\b") elif char == "\t": out.append("\\t") elif char == "\n": out.append("\\n") elif char == "\f": out.append("\\f") elif char == "\r": out.append("\\r") elif ord(char) < 0x20 or ord(char) == 0x7F: out.append("\\u%04X" % ord(char)) else: out.append(char) out.append('"') return "".join(out) def cursor_server(allow_secret=True): return { "url": f"{ORIGIN}/mcp", "headers": { "Authorization": authorization_header( "Bearer ${env:STEPS_TOKEN}", allow_secret ) }, } def claude_server(allow_secret=True): return { "type": "http", "url": f"{ORIGIN}/mcp", "headers": { "Authorization": authorization_header("Bearer ${STEPS_TOKEN}", allow_secret) }, } def gemini_server(): return { "httpUrl": f"{ORIGIN}/mcp", "headers": {"Authorization": authorization_header("Bearer ${STEPS_TOKEN}")}, } def opencode_server(): return { "type": "remote", "url": f"{ORIGIN}/mcp", "enabled": True, "oauth": False, "headers": {"Authorization": authorization_header("Bearer {env:STEPS_TOKEN}")}, } def detected(): found = [] def has(*cmds): return any(shutil.which(cmd) for cmd in cmds) base = home() if has("agent", "cursor") or (base / ".cursor").is_dir(): found.append("cursor") if has("claude") or (base / ".claude").is_dir() or (base / ".claude.json").is_file(): found.append("claude") desktop = [ Path.home() / "Library/Application Support/Claude", Path("/Applications/Claude.app"), base / ".config/Claude", ] appdata = os.environ.get("APPDATA") if appdata: desktop.append(Path(appdata) / "Claude") if any(path.exists() for path in desktop): found.append("claude-desktop") if has("codex") or codex_home().is_dir(): found.append("codex") if has("gemini") or (base / ".gemini").is_dir(): found.append("gemini") if has("opencode") or (xdg_config() / "opencode").is_dir(): found.append("opencode") if has("goose") or (xdg_config() / "goose").is_dir(): found.append("goose") return found def copy_clipboard(text): commands = ( ["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ) for cmd in commands: if not shutil.which(cmd[0]): continue try: subprocess.run(cmd, input=text.encode(), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return True except (OSError, subprocess.CalledProcessError): continue return False def cursor_mdc(): return ( "---\n" "description: Search Steps first, and ask before creating a workflow or suite\n" "alwaysApply: true\n" "---\n\n" + marked(rule_body()) ) def install_cursor_rule(path: Path): if uninstall: if path.exists() and BEGIN in path.read_text(encoding="utf-8"): delete_path(path) else: record("unchanged", path) return write_text(path, cursor_mdc()) def install_markdown(path: Path): upsert_markers(path, BEGIN, END, marked(rule_body())) def install_cursor(): mcp = home() / ".cursor" / "mcp.json" data = load_json(mcp) set_named(data, "mcpServers", "steps", cursor_server()) save_json(mcp, data, secret_ok=store_token or uninstall) if project: install_project_server( project / ".cursor" / "mcp.json", "mcpServers", cursor_server(allow_secret=False), create_missing=False, ) # Uninstall may still remove a legacy ~/.cursor/rules/steps.mdc from older installs. legacy_home_rule = home() / ".cursor" / "rules" / "steps.mdc" if uninstall: install_cursor_rule(legacy_home_rule) elif legacy_home_rule.exists() and BEGIN in legacy_home_rule.read_text(encoding="utf-8"): record("unchanged", legacy_home_rule) if project: install_cursor_rule(project / ".cursor" / "rules" / "steps.mdc") install_markdown(project / "AGENTS.md") record( "manual", "open Customize in the sidebar → Rules (User Rules; paste the text printed below)", ) def install_claude(): path = home() / ".claude.json" data = load_json(path) set_named(data, "mcpServers", "steps", claude_server()) save_json(path, data, secret_ok=store_token or uninstall) install_markdown(home() / ".claude" / "CLAUDE.md") if project: install_project_server( project / ".mcp.json", "mcpServers", claude_server(allow_secret=False), create_missing=True, ) install_markdown(project / "CLAUDE.md") def install_claude_desktop(): record( "manual", "Claude Desktop has no remote-MCP config file. Settings → Connectors → Add custom connector. " f"Name: Steps. URL: {ORIGIN}/mcp. Header name: Authorization. " "Header value: Bearer, a space, then the STEPS_TOKEN value (not printed here). " "Paste the instruction block below into the desktop app's custom instructions.", ) def codex_block(): if store_token: header = "http_headers = { Authorization = " + toml_quote(authorization_header("")) + " }" else: header = 'bearer_token_env_var = "STEPS_TOKEN"' return hash_marked( "[mcp_servers.steps]\n" f'url = "{ORIGIN}/mcp"\n' f"{header}\n" "enabled = true" ) def install_codex(): path = codex_home() / "config.toml" block = "" if uninstall else codex_block() if not path.exists() and not uninstall: write_text(path, block, secret_ok=store_token) else: upsert_hash_block( path, block, table_header="[mcp_servers.steps]", secret_ok=store_token or uninstall, ) install_markdown(codex_home() / "AGENTS.md") if project: install_markdown(project / "AGENTS.md") def install_gemini(): path = home() / ".gemini" / "settings.json" data = load_json(path) set_named(data, "mcpServers", "steps", gemini_server()) save_json(path, data, secret_ok=store_token or uninstall) install_markdown(home() / ".gemini" / "GEMINI.md") if project: install_markdown(project / "GEMINI.md") def install_opencode(): path = xdg_config() / "opencode" / "opencode.jsonc" data = load_json(path) if not uninstall and "$schema" not in data and not path.exists(): data["$schema"] = "https://opencode.ai/config.json" set_named(data, "mcp", "steps", opencode_server()) save_json(path, data, drop_if_only_schema=True, secret_ok=store_token or uninstall) install_markdown(xdg_config() / "opencode" / "AGENTS.md") if project: install_markdown(project / "AGENTS.md") def goose_block(): header = toml_quote(authorization_header("Bearer ${STEPS_TOKEN}")) return hash_marked( " steps:\n" " enabled: true\n" " type: streamable_http\n" " name: steps\n" f' uri: "{ORIGIN}/mcp"\n' " headers:\n" f" Authorization: {header}\n" " timeout: 300" ) def install_goose(): path = xdg_config() / "goose" / "config.yaml" block = "" if uninstall else goose_block() if not path.exists() and not uninstall: write_text(path, "extensions:\n" + block, secret_ok=store_token) else: upsert_hash_block(path, block, yaml_key="steps", secret_ok=store_token or uninstall) install_markdown(xdg_config() / "goose" / "AGENTS.md") install_markdown(xdg_config() / "goose" / ".goosehints") if project: install_markdown(project / "AGENTS.md") install_markdown(project / ".goosehints") record("manual", "Goose loads hints when the Developer extension is enabled (the default profile).") INSTALLERS = { "cursor": install_cursor, "claude": install_claude, "claude-desktop": install_claude_desktop, "codex": install_codex, "gemini": install_gemini, "opencode": install_opencode, "goose": install_goose, } def usage(): print( """Steps installer Merges the Steps MCP server and writes the lasting instruction where each client loads it every session. Other servers in those files are left in place. connect.sh [--dry-run] [--uninstall] [--keep-backups] [--yes] [--all] [--store-token] [--harness NAME]... [--project DIR] [--no-project] --harness cursor, claude, codex, gemini, opencode, goose, claude-desktop --all every harness above --dry-run print the plan and write nothing --uninstall remove the steps server and marked instruction blocks, then delete installer backups named file.bak.YYYYMMDDHHMMSS or file.bak.YYYYMMDDHHMMSS.N for files this installer manages. Other files are left alone. If an edit fails or the result does not parse, the file is restored and that backup is kept. --keep-backups with --uninstall, leave installer backups in place --store-token write the token into user-level MCP config files (mode 600) instead of an environment-variable reference. Use this when the app is opened from the Dock or Start menu and cannot see a shell export. Project MCP files keep an environment-variable reference, or lose a steps entry that would hide the user config. The token is still not printed and is not written into rule files. --project directory that receives project rules (default: the current directory when it looks like a project and is not your home) --no-project skip project files --yes do not ask before writing. Required when input is not a terminal, including for --uninstall. STEPS_URL overrides the baked-in origin. STEPS_TOKEN is read from the environment or a hidden prompt. The token is not printed and is not written into instruction files. Without --store-token, config files name STEPS_TOKEN. In a terminal, Cursor's prompt defaults to saving the token. """ ) def parse_args(argv): global dry, uninstall, assume_yes, project, store_token, keep_backups selected = [] use_all = False no_project = False project_arg = None i = 0 while i < len(argv): arg = argv[i] if arg in {"-h", "--help"}: usage() raise SystemExit(0) if arg == "--dry-run": dry = True elif arg == "--uninstall": uninstall = True elif arg == "--yes": assume_yes = True elif arg == "--store-token": store_token = True elif arg == "--keep-backups": keep_backups = True elif arg == "--all": use_all = True elif arg == "--no-project": no_project = True elif arg == "--harness": i += 1 if i >= len(argv): die("--harness needs a name") name = argv[i] if name not in HARNESSES: die(f"unknown harness {name}. Choose from: {', '.join(HARNESSES)}") selected.append(name) elif arg == "--project": i += 1 if i >= len(argv): die("--project needs a directory") project_arg = argv[i] else: die(f"unknown argument {arg}. Try --help.") i += 1 if not re.match(r"^https?://[A-Za-z0-9._:\-\[\]]+$", ORIGIN): die("set STEPS_URL to the Steps origin, or run the /connect.sh served by the app.") if no_project: project = None elif project_arg: project = Path(project_arg).expanduser() if project.exists() and not project.is_dir(): die(f"project is not a directory: {project}") else: cwd = Path.cwd() if cwd != home() and cwd != Path("/"): markers = [".git", "Cargo.toml", "package.json", "go.mod", "pyproject.toml", ".cursor"] if any((cwd / name).exists() for name in markers): project = cwd if use_all: for name in HARNESSES: if name not in selected: selected.append(name) if not selected: selected = detected() if not selected: die( "no harness detected. Re-run with --harness NAME or --all. " f"Names: {', '.join(HARNESSES)}" ) return selected def main(): selected = parse_args(sys.argv[1:]) require_token() ask_store_token(selected) confirm(selected) if project is not None and not dry and not project.exists(): project.mkdir(parents=True, exist_ok=True) mode = "dry-run" if dry else "uninstall" if uninstall else "install" print(f"Steps installer ({mode})") print(f"Origin: {ORIGIN}") print("Token in MCP config: " + ("yes" if store_token else "no (env reference)")) print("Harnesses: " + ", ".join(selected)) if project: print(f"Project: {project}") else: print("Project: (none; home config only)") for name in selected: print(f"\n{name}") before = len(changes) INSTALLERS[name]() if len(changes) == before: print(" unchanged") else: for line in changes[before:]: print(line) if uninstall: before = len(changes) sweep_old_backups() extra = changes[before:] if extra: print("\ninstaller backups") for line in extra: print(line) if "cursor" in selected and not uninstall: text = rule_body().rstrip() + "\n" print("\nCursor User Rules are not a file. The CLI cannot set them.") if project: print("In the project, wrote .cursor/rules/steps.mdc with alwaysApply: true.") print("Open Customize in the sidebar → Rules and paste this as a User Rule:") print("---") print(text, end="" if text.endswith("\n") else "\n") print("---") if dry: print("Clipboard: skipped in --dry-run") elif copy_clipboard(text): print("Clipboard: copied the User Rule text.") else: print("Clipboard: no clipboard tool found. Copy the text above.") if store_token: print("The Cursor MCP config holds the token, so a Dock or Start menu launch can connect.") else: print("Export STEPS_TOKEN in the environment that launches Cursor.") print("A Cursor window opened from the Dock or Start menu does not see a shell export.") print("Re-run with --store-token to save the token in the MCP config.") if store_token and not uninstall: verb = "would be stored" if dry else "is stored" print(f"\nThe token {verb} in these MCP config files. It was not printed.") if secret_files: for path in secret_files: print(f" {path}") else: print(" (none; this run did not write an MCP config)") print("Those files are mode 600. Do not commit them. Rule files do not contain the token.") elif not uninstall: print("\nMCP configs name STEPS_TOKEN and do not contain the token.") if uninstall and keep_backups: print("\nInstaller backups were kept because --keep-backups was set.") if secret_backups: if dry: print("These backups would still contain the token. The token was not printed.") else: print("These backups still contain the token. They are mode 600. The token was not printed.") for path in secret_backups: print(f" {path}") elif uninstall and deleted_backups: label = "Would remove installer backups" if dry else "Removed installer backups" print(f"\n{label} (paths only; no token values):") for path in deleted_backups: print(f" {path}") if restored: print("\nAn edit failed or the result did not parse. The original file was restored and the backup was kept:") for line in restored: print(f" {line}") print("\nDone.") if restored: raise SystemExit(1) if __name__ == "__main__": main() PY python3 "$tmp" "$@"