diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 5988163..7cf3318 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -18,6 +18,10 @@ jobs: python-version: "3.12" - name: Validate plugin structure run: python3 tests/validate.py + - name: Hook and content tests + run: | + python3 tests/test_hooks.py + python3 tests/test_content.py smoke-mcp: name: Live MCP smoke test diff --git a/CHANGELOG.md b/CHANGELOG.md index 20129ba..fa763cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to the CPZAI plugin are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.1.0] - 2026-11-25 + +### Fixed +- The pre-trade guard and the audit log never ran: they matched `mcp__cpzai__*`, while Claude Code names this plugin's tools `mcp__plugin_cpzai_cpzai__*`. The hooks now match both spellings, and every `allowed-tools`, `tools` and `disallowedTools` list uses the plugin names, so the agents can reach the CPZAI tools at all (cpzai#2908). +- The guard blocked every order and strategy run with "ask the user and re-issue", keeping no record of the answer, so a confirmed call was blocked again. It now answers `permissionDecision: "ask"`: Claude Code shows the call once with a summary and runs it when the user approves (cpzai#2908). It is now `scripts/pre_trade_guard.py`. +- The audit log recorded `ok: true` for every call (it read a `success` field PostToolUse does not send). It now reads the tool's answer and records `null` when the answer does not say. +- `/backtest` and the backtesting, strategy-development and alpha-research skills sent Claude to `execute_strategy` to backtest. That tool runs the strategy's code and can submit orders. `/backtest` now reads saved runs only and says runs start in CPZAI Strategy Lab; the quant-researcher agent can no longer call `execute_strategy` (cpzai#2797). +- Equity, cash and buying power came from `list_accounts`, which holds no balances. Commands, skills and agents now use `cash_summary` (cpzai#2906). +- Commands and skills asked for figures no tool returns (IV, Greeks, P/E, ROE, sector and factor exposure, week and month P&L, margin used) and pointed history-based figures (52-week range, moving averages, RSI, relative volume, per-holding beta and volatility, covariance) at the quote or the risk check. History now comes from `get_bars`; every command says to write "not available from CPZAI" for the rest, never fill it from memory; CONNECTORS.md lists what each tool returns (cpzai#2886, cpzai#2909). + +- The audit log (now `scripts/audit_log.py`) logged a refused order as ok, kept no broker reply, skipped calls that failed outright and cut the input at 240 characters. It now records refusals with their reason, the broker's order id and status, failed calls (PostToolUseFailure), and the whole input with credential fields redacted (cpzai#3024). +- The risk-management skill's risk contributions had an extra weight and added up to far more than 100%; portfolio-optimization described risk parity with the minimum-variance condition; strategy-development said inverse volatility equalizes risk contribution without the equal-correlation condition (cpzai#3012). +- Six formulas and rules: risk reversal sign, breadth, factor model parameter count, what scikit-learn's Ledoit-Wolf shrinks toward, the trade count for a meaningful backtest, and /trade-idea's expected value leaving out the worst case (cpzai#3022). +- SEC Rule 17a-4 retention: order memoranda 3 years, blotters and ledgers 6 (cpzai#3023). +- `/trade` takes a stop price, takes shares only, says orders are day orders, shows the limit and stop before approval, and never resends after a timeout; order-execution no longer offers GTC, IOC, FOK, extended hours, trailing or bracket orders through `place_order` (cpzai#3014, cpzai#3034). +- `/strategy-builder` writes the format Strategy Lab backtests: `SYMBOLS` and one module-level `generate_signals`, `generate_signal` or `on_bar` (cpzai#3013). +- `/positions`, `/portfolio-review`, `/risk-report` and `/orders` page until a short page instead of treating one page as the whole book (cpzai#3037). +- The pre-trade guard fails closed: empty or malformed events, unrecognised tool names and errors inside the guard are asked about instead of passing. The session banner reads the confirmation option as the guard does and says when python3 is missing. + +### Added +- `tests/test_hooks.py` and `tests/test_content.py`, run by `tests/run-all.sh` and CI. + ## [2.0.0] — 2026-04-30 State-of-the-art upgrade aligning the plugin with the current Claude Code / Cowork plugin specification. diff --git a/README.md b/README.md index 44df730..66efe51 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ [![Claude Cowork](https://img.shields.io/badge/Claude-Cowork-000000?logo=anthropic&logoColor=white)](https://claude.com/product/cowork) [![Claude Code](https://img.shields.io/badge/Claude-Code-000000?logo=anthropic&logoColor=white)](https://claude.com/product/claude-code) [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](cpzai/LICENSE) -[![Version](https://img.shields.io/badge/Version-2.0.0-blue)]() +[![Version](https://img.shields.io/badge/Version-2.1.0-blue)]() [![Skills](https://img.shields.io/badge/Skills-10-green)]() [![Commands](https://img.shields.io/badge/Commands-17-green)]() [![Agents](https://img.shields.io/badge/Agents-3-green)]() @@ -76,7 +76,7 @@ Claude Code prompts for your CPZ API key and secret on first use. To re-configur | Command | Description | |---------|-------------| | `/cpzai:strategy-builder` | Guided strategy creation — describe a trading idea and Claude writes the code | -| `/cpzai:backtest` | Run a strategy backtest, analyze metrics, and identify improvements | +| `/cpzai:backtest` | Analyze a strategy's saved backtest runs and identify improvements (runs start in CPZAI Strategy Lab) | | `/cpzai:risk-report` | Generate a risk report — VaR, Sharpe, drawdown, with recommendations | | `/cpzai:portfolio-review` | Full portfolio health check — positions, diversification, attribution | | `/cpzai:market-scan` | Scan sectors or themes with real-time quotes and context | @@ -126,14 +126,14 @@ Read-only by design: `risk-auditor` and `execution-reviewer` cannot place orders ## MCP Tools -The CPZAI MCP server provides 18 tools across 8 categories. Every tool carries a safety annotation (`readOnlyHint`, or `destructiveHint`) per the MCP specification. +The CPZAI MCP server's main tools are below (`tools/list` has the full catalog). Every tool carries a safety annotation (`readOnlyHint`, or `destructiveHint`) per the MCP specification. [CONNECTORS.md](cpzai/CONNECTORS.md#what-the-tools-return-and-what-they-do-not) lists what each tool returns and which figures no tool provides. | Category | Read-Only | Write | Destructive | |----------|-----------|-------|-------------| | Strategies | `list_strategies`, `get_strategy` | `create_strategy`, `update_strategy` | — | -| Backtesting | `get_backtest_results` | — | — | -| Trading | `list_orders`, `list_positions`, `list_accounts` | `sync_portfolio` | `place_order` | -| Market Data | `get_market_data` | — | — | +| Backtesting | `get_backtest_results`, `get_backtest_result` (saved runs; no tool starts one) | | | +| Trading | `list_orders`, `list_positions`, `list_accounts`, `cash_summary`, `export_transactions` | `sync_portfolio` | `place_order` | +| Market Data | `get_market_data`, `get_bars` | | | | Risk | `list_risk_snapshots` | `compute_risk` | — | | Execution | — | — | `execute_strategy` | | Webhooks | `list_webhooks` | `create_webhook` | `delete_webhook` | @@ -177,7 +177,7 @@ The `risk-auditor` agent pulls live positions, computes current VaR/Sharpe/drawd /cpzai:backtest my momentum strategy from 2020-01 to 2024-12 with weekly rebalance ``` -Runs the backtest, analyzes results (Sharpe, max drawdown, win rate), checks robustness across sub-periods, and suggests parameter improvements grounded in the `backtesting` skill. +Finds the saved run for that period in your CPZAI account, analyzes it (Sharpe, max drawdown, win rate), checks robustness across sub-periods, and suggests parameter improvements grounded in the `backtesting` skill. No plugin tool starts a backtest: run it in CPZAI Strategy Lab first. ### Place a guarded order @@ -210,7 +210,7 @@ The `cpzai/.mcp.json` config wires `userConfig` values into HTTP headers automat "headers": { "X-CPZ-Key": "${user_config.cpz_api_key}", "X-CPZ-Secret": "${user_config.cpz_api_secret}", - "X-CPZ-Client": "claude-plugin/2.0.0" + "X-CPZ-Client": "claude-plugin/2.1.0" } } } diff --git a/cpzai/.claude-plugin/plugin.json b/cpzai/.claude-plugin/plugin.json index 8288e86..5075b48 100644 --- a/cpzai/.claude-plugin/plugin.json +++ b/cpzai/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json", "name": "cpzai", - "version": "2.0.0", + "version": "2.1.0", "description": "AI-native systematic trading — build strategies, backtest, manage risk, and execute trades. Connects to CPZAI for live portfolio, market data, and order management.", "author": { "name": "CPZ Lab", diff --git a/cpzai/.mcp.json b/cpzai/.mcp.json index 5733c72..9cbddbf 100644 --- a/cpzai/.mcp.json +++ b/cpzai/.mcp.json @@ -6,7 +6,7 @@ "headers": { "X-CPZ-Key": "${user_config.cpz_api_key}", "X-CPZ-Secret": "${user_config.cpz_api_secret}", - "X-CPZ-Client": "claude-plugin/2.0.0" + "X-CPZ-Client": "claude-plugin/2.1.0" } } } diff --git a/cpzai/CONNECTORS.md b/cpzai/CONNECTORS.md index 7e55cd0..94539c6 100644 --- a/cpzai/CONNECTORS.md +++ b/cpzai/CONNECTORS.md @@ -2,7 +2,7 @@ ## Overview -Plugin files reference the CPZAI MCP server (key `cpzai` in `.mcp.json`). Tools surface to Claude as `mcp__cpzai__`. The placeholder `~~cpzai` is used in skill and command prose as a reminder that the tools require the CPZAI MCP server to be connected — without valid credentials, every call returns `401 Unauthorized`. +Plugin files reference the CPZAI MCP server (key `cpzai` in `.mcp.json`). Claude Code names a plugin's bundled MCP tools `mcp__plugin____`, so the CPZAI tools surface as `mcp__plugin_cpzai_cpzai__` (for example `mcp__plugin_cpzai_cpzai__place_order`). A standalone server you add yourself under the name `cpzai` surfaces as `mcp__cpzai__`; the hooks match both. The placeholder `~~cpzai` is used in skill and command prose as a reminder that the tools require the CPZAI MCP server to be connected: without valid credentials, every call returns `401 Unauthorized`. ## Authentication @@ -31,7 +31,7 @@ The plugin's `cpzai/.mcp.json` wires `userConfig` values into HTTP headers autom "headers": { "X-CPZ-Key": "${user_config.cpz_api_key}", "X-CPZ-Secret": "${user_config.cpz_api_secret}", - "X-CPZ-Client": "claude-plugin/2.0.0" + "X-CPZ-Client": "claude-plugin/2.1.0" } } } @@ -48,7 +48,7 @@ The user supplies the key and secret via the `/plugin` configuration UI. Both fi ## Available Tools -The CPZAI MCP server exposes 18 tools across 8 categories. Every tool carries a safety annotation per the [Model Context Protocol specification](https://modelcontextprotocol.io/specification/server/tools). +The CPZAI MCP server's main tools are below; `tools/list` has the full current catalog. Every tool carries a safety annotation per the [Model Context Protocol specification](https://modelcontextprotocol.io/specification/server/tools). | Category | Tool | Annotation | Description | |----------|------|------------|-------------| @@ -56,21 +56,45 @@ The CPZAI MCP server exposes 18 tools across 8 categories. Every tool carries a | Strategies | `get_strategy` | `readOnlyHint` | Fetch one strategy by UUID | | Strategies | `create_strategy` | write | Create a new strategy with optional Python code | | Strategies | `update_strategy` | write | Patch any field on an existing strategy | -| Backtesting | `get_backtest_results` | `readOnlyHint` | List backtest runs, optionally filtered by strategy | +| Backtesting | `get_backtest_results` | `readOnlyHint` | List saved backtest runs, optionally filtered by strategy. Does not start a run | +| Backtesting | `get_backtest_result` | `readOnlyHint` | One saved run: configuration, result, code. Does not start a run | | Trading | `list_orders` | `readOnlyHint` | Filter by status, symbol, side, strategy | | Trading | `list_positions` | `readOnlyHint` | Filter by account or symbol | -| Trading | `list_accounts` | `readOnlyHint` | Connected broker credentials (sensitive fields masked) | +| Trading | `list_accounts` | `readOnlyHint` | Connected accounts: broker, environment (paper/live), tradable. No balances | +| Trading | `cash_summary` | `readOnlyHint` | Cash, buying power and equity per account as last synced, with `as_of` and `stale` | +| Trading | `export_transactions` | `readOnlyHint` | Fills by fill time, for statements | | Trading | `place_order` | **`destructiveHint`** | Place an order through a connected broker | | Trading | `sync_portfolio` | write | Force-sync positions, balances, and orders across brokers | -| Market Data | `get_market_data` | `readOnlyHint` | Real-time quotes (price, bid/ask, volume) for a list of symbols | +| Market Data | `get_market_data` | `readOnlyHint` | Real-time quotes (price, change, bid/ask, volume) for stocks, ETFs and crypto. Not option contracts | +| Market Data | `get_bars` | `readOnlyHint` | Historical OHLCV bars (intraday, daily, weekly, monthly) over a date range | | Risk | `list_risk_snapshots` | `readOnlyHint` | Historical risk snapshots for trend analysis | | Risk | `compute_risk` | write | Compute a fresh portfolio risk snapshot (VaR/Sharpe/drawdown/exposures) | -| Execution | `execute_strategy` | **`destructiveHint`** | Run strategy code on the compute backend | +| Execution | `execute_strategy` | **`destructiveHint`** | Run a strategy's code. It can submit orders. It is not a backtest | | Webhooks | `list_webhooks` | `readOnlyHint` | View configured webhook subscriptions | | Webhooks | `create_webhook` | write | Subscribe to platform events; signing secret returned once | | Webhooks | `delete_webhook` | **`destructiveHint`** | Remove a webhook subscription | | User | `get_profile` | `readOnlyHint` | Authenticated user profile and subscription tier | +## What the Tools Return (and What They Do Not) + +Commands, skills and agents use only figures a tool returns. Where a template asks for something no tool provides, write **not available from CPZAI** in its place. Never fill it from memory or general knowledge; if the user supplies a figure, label it as user-supplied. + +| Figure | Where it comes from | +|--------|--------------------| +| Holdings: quantity, average cost, market value, unrealized P&L | `list_positions` (page until a short page; read `account_errors`) | +| Sector of a holding | `list_positions` `sector`, when recorded. Often null: then "sector not recorded", never a guess | +| Equity, cash, buying power per account | `cash_summary` (last sync; say when `stale` is true) | +| Which accounts exist, paper or live, tradable | `list_accounts` (it holds no balances) | +| Current price, day change, bid/ask, today's volume | `get_market_data` | +| 52-week range, moving averages, RSI, relative volume, average daily volume, realized volatility, per-holding beta, correlations, covariance | Computed from `get_bars` daily bars (a year for 52-week figures, SPY bars for beta) | +| Portfolio VaR, Sharpe, Sortino, max drawdown, beta, alpha, concentration, holdings correlation | `compute_risk`. These are today's holdings at today's weights replayed over `return_window`; quote its `method_note`, never call them the account's track record | +| Saved backtest metrics | `get_backtest_results`, `get_backtest_result` | +| Fills for statements | `export_transactions` | + +**Not available from any CPZAI tool:** option chains, implied volatility, IV rank or percentile, Greeks, put/call ratio, skew and term structure; company fundamentals (P/E, ROE, margins, revenue, EPS, estimates, market cap, dividends, earnings dates); factor exposures or tilts; margin used; week or month account P&L; per-position contribution to VaR (compute it from `get_bars` covariance if needed and say so); starting a backtest. + +**Backtests:** no CPZAI tool starts one. Run it in CPZAI Strategy Lab (ai.cpz-lab.com), then read it with `get_backtest_results`. Never call `execute_strategy` to backtest: it runs the strategy's code and can submit orders. + ## Plugin-Side Safety Layers Three safety layers wrap destructive tools — they apply automatically when the plugin is enabled. @@ -81,30 +105,33 @@ Every command in `cpzai/commands/` declares `allowed-tools` listing only the MCP ```yaml allowed-tools: - - mcp__cpzai__list_accounts - - mcp__cpzai__list_positions - - mcp__cpzai__get_market_data - - mcp__cpzai__place_order - - mcp__cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__place_order + - mcp__plugin_cpzai_cpzai__list_orders ``` ### 2. PreToolUse safety hook -`cpzai/hooks/hooks.json` registers a `PreToolUse` hook that matches `mcp__cpzai__place_order|mcp__cpzai__execute_strategy|mcp__cpzai__delete_webhook`. The hook script (`cpzai/scripts/pre-trade-guard.sh`) blocks the call with a structured `{"decision":"block","reason":"..."}` response, instructing the calling agent to summarize the action and obtain explicit user confirmation via `AskUserQuestion` before re-issuing the tool call. +`cpzai/hooks/hooks.json` registers a `PreToolUse` hook for every state-changing CPZAI tool (`place_order`, `execute_strategy`, `create_strategy`, `update_strategy`, `configure_overlay`, `create_webhook`, `delete_webhook`, `sync_portfolio`, `create_connection`), under both tool spellings. The hook script (`cpzai/scripts/pre_trade_guard.py`) answers `permissionDecision: "ask"`: Claude Code shows you the call with a summary (for an order: side, quantity, symbol, type, price, account, and your default environment) and runs it once you approve. You are asked once per call, and an approved call goes through; there is no block-and-retry loop. The guard fails closed: an event it cannot read, a tool name it does not recognise, or an error inside it is asked about, never let through. It needs a working `python3`; the session banner runs it and shows `guard=OFF` when it does not answer (for example the `/usr/bin/python3` stub on a Mac without the developer tools). The hook entry has `"onFailure": "block"` (Claude Code 2.1.295 and later): a guard that cannot start, exits with an error or times out blocks the call instead of letting it through. + +`add_to_watchlist` and `remove_from_watchlist` are not guarded: they change a list of at most 10 symbols to watch, move no money, place nothing and are undone by the opposite call, and asking on each would train you to approve without reading. -`delete_webhook` is default-deny — the hook always blocks first time. +The default environment is a reminder, not an account check: the order input carries the account id, not its environment, so the hook cannot see whether the account is paper or live. `/cpzai:trade` and the execution-reviewer agent check the account's `environment` with `list_accounts` before an order. To opt out (not recommended): set `userConfig.require_trade_confirmation = false` via the `/plugin` UI. -### 3. PostToolUse audit log +### 3. Audit log -`cpzai/scripts/audit-log.sh` runs after every state-mutating CPZAI tool call and appends a single-line JSON record to `${CLAUDE_PLUGIN_DATA}/audit.log` (typically `~/.claude/plugins/data/cpzai-cpzai-plugin/audit.log`). Record shape: +`cpzai/scripts/audit_log.py` runs after every state-changing CPZAI tool call, on `PostToolUse` and on `PostToolUseFailure` (a call that failed outright), and appends one JSON line to `${CLAUDE_PLUGIN_DATA}/audit.log` (typically `~/.claude/plugins/data/cpzai-cpzai-plugin/audit.log`). Record shape: ```json -{"ts":"2026-04-30T13:00:13Z","tool":"mcp__cpzai__place_order","ok":true,"input_preview":"{\"symbol\":\"AAPL\",\"quantity\":10,\"side\":\"buy\",\"order_type\":\"market\"}"} +{"ts":"2026-11-25T13:00:13Z","event":"PostToolUse","tool":"mcp__plugin_cpzai_cpzai__place_order","ok":true,"input":{"account_id":"PA3...","broker_credential_id":"...","symbol":"AAPL","side":"buy","order_type":"limit","quantity":10,"price":200.5},"order_id":"alp-123","status":"accepted"} ``` -The log persists across plugin updates. Input previews are truncated to 240 characters and never include credentials. +`ok` is false when the call failed or the tool answered an error or a refusal (with `error` holding the reason), true when it answered without one, and null when the answer says neither; it is never assumed true. `order_id` and `status` come from the tool's answer. The input is recorded whole, with any field named like a key, secret, token or password replaced by `[redacted]`. The log persists across plugin updates. ## Privacy Policy diff --git a/cpzai/agents/execution-reviewer.md b/cpzai/agents/execution-reviewer.md index 50f97d6..05a7196 100644 --- a/cpzai/agents/execution-reviewer.md +++ b/cpzai/agents/execution-reviewer.md @@ -6,23 +6,25 @@ effort: medium maxTurns: 8 tools: - Read - - mcp__cpzai__list_accounts - - mcp__cpzai__list_positions - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk - - mcp__cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_orders - AskUserQuestion skills: - order-execution - risk-management disallowedTools: - - mcp__cpzai__place_order - - mcp__cpzai__execute_strategy - - mcp__cpzai__create_strategy - - mcp__cpzai__update_strategy - - mcp__cpzai__sync_portfolio - - mcp__cpzai__create_webhook - - mcp__cpzai__delete_webhook + - mcp__plugin_cpzai_cpzai__place_order + - mcp__plugin_cpzai_cpzai__execute_strategy + - mcp__plugin_cpzai_cpzai__create_strategy + - mcp__plugin_cpzai_cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__sync_portfolio + - mcp__plugin_cpzai_cpzai__create_webhook + - mcp__plugin_cpzai_cpzai__delete_webhook --- # Execution Reviewer @@ -36,18 +38,19 @@ You never place trades yourself. You produce a structured review and either appr For every proposed order, walk through all seven steps and document each. ### 1. Account verification -- Which broker account will receive this order? (`list_accounts`) -- Is it the intended environment (paper vs live)? +- Which broker account will receive this order? (`list_accounts`: it must be `tradable`) +- Is it the intended environment? Read the account's `environment` from `list_accounts`. If it is live and the plugin's default environment is paper, the user must say explicitly that this trade is live - Is the account active and connected? **Reject if:** account_id is missing, account is paper but trade is intended for live (or vice versa), or no broker is connected. ### 2. Buying power & margin -- Does the account have sufficient buying power for this order size? -- Will this order push the account into margin call territory? +- Does the account have sufficient buying power for this order size? (`cash_summary`; `list_accounts` holds no balances) +- If `cash_summary` marks the balance `stale` or the account has no balance source, buying power is not known: say so and ask, never assume it suffices +- Margin requirements are not available from CPZAI; flag a leveraged or short order for the user to check at the broker - For shorts: is the security shortable in this account? -**Reject if:** insufficient buying power, or order would breach a margin maintenance requirement. +**Reject if:** buying power is insufficient, or it is not known and the user has not confirmed it. ### 3. Existing exposure - Does the user already hold this symbol? (`list_positions`) @@ -58,13 +61,13 @@ For every proposed order, walk through all seven steps and document each. ### 4. Market quality - What's the current bid/ask spread? (`get_market_data`) -- Is volume reasonable today vs typical? +- Is volume reasonable today vs typical? (today's volume from `get_market_data` against the 20-day average from `get_bars` daily bars) - Is the symbol currently halted, in auction, or in late session? **Reject if:** the spread is more than 50 bps for a security where it's typically tight (suggests halt, news, or low liquidity moment), or volume is < 10% of typical (indicates illiquid window). ### 5. Sizing sanity -- Is the order size > 1% of the symbol's average daily volume? (market impact concern) +- Is the order size > 1% of the symbol's average daily volume? (ADV from 20 sessions of `get_bars`; market impact concern) - For market orders > $50k: warn about implementation shortfall. - Is the requested quantity an integer (or fractional shares supported by the broker)? diff --git a/cpzai/agents/quant-researcher.md b/cpzai/agents/quant-researcher.md index 76a7ada..2905b09 100644 --- a/cpzai/agents/quant-researcher.md +++ b/cpzai/agents/quant-researcher.md @@ -14,24 +14,26 @@ tools: - WebFetch - WebSearch - TodoWrite - - mcp__cpzai__list_strategies - - mcp__cpzai__get_strategy - - mcp__cpzai__create_strategy - - mcp__cpzai__update_strategy - - mcp__cpzai__execute_strategy - - mcp__cpzai__get_backtest_results - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_strategies + - mcp__plugin_cpzai_cpzai__get_strategy + - mcp__plugin_cpzai_cpzai__create_strategy + - mcp__plugin_cpzai_cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__get_backtest_results + - mcp__plugin_cpzai_cpzai__get_backtest_result + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__compute_risk skills: - alpha-research - backtesting - strategy-development - portfolio-optimization disallowedTools: - - mcp__cpzai__place_order - - mcp__cpzai__sync_portfolio - - mcp__cpzai__create_webhook - - mcp__cpzai__delete_webhook + - mcp__plugin_cpzai_cpzai__place_order + - mcp__plugin_cpzai_cpzai__execute_strategy + - mcp__plugin_cpzai_cpzai__sync_portfolio + - mcp__plugin_cpzai_cpzai__create_webhook + - mcp__plugin_cpzai_cpzai__delete_webhook --- # Quant Researcher diff --git a/cpzai/agents/risk-auditor.md b/cpzai/agents/risk-auditor.md index a5b68bb..b6813ac 100644 --- a/cpzai/agents/risk-auditor.md +++ b/cpzai/agents/risk-auditor.md @@ -8,21 +8,23 @@ tools: - Read - Bash - TodoWrite - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk - - mcp__cpzai__list_risk_snapshots - - mcp__cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_risk_snapshots + - mcp__plugin_cpzai_cpzai__list_orders skills: - risk-management - portfolio-analytics disallowedTools: - - mcp__cpzai__place_order - - mcp__cpzai__execute_strategy - - mcp__cpzai__create_strategy - - mcp__cpzai__update_strategy - - mcp__cpzai__delete_webhook + - mcp__plugin_cpzai_cpzai__place_order + - mcp__plugin_cpzai_cpzai__execute_strategy + - mcp__plugin_cpzai_cpzai__create_strategy + - mcp__plugin_cpzai_cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__delete_webhook --- # Risk Auditor @@ -37,12 +39,12 @@ For every audit, complete the following dimensions: - Gross exposure (sum of |position values| / equity) - Net exposure (sum of position values / equity) - Cash buffer (% of portfolio) -- Margin used and headroom +- Equity and buying power from `cash_summary` (margin used is not available from CPZAI) ### 2. Concentration - Largest single position (flag if > 15%) - Top-3 weight (flag if > 35%) -- Sector concentration (flag any sector > 30%) +- Sector concentration from each position's `sector` in `list_positions` (flag any sector > 30%; "sector not recorded" where null, never guessed) - Factor exposure (beta, momentum tilt, value tilt, size tilt) ### 3. Correlation diff --git a/cpzai/commands/backtest.md b/cpzai/commands/backtest.md index 4f408ab..43dd40d 100644 --- a/cpzai/commands/backtest.md +++ b/cpzai/commands/backtest.md @@ -1,21 +1,25 @@ --- -description: Run a strategy backtest, analyze performance metrics, and suggest improvements +description: Analyze a strategy's saved backtest runs and suggest improvements (runs start in CPZAI Strategy Lab) argument-hint: " [date range] [parameters]" allowed-tools: - - mcp__cpzai__list_strategies - - mcp__cpzai__get_strategy - - mcp__cpzai__update_strategy - - mcp__cpzai__execute_strategy - - mcp__cpzai__get_backtest_results + - mcp__plugin_cpzai_cpzai__list_strategies + - mcp__plugin_cpzai_cpzai__get_strategy + - mcp__plugin_cpzai_cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__get_backtest_results + - mcp__plugin_cpzai_cpzai__get_backtest_result --- # Backtest > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Backtest results reflect historical performance and do not guarantee future returns. Be aware of common pitfalls like overfitting, survivorship bias, and look-ahead bias. -Run a strategy backtest, pull results, and provide a thorough analysis with improvement suggestions. +Read a strategy's saved backtest runs and provide a thorough analysis with improvement suggestions. + +**No CPZAI tool starts a backtest.** Runs are started in CPZAI Strategy Lab. Never call `execute_strategy` for a backtest: it runs the strategy's code and can submit orders, and it takes no date range or backtest settings. ## Usage @@ -25,9 +29,9 @@ Run a strategy backtest, pull results, and provide a thorough analysis with impr ### Arguments -- `strategy` — Strategy name or ID to backtest -- `date range` (optional) — Start and end dates, e.g. `2020-01 to 2024-12` -- `parameters` (optional) — Override default parameters, e.g. `lookback=20 threshold=2.0` +- `strategy`: Strategy name or ID whose runs to analyze +- `date range` (optional): The run to pick, by its backtest period, e.g. `2020-01 to 2024-12` +- `parameters` (optional): The run to pick, by its parameters, e.g. `lookback=20 threshold=2.0` ## Workflow @@ -36,16 +40,18 @@ Run a strategy backtest, pull results, and provide a thorough analysis with impr If ~~cpzai is connected: - Call `list_strategies` to find the strategy by name or ID - Call `get_strategy` to retrieve its code and current parameters -- Confirm with the user which strategy and parameters to test +- Confirm with the user which strategy and which saved run to analyze If no connection: -> Connect your CPZAI account to run backtests directly. To analyze existing results, provide the performance metrics. +> Connect your CPZAI account to read your saved backtest runs. To analyze results from elsewhere, provide the performance metrics. + +### 2. Find the Saved Run -### 2. Execute the Backtest +- Call `get_backtest_results` with the strategy ID to list its saved runs (newest first) +- Pick the run matching the requested period and parameters, and call `get_backtest_result` for its configuration and result +- If no saved run matches, say so and stop: ask the user to run it in CPZAI Strategy Lab, then run this command again. Do not start a run any other way -- Call `execute_strategy` with the strategy ID and backtest parameters -- Wait for completion (poll if needed) -- Call `get_backtest_results` to retrieve the output +Report only metrics the saved run contains; any line of the templates below that the run does not hold is "not available from CPZAI". ### 3. Performance Summary @@ -99,7 +105,7 @@ Assess whether results are likely to hold out-of-sample: - **Parameter sensitivity** — How much do results change with ±20% parameter shifts? - **Time stability** — Is performance consistent across sub-periods (halves, thirds)? -- **Trade count** — Are there enough trades for statistical significance (>30)? +- **Trade count**: 30+ trades is directional only; a meaningful Sharpe needs 100+, robust inference 250+ (backtesting skill) - **Overfitting indicators** — Sharpe > 3.0 in backtest is suspicious; very high win rates with few trades; performance only in one regime ### 6. Improvement Suggestions @@ -116,5 +122,5 @@ Based on the results, suggest 2-3 specific improvements: Recommend the logical next action: - If results are strong: "Consider paper trading — use `/cpzai:risk-report` after a few days to monitor" -- If results need work: "Try adjusting [parameter] — I can update the strategy code for you" +- If results need work: "Try adjusting [parameter]. I can update the strategy code; run the new version in Strategy Lab and I will analyze it" - If results are poor: "This signal may not have edge. Consider a fundamentally different approach like [suggestion]" diff --git a/cpzai/commands/earnings-preview.md b/cpzai/commands/earnings-preview.md index d6c35d7..1ec68e8 100644 --- a/cpzai/commands/earnings-preview.md +++ b/cpzai/commands/earnings-preview.md @@ -2,8 +2,8 @@ description: Preview upcoming earnings — expectations, key metrics to watch, historical patterns, and positioning ideas argument-hint: "" allowed-tools: - - mcp__cpzai__get_market_data - - mcp__cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__list_positions - WebSearch - WebFetch --- @@ -11,6 +11,8 @@ allowed-tools: # Earnings Preview > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Earnings previews are based on consensus estimates and historical patterns. Actual results may differ materially. This is not investment advice. diff --git a/cpzai/commands/equity-research.md b/cpzai/commands/equity-research.md index 606b7ec..9b21222 100644 --- a/cpzai/commands/equity-research.md +++ b/cpzai/commands/equity-research.md @@ -2,7 +2,7 @@ description: Generate a comprehensive equity research report on any publicly traded company argument-hint: "" allowed-tools: - - mcp__cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_market_data - WebSearch - WebFetch --- @@ -10,6 +10,8 @@ allowed-tools: # Equity Research > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Equity research reports are for informational purposes only. They do not constitute investment advice or buy/sell recommendations. All investment decisions should be made independently. diff --git a/cpzai/commands/factor-screen.md b/cpzai/commands/factor-screen.md index 5233b2a..2f92375 100644 --- a/cpzai/commands/factor-screen.md +++ b/cpzai/commands/factor-screen.md @@ -2,13 +2,16 @@ description: Screen stocks by quantitative factors — value, momentum, quality, volatility, size, and custom signals argument-hint: " [universe]" allowed-tools: - - mcp__cpzai__get_market_data - - mcp__cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__list_positions --- # Factor Screen > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Factor screens are quantitative filters for research purposes only. They do not constitute buy/sell recommendations. Factor performance is cyclical and past factor returns do not predict future results. @@ -52,8 +55,11 @@ Map the user's request to specific quantitative metrics: If ~~cpzai is connected: - Call `get_market_data` for the universe to get current prices and volume +- Call `get_bars` (daily, about 13 months) for the price-based factors: momentum, reversal, low volatility and beta, 52-week high proximity - Call `list_positions` to flag which screened stocks the user already owns +**No CPZAI tool returns fundamentals** (P/E, P/B, EV/EBITDA, ROE, margins, growth, estimates, market cap, dividends). Value, quality, size, growth and dividend screens cannot be run from CPZAI data: say so, and mark those columns "not available from CPZAI" rather than filling them from memory. + ### 3. Screen Results Present the top-ranked stocks: diff --git a/cpzai/commands/market-scan.md b/cpzai/commands/market-scan.md index 9b3ea13..a61ed43 100644 --- a/cpzai/commands/market-scan.md +++ b/cpzai/commands/market-scan.md @@ -2,13 +2,16 @@ description: Scan markets by sector, theme, or custom criteria with real-time data argument-hint: "" allowed-tools: - - mcp__cpzai__get_market_data - - mcp__cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__list_positions --- # Market Scan > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Market scans provide information for research purposes only. They do not constitute buy/sell recommendations. All investment decisions should be made independently. @@ -42,6 +45,7 @@ Map the user's input to a concrete list of symbols: If ~~cpzai is connected: - Call `get_market_data` for all symbols in the universe - Collect: price, change, volume, bid/ask spread +- Call `get_bars` (daily, at least 200 sessions) for relative volume, the 50 and 200-day averages, RSI and realized volatility If no connection: > Connect your CPZAI account to pull real-time quotes. I can still provide analysis frameworks and discuss the sector/theme qualitatively. diff --git a/cpzai/commands/optimize.md b/cpzai/commands/optimize.md index beaef48..8be7890 100644 --- a/cpzai/commands/optimize.md +++ b/cpzai/commands/optimize.md @@ -2,16 +2,19 @@ description: Optimize portfolio allocation using quantitative methods — mean-variance, Black-Litterman, risk parity, or HRP argument-hint: "[method] [constraints]" allowed-tools: - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk - - mcp__cpzai__list_risk_snapshots + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_risk_snapshots --- # Optimize > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Portfolio optimization outputs are model-dependent and sensitive to input assumptions. They should be treated as a starting point for analysis, not as definitive allocations. All portfolio decisions should be reviewed by qualified professionals. @@ -43,8 +46,9 @@ Run portfolio optimization on your current holdings or a proposed portfolio — If ~~cpzai is connected: - Call `list_positions` to get current holdings and weights - Call `get_market_data` for current prices -- Call `compute_risk` for the current risk profile -- Call `list_accounts` for total portfolio value +- Call `get_bars` for daily bars of every holding (and any candidate), one to three years: expected returns and the covariance matrix are estimated from these +- Call `compute_risk` for the current risk profile (it returns summary figures, not covariance inputs) +- Call `cash_summary` for total equity and cash If no connection: > Connect your CPZAI account to optimize your live portfolio. Alternatively, provide a list of holdings (symbol, weight or dollar amount). @@ -61,14 +65,14 @@ Positions: XX Expected Return: XX.X% (annualized) Volatility: XX.X% (annualized) Sharpe Ratio: X.XX -Max Drawdown: XX.X% (historical) +Max Drawdown: XX.X% (current holdings replayed over the bars used) ``` | Symbol | Current Weight | Return Contrib. | Risk Contrib. | |--------|---------------|----------------|---------------| | ... | XX.X% | XX.X% | XX.X% | -Flag imbalances: positions where risk contribution far exceeds weight. +Risk Contrib. is each position's percent contribution `w_i (Σw)_i / (w'Σw)` from the `get_bars` covariance; the column adds up to 100%. Flag imbalances: positions where risk contribution far exceeds weight. ### 3. Run Optimization @@ -85,7 +89,7 @@ Execute the selected optimization method: - Blend views with equilibrium using the BL formula **Risk Parity:** -- Each asset contributes equally to total portfolio risk +- Each asset contributes equally to total portfolio risk: `w_i (Σw)_i / (w'Σw) = 1/N`, solved numerically (inverse volatility is exact only when all correlations are equal) - No return assumptions needed — purely risk-based **HRP (Hierarchical Risk Parity):** diff --git a/cpzai/commands/options-analysis.md b/cpzai/commands/options-analysis.md index 8d3e84f..a155866 100644 --- a/cpzai/commands/options-analysis.md +++ b/cpzai/commands/options-analysis.md @@ -2,14 +2,17 @@ description: Analyze options strategies, Greeks, volatility surface, and derivatives positioning for a ticker argument-hint: " [strategy type]" allowed-tools: - - mcp__cpzai__get_market_data - - mcp__cpzai__list_positions - - mcp__cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__compute_risk --- # Options Analysis > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Options involve significant risk and are not suitable for all investors. This analysis is for educational and research purposes only. All options trading decisions should be made independently with full understanding of the risks. @@ -35,9 +38,12 @@ Analyze the options landscape for a given ticker — implied volatility, Greeks, ### 1. Current Market Context If ~~cpzai is connected: -- Call `get_market_data` for the ticker (price, volume, recent move) +- Call `get_market_data` for the underlying (price, volume, day move). It does not quote option contracts +- Call `get_bars` for a year of the underlying's daily bars: realized volatility (HV) is computed from them - Call `compute_risk` if the user holds the underlying (portfolio context) +**No CPZAI tool returns option chains, option quotes, implied volatility, IV rank, Greeks, put/call ratio, skew or term structure.** Mark each of those "not available from CPZAI" in the templates below. If the user pastes option quotes or IVs, use them and label them as user-supplied; Greeks may then be computed from them with a stated model (e.g. Black-Scholes), labeled as computed here. + Establish the setup: ``` diff --git a/cpzai/commands/orders.md b/cpzai/commands/orders.md index eb2fff5..619d1d9 100644 --- a/cpzai/commands/orders.md +++ b/cpzai/commands/orders.md @@ -2,13 +2,15 @@ description: View recent orders — open, filled, cancelled — with status and fill details argument-hint: "[status] [symbol]" allowed-tools: - - mcp__cpzai__list_orders - - mcp__cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_accounts --- # Orders > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. Pull your recent order history and present status, fills, and execution details. @@ -32,7 +34,7 @@ Pull your recent order history and present status, fills, and execution details. ### 1. Fetch Orders If ~~cpzai is connected: -- Call `list_orders` with any status/symbol filters +- Call `list_orders` with any status/symbol filters, and keep paging (`offset` += rows returned) until a page comes back shorter than the limit or the orders are older than the period shown; the Last 7 Days counts need every order of the 7 days. Read `account_errors`: orders listed for an account named there are incomplete - Call `list_accounts` to identify which broker account(s) are active If no connection: diff --git a/cpzai/commands/portfolio-review.md b/cpzai/commands/portfolio-review.md index d0d591b..84d72bc 100644 --- a/cpzai/commands/portfolio-review.md +++ b/cpzai/commands/portfolio-review.md @@ -1,17 +1,21 @@ --- description: Full portfolio health check — positions, performance, diversification, and actionable insights allowed-tools: - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk - - mcp__cpzai__list_orders - - mcp__cpzai__list_risk_snapshots + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_risk_snapshots --- # Portfolio Review > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Portfolio reviews are informational and do not constitute investment advice. Consult a qualified financial advisor before making portfolio changes. @@ -30,8 +34,9 @@ No arguments needed — pulls the full portfolio from connected accounts. ### 1. Gather Portfolio Data If ~~cpzai is connected: -- Call `list_positions` for all open positions -- Call `list_accounts` for account summaries (equity, buying power, margin) +- Call `list_positions` and keep paging (`offset` += rows returned) until a page comes back shorter than the limit; `count` is the page size, not the total. Read `account_errors`: an account named there was not read, so totals leave it out and say so +- Call `cash_summary` for equity, cash and buying power per account (last sync; note `stale`) +- Call `list_accounts` for each account's broker and environment; it holds no balances - Call `get_market_data` for current prices on all holdings - Call `compute_risk` for the latest risk snapshot - Call `list_orders` with status `filled` for recent trade history @@ -45,16 +50,15 @@ If no connection: PORTFOLIO REVIEW — [Date] ═════════════════════════ -Total Equity: $XX,XXX -Cash / Buying Power: $XX,XXX (XX% of portfolio) +Equity (paper): $XX,XXX Equity (live): $XX,XXX +Cash / Buying Power: paper $XX,XXX / $XX,XXX, live $XX,XXX / $XX,XXX Positions: XX open positions -Margin Used: $XX,XXX -Today's P&L: $X,XXX (X.X%) -Week P&L: $X,XXX (X.X%) -Month P&L: $X,XXX (X.X%) +Today's P&L: $X,XXX (X.X%) (from `get_market_data` day change x quantity) ``` +Paper and live money are never added together: `cash_summary` leaves its headline total empty when both are present, and `totals.by_environment` has each. + ### 3. Holdings Breakdown | Symbol | Shares | Avg Cost | Current | P&L ($) | P&L (%) | Weight | @@ -78,20 +82,19 @@ Sort by weight (largest first). ### 5. Diversification Assessment -**Sector Exposure:** +**Sector Exposure** (from each position's `sector` in `list_positions`; a position with no sector recorded is listed as "sector not recorded", never assigned one from memory): | Sector | Weight | # Positions | |--------|--------|-------------| | ... | ... | ... | **Key Observations:** -- Sector over/under-weights vs a benchmark (e.g. S&P 500) - Single-stock concentration risk (any position > 15%) - Cash level relative to market conditions - Long/short balance (if applicable) ### 6. Risk Summary -Pull from the `compute_risk` results: +Pull from the `compute_risk` results. They are today's holdings replayed over `return_window`; quote its `method_note` and never present them as the account's own track record: - VaR (95%, 1-day) - Max drawdown (current and from peak) - Sharpe and Sortino diff --git a/cpzai/commands/positions.md b/cpzai/commands/positions.md index 0b96ddd..33d9bde 100644 --- a/cpzai/commands/positions.md +++ b/cpzai/commands/positions.md @@ -1,14 +1,17 @@ --- description: View your current portfolio positions — holdings, P&L, weights, and today's movers allowed-tools: - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data --- # Positions > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. Pull your live portfolio positions and present a clean summary with P&L, weights, and today's activity. @@ -25,8 +28,9 @@ No arguments needed — pulls all open positions from connected accounts. ### 1. Fetch Positions If ~~cpzai is connected: -- Call `list_positions` to get all open positions -- Call `list_accounts` for account-level info (equity, buying power) +- Call `list_positions` and keep paging (`offset` += rows returned) until a page comes back shorter than the limit; `count` is the page size, not the total. Read `account_errors`: an account named there was not read, so totals leave it out and say so +- Call `cash_summary` for equity and buying power per account (last sync: show `as_of`, and say so when `stale` is true) +- Call `list_accounts` for each account's broker and environment (paper or live); it holds no balances - Call `get_market_data` for current prices on all held symbols If no connection: @@ -37,12 +41,14 @@ If no connection: ``` PORTFOLIO — [Date] ══════════════════ -Total Equity: $XX,XXX.XX -Buying Power: $XX,XXX.XX +Paper: Equity $XX,XXX.XX Buying Power $XX,XXX.XX +Live: Equity $XX,XXX.XX Buying Power $XX,XXX.XX Positions: XX open Today's P&L: +$XXX.XX (+X.XX%) ``` +Paper and live money are never added together: `cash_summary` leaves its headline total empty when both are present, and `totals.by_environment` has each. + ### 3. Holdings Table | Symbol | Shares | Avg Cost | Current | P&L ($) | P&L (%) | Weight | diff --git a/cpzai/commands/price.md b/cpzai/commands/price.md index c33cf20..6ae6f26 100644 --- a/cpzai/commands/price.md +++ b/cpzai/commands/price.md @@ -2,12 +2,15 @@ description: Get real-time quotes — price, change, volume, bid/ask — for one or more symbols argument-hint: "" allowed-tools: - - mcp__cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars --- # Price > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. Fetch real-time market data for one or more symbols and present a clean quote summary. @@ -56,6 +59,6 @@ For multiple symbols: ### 3. Quick Context (if single symbol) For a single ticker, add a one-line note on: -- Where price sits relative to 52-week range -- Unusual volume (if >1.5x average) +- Where price sits relative to its 52-week range (from one year of `get_bars` daily bars; the quote carries no range) +- Unusual volume (today's volume over the 20-day average from `get_bars`, if >1.5x) - Proximity to round numbers or key levels diff --git a/cpzai/commands/risk-report.md b/cpzai/commands/risk-report.md index 21ec025..3516f06 100644 --- a/cpzai/commands/risk-report.md +++ b/cpzai/commands/risk-report.md @@ -2,16 +2,20 @@ description: Generate a comprehensive risk report for your portfolio or a specific strategy argument-hint: "[portfolio | strategy ]" allowed-tools: - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk - - mcp__cpzai__list_risk_snapshots + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_risk_snapshots --- # Risk Report > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Risk metrics are estimates based on historical data and models. They do not predict future losses. All risk assessments should be reviewed by qualified professionals. @@ -35,10 +39,11 @@ Pull live positions, compute risk metrics, and produce an actionable risk report ### 1. Gather Current State If ~~cpzai is connected: -- Call `list_positions` to get all open positions with market values -- Call `list_accounts` to get account-level info (buying power, equity) +- Call `list_positions` and keep paging (`offset` += rows returned) until a page comes back shorter than the limit; `count` is the page size, not the total. Read `account_errors`: an account named there was not read, so totals leave it out and say so +- Call `cash_summary` for equity and buying power per account (last sync; note `stale`) - Call `get_market_data` for current prices on all held symbols -- Call `compute_risk` to get a fresh risk snapshot +- Call `compute_risk` to get a fresh risk snapshot. Its figures are today's holdings replayed over `return_window`: quote `method_note` with them +- Call `get_bars` for a year of daily bars of each holding and SPY, for the position-level figures below If no connection: > Connect your CPZAI account to pull live portfolio data. To analyze manually, provide your current positions (symbol, quantity, entry price). @@ -73,6 +78,8 @@ Break down risk by position: |--------|--------|-----|------|------------|---------------------| | ... | ... | ... | ... | ... | ... | +Weight and P&L come from `list_positions`. Beta (against SPY), annualized volatility and contribution to VaR are computed from the `get_bars` daily returns and the weights; say they were computed here. `compute_risk` returns no per-holding beta or volatility. + Flag positions that: - Exceed 20% portfolio weight (concentration risk) - Have annualized volatility > 50% @@ -83,8 +90,8 @@ Flag positions that: Assess diversification across: - **Single-name concentration** — largest position as % of portfolio -- **Sector concentration** — exposure by GICS sector -- **Factor concentration** — beta, momentum, value tilts +- **Sector concentration**: from each position's `sector` in `list_positions`; "sector not recorded" where it is null +- **Factor concentration**: not available from CPZAI (no tool returns factor exposures); beta from `get_bars` only - **Correlation** — average pairwise correlation of positions ### 5. Risk Flags diff --git a/cpzai/commands/strategies.md b/cpzai/commands/strategies.md index 77f9830..5838683 100644 --- a/cpzai/commands/strategies.md +++ b/cpzai/commands/strategies.md @@ -2,15 +2,17 @@ description: List, view, and manage your trading strategies — status, last backtest, and quick actions argument-hint: "[strategy name | list | status]" allowed-tools: - - mcp__cpzai__list_strategies - - mcp__cpzai__get_strategy - - mcp__cpzai__get_backtest_results - - mcp__cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__list_strategies + - mcp__plugin_cpzai_cpzai__get_strategy + - mcp__plugin_cpzai_cpzai__get_backtest_results + - mcp__plugin_cpzai_cpzai__update_strategy --- # Strategies > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. View and manage your strategy library — list all strategies, check status, view code, or take quick actions. diff --git a/cpzai/commands/strategy-builder.md b/cpzai/commands/strategy-builder.md index 819a580..9f8eef9 100644 --- a/cpzai/commands/strategy-builder.md +++ b/cpzai/commands/strategy-builder.md @@ -2,16 +2,18 @@ description: Build a trading strategy from a natural language idea — generates Python code and creates it on the platform argument-hint: "" allowed-tools: - - mcp__cpzai__list_strategies - - mcp__cpzai__get_strategy - - mcp__cpzai__create_strategy - - mcp__cpzai__update_strategy - - mcp__cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__list_strategies + - mcp__plugin_cpzai_cpzai__get_strategy + - mcp__plugin_cpzai_cpzai__create_strategy + - mcp__plugin_cpzai_cpzai__update_strategy + - mcp__plugin_cpzai_cpzai__get_market_data --- # Strategy Builder > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: This command generates strategy code to assist development. All strategies should be thoroughly backtested and reviewed before live deployment. Trading carries risk of loss. @@ -48,15 +50,22 @@ If any critical element is missing, ask one focused follow-up question. Don't as ### 2. Generate the Strategy Code -Write a complete Python strategy following standard systematic trading conventions: +Write `strategy.py` in the format CPZAI's Strategy Lab backtests. Code in any other shape (a class, a script, a function under another name) fails before its first bar with "No strategy interface function is available". -Requirements: -- Clean, readable Python with clear parameter definitions and defaults -- Signal logic separated from execution logic -- Position sizing with configurable method (equal-weight, vol-scaled, or signal-weighted) -- Risk checks built in (max position size, exposure limits, stop-loss levels) -- Use standard libraries (numpy, pandas) for calculations -- Keep it simple — no over-engineering for a first version; fewer parameters = less overfitting +The format: +- A flat module of imports, constants and functions. No class wrapping the signal, no code that runs at import time beyond definitions +- `SYMBOLS = ["AAPL", "MSFT", ...]`: a literal list of every ticker the code reads, including a benchmark or filter symbol such as SPY. Never a function call, comprehension or screener result +- Exactly one module-level signal function: + - `def generate_signals(data, state, **kwargs)` (preferred) or `def generate_signal(data, state)`: `data` holds point-in-time history per symbol (polars DataFrames with `timestamp, open, high, low, close, volume`); return a dict of symbol to target weight + - or `def on_bar(context, data)`, which calls `context.target_weights(weights)` +- Weights, not share quantities or orders: an empty dict means no rebalance, an explicit 0 closes a position. The backtest fills at the next bar's open +- Use only the supplied history: no broker orders, live data, API clients or screeners inside the signal or at import +- numpy and polars are available; for pandas, build the frame with `pd.DataFrame(df.to_dict(as_series=False))` (`to_pandas()` needs pyarrow, which the runner does not have) + +Within that format: +- Clear parameters with defaults as module constants +- Position sizing in the returned weights (equal-weight, vol-scaled, or signal-weighted), with caps on single-name weight and gross exposure +- Keep it simple: fewer parameters means less overfitting ### 3. Explain the Logic @@ -69,10 +78,10 @@ Provide a brief summary covering: ### 4. Create on the Platform If ~~cpzai is connected: -- Call `create_strategy` with the generated code +- Call `create_strategy` with the generated code as `python_code` - Set strategy type, title, and description - Report the created strategy ID back to the user -- Suggest next step: "Run `/cpzai:backtest` to test this strategy" +- Suggest next step: "Backtest it in CPZAI Strategy Lab, then run `/cpzai:backtest` to analyze the run" If no connection: > Connect your CPZAI account to create the strategy automatically. For now, here's the code — you can paste it into the Strategy Lab at [ai.cpz-lab.com](https://ai.cpz-lab.com). diff --git a/cpzai/commands/sync.md b/cpzai/commands/sync.md index 1ad88f8..7f22db4 100644 --- a/cpzai/commands/sync.md +++ b/cpzai/commands/sync.md @@ -1,14 +1,17 @@ --- description: Sync your portfolio — pull latest positions, balances, and orders from all connected brokers allowed-tools: - - mcp__cpzai__sync_portfolio - - mcp__cpzai__list_accounts - - mcp__cpzai__list_positions + - mcp__plugin_cpzai_cpzai__sync_portfolio + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__list_positions --- # Sync > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. Trigger a portfolio sync across all connected broker accounts to pull the latest positions, balances, and order status. @@ -45,7 +48,7 @@ Last sync: [Timestamp] ### 3. Updated Summary After sync completes, show the refreshed state: -- Total equity across all accounts +- Cash and buying power per environment from `cash_summary` `totals.by_environment` (paper and live on separate lines, never added together), equity per account, and which accounts have no balance - Position count - Any changes since last sync (new fills, position changes) diff --git a/cpzai/commands/trade-idea.md b/cpzai/commands/trade-idea.md index aa2035e..77475f7 100644 --- a/cpzai/commands/trade-idea.md +++ b/cpzai/commands/trade-idea.md @@ -2,15 +2,18 @@ description: Generate a structured trade idea with entry, exit, sizing, and risk management — based on your portfolio context argument-hint: "" allowed-tools: - - mcp__cpzai__list_positions - - mcp__cpzai__list_accounts - - mcp__cpzai__get_market_data - - mcp__cpzai__compute_risk + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__get_bars + - mcp__plugin_cpzai_cpzai__compute_risk --- # Trade Idea > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: Trade ideas are generated for research and educational purposes only. They are not recommendations to buy or sell any security. All trading involves risk of loss. Make decisions independently and consider your own financial situation. @@ -37,8 +40,9 @@ Generate a structured, institutional-quality trade idea with clear thesis, entry If ~~cpzai is connected: - Call `list_positions` to understand current exposure - Call `compute_risk` for portfolio-level risk metrics -- Call `list_accounts` for available capital and buying power +- Call `cash_summary` for available capital and buying power (last sync; note `stale`) - Call `get_market_data` for current prices +- Call `get_bars` for the idea's symbol and the largest holdings (daily, one year) for levels, volatility and correlation Frame the idea relative to the user's existing portfolio — don't suggest buying something they're already overweight. @@ -113,14 +117,14 @@ Sizing methods: | Stop Out | $XX.XX | -$XXX (-X.X%) | ~XX% | | Worst Case | $XX.XX | -$XXX (-XX.X%) | ~X% | -**Expected value:** (P_bull × R_bull) + (P_base × R_base) + (P_stop × R_stop) = +X.X% +**Expected value:** (P_bull × R_bull) + (P_base × R_base) + (P_stop × R_stop) + (P_worst × R_worst) = +X.X%, with the four probabilities adding up to 100% ### 6. Correlation & Portfolio Impact Assess how this trade interacts with existing positions: - Correlation with current holdings -- Factor exposure overlap (are you doubling down on momentum, beta, etc.?) -- Sector concentration after adding this trade +- Correlation with the largest holdings, from `get_bars` daily returns (factor exposures are not available from CPZAI) +- Sector concentration after adding this trade, from `list_positions` `sector` where recorded - Impact on portfolio-level VaR ### 7. Monitoring Plan diff --git a/cpzai/commands/trade.md b/cpzai/commands/trade.md index c7333d8..e3c5af4 100644 --- a/cpzai/commands/trade.md +++ b/cpzai/commands/trade.md @@ -1,18 +1,21 @@ --- description: Place a trade — buy or sell stocks, ETFs, or crypto through your connected broker -argument-hint: " [order type] [limit price]" +argument-hint: " [market|limit|stop|stop-limit] [limit price] [stop price]" allowed-tools: - - mcp__cpzai__list_accounts - - mcp__cpzai__list_positions - - mcp__cpzai__get_market_data - - mcp__cpzai__place_order - - mcp__cpzai__list_orders + - mcp__plugin_cpzai_cpzai__list_accounts + - mcp__plugin_cpzai_cpzai__cash_summary + - mcp__plugin_cpzai_cpzai__list_positions + - mcp__plugin_cpzai_cpzai__get_market_data + - mcp__plugin_cpzai_cpzai__place_order + - mcp__plugin_cpzai_cpzai__list_orders - AskUserQuestion --- # Trade > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../CONNECTORS.md). +> +> Use only figures a CPZAI tool returns. Anything a template below asks for that no tool provides (see [What the Tools Return](../CONNECTORS.md#what-the-tools-return-and-what-they-do-not)) is written "not available from CPZAI", never filled from memory. **Important**: This command places real orders through your connected broker. Orders are irreversible once filled. Double-check all details before confirming. Trading carries risk of loss. @@ -21,24 +24,26 @@ Place a buy or sell order through your connected brokerage account. ## Usage ``` -/cpzai:trade [order type] [limit price] +/cpzai:trade [order type] [limit price] [stop price] ``` ### Arguments - `side` — `buy` or `sell` -- `quantity` — Number of shares (or `$500` for notional amount) +- `shares`: number of shares (fractional where the broker allows). `place_order` takes a quantity, not a dollar amount: for "$500 of SPY", work out the shares from the current price and show the user that quantity - `symbol` — Ticker symbol (e.g. `AAPL`, `SPY`, `BTC/USD`) - `order type` (optional) — `market` (default), `limit`, `stop`, `stop-limit` -- `limit price` (optional) — Required for limit and stop-limit orders +- `limit price`: required for `limit` and `stop-limit` orders +- `stop price`: the trigger, required for `stop` and `stop-limit` orders. For `stop` it is the only price (`stop 850.00`); for `stop-limit` give both, limit then stop (`stop-limit 845.00 850.00`). Never pick a trigger for the user +- Orders are day orders: `place_order` takes `time_in_force: day` only. GTC, IOC, FOK, extended hours, trailing stops and brackets are not available through it ### Examples ``` /cpzai:trade buy 10 AAPL /cpzai:trade sell 50 MSFT limit 420.00 -/cpzai:trade buy $1000 SPY -/cpzai:trade buy 5 NVDA stop-limit 850.00 +/cpzai:trade sell 10 AAPL stop 180.00 +/cpzai:trade buy 5 NVDA stop-limit 855.00 850.00 ``` ## Workflow @@ -54,7 +59,8 @@ Parse the user's input and confirm all required fields: ### 2. Pre-Trade Check If ~~cpzai is connected: -- Call `list_accounts` to verify the user has a connected broker and sufficient buying power +- Call `list_accounts` to pick the account: it must be `tradable`, and its `environment` must be the one intended. If the account is live and the plugin's default environment is paper, stop and ask the user to confirm a live trade explicitly +- Call `cash_summary` for that account's buying power (last sync: if `stale` is true or it has no balance source, say the buying power is not known; never assume it is sufficient) - Call `list_positions` to check existing exposure to this symbol - Call `get_market_data` to get the current price @@ -64,7 +70,9 @@ Present a confirmation: ORDER CONFIRMATION ══════════════════ Action: BUY 10 AAPL -Order Type: Market +Order Type: Market | Limit | Stop | Stop-limit (day) +Limit: $XXX.XX (limit and stop-limit) +Stop: $XXX.XX (stop and stop-limit: the trigger) Est. Price: ~$XXX.XX Est. Total: ~$X,XXX.XX Account: [Broker Name] ([Paper/Live]) @@ -75,11 +83,12 @@ Current Position: [None | XX shares @ $XXX.XX avg] ### 3. Confirm and Execute -Ask for explicit confirmation before placing: +If this session's `[cpzai v...]` banner shows `confirm=true`, the plugin's guard runs: call `place_order` with the validated parameters, and Claude Code shows the user this order and places it only after they approve it there. That approval is the confirmation, so do not ask a second time in chat. + +If there is no banner (the client does not run plugin hooks) or it shows `confirm=false`, nothing else will ask: ask in chat first and call `place_order` only after an explicit yes: > "Ready to place this order. Confirm? (yes/no)" -On confirmation: -- Call `place_order` with the validated parameters +After the call: - Report the order ID and status back to the user ``` @@ -97,7 +106,14 @@ After placing: - Note impact on portfolio concentration - Suggest: "Run `/cpzai:risk-report` to check how this affects your portfolio risk" -### 5. Error Handling +### 5. Timeouts and Retries + +Pass a `client_order_id` you generate for every order and show it to the user. A resend with the same id is **not** guaranteed to be deduplicated (`cpzai://guides/tool-usage`: there is no end-to-end idempotent order retry guarantee). After a timeout or an unclear answer: +- Do not call `place_order` again +- Page through `list_orders` with `status=all` and the symbol, and look for that `client_order_id` and for any order on the account placed since the attempt +- Tell the user what you found; resubmit only if they decide to, knowing the first order may exist + +### 6. Error Handling If the order fails: - Insufficient buying power → show available balance and suggest reducing size diff --git a/cpzai/hooks/hooks.json b/cpzai/hooks/hooks.json index a8c8f34..656edf0 100644 --- a/cpzai/hooks/hooks.json +++ b/cpzai/hooks/hooks.json @@ -12,22 +12,34 @@ ], "PreToolUse": [ { - "matcher": "mcp__cpzai__place_order|mcp__cpzai__execute_strategy|mcp__cpzai__create_strategy|mcp__cpzai__update_strategy|mcp__cpzai__delete_webhook|mcp__cpzai__create_webhook|mcp__cpzai__sync_portfolio|mcp__cpzai__create_connection", + "matcher": "^mcp__(plugin_cpzai_)?cpzai__(place_order|execute_strategy|create_strategy|update_strategy|configure_overlay|create_webhook|delete_webhook|sync_portfolio|create_connection)$", "hooks": [ { "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/pre-trade-guard.sh" + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/pre_trade_guard.py", + "onFailure": "block" } ] } ], "PostToolUse": [ { - "matcher": "mcp__cpzai__place_order|mcp__cpzai__execute_strategy|mcp__cpzai__create_strategy|mcp__cpzai__update_strategy|mcp__cpzai__sync_portfolio|mcp__cpzai__create_webhook|mcp__cpzai__delete_webhook|mcp__cpzai__create_connection", + "matcher": "^mcp__(plugin_cpzai_)?cpzai__(place_order|execute_strategy|create_strategy|update_strategy|configure_overlay|create_webhook|delete_webhook|sync_portfolio|create_connection)$", "hooks": [ { "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/audit-log.sh" + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/audit_log.py" + } + ] + } + ], + "PostToolUseFailure": [ + { + "matcher": "^mcp__(plugin_cpzai_)?cpzai__(place_order|execute_strategy|create_strategy|update_strategy|configure_overlay|create_webhook|delete_webhook|sync_portfolio|create_connection)$", + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/audit_log.py" } ] } diff --git a/cpzai/scripts/audit-log.sh b/cpzai/scripts/audit-log.sh deleted file mode 100755 index f8fe361..0000000 --- a/cpzai/scripts/audit-log.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# CPZAI plugin — PostToolUse hook -# -# Appends a single-line JSON audit record for every state-mutating -# CPZAI MCP tool call. The log lives in the plugin's persistent data -# directory so it survives plugin updates. -set -euo pipefail - -DATA_DIR="${CLAUDE_PLUGIN_DATA:-${HOME}/.claude/plugins/data/cpzai}" -mkdir -p "$DATA_DIR" -LOG_FILE="$DATA_DIR/audit.log" - -# Cache stdin in a temp file so we can hand it to python without conflicting -# with the heredoc. -EVENT_FILE="$(mktemp)" -trap 'rm -f "$EVENT_FILE"' EXIT -cat > "$EVENT_FILE" - -EVENT_FILE="$EVENT_FILE" python3 - >> "$LOG_FILE" <<'PY' -import json, os, datetime -ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -try: - with open(os.environ["EVENT_FILE"]) as f: - raw = f.read() - d = json.loads(raw) if raw.strip() else {} -except Exception: - d = {} -tool = d.get("tool_name") or d.get("toolName") or "" -ok = d.get("success", True) -inp = d.get("tool_input") or d.get("toolInput") or {} -input_preview = json.dumps(inp, separators=(",", ":"))[:240] -record = {"ts": ts, "tool": tool, "ok": ok, "input_preview": input_preview} -print(json.dumps(record, separators=(",", ":"))) -PY diff --git a/cpzai/scripts/audit_log.py b/cpzai/scripts/audit_log.py new file mode 100755 index 0000000..d6e48de --- /dev/null +++ b/cpzai/scripts/audit_log.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""CPZAI plugin: PostToolUse and PostToolUseFailure audit log. + +Appends one JSON line per state-changing CPZAI tool call to +${CLAUDE_PLUGIN_DATA}/audit.log, the file the compliance skill calls the +primary audit source (cpzai#3024). Each record has: + + ts, event, tool when, PostToolUse or PostToolUseFailure, which tool + ok false when the tool answered an error or a refusal, + true when it answered without one, null when the + answer says neither or the call failed without an + answer (a timeout can still have placed the order: + the record says to reconcile) + is_interrupt, duration_ms on a failed call, as Claude Code reports them + input the full tool input, with any credential-like field + replaced by "[redacted]"; create_connection's + configuration is logged as its field names only; + never cut short +The log file is created owner-read/write only (0600). + order_id, status from the tool's answer when it carries them + (place_order: the broker's order id and status) + error the tool's error text, when there is one + +A record that cannot be built is still written, with the reason, so a call is +never silently missing from the log. +""" +from __future__ import annotations + +import datetime +import json +import os +import re +import sys +from pathlib import Path + +SENSITIVE = re.compile(r"(key|secret|token|passw|passphrase|pass|pwd|pin|auth|credential|bearer|cookie|private|signature)", re.I) +# Identifiers are not secrets: an order's broker_credential_id and account_id say which +# account it went to, and the audit needs them. +NOT_SECRET = re.compile(r"(_id|_ids)$", re.I) + +# Tools whose outcome is unknown when the call fails without an answer: the request may +# have reached the broker or the platform before the failure. +STATE_CHANGING = { + "place_order", "execute_strategy", "create_strategy", "update_strategy", "configure_overlay", + "create_webhook", "delete_webhook", "sync_portfolio", "create_connection", +} +TRADING = {"place_order", "execute_strategy"} +TOOL_NAME = re.compile(r"^mcp__(?:plugin_cpzai_)?cpzai__([a-z0-9_]+)$") + + +def redact(value): + if isinstance(value, dict): + out = {} + for k, v in value.items(): + key = str(k) + out[k] = "[redacted]" if SENSITIVE.search(key) and not NOT_SECRET.search(key) else redact(v) + return out + if isinstance(value, list): + return [redact(v) for v in value] + return value + + +def logged_input(tool: str, inp): + """The input as logged: redacted; a connection's configuration as its key names only.""" + if isinstance(inp, dict) and tool == "create_connection" and isinstance(inp.get("configuration"), dict): + inp = {**inp, "configuration": {"fields": sorted(str(k) for k in inp["configuration"])}} + return redact(inp) + + +def answer_body(resp): + """The tool's JSON answer: structuredContent, or the first text block that parses.""" + if isinstance(resp, dict): + sc = resp.get("structuredContent") + if isinstance(sc, dict): + return sc + content = resp.get("content") + elif isinstance(resp, list): + content = resp + else: + content = None + if isinstance(resp, str): + content = [{"type": "text", "text": resp}] + for block in content or []: + if isinstance(block, dict) and block.get("type") == "text": + try: + parsed = json.loads(block.get("text") or "") + except (TypeError, ValueError): + continue + if isinstance(parsed, dict): + return parsed + return resp if isinstance(resp, dict) else None + + +def pick(body, *keys): + if not isinstance(body, dict): + return None + for scope in (body, body.get("data") if isinstance(body.get("data"), dict) else None, body.get("order") if isinstance(body.get("order"), dict) else None): + if not isinstance(scope, dict): + continue + for k in keys: + v = scope.get(k) + if v not in (None, ""): + return v + return None + + +def record(event: dict) -> dict: + ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + name = event.get("hook_event_name") or event.get("hookEventName") or "PostToolUse" + tool = event.get("tool_name") or event.get("toolName") or "" + m = TOOL_NAME.match(tool) if isinstance(tool, str) else None + short = m.group(1) if m else "" + inp = event.get("tool_input") if "tool_input" in event else event.get("toolInput") + rec = {"ts": ts, "event": name, "tool": tool, "ok": None, "input": logged_input(short, inp)} + + if name == "PostToolUseFailure": + err = event.get("error") or event.get("tool_error") or "the tool call failed" + rec["error"] = err if isinstance(err, str) else json.dumps(err) + rec["is_interrupt"] = event.get("is_interrupt") + rec["duration_ms"] = event.get("duration_ms") + if short in STATE_CHANGING: + # No answer is not "not done": a timed-out order may have been placed. + rec["ok"] = None + rec["outcome"] = ( + "unknown: reconcile with list_orders before any resubmission" + if short in TRADING + else "unknown: check the resource before retrying" + ) + else: + rec["ok"] = False + return rec + + resp = event.get("tool_response") if "tool_response" in event else event.get("toolResponse") + body = answer_body(resp) + is_error = resp.get("isError") if isinstance(resp, dict) else None + error = pick(body, "error", "message") if isinstance(body, dict) and ("error" in body or is_error) else None + refused = isinstance(body, dict) and (body.get("success") is False or body.get("ok") is False or "error" in body) + if is_error is True or refused: + rec["ok"] = False + elif is_error is False or (isinstance(body, dict) and body): + rec["ok"] = True + rec["order_id"] = pick(body, "order_id", "broker_order_id", "id") + rec["status"] = pick(body, "status") + if error is not None: + rec["error"] = error if isinstance(error, str) else json.dumps(error) + return rec + + +def main() -> int: + data_dir = Path(os.environ.get("CLAUDE_PLUGIN_DATA") or Path.home() / ".claude" / "plugins" / "data" / "cpzai") + data_dir.mkdir(parents=True, exist_ok=True) + raw = sys.stdin.read() + try: + event = json.loads(raw) if raw.strip() else {} + rec = record(event if isinstance(event, dict) else {}) + except Exception as e: # The call happened: log that it did, and why the record is thin. + rec = { + "ts": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "event": "unreadable", + "ok": None, + "error": f"audit record could not be built: {type(e).__name__}: {e}", + # Not the raw event: it can hold a credential (create_connection). + "raw_length": len(raw), + } + path = data_dir / "audit.log" + # Owner-only: the log holds order details and account ids. + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) + os.chmod(path, 0o600) + with os.fdopen(fd, "a") as f: + f.write(json.dumps(rec, separators=(",", ":")) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cpzai/scripts/pre-trade-guard.sh b/cpzai/scripts/pre-trade-guard.sh deleted file mode 100755 index 926d2cf..0000000 --- a/cpzai/scripts/pre-trade-guard.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash -# CPZAI plugin — PreToolUse hook for destructive MCP tools. -# -# Reads the hook event JSON from stdin, decides whether to allow the -# tool call to proceed, and either: -# - exit 0 with no output → allow -# - exit 0 with JSON {"decision":"block","reason":"..."} → block -# - exit 2 → block with a default reason -# -# Behaviour: -# - If require_trade_confirmation=false → allow (user opted out) -# - For place_order / execute_strategy → block with structured reason -# so the agent must summarize and re-confirm via AskUserQuestion. -# - delete_webhook is default-deny. -set -euo pipefail - -EVENT_FILE="$(mktemp)" -trap 'rm -f "$EVENT_FILE"' EXIT -cat > "$EVENT_FILE" - -TOOL="$(EVENT_FILE="$EVENT_FILE" python3 - <<'PY' -import json, os, sys -try: - with open(os.environ["EVENT_FILE"]) as f: - d = json.load(f) - print(d.get("tool_name") or d.get("toolName") or "") -except Exception: - print("") -PY -)" - -CONFIRM="${CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION:-true}" -ENV="${CLAUDE_PLUGIN_OPTION_DEFAULT_ENVIRONMENT:-paper}" - -if [ "$CONFIRM" != "true" ]; then - exit 0 -fi - -if [ "$TOOL" = "mcp__cpzai__delete_webhook" ]; then - cat <___, so this plugin's tools are +mcp__plugin_cpzai_cpzai__place_order and so on. The guard used to match +mcp__cpzai__place_order only, so it never ran (cpzai#2908). Both spellings +are accepted here (the short one is what a standalone `cpzai` MCP server is +called), and hooks.json matches both. + +It used to answer {"decision":"block"} and tell Claude to ask the user and +re-issue the call. It kept no record of a confirmation, so the re-issued +call was blocked again, every time. Now it answers permissionDecision "ask": +Claude Code itself shows the user this call with the reason below, once, +and runs it when the user approves. The approval is the user's, in Claude +Code's own prompt, never the model's say-so. + +Stdin: the PreToolUse event JSON. Stdout: nothing (the normal permission +flow applies) or one JSON object. A call this guard cannot read is asked +about, never let through silently. +""" +from __future__ import annotations + +import json +import os +import re +import sys + +TOOL_NAME = re.compile(r"^mcp__(?:plugin_cpzai_)?cpzai__([a-z0-9_]+)$") + +# Tools that move money or run code that can. +TRADING = {"place_order", "execute_strategy"} +# Tools that change platform state. +MUTATING = { + "create_strategy", + "update_strategy", + "configure_overlay", + "create_webhook", + "delete_webhook", + "sync_portfolio", + "create_connection", +} +GUARDED = TRADING | MUTATING + + +def option(name: str, default: str) -> str: + return os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name}", default).strip() + + +def confirmation_required() -> bool: + return option("REQUIRE_TRADE_CONFIRMATION", "true").lower() not in ("false", "0", "no", "off") + + +def ask(reason: str) -> None: + print(json.dumps({ + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "ask", + "permissionDecisionReason": reason, + } + })) + + +def field(inp: dict, key: str) -> str: + v = inp.get(key) + return "?" if v is None or v == "" else str(v) + + +def describe(tool: str, inp: dict, default_env: str) -> str: + if tool == "place_order": + price = "" + if inp.get("price") is not None: + price += f" limit {inp['price']}" + if inp.get("stop_price") is not None: + price += f" stop {inp['stop_price']}" + env_note = ( + "Your default trading environment is paper: approve only if this account is a paper account. " + "A live account trades real money." + if default_env.lower() == "paper" + else f"Your default trading environment is {default_env}. A live account trades real money." + ) + return ( + f"CPZAI order: {field(inp, 'side').upper()} {field(inp, 'quantity')} {field(inp, 'symbol')} " + f"{field(inp, 'order_type')}{price}, account {field(inp, 'account_id')} " + f"(credential {field(inp, 'broker_credential_id')}). {env_note} Approve to place it once." + ) + if tool == "execute_strategy": + override = " with a code override" if inp.get("code") else "" + return ( + f"CPZAI strategy run: strategy {field(inp, 'strategy_id')}{override}. " + "A strategy run executes the strategy's code and can submit orders; it is not a backtest. " + f"Default trading environment: {default_env}. Approve to run it once." + ) + if tool == "delete_webhook": + return ( + f"CPZAI: delete webhook {field(inp, 'id')}. Its signing secret cannot be recovered. " + "Approve to delete it." + ) + return f"CPZAI: {tool} changes your CPZAI account. Approve to run it once." + + +UNREADABLE = "CPZAI safety guard could not read this tool call. Review it before approving." + + +def decide(raw: str) -> str | None: + """The reason to ask the user about this call, or None to leave the normal permission flow. + + This hook only runs for the CPZAI tools hooks.json matches, so anything it + cannot read, or a name it does not recognise, is asked about: the guard + fails closed, never open. + """ + try: + event = json.loads(raw) if raw.strip() else None + except (json.JSONDecodeError, ValueError): + event = None + if not isinstance(event, dict): + return UNREADABLE + name = event.get("tool_name") or event.get("toolName") + if not isinstance(name, str) or not name: + return UNREADABLE + m = TOOL_NAME.match(name) + if not m or m.group(1) not in GUARDED: + return f"CPZAI safety guard does not recognise the tool {name[:80]}. Review it before approving." + # The user's own opt-out (userConfig.require_trade_confirmation = false). + if not confirmation_required(): + return None + inp = event.get("tool_input") if "tool_input" in event else event.get("toolInput") + if not isinstance(inp, dict): + inp = {} + return describe(m.group(1), inp, option("DEFAULT_ENVIRONMENT", "paper") or "paper") + + +def main() -> int: + try: + reason = decide(sys.stdin.read()) + except Exception as e: # Fail closed: an error here must never let the call through unasked. + reason = f"{UNREADABLE} ({type(e).__name__})" + if reason is not None: + ask(reason) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cpzai/scripts/session-start.sh b/cpzai/scripts/session-start.sh index 0d9a4ed..6bb84ca 100755 --- a/cpzai/scripts/session-start.sh +++ b/cpzai/scripts/session-start.sh @@ -4,12 +4,27 @@ # context every session. set -euo pipefail -PLUGIN_VERSION="2.0.0" +PLUGIN_VERSION="2.1.0" MCP_URL="${CPZAI_MCP_URL:-https://mcp.cpz-lab.com/mcp}" ENV="${CLAUDE_PLUGIN_OPTION_DEFAULT_ENVIRONMENT:-paper}" HAS_KEY="$([ -n "${CLAUDE_PLUGIN_OPTION_CPZ_API_KEY:-}" ] && echo "configured" || echo "OAuth/unset")" -CONFIRM="${CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION:-true}" +# The same reading of the option as scripts/pre_trade_guard.py: only false/0/no/off turn it off. +RAW_CONFIRM="$(printf '%s' "${CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION:-true}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" +case "$RAW_CONFIRM" in + false|0|no|off) CONFIRM="false" ;; + *) CONFIRM="true" ;; +esac +# The guard and the audit log are Python. `command -v` is not enough: a Mac without the +# developer tools has a /usr/bin/python3 stub that exists but cannot run a script. So +# python3 is run, and only one that answers counts. Without it the guard cannot start; +# hooks.json has it block (onFailure) rather than let an order through, and nothing is logged. +if command -v python3 >/dev/null 2>&1 && [ "$(python3 -c 'import json, re, sys; print("ok")' 2>/dev/null)" = "ok" ]; then + GUARD="on" +else + GUARD="OFF (no working python3: CPZAI orders and strategy runs are blocked and nothing is logged)" + CONFIRM="false" +fi cat < str: + return (PLUGIN / rel).read_text() + + +def tools(rel: str) -> set[str]: + """The CPZAI tools a command allows or an agent may use (not its disallowedTools).""" + fm = text(rel).split("\n---", 1)[0] + out: set[str] = set() + key = None + for line in fm.splitlines(): + m = re.match(r"^([\w-]+):", line) + if m: + key = m.group(1) + continue + item = re.match(r"^\s*-\s*" + re.escape(P) + r"([a-z_]+)\s*$", line) + if item and key in ("tools", "allowed-tools"): + out.add(item.group(1)) + return out + + +class Backtests(unittest.TestCase): + """#2797: no CPZAI tool starts a backtest, and execute_strategy can submit orders.""" + + def test_nothing_backtests_with_execute_strategy(self): + old = [ + "Call `execute_strategy` with the strategy ID and backtest parameters", + "run the backtest with specified date range and parameters", + "run a backtest with the new signal", + "Follow up with `execute_strategy` to backtest", + "run the strategy on the compute backend (backtest or live)", + ] + for f in FILES: + body = f.read_text() + for phrase in old: + self.assertNotIn(phrase, body, f.relative_to(ROOT)) + + def test_backtest_command_reads_saved_runs_only(self): + self.assertNotIn("execute_strategy", tools("commands/backtest.md")) + self.assertTrue({"get_backtest_results", "get_backtest_result"} <= tools("commands/backtest.md")) + self.assertIn("No CPZAI tool starts a backtest", text("commands/backtest.md")) + + def test_the_research_agent_cannot_run_strategy_code(self): + self.assertNotIn("execute_strategy", tools("agents/quant-researcher.md")) + + +class Balances(unittest.TestCase): + """#2906: list_accounts holds no balances; cash_summary does.""" + + def test_no_file_reads_balances_from_list_accounts(self): + pattern = re.compile(r"`list_accounts`[^\n]*(equity|buying power|margin|capital|portfolio value)", re.I) + for f in FILES: + for line in f.read_text().splitlines(): + if pattern.search(line) and "no balances" not in line and "cash_summary" not in line: + self.fail(f"{f.relative_to(ROOT)}: {line.strip()}") + + def test_commands_that_show_balances_can_call_cash_summary(self): + for rel in ("commands/positions.md", "commands/portfolio-review.md", "commands/risk-report.md", + "commands/trade.md", "commands/trade-idea.md", "commands/optimize.md", "commands/sync.md", + "agents/execution-reviewer.md", "agents/risk-auditor.md"): + self.assertIn("cash_summary", tools(rel), rel) + + def test_portfolio_review_drops_figures_no_tool_has(self): + body = text("commands/portfolio-review.md") + for line in ("Margin Used:", "Week P&L:", "Month P&L:"): + self.assertNotIn(line, body) + + +class History(unittest.TestCase): + """#2909: history-based figures come from get_bars, not the quote or the risk check.""" + + def test_commands_that_need_price_history_can_call_get_bars(self): + for rel in ("commands/price.md", "commands/market-scan.md", "commands/optimize.md", "commands/risk-report.md", + "commands/trade-idea.md", "commands/options-analysis.md", "commands/factor-screen.md", + "agents/execution-reviewer.md"): + self.assertIn("get_bars", tools(rel), rel) + + def test_optimize_takes_covariance_from_bars(self): + self.assertNotIn("get current risk metrics (covariance inputs)", text("skills/portfolio-optimization/SKILL.md")) + self.assertIn("covariance matrix are estimated from these", text("commands/optimize.md")) + + +class Unavailable(unittest.TestCase): + """#2886, #2909: figures no tool returns are said to be unavailable, never filled from memory.""" + + def test_every_command_carries_the_rule(self): + for f in sorted(PLUGIN.glob("commands/*.md")): + self.assertIn('"not available from CPZAI", never filled from memory', f.read_text(), f.name) + + def test_options_and_fundamentals_are_named_unavailable(self): + self.assertIn("No CPZAI tool returns option chains, option quotes, implied volatility, IV rank, Greeks", + text("commands/options-analysis.md")) + self.assertIn("No CPZAI tool returns fundamentals", text("commands/factor-screen.md")) + self.assertIn("**Not available from any CPZAI tool:**", text("CONNECTORS.md")) + + +class Formulas(unittest.TestCase): + """cpzai#3012, #3022, #3023: formulas and rules the skills give Claude.""" + + def test_risk_contributions_add_up_to_100_percent(self): + body = text("skills/risk-management/SKILL.md") + self.assertIn("MCTR_i = ∂σ_p / ∂w_i = (Σw)_i / σ_p", body) + self.assertIn("Σ PCR_i = 100%", body) + self.assertNotIn("Σ CR_i = σ²_portfolio", body) + self.assertNotIn("MCTR_i = w_i × (Σw)_i / σ_portfolio", body) + # Reference: a 4-asset book. The derivative of σ_p equals (Σw)_i/σ_p, and the + # percent contributions w_i(Σw)_i/(w'Σw) add up to 1; the old CR_i = w_i²(Σw)_i/σ_p did not add up to σ². + vol = [0.30, 0.20, 0.25, 0.05] + corr = [[1, .5, .6, 0], [.5, 1, .4, .1], [.6, .4, 1, 0], [0, .1, 0, 1]] + cov = [[vol[i] * vol[j] * corr[i][j] for j in range(4)] for i in range(4)] + w = [.4, .25, .25, .1] + sw = [sum(cov[i][j] * w[j] for j in range(4)) for i in range(4)] + var = sum(w[i] * sw[i] for i in range(4)) + sp = var ** 0.5 + for i in range(4): + h = 1e-7 + w2 = [w[j] + (h if j == i else 0) for j in range(4)] + sp2 = sum(w2[a] * cov[a][b] * w2[b] for a in range(4) for b in range(4)) ** 0.5 + self.assertAlmostEqual((sp2 - sp) / h, sw[i] / sp, places=5) + self.assertAlmostEqual(sum(w[i] * sw[i] / var for i in range(4)), 1.0, places=12) + old_cr = [w[i] * (w[i] * sw[i] / sp) for i in range(4)] + self.assertNotAlmostEqual(sum(old_cr), var, places=3) + + def test_risk_parity_is_described_as_equal_total_contribution(self): + po = text("skills/portfolio-optimization/SKILL.md") + self.assertNotIn("each asset's marginal contribution to portfolio volatility is identical", po) + self.assertIn("the minimum-variance one", po) + self.assertNotIn("`w_i = (1/σ_i) / Σ(1/σ_j)`. Equalizes risk contribution.", text("skills/strategy-development/SKILL.md")) + + def test_six_rules_from_3022(self): + self.assertIn("IV(25d call) - IV(25d put)", text("skills/volatility-and-derivatives/SKILL.md")) + self.assertNotIn("BR of ~125,000", text("skills/alpha-research/SKILL.md")) + po = text("skills/portfolio-optimization/SKILL.md") + self.assertIn("5,000 + 55 + 500 = 5,555", po) + self.assertIn("scaled identity", po) + self.assertNotIn("statistical significance (>30)", text("commands/backtest.md")) + self.assertIn("(P_worst × R_worst)", text("commands/trade-idea.md")) + + def test_17a4_retention(self): + body = text("skills/compliance-and-recordkeeping/SKILL.md") + self.assertNotIn("order records for 6 years", body) + self.assertNotIn("6-year order record retention", body) + self.assertIn("order memoranda (Rule 17a-3(a)(6)) for 3 years", body) + + +class Orders(unittest.TestCase): + """cpzai#3014, #3034: /trade matches place_order's fields and never resends blindly.""" + + def test_trade_takes_a_stop_price_and_shares_only(self): + body = text("commands/trade.md") + self.assertIn("[stop price]", body) + self.assertNotIn("`$500` for notional", body) + self.assertNotIn("buy $1000 SPY", body) + self.assertIn("Stop: $XXX.XX", body) + self.assertIn("`time_in_force: day` only", body) + self.assertNotIn("(day, GTC, IOC, FOK)", text("skills/order-execution/SKILL.md")) + + def test_trade_never_resends_after_a_timeout(self): + body = text("commands/trade.md") + self.assertIn("Do not call `place_order` again", body) + self.assertIn("not** guaranteed to be deduplicated", body) + + +class StrategyFormat(unittest.TestCase): + """cpzai#3013: /strategy-builder writes the format Strategy Lab backtests.""" + + def test_names_symbols_and_the_signal_interface(self): + body = text("commands/strategy-builder.md") + for part in ("SYMBOLS = [", "def generate_signals(data, state, **kwargs)", "def on_bar(context, data)", "No strategy interface function is available"): + self.assertIn(part, body) + + +class Paging(unittest.TestCase): + """cpzai#3037: a page of positions or orders is not the whole book.""" + + def test_book_commands_page_until_a_short_page(self): + for rel in ("commands/positions.md", "commands/portfolio-review.md", "commands/risk-report.md", "commands/orders.md"): + self.assertIn("until a page comes back shorter than the limit", text(rel), rel) + + +class Environments(unittest.TestCase): + """cpzai#3120: paper and live money are never one total.""" + + def test_balance_lines_are_per_environment(self): + self.assertNotIn("Total equity across all accounts", text("commands/sync.md")) + self.assertIn("totals.by_environment", text("commands/sync.md")) + for rel in ("commands/positions.md", "commands/portfolio-review.md"): + body = text(rel) + self.assertNotIn("Total Equity:", body, rel) + self.assertIn("Paper and live money are never added together", body, rel) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_hooks.py b/tests/test_hooks.py new file mode 100644 index 0000000..4279ade --- /dev/null +++ b/tests/test_hooks.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Tests for the plugin's hooks (cpzai#2908). + +The pre-trade guard named the CPZAI tools mcp__cpzai__*, while Claude Code +lists a plugin's bundled MCP tools as mcp__plugin_cpzai_cpzai__*, so the +guard and the audit log never ran. And the guard blocked every call with +"ask the user and re-issue", keeping no record of the answer, so a fixed +name alone would have blocked a confirmed order forever. + +Run: python3 tests/test_hooks.py +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import shutil +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PLUGIN = ROOT / "cpzai" +GUARD = PLUGIN / "scripts" / "pre_trade_guard.py" +AUDIT = PLUGIN / "scripts" / "audit_log.py" +HOOKS = json.loads((PLUGIN / "hooks" / "hooks.json").read_text()) + +PLUGIN_NAME = "mcp__plugin_cpzai_cpzai__{}" + + +def run_guard(event: dict | str, **env: str) -> dict | None: + full_env = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE_PLUGIN_OPTION_")} + full_env.update(env) + raw = event if isinstance(event, str) else json.dumps(event) + out = subprocess.run([str(GUARD)], input=raw, capture_output=True, text=True, env=full_env, check=True) + return json.loads(out.stdout) if out.stdout.strip() else None + + +def matcher(event: str) -> re.Pattern: + entries = HOOKS["hooks"][event] + return re.compile(entries[0]["matcher"]) + + +ORDER = { + "account_id": "PA3VZ41G5INS", + "broker_credential_id": "6f1c2e2a-1111-4222-8333-944455556666", + "symbol": "AAPL", + "side": "buy", + "order_type": "limit", + "quantity": 10, + "price": 200.5, +} + + +class HookMatchers(unittest.TestCase): + def test_pre_and_post_hooks_match_the_names_claude_code_gives_plugin_tools(self): + for event in ("PreToolUse", "PostToolUse", "PostToolUseFailure"): + m = matcher(event) + for tool in ("place_order", "execute_strategy", "delete_webhook", "create_strategy", "configure_overlay"): + self.assertTrue(m.search(PLUGIN_NAME.format(tool)), f"{event} misses {tool}") + self.assertTrue(m.search(f"mcp__cpzai__{tool}"), f"{event} misses standalone {tool}") + + def test_reads_are_not_matched(self): + for event in ("PreToolUse", "PostToolUse"): + m = matcher(event) + for tool in ("list_positions", "list_orders", "cash_summary", "get_market_data"): + self.assertIsNone(m.search(PLUGIN_NAME.format(tool))) + # Another server's tool of the same name is not CPZAI's. + self.assertIsNone(m.search("mcp__other__place_order")) + + def test_every_hook_command_exists_and_is_executable(self): + for entries in HOOKS["hooks"].values(): + for entry in entries: + for hk in entry["hooks"]: + path = PLUGIN / hk["command"].replace("${CLAUDE_PLUGIN_ROOT}/", "").split()[0] + self.assertTrue(path.exists(), path) + self.assertTrue(os.access(path, os.X_OK), path) + + +class PreTradeGuard(unittest.TestCase): + def test_an_order_is_asked_about_once_in_claude_codes_own_prompt_never_blocked(self): + out = run_guard({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER}) + self.assertIsNotNone(out) + spec = out["hookSpecificOutput"] + self.assertEqual(spec["hookEventName"], "PreToolUse") + # "ask": the user approves in Claude Code's prompt and the call runs. Never "deny" or block. + self.assertEqual(spec["permissionDecision"], "ask") + self.assertNotIn("decision", out) + reason = spec["permissionDecisionReason"] + for part in ("BUY 10 AAPL", "limit 200.5", "PA3VZ41G5INS", "paper"): + self.assertIn(part, reason) + self.assertNotIn("re-issue", reason) + + def test_a_confirmed_call_is_not_blocked_again(self): + # The same call twice: each answer is an ask the user can approve; nothing is ever a block. + for _ in range(2): + out = run_guard({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER}) + self.assertEqual(out["hookSpecificOutput"]["permissionDecision"], "ask") + + def test_strategy_runs_and_webhook_deletes_are_asked_about(self): + run = run_guard({"tool_name": PLUGIN_NAME.format("execute_strategy"), "tool_input": {"strategy_id": "s-1"}}) + self.assertIn("can submit orders", run["hookSpecificOutput"]["permissionDecisionReason"]) + self.assertIn("not a backtest", run["hookSpecificOutput"]["permissionDecisionReason"]) + delete = run_guard({"tool_name": PLUGIN_NAME.format("delete_webhook"), "tool_input": {"id": "w-1"}}) + self.assertIn("w-1", delete["hookSpecificOutput"]["permissionDecisionReason"]) + + def test_live_default_environment_is_named(self): + out = run_guard({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER}, + CLAUDE_PLUGIN_OPTION_DEFAULT_ENVIRONMENT="live") + self.assertIn("default trading environment is live", out["hookSpecificOutput"]["permissionDecisionReason"]) + + def test_opt_out_leaves_the_normal_permission_flow(self): + self.assertIsNone(run_guard({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER}, + CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION="false")) + + # Review of plugin #1: the guard failed open on malformed events. + def test_a_name_the_guard_does_not_recognise_is_asked_about(self): + for name in (PLUGIN_NAME.format("list_positions"), "mcp__other__place_order"): + out = run_guard({"tool_name": name, "tool_input": {}}) + self.assertEqual(out["hookSpecificOutput"]["permissionDecision"], "ask", name) + + def test_an_unreadable_event_is_asked_about_not_let_through(self): + for raw in ("not json", "", "{}", "[]", '{"tool_input": {}}', '{"tool_name": 5}', '{"tool_name": null}', '{"tool_name": ["x"]}'): + out = run_guard(raw) + self.assertIsNotNone(out, raw) + self.assertEqual(out["hookSpecificOutput"]["permissionDecision"], "ask", raw) + + def test_a_non_object_tool_input_still_asks(self): + out = run_guard({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": "AAPL"}) + self.assertEqual(out["hookSpecificOutput"]["permissionDecision"], "ask") + + +class SessionBanner(unittest.TestCase): + SCRIPT = PLUGIN / "scripts" / "session-start.sh" + + def banner(self, path: str | None = None, **env: str) -> str: + full = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE_PLUGIN_OPTION_")} + full.update(env) + if path is not None: + full["PATH"] = path + return subprocess.run(["/bin/bash", str(self.SCRIPT)], capture_output=True, text=True, env=full, check=True).stdout + + def test_confirm_is_read_the_way_the_guard_reads_it(self): + self.assertIn("confirm=true", self.banner()) + self.assertIn("confirm=true", self.banner(CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION="yes please")) + for off in ("false", "FALSE", " off ", "0", "no"): + self.assertIn("confirm=false", self.banner(CLAUDE_PLUGIN_OPTION_REQUIRE_TRADE_CONFIRMATION=off), off) + + def test_says_when_python3_is_missing(self): + self.assertIn("guard=on", self.banner()) + with tempfile.TemporaryDirectory() as d: + # The tools the banner uses, and no python3. + for tool in ("tr", "cat"): + os.symlink(shutil.which(tool), os.path.join(d, tool)) + out = self.banner(path=d) + self.assertIn("guard=OFF (no working python3", out) + self.assertIn("confirm=false", out) + + # Re-review of plugin #1: the /usr/bin/python3 stub on a Mac without the developer + # tools passes `command -v` but cannot run anything; the banner said guard=on. + def test_says_when_python3_exists_but_does_not_run(self): + with tempfile.TemporaryDirectory() as d: + for tool in ("tr", "cat"): + os.symlink(shutil.which(tool), os.path.join(d, tool)) + stub = os.path.join(d, "python3") + with open(stub, "w") as f: + f.write("#!/bin/sh\necho 'xcode-select: note: No developer tools were found' >&2\nexit 1\n") + os.chmod(stub, 0o755) + out = self.banner(path=d) + self.assertIn("guard=OFF (no working python3", out) + self.assertIn("confirm=false", out) + + +class GuardFailure(unittest.TestCase): + def test_a_guard_that_cannot_run_blocks_the_call(self): + entry = HOOKS["hooks"]["PreToolUse"][0]["hooks"][0] + self.assertTrue(entry["command"].endswith("pre_trade_guard.py")) + self.assertEqual(entry.get("onFailure"), "block") + + +class AuditLog(unittest.TestCase): + def run_audit(self, event: dict) -> dict: + with tempfile.TemporaryDirectory() as d: + env = {**os.environ, "CLAUDE_PLUGIN_DATA": d} + subprocess.run([str(AUDIT)], input=json.dumps(event), text=True, env=env, check=True) + lines = (Path(d) / "audit.log").read_text().splitlines() + self.assertEqual(len(lines), 1) + return json.loads(lines[0]) + + def test_records_the_outcome_from_the_tool_response_never_assumes_ok(self): + name = PLUGIN_NAME.format("place_order") + self.assertIs(self.run_audit({"tool_name": name, "tool_input": ORDER, "tool_response": {"isError": True}})["ok"], False) + self.assertIs(self.run_audit({"tool_name": name, "tool_input": ORDER, "tool_response": {"isError": False}})["ok"], True) + rec = self.run_audit({"tool_name": name, "tool_input": ORDER}) + self.assertIsNone(rec["ok"]) + self.assertEqual(rec["tool"], name) + + # cpzai#3024: a refused order was logged ok, with no broker reply. + def test_a_refused_order_is_logged_as_refused_with_the_reason(self): + refusal = {"error": "Insufficient buying power", "code": "insufficient_buying_power"} + rec = self.run_audit({ + "hook_event_name": "PostToolUse", "tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER, + "tool_response": {"isError": True, "content": [{"type": "text", "text": json.dumps(refusal)}]}, + }) + self.assertIs(rec["ok"], False) + self.assertEqual(rec["error"], "Insufficient buying power") + + def test_an_accepted_order_is_logged_with_the_broker_order_id_and_status(self): + answer = {"data": {"id": "row-1", "order_id": "alp-123", "status": "accepted", "symbol": "AAPL"}} + rec = self.run_audit({ + "hook_event_name": "PostToolUse", "tool_name": PLUGIN_NAME.format("place_order"), "tool_input": ORDER, + "tool_response": {"content": [{"type": "text", "text": json.dumps(answer)}]}, + }) + self.assertIs(rec["ok"], True) + self.assertEqual((rec["order_id"], rec["status"]), ("alp-123", "accepted")) + + # Re-review: a timed-out order may have been placed, so its outcome is unknown, not false. + def test_a_trading_call_that_failed_without_an_answer_is_logged_as_unknown(self): + rec = self.run_audit({"hook_event_name": "PostToolUseFailure", "tool_name": PLUGIN_NAME.format("place_order"), + "tool_input": ORDER, "error": "MCP request timed out", "is_interrupt": False, "duration_ms": 60012}) + self.assertIsNone(rec["ok"]) + self.assertEqual(rec["outcome"], "unknown: reconcile with list_orders before any resubmission") + self.assertEqual(rec["error"], "MCP request timed out") + self.assertEqual((rec["is_interrupt"], rec["duration_ms"]), (False, 60012)) + + def test_other_state_changing_failures_are_unknown_too(self): + rec = self.run_audit({"hook_event_name": "PostToolUseFailure", "tool_name": PLUGIN_NAME.format("create_strategy"), + "tool_input": {"title": "x"}, "error": "socket hang up", "is_interrupt": True, "duration_ms": 5}) + self.assertIsNone(rec["ok"]) + self.assertEqual(rec["outcome"], "unknown: check the resource before retrying") + self.assertIs(rec["is_interrupt"], True) + + def test_redaction_covers_credential_like_fields_but_keeps_identifiers(self): + rec = self.run_audit({"tool_name": PLUGIN_NAME.format("place_order"), "tool_response": {"isError": False}, + "tool_input": {**ORDER, "Authorization": "Bearer abc", "x_bearer": "abc", "cookie": "c=1", + "pass": "p", "pwd": "p", "pin": "1234", "private_key_pem": "k", "signature": "s", + "credential": "c", "nested": {"auth_header": "h", "note": "fine"}}}) + inp = rec["input"] + for k in ("Authorization", "x_bearer", "cookie", "pass", "pwd", "pin", "private_key_pem", "signature", "credential"): + self.assertEqual(inp[k], "[redacted]", k) + self.assertEqual(inp["nested"], {"auth_header": "[redacted]", "note": "fine"}) + # Which account the order went to stays on record. + self.assertEqual(inp["broker_credential_id"], ORDER["broker_credential_id"]) + self.assertEqual(inp["account_id"], ORDER["account_id"]) + + def test_a_connection_configuration_is_logged_as_key_names_only(self): + rec = self.run_audit({"tool_name": PLUGIN_NAME.format("create_connection"), "tool_response": {"isError": False}, + "tool_input": {"connection_type": "vipe", "configuration": {"base_url": "https://x", "login": "me@example.com"}}}) + self.assertEqual(rec["input"]["configuration"], {"fields": ["base_url", "login"]}) + self.assertNotIn("me@example.com", json.dumps(rec)) + + def test_the_log_is_owner_only(self): + with tempfile.TemporaryDirectory() as d: + env = {**os.environ, "CLAUDE_PLUGIN_DATA": d} + subprocess.run([str(AUDIT)], input=json.dumps({"tool_name": PLUGIN_NAME.format("place_order")}), text=True, env=env, check=True) + self.assertEqual(os.stat(Path(d) / "audit.log").st_mode & 0o777, 0o600) + + def test_the_whole_order_is_kept_and_credentials_are_not(self): + long_order = {**ORDER, "order_type": "stop_limit", "stop_price": 199.5, "client_order_id": "c" * 50} + rec = self.run_audit({"tool_name": PLUGIN_NAME.format("place_order"), "tool_input": long_order, "tool_response": {"isError": False}}) + self.assertEqual(rec["input"], long_order) + conn = self.run_audit({"tool_name": PLUGIN_NAME.format("create_connection"), + "tool_input": {"connection_type": "polygon", "api_key": "abc123", "secret_token": "s3cr3t"}, + "tool_response": {"isError": False}}) + self.assertEqual(conn["input"], {"connection_type": "polygon", "api_key": "[redacted]", "secret_token": "[redacted]"}) + self.assertNotIn("abc123", json.dumps(conn)) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/validate.py b/tests/validate.py index 5f5d174..5e99bf9 100755 --- a/tests/validate.py +++ b/tests/validate.py @@ -27,28 +27,27 @@ ROOT = Path(__file__).resolve().parent.parent PLUGIN = ROOT / "cpzai" -# Live tool list as of plugin v2.0.0. Update when the MCP server adds tools. +# Live tool list (the MCP server's tools/list, mirrored in CPZ-Lab/cpzai +# src/lib/mcp-tool-catalog.json). Update when the MCP server adds tools. LIVE_TOOLS = { - "list_strategies", - "get_strategy", - "create_strategy", - "update_strategy", - "get_backtest_results", - "list_orders", - "place_order", - "list_positions", - "sync_portfolio", - "list_accounts", - "get_market_data", - "compute_risk", - "list_risk_snapshots", - "execute_strategy", - "list_webhooks", - "create_webhook", - "delete_webhook", - "get_profile", + "add_to_watchlist", "cash_summary", "compute_risk", "configure_overlay", + "create_connection", "create_strategy", "create_webhook", "delete_webhook", + "execute_strategy", "export_transactions", "get_backtest_result", + "get_backtest_results", "get_bars", "get_data_file", "get_market_data", + "get_order", "get_overlay_exposure", "get_profile", "get_risk_snapshot", + "get_strategy", "list_accounts", "list_cash_flows", "list_connections", + "list_data_files", "list_deals", "list_fund_periods", "list_journal_entries", + "list_lifecycle_events", "list_orders", "list_overlays", "list_positions", + "list_risk_snapshots", "list_strategies", "list_watchlist", "list_webhooks", + "place_order", "remove_from_watchlist", "sync_portfolio", "update_strategy", } +# Claude Code names a plugin's bundled MCP tools mcp__plugin____. +# Inside this plugin the CPZAI tools are mcp__plugin_cpzai_cpzai__; the short +# mcp__cpzai__ names no tool, so a tools: list or a hook matcher written with +# it silently does nothing (cpzai#2908). +PLUGIN_SERVER = "plugin_cpzai_cpzai" + # Built-in Claude Code tools that may appear in allowed-tools. BUILTIN_TOOLS = { "Read", "Write", "Edit", "Bash", "Glob", "Grep", "WebFetch", "WebSearch", @@ -236,7 +235,9 @@ def validate_command(path: Path) -> None: m = TOOL_REF.match(t) if m: server, tool = m.group(1), m.group(2) - if server == "cpzai" and tool not in LIVE_TOOLS: + if server == "cpzai": + err(f"{rel}: allowed-tools names '{t}'; inside the plugin the tool is mcp__{PLUGIN_SERVER}__{tool}") + elif server == PLUGIN_SERVER and tool not in LIVE_TOOLS: err(f"{rel}: allowed-tools references unknown CPZAI tool '{tool}'") elif t not in BUILTIN_TOOLS and not t.startswith("Bash("): warn(f"{rel}: allowed-tools entry '{t}' is not a known built-in or mcp__server__tool reference") @@ -269,11 +270,16 @@ def validate_agent(path: Path) -> None: err(f"{rel}: missing '{required}' in frontmatter") if "name" in fm and not KEBAB.match(fm["name"]): err(f"{rel}: agent name '{fm['name']}' is not kebab-case") - if "tools" in fm and isinstance(fm["tools"], list): - for t in fm["tools"]: - m = TOOL_REF.match(t) - if m and m.group(1) == "cpzai" and m.group(2) not in LIVE_TOOLS: - err(f"{rel}: tools references unknown CPZAI tool '{m.group(2)}'") + for key in ("tools", "disallowedTools"): + if key in fm and isinstance(fm[key], list): + for t in fm[key]: + m = TOOL_REF.match(t) + if not m: + continue + if m.group(1) == "cpzai": + err(f"{rel}: {key} names '{t}'; inside the plugin the tool is mcp__{PLUGIN_SERVER}__{m.group(2)}") + elif m.group(1) == PLUGIN_SERVER and m.group(2) not in LIVE_TOOLS: + err(f"{rel}: {key} references unknown CPZAI tool '{m.group(2)}'") def main() -> int: @@ -302,7 +308,7 @@ def main() -> int: validate_agent(a) scripts_dir = PLUGIN / "scripts" - scripts = sorted(scripts_dir.glob("*.sh")) if scripts_dir.exists() else [] + scripts = sorted([*scripts_dir.glob("*.sh"), *scripts_dir.glob("*.py")]) if scripts_dir.exists() else [] print(f" scripts: {len(scripts)}") for sc in scripts: if not (sc.stat().st_mode & stat.S_IXUSR):