From fc9485c6cd558ae16f86d0699b23c5393286e39f Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 09:24:02 +0530 Subject: [PATCH 1/6] copper-pilot mcp serves CopperPilot's design tools, with login inside the MCP host The default MCP server is now the tool session the Claude Agent and Codex chats use (about 160 design tools, the playbook, copperpilot_subagent) instead of the delegating ask/plan/run conductor (kept as --conductor). - Starts without a login: lists copperpilot_login and copperpilot_status; copperpilot_login runs the browser device login from the host, returns the link to show the user, and sends tools/list_changed once approved. - The CopperPilot guide is the server's instructions when logged in. - Altium staged edits are applied after each edit call (MCP has no turn end). - Workspace defaults to CLAUDE_PROJECT_DIR, else cwd. - auth login prints the link and skips the flow when already logged in (--force to log in again); browsers open without inheriting stdout. - README: step-by-step install for an agent asked to install the MCP. - Plugin 0.2.0 uses the design tools (server name copperpilot). --- .claude-plugin/marketplace.json | 6 +- README.md | 80 +++- docs/cli.md | 70 ++-- docs/harness.md | 49 +-- .../copper-pilot/.claude-plugin/plugin.json | 4 +- plugins/copper-pilot/.mcp.json | 2 +- plugins/copper-pilot/agents/copper-pilot.md | 20 +- .../skills/copper-pilot-review/SKILL.md | 14 +- src/copper_pilot_cli/agents/cli.py | 56 +-- src/copper_pilot_cli/agents/mcp_server.py | 27 +- src/copper_pilot_cli/agents/standalone.py | 366 ++++++++++++++++++ src/copper_pilot_cli/copper_auth.py | 121 +++++- src/copper_pilot_cli/copper_main.py | 72 +++- tests/test_byo_runtime.py | 6 +- tests/test_main.py | 2 +- tests/test_mcp_standalone.py | 190 +++++++++ tests/test_plugin_manifest.py | 5 +- 17 files changed, 918 insertions(+), 172 deletions(-) create mode 100644 src/copper_pilot_cli/agents/standalone.py create mode 100644 tests/test_mcp_standalone.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 9227f3a..c810021 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -4,14 +4,14 @@ "name": "CopperPilot" }, "metadata": { - "description": "CopperPilot Claude Code plugin: delegate electronics design to the hosted agent.", - "version": "0.1.5" + "description": "CopperPilot Claude Code plugin: CopperPilot's electronics design tools over MCP.", + "version": "0.2.0" }, "plugins": [ { "name": "copper-pilot", "source": "./plugins/copper-pilot", - "description": "MCP conductor plus @copper-pilot and /copper-pilot-review." + "description": "CopperPilot design tools over MCP (login included), plus @copper-pilot and /copper-pilot-review." } ] } diff --git a/README.md b/README.md index 8ca1ee2..f8cce57 100644 --- a/README.md +++ b/README.md @@ -129,28 +129,76 @@ ready message for `copper-pilot --mode agent`. Exit codes: 0 pass, 1 fail, 2 config error, 3 incomplete, 4 not logged in or usage limit. See [docs/validate.md](docs/validate.md). -## Use from Claude Code, Cursor, or Codex +## Use from Claude Code, Cursor, or Codex (MCP) -CopperPilot stays the electronics agent. Copy -[`skills/copper-pilot-review/SKILL.md`](skills/copper-pilot-review/SKILL.md) into -your harness, or expose the same agent over MCP: +`copper-pilot mcp` gives any MCP host CopperPilot's design tools: about 160 +tools to read, edit and check schematics, PCBs and libraries (KiCad and +Altium), run ERC/DRC and the autorouter, and research parts, plus +CopperPilot's playbook and the optional `copperpilot_subagent` (a hosted +CopperPilot turn). Your agent does the design work with them, the same way +it does when the CopperPilot app runs it as a Claude Agent. -```console -claude mcp add copper-pilot -- copper-pilot mcp -``` +### Install the CopperPilot MCP in Claude Code + +If you are an AI agent asked to "install the CopperPilot MCP", follow these +steps in order and run the commands yourself. + +1. Install the CLI (Python 3.11+). Use the first command that works: + + ```console + uv tool install copper-pilot-cli # recommended + pipx install copper-pilot-cli # if uv is not installed + python3 -m pip install --user copper-pilot-cli # last resort + ``` + + Then check `copper-pilot --version`. If the command is not found, the + installer printed the folder it used (usually `~/.local/bin`): use the full + path below. + +2. Register the MCP server for every project of this user: + + ```console + claude mcp add --scope user copperpilot -- copper-pilot mcp + ``` + +3. Log in to CopperPilot (once per machine). The user needs a CopperPilot + account; a free one can be created on the sign-in page. Tell the user a + browser page is about to open where they sign in (Google or email) and + approve this device, then run: + + ```console + copper-pilot auth login + ``` + + It opens the page, prints the link (for when no browser opens, e.g. over + SSH) and waits until the user approves, up to 15 minutes: run it with a + long timeout and wait for "Authenticated". If you cannot wait on it, skip + this step: after the restart the MCP server offers a `copperpilot_login` + tool that does the same from inside Claude Code. + +4. Tell the user to restart Claude Code (exit, then run `claude` again in + their project folder) so it loads the new server; `/mcp` then lists + `copperpilot` as connected. Claude Code loads MCP servers only at start. + +5. Work in the project folder (the folder with the `.kicad_pro`, or an empty + folder for a new design). The tools use the folder Claude Code was started + in. -Claude Code can also install the in-repo plugin: +Or install the in-repo plugin, which registers the same server and adds +`@copper-pilot` and `/copper-pilot-review` (the CLI from step 1 and the login +are still needed): ```text /plugin marketplace add CopperPilot/copper-pilot-cli /plugin install copper-pilot ``` -That plugin starts `copper-pilot mcp` (tools `status`, `ask`, `plan`, `run`, -`resume`, `threads_list`, `validate`) and adds `@copper-pilot` plus -`/copper-pilot-review`. Editors that speak the Agent Client Protocol, such as -Zed, can run `copper-pilot acp` after `pip install "copper-pilot-cli[acp]"`. -Setup for Cursor, Codex, Zed, and approvals: [docs/harness.md](docs/harness.md). +Cursor, Codex, Zed and other hosts: point them at the stdio command +`copper-pilot mcp`; see [docs/harness.md](docs/harness.md). The older +delegating tools (`ask`, `plan`, `run`, `resume`, `validate`) are still +available with `copper-pilot mcp --conductor`. Editors that speak the Agent +Client Protocol can run `copper-pilot acp` after +`pip install "copper-pilot-cli[acp]"`. ## Configuration @@ -214,9 +262,9 @@ normalizes hosted tool names, approval decisions, and result envelopes. Computer use, local model execution, LangSmith tracing, content telemetry, MCP **host**/plugin-runtime controls, and server -implementation code are not part of this package. A thin MCP **server** -(`copper-pilot mcp`) and an ACP **server** (`copper-pilot acp`) that delegate -to the hosted agent are. +implementation code are not part of this package. An MCP **server** +(`copper-pilot mcp`, CopperPilot's design tools for your agent) and an ACP +**server** (`copper-pilot acp`) are. See [UPSTREAM.md](UPSTREAM.md) and [NOTICE](NOTICE) for the retained Textual client attribution. diff --git a/docs/cli.md b/docs/cli.md index e3e9810..73e0dbb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -158,8 +158,8 @@ tools. **What the agent gets.** The agent keeps its own system prompt, built-in tools, settings (Claude loads your user, project and local settings: CLAUDE.md, permission rules, hooks, skills and your MCP servers) and native subagents. -CopperPilot adds, over MCP (in-process for Claude; `copper-pilot mcp ---tools-session` for Codex): +CopperPilot adds, over MCP (in-process for Claude; `copper-pilot mcp` for +Codex): - every design, check, edit and search tool the server offers for your EDA tool (about 150: `query_design`, ERC/DRC, `place_*`, `connect_*`, @@ -296,12 +296,46 @@ Flags, config, the default graph and the fix loop: [validate.md](validate.md). ## MCP ```console -copper-pilot mcp +copper-pilot mcp [--workspace DIR] [--approval auto|yolo] [--provider NAME] +copper-pilot mcp --conductor ``` -Serves a stdio MCP conductor for Claude Code, Cursor, Codex, and other MCP -hosts. Uses the stored device-login credential. Does not open a browser. Do not -write to stdout; the protocol owns it. +Serves CopperPilot's design tools over stdio MCP for Claude Code, Cursor, +Codex and any other MCP host: the same tools a Claude Agent or Codex chat gets +in the CLI and desktop app (see [Bring your own agent](#bring-your-own-agent)). +Do not write to stdout; the protocol owns it. + +- **Tools.** Every tool the server offers over `WS /api/copperpilot/tools/ws` + (about 160: design reads and edits, batches, `sync_schematic_to_pcb`, ERC / + DRC, autorouter skills, research, `read_copperpilot_playbook`, + `load_server_skill`), the optional `copperpilot_subagent`, and two local + tools: `copperpilot_status` (login, server, workspace, design files) and, + while logged out, `copperpilot_login`. +- **Guide.** The server's `instructions` carry CopperPilot's guide when the + user is logged in at start; it is also the resource `copperpilot://guide`. +- **Login.** Without a stored login the server still starts and lists only + `copperpilot_login` and `copperpilot_status`. `copperpilot_login` starts the + browser device login, opens the page (honoring `BROWSER`, never writing to + stdout) and returns the link for the agent to show the user; a second call + waits for the approval (up to 4 minutes per call). Once approved, the + server connects and sends `notifications/tools/list_changed`, so the host + loads the design tools without a restart. A login stored for another + server URL does not count, and a revoked key (HTTP 401/403) falls back to + `copperpilot_login`. +- **Workspace.** `--workspace`, else `CLAUDE_PROJECT_DIR`, else the current + directory (Claude Code starts the server in the project folder). +- **Approvals.** Reads run freely; local writes and shell follow `--approval` + (`auto` by default, `yolo` when asked). Nobody can answer a prompt here, so + what Auto would ask about is refused. Design files written by CopperPilot's + edit tools inside the workspace are routine. +- **Staged edits.** An MCP host does not report turn ends, so Altium edits + staged by an edit tool are applied right after that call. +- The socket reconnects for up to 60 s when it drops. When the TUI starts + Codex it passes a private `--relay` instead, so the TUI keeps the chat's one + tool socket, the prompts and the subagent rows. + +`--conductor` serves the older delegating tools instead, which hand whole +tasks to the hosted CopperPilot agent: | Tool | Role | |------|------| @@ -314,27 +348,9 @@ write to stdout; the protocol owns it. | `threads_list` | List threads for this workspace (`limit`, `all_workspaces`). | | `validate` | Read-only stage-gated review; returns `verdict`, `exit_code`, `report_path`, `next_actions`. | -Workspace is the tool argument, else `CLAUDE_PROJECT_DIR`, else the process -current directory. Manual approval is TUI-only. Passing `model` selects -Intelligence on that model; the result carries `model` (requested) and -`answered_model` (after any server fallback). See [harness.md](harness.md). - -### Tools session (`copper-pilot mcp --tools-session`) - -```console -copper-pilot mcp --tools-session [--workspace DIR] [--approval auto|yolo] [--provider NAME] -``` - -Serves CopperPilot's tools for your own agent instead of the delegating -conductor: the server's tools (edits included), the optional `copperpilot_subagent` and the -`copperpilot://guide` resource. It opens `WS /api/copperpilot/tools/ws` with -the stored login, answers the server's file and shell requests with the local -tool broker (reads return `content_sha256`; writes carrying `if_match` are -refused with `FILE_CHANGED` when the file changed since it was read), and -reconnects for up to 60 s when the socket drops. Nobody can answer a prompt -here, so what Auto would ask about is refused. When the TUI starts Codex it -passes a private `--relay` instead, so the TUI keeps the chat's one tool -socket, the prompts and the subagent rows. +Passing `model` selects Intelligence on that model; the result carries +`model` (requested) and `answered_model` (after any server fallback). See +[harness.md](harness.md). ## ACP diff --git a/docs/harness.md b/docs/harness.md index 0d49c64..e3692b5 100644 --- a/docs/harness.md +++ b/docs/harness.md @@ -1,15 +1,16 @@ # Use CopperPilot from Claude Code, Cursor, or Codex -CopperPilot stays the electronics agent. The outer tool (Claude Code, Cursor, -Codex, or a script) only **delegates**. Do not hand-edit KiCad files while a -CopperPilot run is in flight. +Two ways in: -Install the CLI and log in once from a terminal: +- **MCP (recommended):** `copper-pilot mcp` gives the outer agent + CopperPilot's design tools, guide and playbook; the outer agent does the + design work (Option 2). +- **Delegation:** the outer agent hands whole tasks to the hosted CopperPilot + agent, through the CLI (Option 1) or `copper-pilot mcp --conductor`. -```console -pip install copper-pilot-cli -copper-pilot auth login -``` +Install the CLI once (`uv tool install copper-pilot-cli`, or `pipx` / `pip`). +Log in from a terminal with `copper-pilot auth login`, or let the MCP host +call the `copperpilot_login` tool. ## Option 1: shell out to the CLI @@ -55,22 +56,22 @@ copper-pilot --provider codex Your agent uses its own login and settings; CopperPilot never handles its credentials or bills its tokens. To give another MCP host the same tools -without the CopperPilot UI, point it at `copper-pilot mcp --tools-session` -(the design tools including edits, the optional `copperpilot_subagent`, and the -`copperpilot://guide` resource). See [cli.md](cli.md#bring-your-own-agent). +without the CopperPilot UI, point it at `copper-pilot mcp` (Option 2). See [cli.md](cli.md#bring-your-own-agent). -## Option 2: MCP conductor (`copper-pilot mcp`) +## Option 2: MCP (`copper-pilot mcp`) The same process as the CLI, same stored credential. Stdio JSON-RPC; do not -write logs to stdout. +write logs to stdout. What it serves (tools, login, guide, approvals) is in +[cli.md](cli.md#mcp). ### Claude Code ```console -claude mcp add copper-pilot -- copper-pilot mcp +claude mcp add --scope user copperpilot -- copper-pilot mcp ``` -Or install the in-repo plugin (starts the same server automatically): +Restart Claude Code to load it. Or install the in-repo plugin (starts the +same server automatically): ```text /plugin marketplace add CopperPilot/copper-pilot-cli @@ -92,7 +93,7 @@ Add a stdio server in `.cursor/mcp.json`: ```json { "mcpServers": { - "copper-pilot": { + "copperpilot": { "command": "copper-pilot", "args": ["mcp"] } @@ -102,18 +103,10 @@ Add a stdio server in `.cursor/mcp.json`: ### Codex and other MCP hosts -Point the host at `copper-pilot mcp` on stdio. Tools: - -| Tool | Role | -|------|------| -| `status` | Login state and discovered schematic/PCB paths | -| `models` | Intelligence model catalog for the `model` argument; no hosted turn | -| `ask` | Read-oriented specialist (`--mode ask`); optional `effort`, `model` | -| `plan` | Plan without applying (`--mode plan`); optional `effort`, `model` | -| `run` | Mutating agent turn (`--mode agent`); optional `effort`, `model` | -| `resume` | Continue `thread_id` (`mode` defaults to `agent`; optional `effort`, `model`) | -| `threads_list` | List threads for this workspace | -| `validate` | Read-only stage-gated review graph (`copper-pilot validate`); returns `next_actions` | +Point the host at `copper-pilot mcp` on stdio. For the delegating tools +(`status`, `models`, `ask`, `plan`, `run`, `resume`, `threads_list`, +`validate`), use `copper-pilot mcp --conductor`; they are listed in +[cli.md](cli.md#mcp). Workspace is the tool `workspace` argument, else `CLAUDE_PROJECT_DIR`, else the process current directory. diff --git a/plugins/copper-pilot/.claude-plugin/plugin.json b/plugins/copper-pilot/.claude-plugin/plugin.json index 5593db3..efa82e2 100644 --- a/plugins/copper-pilot/.claude-plugin/plugin.json +++ b/plugins/copper-pilot/.claude-plugin/plugin.json @@ -1,8 +1,8 @@ { "name": "copper-pilot", "displayName": "CopperPilot", - "description": "Delegate electronics design tasks to the CopperPilot hosted agent.", - "version": "0.1.5", + "description": "CopperPilot's electronics design tools for Claude Code: schematic, PCB, libraries, ERC/DRC, routing and part research.", + "version": "0.2.0", "author": { "name": "CopperPilot" }, diff --git a/plugins/copper-pilot/.mcp.json b/plugins/copper-pilot/.mcp.json index 13a8085..17514b1 100644 --- a/plugins/copper-pilot/.mcp.json +++ b/plugins/copper-pilot/.mcp.json @@ -1,6 +1,6 @@ { "mcpServers": { - "copper-pilot": { + "copperpilot": { "command": "copper-pilot", "args": ["mcp"] } diff --git a/plugins/copper-pilot/agents/copper-pilot.md b/plugins/copper-pilot/agents/copper-pilot.md index 42ee200..22549fe 100644 --- a/plugins/copper-pilot/agents/copper-pilot.md +++ b/plugins/copper-pilot/agents/copper-pilot.md @@ -1,20 +1,16 @@ --- name: copper-pilot -description: Delegate schematic, PCB, ERC, DRC, and electronics design tasks to the CopperPilot hosted agent. Use when the user asks to review a board, inspect a net or reference, check ERC/DRC, or change KiCad files. +description: Electronics designer with CopperPilot's tools. Use for schematic, PCB, library, ERC, DRC, routing and part research tasks on KiCad or Altium projects. disallowedTools: Write, Edit -tools: Read, mcp__plugin_copper-pilot_copper-pilot__status, mcp__plugin_copper-pilot_copper-pilot__ask, mcp__plugin_copper-pilot_copper-pilot__plan, mcp__plugin_copper-pilot_copper-pilot__run, mcp__plugin_copper-pilot_copper-pilot__resume, mcp__plugin_copper-pilot_copper-pilot__threads_list, mcp__plugin_copper-pilot_copper-pilot__validate --- -You are CopperPilot's specialist inside Claude Code. You do not invent ERC, DRC, stackup, or footprint judgments. You delegate to the CopperPilot MCP tools. +You are an electronics designer working with CopperPilot's MCP tools (server `copperpilot`; in this plugin their names start with `mcp__plugin_copper-pilot_copperpilot__`). Rules: -- Call `status` first if login or workspace paths are unknown. -- Prefer `ask` unless the user asked for a schematic or PCB change. Use `plan` for a plan, `run` to apply a change, `resume` with a prior `thread_id`. `resume` defaults to agent mode (mutating); pass `mode="ask"` to continue a read-only conversation without escalating write access. -- Use `effort="intelligence"` only when the user requests a deep survey or Intelligence and has a paid plan. Balanced is the default. Intelligence workers survey only; the parent owns the final answer or plan. -- Pass `approval=yolo` only when the user explicitly asked to skip local approval. Default is Auto. -- Do not Edit or Write KiCad files. Leave schematic and PCB side effects to CopperPilot. -- If a tool returns `login_required`, tell the user to run `copper-pilot auth login` in a terminal. -- MCP cannot answer interactive clarification prompts. If one is rejected, return the `thread_id` and ask the user to continue it in the CopperPilot terminal TUI. -- Use `validate` for readiness or sign-off questions. It is read-only and stage-gated; report the `verdict` and `next_actions`, fix with `run` citing finding IDs, then `validate` again. -- Return a short specialist memo plus `thread_id`. Firmware, git, and docs stay with the parent agent. +- If only `copperpilot_login` and `copperpilot_status` are listed, the user is not logged in: call `copperpilot_login`, show the user the link it returns, and call it again once they say they approved the device in the browser. +- Before your first design edit, read the guide resource `copperpilot://guide` and the playbook sections it names (`read_copperpilot_playbook`). +- Read before you edit (`query_design`, `get_component_info`), edit only with CopperPilot's edit tools (never by hand: Write and Edit are disabled here), and check after you edit (`validate_schematic_layout`, `run_erc`, `run_drc`). Report real check results only. +- Ask the user when a choice is theirs (part selection, board size, connectors, cost versus performance). +- `copperpilot_subagent` runs a hosted CopperPilot turn billed to the user's CopperPilot plan; use it only when the user asks for CopperPilot itself or a second opinion. +- Name the files you changed. Firmware, git and docs stay with the parent agent. diff --git a/plugins/copper-pilot/skills/copper-pilot-review/SKILL.md b/plugins/copper-pilot/skills/copper-pilot-review/SKILL.md index b0d811e..a52e409 100644 --- a/plugins/copper-pilot/skills/copper-pilot-review/SKILL.md +++ b/plugins/copper-pilot/skills/copper-pilot-review/SKILL.md @@ -1,7 +1,7 @@ --- name: copper-pilot-review description: Review a schematic or PCB with CopperPilot. Use when the user asks to review a board, check ERC/DRC, inspect a net or reference, or get electronics feedback. -allowed-tools: Read mcp__plugin_copper-pilot_copper-pilot__status mcp__plugin_copper-pilot_copper-pilot__ask mcp__plugin_copper-pilot_copper-pilot__plan mcp__plugin_copper-pilot_copper-pilot__run mcp__plugin_copper-pilot_copper-pilot__resume mcp__plugin_copper-pilot_copper-pilot__threads_list mcp__plugin_copper-pilot_copper-pilot__validate +allowed-tools: Read mcp__plugin_copper-pilot_copperpilot__copperpilot_status mcp__plugin_copper-pilot_copperpilot__copperpilot_login mcp__plugin_copper-pilot_copperpilot__read_copperpilot_playbook mcp__plugin_copper-pilot_copperpilot__load_server_skill mcp__plugin_copper-pilot_copperpilot__query_design mcp__plugin_copper-pilot_copperpilot__get_component_info mcp__plugin_copper-pilot_copperpilot__run_erc mcp__plugin_copper-pilot_copperpilot__run_drc mcp__plugin_copper-pilot_copperpilot__validate_schematic_layout mcp__plugin_copper-pilot_copperpilot__copperpilot_subagent context: fork agent: copper-pilot background: false @@ -9,7 +9,7 @@ background: false # CopperPilot review -Delegate this request to CopperPilot. Do not invent electrical findings from KiCad source text. +Review this design with CopperPilot's tools. Do not invent electrical findings from KiCad source text. Request: @@ -19,9 +19,7 @@ If `$ARGUMENTS` is empty, use the user's latest message. Steps: -1. Call `status` if login or schematic/PCB paths are unknown. -2. Prefer `ask` unless the user asked for a schematic or PCB change. Use `plan` for a plan and `run` only when they asked to apply a change. -3. Do not Edit or Write KiCad files. -4. If a tool returns `login_required`, tell the user to run `copper-pilot auth login`. -5. For readiness or sign-off questions, call `validate` (read-only, stage-gated). Report its `verdict` and the `next_actions` list; fix them with `run`, citing each finding ID, then call `validate` again. -6. Summarize the specialist memo and quote `thread_id` so the parent can `resume`. +1. If the design tools are not listed, call `copperpilot_status`; if it says the user is not logged in, call `copperpilot_login` and show the user the link. +2. Load CopperPilot's review workflow: `load_server_skill` (its description lists the skill ids; pick the review skill) and the `mode_ask` section of `read_copperpilot_playbook`. +3. Read the design (`query_design`, `get_component_info`) and run the checks (`run_erc`, `run_drc`, `validate_schematic_layout`). Do not edit anything. +4. Report findings worst first, each with the evidence (tool result, reference, net) and a concrete fix. diff --git a/src/copper_pilot_cli/agents/cli.py b/src/copper_pilot_cli/agents/cli.py index e06cde9..3cc59d1 100644 --- a/src/copper_pilot_cli/agents/cli.py +++ b/src/copper_pilot_cli/agents/cli.py @@ -1,4 +1,4 @@ -"""``copper-pilot mcp --tools-session``: CopperPilot's tools for your own agent over stdio MCP. +"""``copper-pilot mcp``: CopperPilot's tools for your own agent over stdio MCP. Two modes: @@ -6,10 +6,11 @@ server that forwards to the TUI process, which owns the chat's tool socket, approval prompts and subagent cards. The relay token comes from the environment, never argv. -* standalone (any MCP host): opens its own tool socket with the stored - CopperPilot login. Reads run freely; writes and shell follow ``--approval`` - (``auto`` by default, ``yolo`` when asked). Nobody can answer a prompt - here, so what Auto would ask about is refused, as in ``copper-pilot mcp``. +* standalone (``copper-pilot mcp``, any MCP host): opens its own tool socket + with the stored CopperPilot login, or offers ``copperpilot_login`` until the + user logs in (``agents/standalone.py``). Reads run freely; writes and shell + follow ``--approval`` (``auto`` by default, ``yolo`` when asked). Nobody can + answer a prompt here, so what Auto would ask about is refused. """ from __future__ import annotations @@ -19,56 +20,35 @@ import sys import uuid -from copper_pilot_cli.agents.mcp_server import ProxyBackend, relay_backend_from_env, serve_stdio -from copper_pilot_cli.agents.tool_proxy import ToolProxy -from copper_pilot_cli.agents.tools_session import ToolSessionClient -from copper_pilot_cli.copper_auth import AuthenticationError, load_credential -from copper_pilot_cli.copper_preferences import shell_auto_allow_settings -from copper_pilot_cli.copper_tools import ApprovalMode, LocalToolBroker -from copper_pilot_cli.copper_workspace import canonical_workspace +from copper_pilot_cli.agents.mcp_server import relay_backend_from_env, serve_stdio +from copper_pilot_cli.copper_tools import ApprovalMode def run_tools_session(args: argparse.Namespace) -> int: if args.relay: asyncio.run(serve_stdio(relay_backend_from_env(args.relay))) return 0 + from copper_pilot_cli.agents.standalone import StandaloneBackend, startup_instructions + from copper_pilot_cli.copper_mcp import resolve_workspace + try: - credential = load_credential() - except AuthenticationError: - credential = None - if credential is None: - print( - "copper-pilot: CopperPilot login is required; run `copper-pilot auth login`.", - file=sys.stderr, - ) - return 2 - try: - workspace = canonical_workspace(args.workspace or ".") + workspace = resolve_workspace(args.workspace) except (FileNotFoundError, NotADirectoryError) as exc: print(f"copper-pilot: {exc}", file=sys.stderr) return 2 - normal_shell, dangerous_shell = shell_auto_allow_settings() - broker = LocalToolBroker( + backend = StandaloneBackend( workspace, - mode=ApprovalMode.YOLO if args.approval == "yolo" else ApprovalMode.AUTO, - always_allow_shell_commands=normal_shell, - always_allow_dangerous_shell_commands=dangerous_shell, - cas_writes=True, - ) - session = ToolSessionClient( - credential, - workspace=workspace, + approval=ApprovalMode.YOLO if args.approval == "yolo" else ApprovalMode.AUTO, + provider=args.provider or "mcp", + model=args.model or "", conversation_id=args.conversation_id or str(uuid.uuid4()), - executor=broker.execute, - agent={"provider": args.provider or "mcp", "model": args.model or ""}, ) - proxy = ToolProxy(session, workspace=workspace, broker=broker) async def main() -> None: try: - await serve_stdio(ProxyBackend(proxy)) + await serve_stdio(backend, instructions=await startup_instructions(backend)) finally: - await session.aclose() + await backend.aclose() asyncio.run(main()) return 0 diff --git a/src/copper_pilot_cli/agents/mcp_server.py b/src/copper_pilot_cli/agents/mcp_server.py index 77dc893..cb9ba59 100644 --- a/src/copper_pilot_cli/agents/mcp_server.py +++ b/src/copper_pilot_cli/agents/mcp_server.py @@ -85,9 +85,16 @@ def _content(item: dict[str, Any]) -> types.TextContent | types.ImageContent: return types.TextContent(type="text", text=str(item.get("text") or "")) -def build_mcp_server(backend: ToolBackend) -> Server: - """One MCP server exposing the backend's tools and the guide resource.""" - server: Server = Server(SERVER_NAME, version=__version__, instructions=INSTRUCTIONS) +def build_mcp_server(backend: ToolBackend, *, instructions: str | None = None) -> Server: + """One MCP server exposing the backend's tools and the guide resource. + + A backend whose tool list can change (the standalone server before and + after login) sets ``tools_changed``; the server then sends + ``notifications/tools/list_changed`` after that call. + """ + server: Server = Server( + SERVER_NAME, version=__version__, instructions=instructions or INSTRUCTIONS + ) @server.list_tools() async def list_tools() -> list[types.Tool]: @@ -108,6 +115,10 @@ async def list_tools() -> list[types.Tool]: async def call_tool(name: str, arguments: dict[str, Any]) -> types.CallToolResult: progress = _progress_reporter(server) outcome = await backend.call_tool(name, dict(arguments or {}), progress=progress) + if getattr(backend, "tools_changed", False): + setattr(backend, "tools_changed", False) # noqa: B010 - optional attribute + with contextlib.suppress(Exception): + await server.request_context.session.send_tool_list_changed() return types.CallToolResult( content=[_content(item) for item in outcome.content], isError=outcome.is_error ) @@ -153,12 +164,16 @@ async def report(message: str) -> None: return report -async def serve_stdio(backend: ToolBackend) -> None: +async def serve_stdio(backend: ToolBackend, *, instructions: str | None = None) -> None: + from mcp.server.lowlevel import NotificationOptions from mcp.server.stdio import stdio_server - server = build_mcp_server(backend) + server = build_mcp_server(backend, instructions=instructions) + options = server.create_initialization_options( + notification_options=NotificationOptions(tools_changed=True) + ) async with stdio_server() as (read_stream, write_stream): - await server.run(read_stream, write_stream, server.create_initialization_options()) + await server.run(read_stream, write_stream, options) # ------------------------------------------------------------------- relay diff --git a/src/copper_pilot_cli/agents/standalone.py b/src/copper_pilot_cli/agents/standalone.py new file mode 100644 index 0000000..999cbf8 --- /dev/null +++ b/src/copper_pilot_cli/agents/standalone.py @@ -0,0 +1,366 @@ +"""``copper-pilot mcp``: CopperPilot's design tools for any MCP host (Claude Code, Cursor, Codex). + +The same tools the CopperPilot CLI and desktop app give a Claude Agent or +Codex chat (bring your own agent): every design read, edit, check and +research tool from the tool socket, the playbook, and the optional +``copperpilot_subagent``. Two local tools are added: + +* ``copperpilot_login``: CopperPilot's browser device login, run from the + host. Before login only it and ``copperpilot_status`` are listed; once the + user approves the device the server connects and sends + ``notifications/tools/list_changed`` so the host loads the design tools + without a restart. +* ``copperpilot_status``: login state, workspace, discovered design files. + +An MCP host does not tell its servers when a turn ends, so staged Altium +edits are applied after each edit call instead of at turn end. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +import uuid +from pathlib import Path +from typing import Any + +from copper_pilot_cli._version import __version__ +from copper_pilot_cli.agents.mcp_server import INSTRUCTIONS, ProgressFn +from copper_pilot_cli.agents.tool_proxy import ToolOutcome, ToolProxy +from copper_pilot_cli.agents.tools_session import ToolSessionClient, ToolSessionError +from copper_pilot_cli.copper_auth import ( + AuthenticationError, + DeviceCredential, + DeviceLogin, + LoginFlow, + load_credential, + open_url_quietly, +) +from copper_pilot_cli.copper_config import api_base_url +from copper_pilot_cli.copper_preferences import shell_auto_allow_settings +from copper_pilot_cli.copper_tools import ApprovalMode, LocalToolBroker +from copper_pilot_cli.copper_workspace import discover_workspace + +logger = logging.getLogger(__name__) + +LOGIN_TOOL = "copperpilot_login" +STATUS_TOOL = "copperpilot_status" +# How long one copperpilot_login call waits for the user before it returns. +FIRST_WAIT_SECONDS = 20.0 +NEXT_WAIT_SECONDS = 240.0 +STARTUP_CONNECT_SECONDS = 20.0 + +LOGGED_OUT_INSTRUCTIONS = ( + "CopperPilot: electronics design tools (KiCad and Altium schematics, PCBs, " + "libraries, ERC/DRC, routing, part research). The user is not logged in to " + "CopperPilot yet, so only copperpilot_login and copperpilot_status are listed. " + "When the user wants CopperPilot, call copperpilot_login: it opens the " + "CopperPilot sign-in page in the user's browser (a free account can be created " + "there) and returns the link. Show the link to the user, ask them to finish in " + "the browser, then call copperpilot_login again to wait for it. After login the " + "design tools appear (if they do not, ask the user to run /mcp and reconnect " + "copperpilot); read the guide resource copperpilot://guide before designing." +) + +LOGIN_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "open_browser": { + "type": "boolean", + "default": True, + "description": ( + "Open the sign-in page in the user's browser (false: only return the link)." + ), + }, + "restart": { + "type": "boolean", + "default": False, + "description": "Start a new login (a new link) instead of waiting on the current one.", + }, + }, +} +STATUS_SCHEMA: dict[str, Any] = {"type": "object", "properties": {}} + +LOGIN_DESCRIPTION = ( + "Log the user in to CopperPilot (needed once per machine). Opens the CopperPilot " + "sign-in page in the user's browser, where they sign in or create a free account " + "and approve this device. Returns the link to show the user if it is still " + "pending; call it again after the user says they finished to wait for the " + "approval. When it succeeds, the CopperPilot design tools become available." +) +STATUS_DESCRIPTION = ( + "CopperPilot status: whether the user is logged in (and to which server), the " + "workspace folder the tools work in, the schematic / PCB files found there, the " + "CLI version and how many design tools are loaded. Makes no design changes." +) + + +def _local_tool(name: str, description: str, schema: dict[str, Any]) -> dict[str, Any]: + return { + "name": name, + "description": description, + "inputSchema": schema, + "readOnly": name == STATUS_TOOL, + "alwaysLoad": True, + } + + +def _safe_credential() -> DeviceCredential | None: + try: + credential = load_credential() + except AuthenticationError: + return None + if credential is None: + return None + # A login stored for another server (e.g. a dev stack) does not count here. + if credential.base_url.rstrip("/") != api_base_url().rstrip("/"): + return None + return credential + + +class StandaloneBackend: + """Tool backend for ``copper-pilot mcp``: login-aware, owns its tool socket.""" + + def __init__( + self, + workspace: Path, + *, + approval: ApprovalMode = ApprovalMode.AUTO, + provider: str = "", + model: str = "", + conversation_id: str | None = None, + session_factory: Any = ToolSessionClient, + login_factory: Any = DeviceLogin, + open_url: Any = open_url_quietly, + ) -> None: + self.workspace = workspace + self.approval = approval + self.provider = provider + self.model = model + self.conversation_id = conversation_id or str(uuid.uuid4()) + self.session_factory = session_factory + self.login_factory = login_factory + self.open_url = open_url + self.tools_changed = False + self.credential: DeviceCredential | None = _safe_credential() + self.proxy: ToolProxy | None = None + self.session: ToolSessionClient | None = None + self.connect_error: str | None = None + self._flow: LoginFlow | None = None + self._login_lock = asyncio.Lock() + self._connect_lock = asyncio.Lock() + + # ------------------------------------------------------------ session + + def _broker(self) -> LocalToolBroker: + normal_shell, dangerous_shell = shell_auto_allow_settings() + return LocalToolBroker( + self.workspace, + mode=self.approval, + always_allow_shell_commands=normal_shell, + always_allow_dangerous_shell_commands=dangerous_shell, + cas_writes=True, + ) + + async def connect(self) -> bool: + """Open the tool socket with the stored login; False (with ``connect_error``) if not.""" + async with self._connect_lock: + if self.proxy is not None: + return True + if self.credential is None: + return False + broker = self._broker() + session = self.session_factory( + self.credential, + workspace=self.workspace, + conversation_id=self.conversation_id, + executor=broker.execute, + agent={"provider": self.provider or "mcp", "model": self.model}, + turn_end=True, + ) + proxy = ToolProxy(session, workspace=self.workspace, broker=broker) + try: + await proxy.start() + except ToolSessionError as exc: + with contextlib.suppress(Exception): + await session.aclose() + self.connect_error = str(exc) + if exc.status in {401, 403}: + # The stored key was revoked or expired: log in again. + self.credential = None + return False + self.session, self.proxy, self.connect_error = session, proxy, None + return True + + async def aclose(self) -> None: + if self.session is not None: + await self.session.aclose() + + @property + def logged_in(self) -> bool: + return self.credential is not None + + # ------------------------------------------------------- ToolBackend + + async def list_tools(self) -> list[dict[str, Any]]: + status = _local_tool(STATUS_TOOL, STATUS_DESCRIPTION, STATUS_SCHEMA) + if await self.connect(): + assert self.proxy is not None + return [*await self.proxy.list_tools(), status] + return [_local_tool(LOGIN_TOOL, LOGIN_DESCRIPTION, LOGIN_SCHEMA), status] + + async def read_guide(self) -> str: + if await self.connect(): + assert self.proxy is not None + return self.proxy.guide + return LOGGED_OUT_INSTRUCTIONS + + async def call_tool( + self, name: str, arguments: dict[str, Any], *, progress: ProgressFn | None = None + ) -> ToolOutcome: + if name == LOGIN_TOOL: + return await self.login(arguments, progress=progress) + if name == STATUS_TOOL: + return ToolOutcome.text(self.status_text()) + if not await self.connect(): + return ToolOutcome.text(self._not_connected(), is_error=True) + assert self.proxy is not None and self.session is not None + outcome = await self.proxy.call_tool(name, arguments, progress=progress) + if not outcome.is_error and not self.proxy.read_only(name): + # No turn ends reach an MCP server: apply staged (Altium) edits now. + note = await self.session.send_turn_end(f"mcp-{uuid.uuid4().hex[:12]}") + if note: + outcome.content.append({"type": "text", "text": note}) + return outcome + + def _not_connected(self) -> str: + if self.credential is None: + return "CopperPilot login is required: call copperpilot_login first." + return f"CopperPilot tools are unavailable: {self.connect_error or 'not connected'}" + + # ------------------------------------------------------------- status + + def status_text(self) -> str: + context = discover_workspace(self.workspace) + lines = [ + f"CopperPilot CLI {__version__}", + f"Server: {api_base_url()}", + "Logged in: yes" if self.credential else "Logged in: no (call copperpilot_login)", + f"Workspace: {self.workspace}", + f"Schematic: {context.schematic_path or 'none found'}", + f"PCB: {context.pcb_path or 'none found'}", + ] + if self.proxy is not None: + lines.append(f"Design tools: {len(self.proxy.tool_names())} loaded") + elif self.connect_error: + lines.append(f"Design tools: unavailable ({self.connect_error})") + if self._flow is not None and not self._flow.expired and self.credential is None: + lines.append(f"Login pending: {self._flow.url}") + return "\n".join(lines) + + # -------------------------------------------------------------- login + + async def login(self, arguments: dict[str, Any], *, progress: ProgressFn | None) -> ToolOutcome: + async with self._login_lock: + if self.credential is not None and not arguments.get("restart"): + if await self.connect(): + return ToolOutcome.text(self._logged_in_text(already=True)) + if self.credential is not None: + return ToolOutcome.text(self._not_connected(), is_error=True) + login = self.login_factory(client_version=__version__) + fresh = self._flow is None or self._flow.expired or bool(arguments.get("restart")) + try: + if fresh: + self._flow = await login.start() + opened = False + if arguments.get("open_browser", True) is not False: + opened = bool(self.open_url(self._flow.url)) + if progress is not None: + await progress("Waiting for the user to approve CopperPilot in the browser") + wait = FIRST_WAIT_SECONDS + else: + opened = True + if progress is not None: + await progress("Waiting for the user to approve CopperPilot in the browser") + wait = NEXT_WAIT_SECONDS + assert self._flow is not None + credential = await login.wait(self._flow, timeout=wait) + except AuthenticationError as exc: + self._flow = None + return ToolOutcome.text( + f"CopperPilot login failed: {exc} Call copperpilot_login again for a new link.", + is_error=True, + ) + except Exception as exc: # noqa: BLE001 - network errors go back to the agent + return ToolOutcome.text( + f"Could not reach CopperPilot at {api_base_url()} " + f"({type(exc).__name__}: {exc}).", + is_error=True, + ) + if credential is None: + return ToolOutcome.text(self._pending_text(self._flow.url, opened, fresh)) + self._flow = None + self.credential = credential + if not await self.connect(): + return ToolOutcome.text( + "Logged in to CopperPilot, but the design tools could not connect: " + f"{self.connect_error}", + is_error=True, + ) + self.tools_changed = True + return ToolOutcome.text(self._logged_in_text(already=False)) + + @staticmethod + def _pending_text(url: str, opened: bool, fresh: bool) -> str: + where = ( + "The CopperPilot sign-in page is open in the user's browser" + if opened + else "Could not open a browser here" + ) + return ( + f"Login pending. {where}. Show the user this link (it works in any browser on " + f"any device):\n\n{url}\n\n" + "Tell the user to sign in there (or create a free CopperPilot account with " + "Google or email) and approve this device, then tell you when it is done. " + "Then call copperpilot_login again; it waits for the approval." + + ("" if fresh else " The same link is still valid.") + ) + + def _logged_in_text(self, *, already: bool) -> str: + count = len(self.proxy.tool_names()) if self.proxy is not None else 0 + head = ( + "Already logged in to CopperPilot." + if already + else "Logged in to CopperPilot; this device is approved." + ) + return ( + f"{head} {count} CopperPilot design tools are available (names start with " + "the server's prefix, e.g. mcp__copperpilot__query_design in Claude Code; if " + "they are not listed yet, ask the user to run /mcp and reconnect copperpilot). " + f"Workspace: {self.workspace}. Before designing, read the guide resource " + "copperpilot://guide and call read_copperpilot_playbook as it says." + ) + + +async def startup_instructions(backend: StandaloneBackend) -> str: + """The MCP ``instructions``: the CopperPilot guide when logged in, else how to log in.""" + if not backend.logged_in: + return LOGGED_OUT_INSTRUCTIONS + try: + async with asyncio.timeout(STARTUP_CONNECT_SECONDS): + connected = await backend.connect() + except TimeoutError: + connected = False + if not connected or backend.proxy is None: + return INSTRUCTIONS + guide = backend.proxy.guide.strip() + return f"{INSTRUCTIONS}\n\n{guide}" if guide else INSTRUCTIONS + + +__all__ = [ + "LOGIN_TOOL", + "STATUS_TOOL", + "StandaloneBackend", + "startup_instructions", +] diff --git a/src/copper_pilot_cli/copper_auth.py b/src/copper_pilot_cli/copper_auth.py index 3c3a8bc..bf772f4 100644 --- a/src/copper_pilot_cli/copper_auth.py +++ b/src/copper_pilot_cli/copper_auth.py @@ -167,6 +167,66 @@ async def validate_credential(credential: DeviceCredential) -> bool: return True +@dataclass(slots=True) +class LoginFlow: + """One started device login: the page the user opens and the token we poll.""" + + token: str + url: str + fingerprint: str + started: float + expires_in: float + + @property + def expired(self) -> bool: + return time.monotonic() - self.started >= self.expires_in + + +def open_url_quietly(url: str) -> bool: + """Open ``url`` in the user's browser without touching this process's stdout. + + ``webbrowser`` lets the browser inherit stdout, which corrupts a stdio MCP + stream; the launcher here gets ``/dev/null`` for its output instead. + Honors ``BROWSER`` like ``webbrowser`` does. Returns False when nothing + could be launched. + """ + import shlex + import subprocess + import sys + + commands: list[list[str]] = [] + for entry in (os.environ.get("BROWSER") or "").split(os.pathsep): + if entry.strip(): + parts = shlex.split(entry) + commands.append( + [part.replace("%s", url) for part in parts] + if any("%s" in part for part in parts) + else [*parts, url] + ) + if sys.platform == "darwin": + commands.append(["open", url]) + elif os.name == "nt": + with contextlib.suppress(OSError): + os.startfile(url) # type: ignore[attr-defined] # noqa: S606 + return True + else: + commands.append(["xdg-open", url]) + for command in commands: + try: + subprocess.Popen( # noqa: S603 - the user's own browser launcher + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + close_fds=True, + ) + except OSError: + continue + return True + return False + + class DeviceLogin: """Run CopperPilot's browser-based device login flow.""" @@ -174,13 +234,16 @@ def __init__(self, base_url: str | None = None, client_version: str = __version_ self.base_url = (base_url or api_base_url()).rstrip("/") self.client_version = client_version - async def login(self, *, open_browser: bool = True) -> DeviceCredential: - """Start a flow, open the browser, and poll until ready.""" + @property + def endpoint(self) -> str: + return f"{self.base_url}/api/copperpilot/auth/api-keys-device-login-flow" + + async def start(self) -> LoginFlow: + """Create a flow; the user approves this device at ``flow.url``.""" fingerprint = build_fingerprint() - endpoint = f"{self.base_url}/api/copperpilot/auth/api-keys-device-login-flow" async with httpx.AsyncClient(timeout=30) as client: response = await client.post( - endpoint, + self.endpoint, json={ "host_name": safe_hostname(), "fingerprint": fingerprint, @@ -190,25 +253,36 @@ async def login(self, *, open_browser: bool = True) -> DeviceCredential: ) response.raise_for_status() body = response.json() - token = normalize_flow_token(body.get("flow_token")) - if open_browser: - webbrowser.open(f"{self.base_url}/createKey?flow_token={quote(token)}") - started = time.monotonic() - expiry_seconds = min( + token = normalize_flow_token(body.get("flow_token")) + return LoginFlow( + token=token, + url=f"{self.base_url}/createKey?flow_token={quote(token)}", + fingerprint=fingerprint, + started=time.monotonic(), + expires_in=min( max(int(body.get("expires_in_seconds") or body.get("expires_in") or 300), 1), 900, - ) - while time.monotonic() - started < expiry_seconds: - elapsed = time.monotonic() - started + ), + ) + + async def wait(self, flow: LoginFlow, timeout: float | None = None) -> DeviceCredential | None: # noqa: ASYNC109 + """Poll until the user approves (saved and returned) or ``timeout`` passes (None). + + Raises ``AuthenticationError`` when the flow expired or was rejected. + """ + deadline = time.monotonic() + (timeout if timeout is not None else flow.expires_in) + async with httpx.AsyncClient(timeout=30) as client: + while not flow.expired: + elapsed = time.monotonic() - flow.started delay = 0.3 if elapsed < 10 else 1.0 - poll = await client.get(endpoint, params={"flow_token": token}) + poll = await client.get(self.endpoint, params={"flow_token": flow.token}) if poll.status_code == 200: result: dict[str, Any] = poll.json() key = str(result.get("api_key") or "") if result.get("status") == "ready" and key.startswith(_KEY_PREFIX): credential = DeviceCredential( api_key=key, - fingerprint=fingerprint, + fingerprint=flow.fingerprint, base_url=self.base_url, issued_at=result.get("issued_at"), expires_at=result.get("expires_at"), @@ -229,5 +303,24 @@ async def login(self, *, open_browser: bool = True) -> DeviceCredential: delay = max(0.2, min(float(retry) / 1000, 5)) else: poll.raise_for_status() + if time.monotonic() + delay > deadline: + return None await asyncio.sleep(delay) raise AuthenticationError("Device login timed out.") + + async def login(self, *, open_browser: bool = True, on_url: Any = None) -> DeviceCredential: + """Start a flow, open the browser, and poll until ready. + + ``on_url(url)`` is called with the login page (to print it for the + user when no browser can open, e.g. over SSH). + """ + flow = await self.start() + if on_url is not None: + on_url(flow.url) + if open_browser and not open_url_quietly(flow.url): + with contextlib.suppress(Exception): + webbrowser.open(flow.url) + credential = await self.wait(flow) + if credential is None: # pragma: no cover - wait() without timeout never returns None + raise AuthenticationError("Device login timed out.") + return credential diff --git a/src/copper_pilot_cli/copper_main.py b/src/copper_pilot_cli/copper_main.py index 4f6a2e2..01ed659 100644 --- a/src/copper_pilot_cli/copper_main.py +++ b/src/copper_pilot_cli/copper_main.py @@ -4,6 +4,7 @@ import argparse import asyncio +import contextlib import importlib.metadata import importlib.util import json @@ -34,6 +35,7 @@ load_credential, validate_credential, ) +from copper_pilot_cli.copper_config import api_base_url from copper_pilot_cli.copper_graph import ( CAPACITY_WAIT_EVENT, PROVIDER_BUSY_PAUSED_MESSAGE, @@ -214,7 +216,10 @@ def command_parser(command: str) -> argparse.ArgumentParser: descriptions = { "auth": "Device login for the hosted CopperPilot agent.", "threads": "List, delete or compact CopperPilot chat threads.", - "mcp": "Run a stdio MCP server that delegates to the hosted agent.", + "mcp": ( + "Run a stdio MCP server with CopperPilot's design tools for Claude Code, " + "Cursor, Codex or any MCP host (login included: copperpilot_login)." + ), "acp": "Run a stdio ACP (Agent Client Protocol) server for editors such as Zed.", "update": "Check for or install the latest CopperPilot CLI release.", } @@ -236,30 +241,38 @@ def command_parser(command: str) -> argparse.ArgumentParser: result.set_defaults(workspace=".", message=None, command=command) if command == "mcp": result.add_argument( - "--tools-session", + "--conductor", action="store_true", help=( - "Serve CopperPilot's tools (design edits included, plus the optional " - "copperpilot_subagent) " - "for your own agent instead of the delegating conductor" + "Serve the older delegating tools (ask, plan, run, resume, validate, " + "threads_list) that hand whole tasks to the hosted CopperPilot agent, " + "instead of the design tools" ), ) + result.add_argument( + "--tools-session", + action="store_true", + help=argparse.SUPPRESS, # the default since 1.0.6; kept for old configs + ) result.add_argument( "--workspace", dest="workspace", - default=".", - help="Workspace directory for --tools-session (default: current directory)", + default=None, + help=("Workspace directory (default: $CLAUDE_PROJECT_DIR, else the current directory)"), ) result.add_argument( "--conversation-id", default=None, - help="Conversation id for --tools-session (default: a new one)", + help="Conversation id for the tool session (default: a new one)", ) result.add_argument( "--approval", choices=["auto", "yolo"], default="auto", - help="Approval for local writes and shell in --tools-session (default: auto)", + help=( + "Approval for local writes and shell (default: auto; nobody can answer " + "a prompt over MCP, so Auto refuses what it would ask about)" + ), ) result.add_argument( "--provider", @@ -292,6 +305,11 @@ def command_parser(command: str) -> argparse.ArgumentParser: default="status", help="login opens a browser; logout clears credentials; status is default", ) + result.add_argument( + "--force", + action="store_true", + help="login: start a new login even when already logged in", + ) return result thread_sub = result.add_subparsers(dest="thread_action", required=True) listing = thread_sub.add_parser("list", help="List threads for this workspace") @@ -332,7 +350,7 @@ def command_parser(command: str) -> argparse.ArgumentParser: return result -async def _auth_command(action: str) -> int: +async def _auth_command(action: str, *, force: bool = False) -> int: if action == "logout": console.print( "Logged out." if clear_credential() else "Already logged out.", @@ -348,8 +366,36 @@ async def _auth_command(action: str) -> int: markup=False, ) return 0 if credential else 1 + existing = None + with contextlib.suppress(AuthenticationError): + existing = load_credential() + same_server = existing is not None and existing.base_url.rstrip("/") == api_base_url().rstrip( + "/" + ) + if existing is not None and same_server and not force: + try: + valid = await validate_credential(existing) + except httpx.HTTPError: + valid = True # offline: keep the stored login rather than replace it + if valid: + console.print( + f"Already logged in to {existing.base_url}. " + "Run `copper-pilot auth login --force` to log in again.", + markup=False, + ) + return 0 console.print("Opening CopperPilot login in your browser…", markup=False) - credential = await DeviceLogin(client_version=__version__).login() + + def show_url(url: str) -> None: + console.print( + f"If the browser did not open, visit:\n {url}\n" + "Sign in or create a free account there and approve this device; " + "this command waits until you do.", + markup=False, + soft_wrap=True, + ) + + credential = await DeviceLogin(client_version=__version__).login(on_url=show_url) console.print(f"Authenticated to {credential.base_url}.", markup=False) return 0 @@ -760,7 +806,7 @@ async def async_main(args: argparse.Namespace) -> int: return await _update_command(args) workspace = canonical_workspace(args.workspace) if args.command == "auth": - return await _auth_command(args.action) + return await _auth_command(args.action, force=getattr(args, "force", False)) if args.command == "threads": return await _threads_command(args, workspace) credential = await _credential() @@ -871,7 +917,7 @@ def cli_main() -> None: raise SystemExit(130) from None return if args.command == "mcp": - if getattr(args, "tools_session", False): + if not getattr(args, "conductor", False): from copper_pilot_cli.agents.cli import run_tools_session try: diff --git a/tests/test_byo_runtime.py b/tests/test_byo_runtime.py index 02712f6..62d1be4 100644 --- a/tests/test_byo_runtime.py +++ b/tests/test_byo_runtime.py @@ -303,7 +303,11 @@ def test_mcp_tools_session_flags() -> None: ["--tools-session", "--workspace", "/tmp", "--approval", "yolo"] # noqa: S108 ) assert args.tools_session and args.approval == "yolo" and args.workspace == "/tmp" # noqa: S108 - assert command_parser("mcp").parse_args([]).tools_session is False + defaults = command_parser("mcp").parse_args([]) + # The design tools are the default; --tools-session is kept for old configs. + assert defaults.tools_session is False and defaults.conductor is False + assert defaults.workspace is None + assert command_parser("mcp").parse_args(["--conductor"]).conductor is True def test_saved_agent_selection_round_trip() -> None: diff --git a/tests/test_main.py b/tests/test_main.py index 051e86f..4096785 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -93,7 +93,7 @@ def test_thread_delete_requires_explicit_yes_flag() -> None: def test_mcp_subcommand_has_no_positional_workspace() -> None: args = command_parser("mcp").parse_args([]) assert args.command == "mcp" - assert args.workspace == "." + assert args.workspace is None # resolved from CLAUDE_PROJECT_DIR, else cwd def test_mcp_help_describes_stdio_server() -> None: diff --git a/tests/test_mcp_standalone.py b/tests/test_mcp_standalone.py new file mode 100644 index 0000000..4748f1c --- /dev/null +++ b/tests/test_mcp_standalone.py @@ -0,0 +1,190 @@ +"""``copper-pilot mcp``: login inside the MCP host, then the design tools.""" + +from __future__ import annotations + +import time +from pathlib import Path +from typing import Any + +import pytest + +from copper_pilot_cli.agents import standalone +from copper_pilot_cli.agents.mcp_server import build_mcp_server +from copper_pilot_cli.agents.standalone import ( + LOGGED_OUT_INSTRUCTIONS, + LOGIN_TOOL, + STATUS_TOOL, + StandaloneBackend, + startup_instructions, +) +from copper_pilot_cli.agents.tools_session import ToolSessionError +from copper_pilot_cli.copper_auth import DeviceCredential, LoginFlow + +BASE = "https://copperpilot.ai" +CREDENTIAL = DeviceCredential(api_key="cf_live_x", fingerprint="fp", base_url=BASE) +TOOLS = [ + {"name": "query_design", "description": "Read", "input_schema": {"type": "object"}}, + {"name": "apply_kicad_schematic_batch", "description": "Edit", "read_only": False}, +] + + +class FakeSession: + instances: list[FakeSession] = [] + fail: ToolSessionError | None = None + + def __init__(self, credential: DeviceCredential, **kwargs: Any) -> None: + self.credential = credential + self.kwargs = kwargs + self.tools = list(TOOLS) + self.guide = "# CopperPilot tools\nguide body" + self.on_progress = None + self.calls: list[str] = [] + self.turn_ends: list[str] = [] + self.closed = False + FakeSession.instances.append(self) + + async def start(self) -> None: + if FakeSession.fail is not None: + raise FakeSession.fail + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + self.calls.append(name) + return {"ok": True, "content": [{"type": "text", "text": f"{name} ok"}]} + + async def send_turn_end(self, turn_id: str) -> str | None: + self.turn_ends.append(turn_id) + return None + + async def aclose(self) -> None: + self.closed = True + + +class FakeLogin: + approve_after = 1 # wait() calls before the user approves + waits = 0 + started = 0 + + def __init__(self, client_version: str = "") -> None: + del client_version + + async def start(self) -> LoginFlow: + FakeLogin.started += 1 + return LoginFlow( + token=f"tok{FakeLogin.started}", + url=f"{BASE}/createKey?flow_token=tok{FakeLogin.started}", + fingerprint="fp", + started=time.monotonic(), + expires_in=300, + ) + + async def wait(self, flow: LoginFlow, timeout: float | None = None) -> DeviceCredential | None: # noqa: ASYNC109 + del flow, timeout + FakeLogin.waits += 1 + return CREDENTIAL if FakeLogin.waits > FakeLogin.approve_after else None + + +@pytest.fixture(autouse=True) +def _reset(monkeypatch: pytest.MonkeyPatch) -> None: + FakeSession.instances = [] + FakeSession.fail = None + FakeLogin.approve_after, FakeLogin.waits, FakeLogin.started = 1, 0, 0 + monkeypatch.setattr(standalone, "api_base_url", lambda: BASE) + + +def _backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, credential=None, opened=None): + monkeypatch.setattr(standalone, "load_credential", lambda: credential) + opened = [] if opened is None else opened + return StandaloneBackend( + tmp_path, + session_factory=FakeSession, + login_factory=FakeLogin, + open_url=lambda url: opened.append(url) or True, + ) + + +async def test_logged_out_lists_only_login_and_status(tmp_path, monkeypatch) -> None: + backend = _backend(tmp_path, monkeypatch) + names = [tool["name"] for tool in await backend.list_tools()] + assert names == [LOGIN_TOOL, STATUS_TOOL] + assert await startup_instructions(backend) == LOGGED_OUT_INSTRUCTIONS + outcome = await backend.call_tool("query_design", {}) + assert outcome.is_error and "copperpilot_login" in outcome.plain() + assert "Logged in: no" in (await backend.call_tool(STATUS_TOOL, {})).plain() + + +async def test_login_returns_link_then_connects_and_flags_tool_change( + tmp_path, monkeypatch +) -> None: + opened: list[str] = [] + backend = _backend(tmp_path, monkeypatch, opened=opened) + first = await backend.call_tool(LOGIN_TOOL, {}) + assert not first.is_error + assert "Login pending" in first.plain() and f"{BASE}/createKey?flow_token=tok1" in first.plain() + assert opened == [f"{BASE}/createKey?flow_token=tok1"] + assert backend.tools_changed is False + # The user approved in the browser; the second call waits on the same flow. + second = await backend.call_tool(LOGIN_TOOL, {}) + assert not second.is_error and "Logged in to CopperPilot" in second.plain() + assert FakeLogin.started == 1 and len(opened) == 1 + assert backend.tools_changed is True + names = [tool["name"] for tool in await backend.list_tools()] + assert {"query_design", "apply_kicad_schematic_batch", "copperpilot_subagent"} <= set(names) + assert STATUS_TOOL in names and LOGIN_TOOL not in names + session = FakeSession.instances[0] + assert session.kwargs["turn_end"] is True and session.kwargs["workspace"] == tmp_path + + +async def test_logged_in_serves_guide_as_instructions_and_proxies_calls( + tmp_path, monkeypatch +) -> None: + backend = _backend(tmp_path, monkeypatch, credential=CREDENTIAL) + instructions = await startup_instructions(backend) + assert "guide body" in instructions + assert "Already logged in" in (await backend.call_tool(LOGIN_TOOL, {})).plain() + read = await backend.call_tool("query_design", {}) + assert read.plain() == "query_design ok" + session = FakeSession.instances[0] + assert session.turn_ends == [] # reads apply nothing + edit = await backend.call_tool("apply_kicad_schematic_batch", {}) + assert not edit.is_error and len(session.turn_ends) == 1 # staged edits applied now + await backend.aclose() + assert session.closed + + +async def test_revoked_key_falls_back_to_login(tmp_path, monkeypatch) -> None: + FakeSession.fail = ToolSessionError("refused (HTTP 401)", status=401) + backend = _backend(tmp_path, monkeypatch, credential=CREDENTIAL) + names = [tool["name"] for tool in await backend.list_tools()] + assert names == [LOGIN_TOOL, STATUS_TOOL] + assert backend.credential is None + + +async def test_login_for_another_server_does_not_count(tmp_path, monkeypatch) -> None: + other = DeviceCredential(api_key="cf_live_y", fingerprint="fp", base_url="http://localhost") + backend = _backend(tmp_path, monkeypatch, credential=other) + assert not backend.logged_in + + +async def test_server_sends_list_changed_after_login(tmp_path, monkeypatch) -> None: + from mcp.shared.memory import create_connected_server_and_client_session + + FakeLogin.approve_after = 0 + backend = _backend(tmp_path, monkeypatch) + server = build_mcp_server(backend, instructions=LOGGED_OUT_INSTRUCTIONS) + changed: list[str] = [] + + async def on_message(message: Any) -> None: + root = getattr(message, "root", None) + if getattr(root, "method", None) == "notifications/tools/list_changed": + changed.append(root.method) + + async with create_connected_server_and_client_session( + server, message_handler=on_message + ) as client: + listed = await client.list_tools() + assert [tool.name for tool in listed.tools] == [LOGIN_TOOL, STATUS_TOOL] + result = await client.call_tool(LOGIN_TOOL, {}) + assert not result.isError + listed = await client.list_tools() + assert "query_design" in [tool.name for tool in listed.tools] + assert changed == ["notifications/tools/list_changed"] diff --git a/tests/test_plugin_manifest.py b/tests/test_plugin_manifest.py index b9a075e..bf36b6c 100644 --- a/tests/test_plugin_manifest.py +++ b/tests/test_plugin_manifest.py @@ -39,7 +39,7 @@ def test_marketplace_and_plugin_manifests_parse() -> None: assert marketplace["plugins"][0]["source"] == "./plugins/copper-pilot" assert plugin["name"] == "copper-pilot" assert re.fullmatch(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", plugin["version"]) - server = mcp["mcpServers"]["copper-pilot"] + server = mcp["mcpServers"]["copperpilot"] assert server["command"] == "copper-pilot" assert server["args"] == ["mcp"] @@ -50,7 +50,8 @@ def test_plugin_agent_and_skill_exist() -> None: assert agent.is_file() assert skill.is_file() agent_text = agent.read_text(encoding="utf-8") - assert "mcp__plugin_copper-pilot_copper-pilot__ask" in agent_text + assert "mcp__plugin_copper-pilot_copperpilot__" in agent_text + assert "copperpilot_login" in agent_text assert "disallowedTools: Write, Edit" in agent_text skill_fields = _frontmatter(skill) assert skill_fields["name"] == "copper-pilot-review" From 782f4f017018d658e8ab8ec64a21e4604cffb7a5 Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 09:29:07 +0530 Subject: [PATCH 2/6] copper-pilot mcp: CopperPilot's own design-file writes are routine under Auto Nobody can approve a prompt over MCP, so every edit tool's bridge write to a .kicad_sch/.kicad_pcb was refused ('ToolRejected: write was rejected'). Same rule as a Claude Agent chat in the TUI (runtime.py): KiCad design files inside the workspace written by CopperPilot's tools are routine; outside still refused. Found in the Haiku design bench (L1, first edit). --- src/copper_pilot_cli/agents/standalone.py | 4 ++++ tests/test_mcp_standalone.py | 24 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/copper_pilot_cli/agents/standalone.py b/src/copper_pilot_cli/agents/standalone.py index 999cbf8..462c06a 100644 --- a/src/copper_pilot_cli/agents/standalone.py +++ b/src/copper_pilot_cli/agents/standalone.py @@ -160,6 +160,10 @@ def _broker(self) -> LocalToolBroker: mode=self.approval, always_allow_shell_commands=normal_shell, always_allow_dangerous_shell_commands=dangerous_shell, + # Design files written by CopperPilot's own edit tools (inside the + # workspace) are routine under Auto, as in a Claude Agent chat: + # nobody can approve a prompt over MCP, so they would be refused. + routine_kicad_writes=True, cas_writes=True, ) diff --git a/tests/test_mcp_standalone.py b/tests/test_mcp_standalone.py index 4748f1c..16ba1a0 100644 --- a/tests/test_mcp_standalone.py +++ b/tests/test_mcp_standalone.py @@ -188,3 +188,27 @@ async def on_message(message: Any) -> None: listed = await client.list_tools() assert "query_design" in [tool.name for tool in listed.tools] assert changed == ["notifications/tools/list_changed"] + + +async def test_design_file_writes_are_routine_under_auto(tmp_path, monkeypatch) -> None: + """CopperPilot's edit tools write .kicad_sch through the bridge; MCP cannot prompt.""" + from copper_pilot_cli.copper_protocol import ToolRequest + + (tmp_path / "board.kicad_sch").write_text("(kicad_sch)\n") + backend = _backend(tmp_path, monkeypatch, credential=CREDENTIAL) + broker = backend._broker() + request = ToolRequest( + tool_call_id="w1", + tool_name="write_file", + arguments={"file_path": str(tmp_path / "board.kicad_sch"), "content": "(kicad_sch x)\n"}, + ) + result = await broker.execute(request) + assert "reject" not in str(result).lower() + assert (tmp_path / "board.kicad_sch").read_text() == "(kicad_sch x)\n" + outside = ToolRequest( + tool_call_id="w2", + tool_name="write_file", + arguments={"file_path": str(tmp_path.parent / "elsewhere.kicad_sch"), "content": "x"}, + ) + with pytest.raises(Exception, match="(?i)reject|outside the workspace"): + await broker.execute(outside) From ec6f1f7c0b9d4ab5d4d5447af9b0a1747ddc9da6 Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 09:54:25 +0530 Subject: [PATCH 3/6] copper-pilot mcp install: one command registers the server with Claude Code and logs in The ST-35 onboarding story (Claude Code on Haiku asked to 'Install the CopperPilot MCP') showed Claude following the README's separate steps but never running the login and never telling the user to restart Claude Code. - copper-pilot mcp install: claude mcp add --scope user copperpilot with this installation's absolute path; device login with the link printed and a ~90 s foreground wait, then a detached helper finishes the login on the same link; ends with 'NEXT STEPS (tell the user)', restart first. - README install section is now two commands plus relaying those steps; tagline and PyPI description/keywords mention the MCP server (discovery). --- README.md | 54 +++---- docs/cli.md | 9 ++ pyproject.toml | 3 +- src/copper_pilot_cli/agents/install.py | 212 +++++++++++++++++++++++++ src/copper_pilot_cli/copper_main.py | 33 ++++ tests/test_mcp_install.py | 118 ++++++++++++++ 6 files changed, 398 insertions(+), 31 deletions(-) create mode 100644 src/copper_pilot_cli/agents/install.py create mode 100644 tests/test_mcp_install.py diff --git a/README.md b/README.md index f8cce57..cd81f94 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@
-

The AI for PCB design, in your terminal.

+

The AI for PCB design, in your terminal, and an MCP server for Claude Code, Cursor and Codex.

@@ -140,8 +140,10 @@ it does when the CopperPilot app runs it as a Claude Agent. ### Install the CopperPilot MCP in Claude Code -If you are an AI agent asked to "install the CopperPilot MCP", follow these -steps in order and run the commands yourself. +If you are an AI agent asked to "install the CopperPilot MCP", run these two +commands yourself, in order. Before the second, tell the user that a browser +page will open where they sign in to CopperPilot (or create a free account +with Google or email) and approve this computer. 1. Install the CLI (Python 3.11+). Use the first command that works: @@ -151,38 +153,30 @@ steps in order and run the commands yourself. python3 -m pip install --user copper-pilot-cli # last resort ``` - Then check `copper-pilot --version`. If the command is not found, the - installer printed the folder it used (usually `~/.local/bin`): use the full - path below. + If `copper-pilot` is then not found, use the full path the installer + printed (usually `~/.local/bin/copper-pilot`). -2. Register the MCP server for every project of this user: +2. Register the MCP server with Claude Code and log in: ```console - claude mcp add --scope user copperpilot -- copper-pilot mcp + copper-pilot mcp install ``` -3. Log in to CopperPilot (once per machine). The user needs a CopperPilot - account; a free one can be created on the sign-in page. Tell the user a - browser page is about to open where they sign in (Google or email) and - approve this device, then run: - - ```console - copper-pilot auth login - ``` - - It opens the page, prints the link (for when no browser opens, e.g. over - SSH) and waits until the user approves, up to 15 minutes: run it with a - long timeout and wait for "Authenticated". If you cannot wait on it, skip - this step: after the restart the MCP server offers a `copperpilot_login` - tool that does the same from inside Claude Code. - -4. Tell the user to restart Claude Code (exit, then run `claude` again in - their project folder) so it loads the new server; `/mcp` then lists - `copperpilot` as connected. Claude Code loads MCP servers only at start. - -5. Work in the project folder (the folder with the `.kicad_pro`, or an empty - folder for a new design). The tools use the folder Claude Code was started - in. + It runs `claude mcp add --scope user copperpilot -- mcp`, opens the + CopperPilot sign-in page, prints its link (show it to the user if no browser + opened) and waits about 90 seconds; if the user is not done by then, the + login finishes on its own once they approve. + +3. Relay the "NEXT STEPS (tell the user)" lines it prints. The user must + **restart Claude Code** (type `/exit`, then run `claude` again in the project + folder): Claude Code loads MCP servers only at start. `/mcp` then shows + `copperpilot` connected, and the CopperPilot tools work in the folder Claude + Code was started in (a KiCad project, or an empty folder for a new design). + +By hand instead of step 2: `claude mcp add --scope user copperpilot -- +copper-pilot mcp`, then `copper-pilot auth login`. If the user is not logged in +when Claude Code starts, the server offers a `copperpilot_login` tool that does +the same from inside Claude Code. Or install the in-repo plugin, which registers the same server and adds `@copper-pilot` and `/copper-pilot-review` (the CLI from step 1 and the login diff --git a/docs/cli.md b/docs/cli.md index 73e0dbb..9c02608 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -297,9 +297,18 @@ Flags, config, the default graph and the fix loop: [validate.md](validate.md). ```console copper-pilot mcp [--workspace DIR] [--approval auto|yolo] [--provider NAME] +copper-pilot mcp install [--scope user|project|local] [--no-login] copper-pilot mcp --conductor ``` +`copper-pilot mcp install` registers the server with Claude Code (`claude mcp +add --scope user copperpilot -- mcp`, replacing an older +`copperpilot` entry), then logs in unless a valid login exists: it prints the +sign-in link, opens the browser and waits about 90 seconds (under an agent's +shell timeout); if the user is not done, a detached helper keeps waiting on the +same link until it expires and stores the login. It ends with the next steps +for the user, chief among them restarting Claude Code. + Serves CopperPilot's design tools over stdio MCP for Claude Code, Cursor, Codex and any other MCP host: the same tools a Claude Agent or Codex chat gets in the CLI and desktop app (see [Bring your own agent](#bring-your-own-agent)). diff --git a/pyproject.toml b/pyproject.toml index ce8da09..560b0b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,8 @@ build-backend = "hatchling.build" [project] name = "copper-pilot-cli" dynamic = ["version"] -description = "CopperPilot hosted agent for the terminal and LangChain" +description = "CopperPilot, the AI for PCB design: terminal agent, MCP server for Claude Code / Cursor / Codex, and LangChain" +keywords = ["mcp", "mcp-server", "claude-code", "kicad", "altium", "pcb", "electronics", "eda", "copperpilot"] readme = "README.md" license = "MIT" license-files = ["LICENSE", "NOTICE"] diff --git a/src/copper_pilot_cli/agents/install.py b/src/copper_pilot_cli/agents/install.py new file mode 100644 index 0000000..cfcfecb --- /dev/null +++ b/src/copper_pilot_cli/agents/install.py @@ -0,0 +1,212 @@ +"""``copper-pilot mcp install``: register the CopperPilot MCP server with Claude Code and log in. + +One command an agent can run when the user says "install the CopperPilot MCP" +(the ST-35 onboarding story found that Claude, following a multi-step README, +registered the server but never ran the login and never told the user to +restart). It: + +1. registers ``copper-pilot mcp`` with ``claude mcp add --scope user`` using + this installation's absolute path (works even when the tool's bin folder is + not on ``PATH``); +2. logs in unless a valid login exists: prints the sign-in link, opens the + browser and waits a short while. If the user is not done by then, a + detached helper keeps waiting on the same link (up to its expiry) and stores + the login when the user approves, so the command returns before an agent's + shell timeout; +3. ends with what the user must do next, worded for the agent to relay: + restart Claude Code. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +from copper_pilot_cli.copper_auth import ( + AuthenticationError, + DeviceLogin, + LoginFlow, + load_credential, + open_url_quietly, + validate_credential, +) +from copper_pilot_cli.copper_config import api_base_url + +SERVER_NAME = "copperpilot" +# Under Claude Code's default 2-minute shell timeout, with room to spare. +FOREGROUND_WAIT_SECONDS = 90.0 +FLOW_ENV = "COPPER_PILOT_LOGIN_FLOW" # token|fingerprint|expires_at_epoch (env, never argv) + + +def server_command() -> list[str]: + """How Claude Code should start this installation's MCP server.""" + script = shutil.which("copper-pilot") + here = Path(sys.argv[0]).resolve() if sys.argv and sys.argv[0] else None + if here is not None and here.name in {"copper-pilot", "copper-pilot-cli"} and here.exists(): + return [str(here), "mcp"] + if script: + return [str(Path(script).resolve()), "mcp"] + return [sys.executable, "-m", "copper_pilot_cli", "mcp"] + + +def _run(argv: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run( # noqa: S603 - the user's own claude binary + argv, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL + ) + + +def register_claude(scope: str = "user") -> tuple[bool, str]: + """``claude mcp add`` (replacing an older ``copperpilot`` entry); (ok, message).""" + claude = shutil.which("claude") + command = server_command() + if claude is None: + return False, ( + "Claude Code (`claude`) is not on PATH. Register the server by hand: " + f"claude mcp add --scope {scope} {SERVER_NAME} -- {' '.join(command)}" + ) + with contextlib.suppress(Exception): + _run([claude, "mcp", "remove", "--scope", scope, SERVER_NAME]) + env_args: list[str] = [] + if os.environ.get("COPPER_PILOT_API_URL"): + # A non-default server (development, e2e) must reach the MCP process too. + env_args = ["-e", f"COPPER_PILOT_API_URL={os.environ['COPPER_PILOT_API_URL']}"] + result = _run([claude, "mcp", "add", "--scope", scope, *env_args, SERVER_NAME, "--", *command]) + if result.returncode != 0: + detail = (result.stderr or result.stdout).strip().splitlines() + return False, f"`claude mcp add` failed: {detail[-1] if detail else result.returncode}" + return True, f"Registered the `{SERVER_NAME}` MCP server for Claude Code ({scope} scope)." + + +async def _logged_in() -> bool: + try: + credential = load_credential() + except AuthenticationError: + return False + if credential is None or credential.base_url.rstrip("/") != api_base_url().rstrip("/"): + return False + try: + return await validate_credential(credential) + except Exception: # noqa: BLE001 - offline: keep the stored login + return True + + +def _detach_waiter(flow: LoginFlow) -> bool: + """Keep waiting on ``flow`` in a detached process; True if it started.""" + expires_at = time.time() + max(0.0, flow.expires_in - (time.monotonic() - flow.started)) + env = dict(os.environ) + env[FLOW_ENV] = f"{flow.token}|{flow.fingerprint}|{expires_at:.0f}" + try: + subprocess.Popen( # noqa: S603 - this CLI itself + [sys.executable, "-m", "copper_pilot_cli", "auth", "login", "--wait-flow"], + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + close_fds=True, + ) + except OSError: + return False + return True + + +async def wait_flow_from_env() -> int: + """``auth login --wait-flow``: finish a login another process started (detached helper).""" + raw = os.environ.get(FLOW_ENV, "") + try: + token, fingerprint, expires_at = raw.split("|") + remaining = float(expires_at) - time.time() + except ValueError: + return 2 + if remaining <= 0: + return 1 + flow = LoginFlow( + token=token, url="", fingerprint=fingerprint, started=time.monotonic(), expires_in=remaining + ) + try: + credential = await DeviceLogin().wait(flow) + except (AuthenticationError, OSError): + return 1 + except Exception: # noqa: BLE001 - detached: nothing to report to + return 1 + return 0 if credential is not None else 1 + + +async def login_step(out: Any, *, wait_seconds: float = FOREGROUND_WAIT_SECONDS) -> str: + """Log in if needed; 'already', 'done' or 'pending'.""" + if await _logged_in(): + out(f"Already logged in to CopperPilot ({api_base_url()}).") + return "already" + login = DeviceLogin() + flow = await login.start() + opened = open_url_quietly(flow.url) + out( + "CopperPilot login: " + + ( + "a sign-in page is opening in your browser." + if opened + else "open this link in a browser." + ) + ) + out(f" {flow.url}") + out("Sign in or create a free CopperPilot account (Google or email), then approve this device.") + credential = await login.wait(flow, timeout=wait_seconds) + if credential is not None: + out("Logged in to CopperPilot.") + return "done" + if _detach_waiter(flow): + return "pending" + out("Login not finished; run `copper-pilot auth login` after approving.") + return "pending" + + +async def install(*, scope: str = "user", login: bool = True, out: Any = print) -> int: + ok, message = register_claude(scope) + out(message) + state = "skipped" + if login: + try: + state = await login_step(out) + except Exception as exc: # noqa: BLE001 - the registration still stands + out(f"Login could not start ({type(exc).__name__}: {exc}).") + state = "failed" + out("") + out("NEXT STEPS (tell the user):") + step = 1 + if state == "pending": + out( + f"{step}. Finish signing in at the link above and approve this device; this " + "computer picks up the login on its own (within 15 minutes)." + ) + step += 1 + elif state in {"failed", "skipped"}: + out( + f"{step}. Log in: run `copper-pilot auth login` (or, after the restart, ask Claude " + "to use the copperpilot_login tool)." + ) + step += 1 + if ok: + out( + f"{step}. Restart Claude Code to load CopperPilot: type /exit, then run `claude` " + "again in your project folder. Check with /mcp (copperpilot: connected)." + ) + step += 1 + out( + f'{step}. Then ask, for example: "Use CopperPilot to design a breakout board for ' + 'an MPU6050" or "Review my KiCad board with CopperPilot".' + ) + return 0 if ok else 1 + + +def run_install(args: Any) -> int: + return asyncio.run(install(scope=args.scope, login=not args.no_login)) + + +__all__ = ["install", "register_claude", "run_install", "server_command", "wait_flow_from_env"] diff --git a/src/copper_pilot_cli/copper_main.py b/src/copper_pilot_cli/copper_main.py index 01ed659..305694c 100644 --- a/src/copper_pilot_cli/copper_main.py +++ b/src/copper_pilot_cli/copper_main.py @@ -240,6 +240,27 @@ def command_parser(command: str) -> argparse.ArgumentParser: ) result.set_defaults(workspace=".", message=None, command=command) if command == "mcp": + result.add_argument( + "action", + nargs="?", + choices=["install"], + default=None, + help=( + "install: register the server with Claude Code (claude mcp add --scope " + "user) and log in to CopperPilot; omit to serve MCP on stdio" + ), + ) + result.add_argument( + "--scope", + choices=["user", "project", "local"], + default="user", + help="install: Claude Code config scope (default: user, every project)", + ) + result.add_argument( + "--no-login", + action="store_true", + help="install: only register the server; log in later", + ) result.add_argument( "--conductor", action="store_true", @@ -310,6 +331,7 @@ def command_parser(command: str) -> argparse.ArgumentParser: action="store_true", help="login: start a new login even when already logged in", ) + result.add_argument("--wait-flow", action="store_true", help=argparse.SUPPRESS) return result thread_sub = result.add_subparsers(dest="thread_action", required=True) listing = thread_sub.add_parser("list", help="List threads for this workspace") @@ -916,6 +938,17 @@ def cli_main() -> None: except KeyboardInterrupt: raise SystemExit(130) from None return + if args.command == "auth" and getattr(args, "wait_flow", False): + from copper_pilot_cli.agents.install import wait_flow_from_env + + raise SystemExit(asyncio.run(wait_flow_from_env())) + if args.command == "mcp" and getattr(args, "action", None) == "install": + from copper_pilot_cli.agents.install import run_install + + try: + raise SystemExit(run_install(args)) + except KeyboardInterrupt: + raise SystemExit(130) from None if args.command == "mcp": if not getattr(args, "conductor", False): from copper_pilot_cli.agents.cli import run_tools_session diff --git a/tests/test_mcp_install.py b/tests/test_mcp_install.py new file mode 100644 index 0000000..79525a6 --- /dev/null +++ b/tests/test_mcp_install.py @@ -0,0 +1,118 @@ +"""``copper-pilot mcp install``: register with Claude Code, log in, tell the user to restart.""" + +from __future__ import annotations + +import subprocess +import time +from typing import Any + +import pytest + +from copper_pilot_cli.agents import install +from copper_pilot_cli.copper_auth import DeviceCredential, LoginFlow + +CREDENTIAL = DeviceCredential( + api_key="cf_live_x", fingerprint="fp", base_url="https://copperpilot.ai" +) + + +class FakeLogin: + approve = False + + def __init__(self, *args: Any, **kwargs: Any) -> None: + del args, kwargs + + async def start(self) -> LoginFlow: + return LoginFlow( + "tok123456", + "https://copperpilot.ai/createKey?flow_token=tok123456", + "fp", + time.monotonic(), + 300, + ) + + async def wait(self, flow: LoginFlow, timeout: float | None = None) -> DeviceCredential | None: # noqa: ASYNC109 + del flow, timeout + return CREDENTIAL if FakeLogin.approve else None + + +@pytest.fixture +def claude(monkeypatch: pytest.MonkeyPatch) -> list[list[str]]: + calls: list[list[str]] = [] + monkeypatch.setattr(install.shutil, "which", lambda name: f"/bin/{name}") + monkeypatch.setattr( + install, + "_run", + lambda argv: calls.append(argv) or subprocess.CompletedProcess(argv, 0, "", ""), + ) + monkeypatch.setattr(install, "DeviceLogin", FakeLogin) + monkeypatch.setattr(install, "open_url_quietly", lambda url: True) + FakeLogin.approve = False + return calls + + +async def test_install_registers_user_scope_and_says_restart(claude, monkeypatch) -> None: + async def logged_in() -> bool: + return True + + monkeypatch.setattr(install, "_logged_in", logged_in) + lines: list[str] = [] + assert await install.install(out=lines.append) == 0 + add = next(call for call in claude if call[1:3] == ["mcp", "add"]) + assert add[3:5] == ["--scope", "user"] and "copperpilot" in add + assert add[-1] == "mcp" + text = "\n".join(lines) + assert "Already logged in" in text + assert "Restart Claude Code" in text and "NEXT STEPS (tell the user)" in text + + +async def test_install_login_done(claude, monkeypatch) -> None: + async def logged_in() -> bool: + return False + + monkeypatch.setattr(install, "_logged_in", logged_in) + FakeLogin.approve = True + lines: list[str] = [] + assert await install.install(out=lines.append) == 0 + text = "\n".join(lines) + assert "createKey?flow_token=tok123456" in text and "Logged in to CopperPilot." in text + + +async def test_install_login_pending_detaches_a_waiter(claude, monkeypatch) -> None: + async def logged_in() -> bool: + return False + + detached: list[LoginFlow] = [] + monkeypatch.setattr(install, "_logged_in", logged_in) + monkeypatch.setattr(install, "_detach_waiter", lambda flow: detached.append(flow) or True) + lines: list[str] = [] + assert await install.install(out=lines.append) == 0 + text = "\n".join(lines) + assert detached and detached[0].token == "tok123456" # noqa: S105 - fake flow token + assert "picks up the login on its own" in text and "Restart Claude Code" in text + + +async def test_wait_flow_from_env_finishes_the_login(monkeypatch) -> None: + monkeypatch.setattr(install, "DeviceLogin", FakeLogin) + FakeLogin.approve = True + monkeypatch.setenv(install.FLOW_ENV, f"tok123456|fp|{time.time() + 120:.0f}") + assert await install.wait_flow_from_env() == 0 + monkeypatch.setenv(install.FLOW_ENV, f"tok123456|fp|{time.time() - 5:.0f}") + assert await install.wait_flow_from_env() == 1 + monkeypatch.setenv(install.FLOW_ENV, "garbage") + assert await install.wait_flow_from_env() == 2 + + +def test_install_without_claude_prints_the_manual_command(monkeypatch) -> None: + monkeypatch.setattr(install.shutil, "which", lambda name: None) + ok, message = install.register_claude() + assert not ok and "claude mcp add --scope user copperpilot --" in message + + +def test_parser_accepts_install(monkeypatch) -> None: + from copper_pilot_cli.copper_main import command_parser + + args = command_parser("mcp").parse_args(["install", "--no-login", "--scope", "project"]) + assert args.action == "install" and args.no_login and args.scope == "project" + assert command_parser("mcp").parse_args([]).action is None + assert command_parser("auth").parse_args(["login", "--wait-flow"]).wait_flow From f23a1cdaed5c60ceabc83bbe2efefcec2ca70820 Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 10:00:46 +0530 Subject: [PATCH 4/6] copper-pilot mcp: skill installs, .kicad_dru and library tables are routine writes Found by the Haiku design bench: every run stalled before routing because install_kicad_autorouter (writes .copperpilot/skills/kicad_autorouter/main.py), install_kicad_lib_search and set_kicad_project_design_rules (writes the .kicad_dru) were refused: nobody can approve a prompt over MCP. - .kicad_dru, sym-lib-table and fp-lib-table count as KiCad design files for tool-socket writes (also fixes the Claude Agent/Codex chats under Auto). - New broker flag routine_skill_writes: files under .copperpilot/skills/ are routine; only the standalone MCP server sets it (its host approves each CopperPilot tool call). The TUI still asks. --- src/copper_pilot_cli/agents/standalone.py | 3 ++ src/copper_pilot_cli/deepagents_tools.py | 37 ++++++++++++++++++++--- tests/test_mcp_standalone.py | 37 +++++++++++++++++++++++ 3 files changed, 72 insertions(+), 5 deletions(-) diff --git a/src/copper_pilot_cli/agents/standalone.py b/src/copper_pilot_cli/agents/standalone.py index 462c06a..be9c007 100644 --- a/src/copper_pilot_cli/agents/standalone.py +++ b/src/copper_pilot_cli/agents/standalone.py @@ -164,6 +164,9 @@ def _broker(self) -> LocalToolBroker: # workspace) are routine under Auto, as in a Claude Agent chat: # nobody can approve a prompt over MCP, so they would be refused. routine_kicad_writes=True, + # Skill installers (install_kicad_autorouter, ...) write their code + # under .copperpilot/skills/; the host approved that tool call. + routine_skill_writes=True, cas_writes=True, ) diff --git a/src/copper_pilot_cli/deepagents_tools.py b/src/copper_pilot_cli/deepagents_tools.py index 7ecc455..f7715db 100644 --- a/src/copper_pilot_cli/deepagents_tools.py +++ b/src/copper_pilot_cli/deepagents_tools.py @@ -148,6 +148,7 @@ class ApprovalRequest: ".kicad_sym", ".kicad_mod", ".kicad_pro", + ".kicad_dru", ".schdoc", ".pcbdoc", ".schlib", @@ -176,6 +177,8 @@ class ApprovalRequest: "yarn.lock", } ) +# KiCad project files without a suffix (written by register_*_library). +KICAD_DESIGN_NAMES = frozenset({"sym-lib-table", "fp-lib-table"}) # CopperPilot work folders whose files are routine for tool-socket writes # (``kicad_writes``); ``.copperpilot/skills`` holds code and is not one. _COPPERPILOT_WORK_DIRS = frozenset({"tmp", "scratch", "notes", "plans", "references"}) @@ -263,12 +266,25 @@ def _is_within(root: Path, path: Path) -> bool: def _routine_write_allowed( - root: Path, arguments: dict[str, Any], *, kicad_writes: bool = False + root: Path, + arguments: dict[str, Any], + *, + kicad_writes: bool = False, + skill_writes: bool = False, ) -> bool: path = _resolve_path(root, arguments.get("file_path")) if path is None or not _is_within(root, path): return False relative_parts = tuple(part.lower() for part in path.relative_to(root).parts) + if ( + skill_writes + and len(relative_parts) > 2 + and relative_parts[:2] == (".copperpilot", "skills") + and not any(part in _SENSITIVE_PARTS for part in relative_parts[2:]) + ): + # CopperPilot's skill installers (autorouter, library search, fab + # order) write their own code here; the host approved that tool call. + return True if ( kicad_writes and len(relative_parts) > 2 @@ -283,7 +299,9 @@ def _routine_write_allowed( return False if path.name.lower() in _SENSITIVE_NAMES | _DEPENDENCY_FILES: return False - if kicad_writes and path.suffix.lower() in KICAD_DESIGN_SUFFIXES: + if kicad_writes and ( + path.suffix.lower() in KICAD_DESIGN_SUFFIXES or path.name.lower() in KICAD_DESIGN_NAMES + ): return True return path.suffix.lower() in _ROUTINE_WRITE_SUFFIXES - _SCRIPT_SUFFIXES @@ -357,11 +375,14 @@ def routine_action( workspace: Path | None = None, *, kicad_writes: bool = False, + skill_writes: bool = False, ) -> bool: """Pinned dcode deterministic Auto policy for locally supported tools. - ``kicad_writes`` also counts KiCad design files as routine writes; only a - ``copperpilot_subagent`` turn's broker sets it. + ``kicad_writes`` also counts KiCad design files as routine writes (tool-socket + and ``copperpilot_subagent`` brokers). ``skill_writes`` also counts files under + ``.copperpilot/skills/`` (the standalone MCP server, whose host approves each + CopperPilot tool call, including the skill installers). """ root = (workspace or Path.cwd()).resolve() @@ -369,7 +390,9 @@ def routine_action( if canonical in _READ_TOOLS: return True if canonical in {"write_file", "edit_file"}: - return _routine_write_allowed(root, arguments, kicad_writes=kicad_writes) + return _routine_write_allowed( + root, arguments, kicad_writes=kicad_writes, skill_writes=skill_writes + ) if canonical == "delete" and kicad_writes: # Tool-socket tools (kicad_copy, staging cleanup) delete their own # scratch files; only CopperPilot's tmp and scratch folders qualify. @@ -392,11 +415,14 @@ def __init__( always_allow_shell_commands: bool = True, always_allow_dangerous_shell_commands: bool = False, routine_kicad_writes: bool = False, + routine_skill_writes: bool = False, cas_writes: bool = True, ) -> None: self.workspace = workspace.resolve() # See ``routine_action``: KiCad design writes from a delegated subagent turn. self.routine_kicad_writes = routine_kicad_writes + # See ``routine_action``: skill installs (standalone MCP server only). + self.routine_skill_writes = routine_skill_writes # ``cas_writes_v1``: reads return ``content_sha256``; writes honour ``if_match``. self.cas_writes = cas_writes self.mode = mode @@ -543,6 +569,7 @@ async def _authorized( request.arguments, self.workspace, kicad_writes=self.routine_kicad_writes, + skill_writes=self.routine_skill_writes, ): return async with self._prompt_lock: diff --git a/tests/test_mcp_standalone.py b/tests/test_mcp_standalone.py index 16ba1a0..72f5d65 100644 --- a/tests/test_mcp_standalone.py +++ b/tests/test_mcp_standalone.py @@ -212,3 +212,40 @@ async def test_design_file_writes_are_routine_under_auto(tmp_path, monkeypatch) ) with pytest.raises(Exception, match="(?i)reject|outside the workspace"): await broker.execute(outside) + + +@pytest.mark.parametrize( + "relative", + [ + ".copperpilot/skills/kicad_autorouter/main.py", + ".copperpilot/skills/kicad_autorouter/SKILL.md", + "design.kicad_dru", + "sym-lib-table", + "fp-lib-table", + ], +) +async def test_tool_installs_and_project_files_are_routine(tmp_path, monkeypatch, relative) -> None: + """Haiku bench: install_kicad_autorouter and set_kicad_project_design_rules were refused.""" + from copper_pilot_cli.copper_protocol import ToolRequest + + backend = _backend(tmp_path, monkeypatch, credential=CREDENTIAL) + broker = backend._broker() + target = tmp_path / relative + request = ToolRequest( + tool_call_id="w", + tool_name="write_file", + arguments={"file_path": str(target), "content": "x\n"}, + ) + result = await broker.execute(request) + assert "reject" not in str(result).lower() + assert target.read_text() == "x\n" + + +def test_skill_writes_stay_gated_outside_the_standalone_server(tmp_path) -> None: + from copper_pilot_cli.copper_tools import routine_action + + path = {"file_path": str(tmp_path / ".copperpilot/skills/kicad_autorouter/main.py")} + assert routine_action("write_file", path, tmp_path, kicad_writes=True) is False + assert routine_action("write_file", path, tmp_path, kicad_writes=True, skill_writes=True) + hook = {"file_path": str(tmp_path / ".copperpilot/skills/x/.git/hooks/pre-commit")} + assert routine_action("write_file", hook, tmp_path, skill_writes=True) is False From f08456e5d953798a526eb171db82e04debcec26d Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 10:10:25 +0530 Subject: [PATCH 5/6] README: one-command MCP install first, for agents reading a summary ST-35 candidate2: Claude read the README through WebFetch (a prompt-shaped summary), kept the by-hand 'claude mcp add' alternative and skipped the login. The install block (uv tool install + copper-pilot mcp install + restart) now sits right under the badges, and the agent section has no by-hand variant. --- README.md | 18 ++++++++++++++---- docs/harness.md | 6 ++++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index cd81f94..f9dac04 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,18 @@
+> **Install the CopperPilot MCP in Claude Code** (AI agents: run these yourself) +> +> ```console +> uv tool install copper-pilot-cli # or: pipx install copper-pilot-cli +> copper-pilot mcp install +> ``` +> +> `copper-pilot mcp install` registers the MCP server with Claude Code and +> logs the user in (a browser page opens: sign in or create a free account, +> then approve this computer). Then tell the user to **restart Claude Code**. +> Details: [Install the CopperPilot MCP in Claude Code](#install-the-copperpilot-mcp-in-claude-code). + CopperPilot in your terminal: a thin, open-source client for CopperPilot electronics design agent, the best AI for PCB Design.

@@ -173,10 +185,8 @@ with Google or email) and approve this computer. `copperpilot` connected, and the CopperPilot tools work in the folder Claude Code was started in (a KiCad project, or an empty folder for a new design). -By hand instead of step 2: `claude mcp add --scope user copperpilot -- -copper-pilot mcp`, then `copper-pilot auth login`. If the user is not logged in -when Claude Code starts, the server offers a `copperpilot_login` tool that does -the same from inside Claude Code. +If the user is not logged in when Claude Code starts, the server offers a +`copperpilot_login` tool that runs the same login from inside Claude Code. Or install the in-repo plugin, which registers the same server and adds `@copper-pilot` and `/copper-pilot-review` (the CLI from step 1 and the login diff --git a/docs/harness.md b/docs/harness.md index e3692b5..bf3c1c5 100644 --- a/docs/harness.md +++ b/docs/harness.md @@ -67,10 +67,12 @@ write logs to stdout. What it serves (tools, login, guide, approvals) is in ### Claude Code ```console -claude mcp add --scope user copperpilot -- copper-pilot mcp +copper-pilot mcp install ``` -Restart Claude Code to load it. Or install the in-repo plugin (starts the +It registers the server (the same as `claude mcp add --scope user copperpilot +-- copper-pilot mcp`, with this installation's full path) and logs in. Restart +Claude Code to load it. Or install the in-repo plugin (starts the same server automatically): ```text From fd7650d6291d510fabd57f5a5baf74dbbd9f9fb2 Mon Sep 17 00:00:00 2001 From: AdityaNG Date: Mon, 30 Nov 2026 10:21:51 +0530 Subject: [PATCH 6/6] mcp install: -e after the server name; always print the restart step ST-35 candidate4: with COPPER_PILOT_API_URL set, 'claude mcp add -e K=V copperpilot' let the variadic -e swallow the name, registration failed and the NEXT STEPS (restart) were never shown. -e now follows the name; on a failed registration the steps give the manual command and still say to restart. README: if Claude Code's auto mode blocks a step, the user runs it with '!'. --- README.md | 2 ++ src/copper_pilot_cli/agents/install.py | 29 ++++++++++++++++---------- tests/test_mcp_install.py | 26 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f9dac04..9e88449 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ > `copper-pilot mcp install` registers the MCP server with Claude Code and > logs the user in (a browser page opens: sign in or create a free account, > then approve this computer). Then tell the user to **restart Claude Code**. +> If Claude Code blocks a step (it changes Claude Code's own settings), ask the +> user to run it with a leading `!`, for example `! copper-pilot mcp install`. > Details: [Install the CopperPilot MCP in Claude Code](#install-the-copperpilot-mcp-in-claude-code). CopperPilot in your terminal: a thin, open-source client for CopperPilot electronics design agent, the best AI for PCB Design. diff --git a/src/copper_pilot_cli/agents/install.py b/src/copper_pilot_cli/agents/install.py index cfcfecb..6035b08 100644 --- a/src/copper_pilot_cli/agents/install.py +++ b/src/copper_pilot_cli/agents/install.py @@ -77,10 +77,15 @@ def register_claude(scope: str = "user") -> tuple[bool, str]: if os.environ.get("COPPER_PILOT_API_URL"): # A non-default server (development, e2e) must reach the MCP process too. env_args = ["-e", f"COPPER_PILOT_API_URL={os.environ['COPPER_PILOT_API_URL']}"] - result = _run([claude, "mcp", "add", "--scope", scope, *env_args, SERVER_NAME, "--", *command]) + # ``-e`` takes several values in Claude Code: it must follow the server name, + # or it swallows the name (ST-35 candidate4). + result = _run([claude, "mcp", "add", "--scope", scope, SERVER_NAME, *env_args, "--", *command]) if result.returncode != 0: detail = (result.stderr or result.stdout).strip().splitlines() - return False, f"`claude mcp add` failed: {detail[-1] if detail else result.returncode}" + return False, ( + f"`claude mcp add` failed ({detail[-1] if detail else result.returncode}). " + f"Run: claude mcp add --scope {scope} {SERVER_NAME} -- {' '.join(command)}" + ) return True, f"Registered the `{SERVER_NAME}` MCP server for Claude Code ({scope} scope)." @@ -192,16 +197,18 @@ async def install(*, scope: str = "user", login: bool = True, out: Any = print) "to use the copperpilot_login tool)." ) step += 1 - if ok: - out( - f"{step}. Restart Claude Code to load CopperPilot: type /exit, then run `claude` " - "again in your project folder. Check with /mcp (copperpilot: connected)." - ) + if not ok: + out(f"{step}. Register the server: {message}") step += 1 - out( - f'{step}. Then ask, for example: "Use CopperPilot to design a breakout board for ' - 'an MPU6050" or "Review my KiCad board with CopperPilot".' - ) + out( + f"{step}. Restart Claude Code to load CopperPilot: type /exit, then run `claude` " + "again in your project folder. Check with /mcp (copperpilot: connected)." + ) + step += 1 + out( + f'{step}. Then ask, for example: "Use CopperPilot to design a breakout board for ' + 'an MPU6050" or "Review my KiCad board with CopperPilot".' + ) return 0 if ok else 1 diff --git a/tests/test_mcp_install.py b/tests/test_mcp_install.py index 79525a6..7cc16ff 100644 --- a/tests/test_mcp_install.py +++ b/tests/test_mcp_install.py @@ -116,3 +116,29 @@ def test_parser_accepts_install(monkeypatch) -> None: assert args.action == "install" and args.no_login and args.scope == "project" assert command_parser("mcp").parse_args([]).action is None assert command_parser("auth").parse_args(["login", "--wait-flow"]).wait_flow + + +async def test_env_follows_the_server_name(claude, monkeypatch) -> None: + """Claude Code's -e is variadic: before the name it swallows it (ST-35 candidate4).""" + monkeypatch.setenv("COPPER_PILOT_API_URL", "http://localhost") + ok, _message = install.register_claude() + assert ok + add = next(call for call in claude if call[1:3] == ["mcp", "add"]) + name = add.index("copperpilot") + assert add[name + 1 : name + 3] == ["-e", "COPPER_PILOT_API_URL=http://localhost"] + assert add[name + 3] == "--" + + +async def test_restart_step_is_printed_even_when_registration_fails(claude, monkeypatch) -> None: + async def logged_in() -> bool: + return True + + monkeypatch.setattr(install, "_logged_in", logged_in) + monkeypatch.setattr( + install, "_run", lambda argv: subprocess.CompletedProcess(argv, 1, "", "boom") + ) + lines: list[str] = [] + assert await install.install(out=lines.append) == 1 + text = "\n".join(lines) + assert "Register the server" in text and "claude mcp add --scope user copperpilot" in text + assert "Restart Claude Code" in text