From 7f220864ce5e2186074f77ddddac8142bb65580e Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:07:36 -0500 Subject: [PATCH 01/10] fix(hooks): guard and audit log run under the plugin's tool names; the guard asks once instead of blocking a confirmed call (cpzai#2908) --- cpzai/hooks/hooks.json | 6 +- cpzai/scripts/audit-log.sh | 10 ++- cpzai/scripts/pre-trade-guard.sh | 61 ------------- cpzai/scripts/pre_trade_guard.py | 129 +++++++++++++++++++++++++++ tests/smoke-mcp.sh | 2 +- tests/test_hooks.py | 145 +++++++++++++++++++++++++++++++ tests/validate.py | 58 +++++++------ 7 files changed, 319 insertions(+), 92 deletions(-) delete mode 100755 cpzai/scripts/pre-trade-guard.sh create mode 100755 cpzai/scripts/pre_trade_guard.py create mode 100644 tests/test_hooks.py diff --git a/cpzai/hooks/hooks.json b/cpzai/hooks/hooks.json index a8c8f34..4aa8b52 100644 --- a/cpzai/hooks/hooks.json +++ b/cpzai/hooks/hooks.json @@ -12,18 +12,18 @@ ], "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" } ] } ], "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", diff --git a/cpzai/scripts/audit-log.sh b/cpzai/scripts/audit-log.sh index f8fe361..5795142 100755 --- a/cpzai/scripts/audit-log.sh +++ b/cpzai/scripts/audit-log.sh @@ -26,7 +26,15 @@ try: except Exception: d = {} tool = d.get("tool_name") or d.get("toolName") or "" -ok = d.get("success", True) +# PostToolUse carries the tool's answer, not a success flag: an MCP error +# result says isError. Anything else is recorded as unknown, never as ok. +resp = d.get("tool_response") if "tool_response" in d else d.get("toolResponse") +if isinstance(resp, dict) and isinstance(resp.get("isError"), bool): + ok = not resp["isError"] +elif isinstance(resp, dict) and resp.get("success") is False: + ok = False +else: + ok = None 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} 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." + + +def main() -> int: + raw = sys.stdin.read() + try: + event = json.loads(raw) if raw.strip() else {} + except json.JSONDecodeError: + event = None + if not isinstance(event, dict): + # Only CPZAI's guarded tools reach this hook; one we cannot read is asked about. + ask("CPZAI safety guard could not read this tool call. Review it before approving.") + return 0 + + name = event.get("tool_name") or event.get("toolName") or "" + m = TOOL_NAME.match(name) + if not m or m.group(1) not in GUARDED: + return 0 + if not confirmation_required(): + return 0 + + tool = m.group(1) + inp = event.get("tool_input") or event.get("toolInput") or {} + if not isinstance(inp, dict): + inp = {} + ask(describe(tool, inp, option("DEFAULT_ENVIRONMENT", "paper") or "paper")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/smoke-mcp.sh b/tests/smoke-mcp.sh index 1bfafa5..954825b 100755 --- a/tests/smoke-mcp.sh +++ b/tests/smoke-mcp.sh @@ -90,7 +90,7 @@ for d in (os.path.join(root, "cpzai", "commands"), os.path.join(root, "cpzai", " if not f.endswith(".md"): continue text = open(os.path.join(d, f)).read() - for m in re.finditer(r"mcp__cpzai__([a-z0-9_]+)", text): + for m in re.finditer(r"mcp__(?:plugin_cpzai_)?cpzai__([a-z0-9_]+)", text): ref.add(m.group(1)) missing = ref - live extra = live - ref diff --git a/tests/test_hooks.py b/tests/test_hooks.py new file mode 100644 index 0000000..9ef2eee --- /dev/null +++ b/tests/test_hooks.py @@ -0,0 +1,145 @@ +#!/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 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.sh" +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"): + 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")) + + def test_other_tools_pass(self): + self.assertIsNone(run_guard({"tool_name": PLUGIN_NAME.format("list_positions"), "tool_input": {}})) + self.assertIsNone(run_guard({"tool_name": "mcp__other__place_order", "tool_input": ORDER})) + + def test_an_unreadable_event_is_asked_about_not_let_through(self): + out = run_guard("not json") + self.assertEqual(out["hookSpecificOutput"]["permissionDecision"], "ask") + + +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(["bash", 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) + + +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): From dff44c9de926068d948b659105128c1370b651af Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:07:40 -0500 Subject: [PATCH 02/10] fix(plugin): commands, skills and agents use tools that return what they ask for (cpzai#2797, #2886, #2906, #2909) --- .github/workflows/validate.yml | 4 + cpzai/CONNECTORS.md | 57 ++++++--- cpzai/agents/execution-reviewer.md | 41 ++++--- cpzai/agents/quant-researcher.md | 26 ++-- cpzai/agents/risk-auditor.md | 28 +++-- cpzai/commands/backtest.md | 40 +++--- cpzai/commands/earnings-preview.md | 6 +- cpzai/commands/equity-research.md | 4 +- cpzai/commands/factor-screen.md | 10 +- cpzai/commands/market-scan.md | 8 +- cpzai/commands/optimize.md | 20 +-- cpzai/commands/options-analysis.md | 14 ++- cpzai/commands/orders.md | 6 +- cpzai/commands/portfolio-review.md | 29 ++--- cpzai/commands/positions.md | 12 +- cpzai/commands/price.md | 9 +- cpzai/commands/risk-report.md | 25 ++-- cpzai/commands/strategies.md | 10 +- cpzai/commands/strategy-builder.md | 12 +- cpzai/commands/sync.md | 11 +- cpzai/commands/trade-idea.md | 18 +-- cpzai/commands/trade.md | 23 ++-- cpzai/skills/alpha-research/SKILL.md | 6 +- cpzai/skills/backtesting/SKILL.md | 6 +- cpzai/skills/market-data/SKILL.md | 11 +- cpzai/skills/order-execution/SKILL.md | 4 +- cpzai/skills/portfolio-analytics/SKILL.md | 4 +- cpzai/skills/portfolio-optimization/SKILL.md | 4 +- cpzai/skills/risk-management/SKILL.md | 2 +- cpzai/skills/strategy-development/SKILL.md | 7 +- .../volatility-and-derivatives/SKILL.md | 2 +- tests/run-all.sh | 5 + tests/test_content.py | 115 ++++++++++++++++++ 33 files changed, 400 insertions(+), 179 deletions(-) create mode 100644 tests/test_content.py 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/cpzai/CONNECTORS.md b/cpzai/CONNECTORS.md index 7e55cd0..137f494 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,18 +105,19 @@ 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. -`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. @@ -101,10 +126,10 @@ To opt out (not recommended): set `userConfig.require_trade_confirmation = false `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: ```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-04-30T13:00:13Z","tool":"mcp__plugin_cpzai_cpzai__place_order","ok":true,"input_preview":"{\"symbol\":\"AAPL\",\"quantity\":10,\"side\":\"buy\",\"order_type\":\"market\"}"} ``` -The log persists across plugin updates. Input previews are truncated to 240 characters and never include credentials. +`ok` is false when the tool answered an error, and null when the answer does not say; it is never assumed true. The log persists across plugin updates. Input previews are truncated to 240 characters and never include credentials. ## 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..c9afaf7 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 @@ -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..c286162 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,7 +65,7 @@ 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. | 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..a1cfddd 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. diff --git a/cpzai/commands/portfolio-review.md b/cpzai/commands/portfolio-review.md index d0d591b..d566c48 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. @@ -31,7 +35,8 @@ No arguments needed — pulls the full portfolio from connected accounts. If ~~cpzai is connected: - Call `list_positions` for all open positions -- Call `list_accounts` for account summaries (equity, buying power, margin) +- 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 @@ -48,11 +53,8 @@ PORTFOLIO REVIEW — [Date] Total Equity: $XX,XXX Cash / Buying Power: $XX,XXX (XX% of portfolio) 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) ``` ### 3. Holdings Breakdown @@ -78,20 +80,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..ec4a64f 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. @@ -26,7 +29,8 @@ No arguments needed — pulls all open positions from connected accounts. If ~~cpzai is connected: - Call `list_positions` to get all open positions -- Call `list_accounts` for account-level info (equity, buying power) +- 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: 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..a85fc69 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. @@ -36,9 +40,10 @@ Pull live positions, compute risk metrics, and produce an actionable risk report 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 `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..7cbd966 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. diff --git a/cpzai/commands/sync.md b/cpzai/commands/sync.md index 1ad88f8..2c7d86b 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 +- Total equity across all accounts (`cash_summary` totals; say 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..c8f1376 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. @@ -119,8 +123,8 @@ Sizing methods: 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..117636f 100644 --- a/cpzai/commands/trade.md +++ b/cpzai/commands/trade.md @@ -2,17 +2,20 @@ description: Place a trade — buy or sell stocks, ETFs, or crypto through your connected broker argument-hint: " [order type] [limit 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. @@ -54,7 +57,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 @@ -75,11 +79,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 ``` diff --git a/cpzai/skills/alpha-research/SKILL.md b/cpzai/skills/alpha-research/SKILL.md index 9af5bc9..3937dee 100644 --- a/cpzai/skills/alpha-research/SKILL.md +++ b/cpzai/skills/alpha-research/SKILL.md @@ -302,9 +302,9 @@ This reveals the unique information each signal contributes. If a signal has zer ## CPZAI Tool Chaining for Alpha Research -1. **`get_market_data`** — fetch current and historical prices for signal computation +1. **`get_bars`**: historical prices for signal computation (`get_market_data` is the current quote only) 2. **`list_strategies`** / **`get_strategy`** — review existing strategies and their signal logic -3. **`execute_strategy`** — run a backtest with the new signal +3. **Backtest in CPZAI Strategy Lab** (the user starts the run). No CPZAI tool starts a backtest: runs are started in CPZAI Strategy Lab. Never call `execute_strategy` to backtest; it runs the strategy's code and can submit orders. 4. **`get_backtest_results`** — pull performance metrics (Sharpe, turnover, drawdown) -5. **`compute_risk`** — check factor exposures of the signal-driven portfolio +5. **`compute_risk`**: portfolio risk of the current book (it returns no factor exposures; compute any from `get_bars` and say so) 6. **`create_strategy`** — deploy the validated signal as a new strategy diff --git a/cpzai/skills/backtesting/SKILL.md b/cpzai/skills/backtesting/SKILL.md index 71332c0..0ba8cc0 100644 --- a/cpzai/skills/backtesting/SKILL.md +++ b/cpzai/skills/backtesting/SKILL.md @@ -205,10 +205,10 @@ When ~~cpzai is connected, execute this workflow: 1. **`list_strategies`** — find the strategy to test (filter by name, type, or status) 2. **`get_strategy`** — inspect the strategy's code, parameters, and configuration -3. **`execute_strategy`** — run the backtest with specified date range and parameters -4. **`get_backtest_results`** — pull the full results (returns, Sharpe, drawdown, trade log) +3. **Run it in CPZAI Strategy Lab** (the user starts the run there). No CPZAI tool starts a backtest: runs are started in CPZAI Strategy Lab. Never call `execute_strategy` to backtest; it runs the strategy's code and can submit orders. +4. **`get_backtest_results`** / **`get_backtest_result`**: read the saved runs (returns, Sharpe, drawdown, trade log, configuration) 5. **Analyze:** apply the metrics framework and robustness checks from this skill. Identify overfitting risks, regime sensitivity, and transaction cost impact. 6. **`update_strategy`** — adjust parameters based on findings -7. **Iterate:** repeat steps 3-5 with modified parameters. Compare results across runs to assess parameter sensitivity. +7. **Iterate:** have the user run the modified version in Strategy Lab, then repeat steps 4-5. Compare results across runs to assess parameter sensitivity. **Guardrail:** If testing multiple parameter sets, track all results — not just the best one. Report how many configurations were tested and the distribution of outcomes to avoid selection bias. diff --git a/cpzai/skills/market-data/SKILL.md b/cpzai/skills/market-data/SKILL.md index 1662557..1f273fd 100644 --- a/cpzai/skills/market-data/SKILL.md +++ b/cpzai/skills/market-data/SKILL.md @@ -31,7 +31,7 @@ Real-time best bid and ask prices. The spread (ask - bid) is a direct trading co ### Fundamental Data -Financial statement data (revenue, earnings, margins, balance sheet items). Available quarterly or annually. +Financial statement data (revenue, earnings, margins, balance sheet items). Available quarterly or annually from fundamentals vendors. No CPZAI tool returns it: mark such figures "not available from CPZAI" rather than quoting them from memory. - **Point-in-time:** use the data as it was available on each date (avoids look-ahead bias) - **Restatements:** historical financials can change — point-in-time databases handle this @@ -136,10 +136,11 @@ CPZAI integrates with multiple data providers: When ~~cpzai is connected, execute this workflow: -1. **`get_market_data`** — fetch real-time quotes (price, bid/ask, volume) for target symbols -2. **`list_positions`** — check if any scanned symbols are already in the portfolio -3. **`compute_risk`** — understand current portfolio context before evaluating new opportunities -4. **Synthesize:** apply technical indicator analysis from this skill to the price data. Compare volume to historical averages, assess spread quality, note any data quality issues. +1. **`get_market_data`**: fetch real-time quotes (price, change, bid/ask, volume) for target symbols +2. **`get_bars`**: daily history for the indicators in this skill (moving averages, RSI, relative volume, 52-week range, realized volatility) +3. **`list_positions`**: check if any scanned symbols are already in the portfolio +4. **`compute_risk`**: understand current portfolio context before evaluating new opportunities +5. **Synthesize:** apply technical indicator analysis from this skill to the price data. Compare volume to historical averages, assess spread quality, note any data quality issues. **For multi-symbol scans:** Call `get_market_data` with a batch of symbols (e.g. sector constituents). Sort by the most relevant metric (volume surge, price change, spread). Highlight standouts and cross-reference with portfolio exposure from `list_positions`. diff --git a/cpzai/skills/order-execution/SKILL.md b/cpzai/skills/order-execution/SKILL.md index 090d88b..2310ce3 100644 --- a/cpzai/skills/order-execution/SKILL.md +++ b/cpzai/skills/order-execution/SKILL.md @@ -217,7 +217,7 @@ Available for users who need: When ~~cpzai is connected, execute this workflow: **Pre-trade:** -1. **`list_accounts`** — verify which broker accounts are connected and check buying power +1. **`list_accounts`**: verify the account is `tradable` and in the intended `environment` (paper or live); **`cash_summary`**: its buying power (last sync; unknown if `stale`) 2. **`list_positions`** — check current holdings to avoid duplicates or unintended concentration 3. **`get_market_data`** — get current price, bid/ask spread, and volume for the target symbol 4. **`compute_risk`** — evaluate current portfolio risk before adding new exposure @@ -231,7 +231,7 @@ When ~~cpzai is connected, execute this workflow: 8. **`compute_risk`** — recompute risk metrics to verify the new position hasn't pushed the portfolio outside risk limits **For strategy-driven execution:** -1. **`execute_strategy`** — run the strategy to generate signals +1. **`execute_strategy`**: run the strategy (only when the user has authorized a live run: it can submit orders itself, so check `list_orders` before placing anything by hand) 2. **`list_positions`** — compare current holdings to target portfolio 3. **`place_order`** (multiple) — execute the rebalancing trades 4. **`sync_portfolio`** — reconcile after all orders fill diff --git a/cpzai/skills/portfolio-analytics/SKILL.md b/cpzai/skills/portfolio-analytics/SKILL.md index 743c8b9..9006ccd 100644 --- a/cpzai/skills/portfolio-analytics/SKILL.md +++ b/cpzai/skills/portfolio-analytics/SKILL.md @@ -179,7 +179,7 @@ When ~~cpzai is connected, execute this workflow: 1. **`sync_portfolio`** — force-sync all broker accounts to ensure positions are current 2. **`list_positions`** — get all holdings with quantity, entry price, and current P&L -3. **`list_accounts`** — get account equity, cash, buying power, margin +3. **`cash_summary`**: account equity, cash and buying power as last synced (margin is not available from CPZAI) 4. **`get_market_data`** — fetch current prices for all held symbols (for real-time valuation) 5. **`compute_risk`** — get VaR, Sharpe, Sortino, beta, max drawdown, risk score 6. **`list_risk_snapshots`** — pull 30-day risk history for trend analysis @@ -187,7 +187,7 @@ When ~~cpzai is connected, execute this workflow: **Synthesize:** combine all data into a complete portfolio review: - Compute weights from position values / total equity -- Run attribution analysis (sector decomposition, factor exposure) +- Run attribution by sector where `list_positions` records one (factor exposure is not available from CPZAI) - Compare risk metrics to historical average from snapshots - Flag concentration, correlation, and drawdown concerns - Identify winners/losers and assess holding periods diff --git a/cpzai/skills/portfolio-optimization/SKILL.md b/cpzai/skills/portfolio-optimization/SKILL.md index a907711..9652fe1 100644 --- a/cpzai/skills/portfolio-optimization/SKILL.md +++ b/cpzai/skills/portfolio-optimization/SKILL.md @@ -257,8 +257,8 @@ Add tax costs as asymmetric transaction costs: ## CPZAI Tool Chaining for Portfolio Optimization 1. **`list_positions`** — get current portfolio weights and values -2. **`get_market_data`** — fetch prices for universe + current holdings -3. **`compute_risk`** — get current risk metrics (covariance inputs) +2. **`get_bars`**: daily history for the universe and current holdings: expected returns and the covariance matrix are estimated from it +3. **`compute_risk`**: current portfolio risk summary (VaR, Sharpe, drawdown); it returns no covariance inputs 4. **Run optimization** — apply chosen method (HRP, mean-variance, risk parity) using the data above 5. **`place_order`** — execute the rebalancing trades 6. **`list_risk_snapshots`** — monitor risk before and after rebalancing diff --git a/cpzai/skills/risk-management/SKILL.md b/cpzai/skills/risk-management/SKILL.md index 177441d..b737010 100644 --- a/cpzai/skills/risk-management/SKILL.md +++ b/cpzai/skills/risk-management/SKILL.md @@ -237,7 +237,7 @@ Apply betas and correlations to estimate portfolio impact under each scenario. When ~~cpzai is connected, execute this workflow: 1. **`list_positions`** — get all open positions with market values and entry prices -2. **`list_accounts`** — get account equity, buying power, margin usage +2. **`cash_summary`**: account equity and buying power as last synced (margin usage is not available from CPZAI; `list_accounts` holds no balances) 3. **`get_market_data`** — fetch current prices for all held symbols (for real-time P&L) 4. **`compute_risk`** — trigger a fresh risk computation (VaR, Sharpe, drawdown, beta, risk score) 5. **`list_risk_snapshots`** — pull historical risk data (last 30 snapshots) for trend analysis diff --git a/cpzai/skills/strategy-development/SKILL.md b/cpzai/skills/strategy-development/SKILL.md index 1e330ee..1567879 100644 --- a/cpzai/skills/strategy-development/SKILL.md +++ b/cpzai/skills/strategy-development/SKILL.md @@ -172,7 +172,8 @@ When ~~cpzai is connected, use these tools in sequence: 2. **`get_strategy`** — inspect a specific strategy's configuration and parameters 3. **`create_strategy`** — create a new strategy from generated Python code 4. **`update_strategy`** — modify parameters or code of an existing strategy -5. **`execute_strategy`** — run the strategy on the compute backend (backtest or live) -6. **`get_backtest_results`** — pull performance metrics after execution +5. **`get_backtest_results`**: read the saved backtest runs once the user has run the strategy in CPZAI Strategy Lab -**Workflow:** Design the signal logic using the frameworks above, then call `create_strategy` to deploy it. Follow up with `execute_strategy` to backtest, and `get_backtest_results` to evaluate. Iterate by calling `update_strategy` with refined parameters. +`execute_strategy` runs the strategy's code and can submit orders; it is not a backtest and takes no date range. No CPZAI tool starts a backtest: runs are started in CPZAI Strategy Lab. Never call `execute_strategy` to backtest; it runs the strategy's code and can submit orders. + +**Workflow:** Design the signal logic using the frameworks above, then call `create_strategy` to save it. Ask the user to backtest it in Strategy Lab, and read the result with `get_backtest_results`. Iterate by calling `update_strategy` with refined parameters. diff --git a/cpzai/skills/volatility-and-derivatives/SKILL.md b/cpzai/skills/volatility-and-derivatives/SKILL.md index 6fa426a..a63ecc1 100644 --- a/cpzai/skills/volatility-and-derivatives/SKILL.md +++ b/cpzai/skills/volatility-and-derivatives/SKILL.md @@ -242,7 +242,7 @@ Trade volatility across: ## CPZAI Tool Chaining for Volatility Analysis -1. **`get_market_data`** — fetch current prices and recent history for vol computation +1. **`get_market_data`**: current price of the underlying; **`get_bars`**: its history, for realized volatility. No CPZAI tool returns option chains, implied volatility or Greeks: mark them "not available from CPZAI" unless the user supplies them 2. **`compute_risk`** — get portfolio-level vol, VaR, and beta 3. **`list_positions`** — identify current exposures for Greeks netting 4. **`list_risk_snapshots`** — track vol regime changes over time diff --git a/tests/run-all.sh b/tests/run-all.sh index 06c00e9..e9b1215 100755 --- a/tests/run-all.sh +++ b/tests/run-all.sh @@ -12,6 +12,11 @@ mode="${1:-online}" echo "=== Structure validation ===" python3 tests/validate.py +echo +echo "=== Hook and content tests ===" +python3 tests/test_hooks.py +python3 tests/test_content.py + if [ "$mode" != "--offline" ]; then echo echo "=== Live MCP smoke test ===" diff --git a/tests/test_content.py b/tests/test_content.py new file mode 100644 index 0000000..65ffb2a --- /dev/null +++ b/tests/test_content.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Content checks: commands, skills and agents send Claude to tools that +return what they ask for (cpzai#2797, #2886, #2906, #2909). + +Run: python3 tests/test_content.py +""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PLUGIN = ROOT / "cpzai" +P = "mcp__plugin_cpzai_cpzai__" +FILES = sorted([*PLUGIN.glob("commands/*.md"), *PLUGIN.glob("skills/*/SKILL.md"), *PLUGIN.glob("agents/*.md")]) + + +def text(rel: str) -> 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")) + + +if __name__ == "__main__": + unittest.main(verbosity=2) From 69bf885087775798a50f7173f9443e15ce33b6b3 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:07:40 -0500 Subject: [PATCH 03/10] chore(release): 2.1.0 --- CHANGELOG.md | 13 +++++++++++++ README.md | 16 ++++++++-------- cpzai/.claude-plugin/plugin.json | 2 +- cpzai/.mcp.json | 2 +- cpzai/scripts/session-start.sh | 2 +- 5 files changed, 24 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20129ba..a0d496c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ 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). + +### 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/scripts/session-start.sh b/cpzai/scripts/session-start.sh index 0d9a4ed..086066e 100755 --- a/cpzai/scripts/session-start.sh +++ b/cpzai/scripts/session-start.sh @@ -4,7 +4,7 @@ # 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")" From 2ad8e46b738dea4bd0dc86b25e8cd3835aff1efc Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:31:54 -0500 Subject: [PATCH 04/10] fix(hooks): audit log records refusals, broker order id and status, failed calls and the whole input (cpzai#3024) --- cpzai/CONNECTORS.md | 8 +-- cpzai/hooks/hooks.json | 13 +++- cpzai/scripts/audit-log.sh | 42 ------------ cpzai/scripts/audit_log.py | 130 +++++++++++++++++++++++++++++++++++++ tests/test_hooks.py | 41 +++++++++++- 5 files changed, 184 insertions(+), 50 deletions(-) delete mode 100755 cpzai/scripts/audit-log.sh create mode 100755 cpzai/scripts/audit_log.py diff --git a/cpzai/CONNECTORS.md b/cpzai/CONNECTORS.md index 137f494..5e075c1 100644 --- a/cpzai/CONNECTORS.md +++ b/cpzai/CONNECTORS.md @@ -121,15 +121,15 @@ The default environment is a reminder, not an account check: the order input car 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__plugin_cpzai_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"} ``` -`ok` is false when the tool answered an error, and null when the answer does not say; it is never assumed true. 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/hooks/hooks.json b/cpzai/hooks/hooks.json index 4aa8b52..6412606 100644 --- a/cpzai/hooks/hooks.json +++ b/cpzai/hooks/hooks.json @@ -27,7 +27,18 @@ "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 5795142..0000000 --- a/cpzai/scripts/audit-log.sh +++ /dev/null @@ -1,42 +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 "" -# PostToolUse carries the tool's answer, not a success flag: an MCP error -# result says isError. Anything else is recorded as unknown, never as ok. -resp = d.get("tool_response") if "tool_response" in d else d.get("toolResponse") -if isinstance(resp, dict) and isinstance(resp.get("isError"), bool): - ok = not resp["isError"] -elif isinstance(resp, dict) and resp.get("success") is False: - ok = False -else: - ok = None -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..8d6a0a8 --- /dev/null +++ b/cpzai/scripts/audit_log.py @@ -0,0 +1,130 @@ +#!/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 call failed or the tool answered an + error or a refusal, true when it answered without + one, null when the answer says neither + input the full tool input, with any credential field + (key, secret, token, password) replaced by + "[redacted]"; never cut short + 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|password|passphrase)", re.I) + + +def redact(value): + if isinstance(value, dict): + return {k: ("[redacted]" if SENSITIVE.search(str(k)) else redact(v)) for k, v in value.items()} + if isinstance(value, list): + return [redact(v) for v in value] + return value + + +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 "" + inp = event.get("tool_input") if "tool_input" in event else event.get("toolInput") + rec = {"ts": ts, "event": name, "tool": tool, "ok": None, "input": redact(inp)} + + if name == "PostToolUseFailure": + rec["ok"] = False + 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) + 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), + } + with open(data_dir / "audit.log", "a") as f: + f.write(json.dumps(rec, separators=(",", ":")) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 9ef2eee..17f513f 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -23,7 +23,7 @@ ROOT = Path(__file__).resolve().parent.parent PLUGIN = ROOT / "cpzai" GUARD = PLUGIN / "scripts" / "pre_trade_guard.py" -AUDIT = PLUGIN / "scripts" / "audit-log.sh" +AUDIT = PLUGIN / "scripts" / "audit_log.py" HOOKS = json.loads((PLUGIN / "hooks" / "hooks.json").read_text()) PLUGIN_NAME = "mcp__plugin_cpzai_cpzai__{}" @@ -55,7 +55,7 @@ def matcher(event: str) -> re.Pattern: class HookMatchers(unittest.TestCase): def test_pre_and_post_hooks_match_the_names_claude_code_gives_plugin_tools(self): - for event in ("PreToolUse", "PostToolUse"): + 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}") @@ -127,7 +127,7 @@ 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(["bash", str(AUDIT)], input=json.dumps(event), text=True, env=env, check=True) + 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]) @@ -140,6 +140,41 @@ def test_records_the_outcome_from_the_tool_response_never_assumes_ok(self): 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")) + + def test_a_call_that_failed_outright_is_logged(self): + rec = self.run_audit({"hook_event_name": "PostToolUseFailure", "tool_name": PLUGIN_NAME.format("place_order"), + "tool_input": ORDER, "error": "MCP request timed out"}) + self.assertIs(rec["ok"], False) + self.assertEqual(rec["error"], "MCP request timed out") + + 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) From c20a7921768ad2a01044a8511843b4b1865150a1 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:31:54 -0500 Subject: [PATCH 05/10] fix(skills): risk contributions add up to 100%, risk parity, 17a-4 retention and five more formula fixes (cpzai#3012, #3022, #3023) --- cpzai/commands/backtest.md | 2 +- cpzai/commands/optimize.md | 4 ++-- cpzai/commands/trade-idea.md | 2 +- cpzai/skills/alpha-research/SKILL.md | 4 ++-- cpzai/skills/compliance-and-recordkeeping/SKILL.md | 4 ++-- cpzai/skills/order-execution/SKILL.md | 6 +++--- cpzai/skills/portfolio-optimization/SKILL.md | 10 +++++----- cpzai/skills/risk-management/SKILL.md | 12 ++++++------ cpzai/skills/strategy-development/SKILL.md | 2 +- cpzai/skills/volatility-and-derivatives/SKILL.md | 2 +- 10 files changed, 24 insertions(+), 24 deletions(-) diff --git a/cpzai/commands/backtest.md b/cpzai/commands/backtest.md index c9afaf7..43dd40d 100644 --- a/cpzai/commands/backtest.md +++ b/cpzai/commands/backtest.md @@ -105,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 diff --git a/cpzai/commands/optimize.md b/cpzai/commands/optimize.md index c286162..8be7890 100644 --- a/cpzai/commands/optimize.md +++ b/cpzai/commands/optimize.md @@ -72,7 +72,7 @@ Max Drawdown: XX.X% (current holdings replayed over the bars used) |--------|---------------|----------------|---------------| | ... | 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 @@ -89,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/trade-idea.md b/cpzai/commands/trade-idea.md index c8f1376..77475f7 100644 --- a/cpzai/commands/trade-idea.md +++ b/cpzai/commands/trade-idea.md @@ -117,7 +117,7 @@ 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 diff --git a/cpzai/skills/alpha-research/SKILL.md b/cpzai/skills/alpha-research/SKILL.md index 3937dee..1b1add5 100644 --- a/cpzai/skills/alpha-research/SKILL.md +++ b/cpzai/skills/alpha-research/SKILL.md @@ -60,7 +60,7 @@ Where: - **BR** = Breadth (number of independent bets per year) **Implications:** -- A small IC (0.03) can produce a good IR if breadth is high (500 stocks daily = BR of ~125,000 per year) +- A small IC (0.03) can produce a good IR if breadth is high. Breadth counts independent forecasts, not trades: 500 stocks rebalanced daily on a signal that persists about a month give roughly 500 × 12 = 6,000 independent bets a year (IR ≈ 0.03 × √6,000 ≈ 2.3 before costs), not 500 × 252 - A high IC (0.10) with low breadth (10 bets per year) produces a mediocre IR - This is why systematic strategies that trade many instruments frequently outperform concentrated stock picking on a risk-adjusted basis — even with much weaker per-stock skill @@ -97,7 +97,7 @@ The Spearman rank correlation between your signal values today and the subsequen IR ≈ IC × √BR ``` -Where IR = information ratio, BR = breadth (number of independent bets per year). With IC = 0.03 and BR = 500 (trading 500 stocks daily), IR ≈ 0.03 × √500 ≈ 0.67 — a respectable risk-adjusted return. +Where IR = information ratio, BR = breadth (number of independent bets per year). With IC = 0.03 and BR = 500 (500 stocks, one independent forecast per stock per year), IR ≈ 0.03 × √500 ≈ 0.67. The same IC with forecasts that renew monthly (BR ≈ 6,000) gives IR ≈ 2.3 before costs: count how often the forecasts are genuinely new, not how often the book trades. ### IC Analysis Best Practices diff --git a/cpzai/skills/compliance-and-recordkeeping/SKILL.md b/cpzai/skills/compliance-and-recordkeeping/SKILL.md index a548c52..e16bf5f 100644 --- a/cpzai/skills/compliance-and-recordkeeping/SKILL.md +++ b/cpzai/skills/compliance-and-recordkeeping/SKILL.md @@ -34,7 +34,7 @@ For every order, capture and retain at minimum: | Fill events (price, qty, venue, timestamp) | Best-execution evidence | | Cancellation events (reason, timestamp) | Demonstrate intent and process | -**Retention:** SEC Rule 17a-4 requires registered broker-dealers to keep order records for 6 years (first 2 readily accessible). Retail traders are not subject to 17a-4 directly, but the best practice is still 7 years on tax-deductible activities and indefinitely on long-term investing decisions. +**Retention:** SEC Rule 17a-4(b)(1) requires registered broker-dealers to keep order memoranda (Rule 17a-3(a)(6)) for 3 years, the first 2 in an easily accessible place; blotters and ledgers (17a-3(a)(1) to (3)) are kept 6 years under 17a-4(a). Retail traders are not subject to 17a-4 directly, but the best practice is still 7 years on tax-deductible activities and indefinitely on long-term investing decisions. ## Decision Audit Trail @@ -98,7 +98,7 @@ When changes happen, append to the change log; do not edit prior entries. ### United States -- **SEC Rule 17a-4** (broker-dealers): 6-year order record retention, write-once media or equivalent, designated third-party access in case of failure. +- **SEC Rule 17a-4** (broker-dealers): order memoranda 3 years and blotters and ledgers 6 years (first 2 easily accessible in both cases), write-once media or equivalent, designated third-party access in case of failure. - **FINRA Rule 4511 / 4512**: customer account records, supervisory procedures. - **Reg SHO**: short sale recordkeeping; locate and close-out requirements. - **Reg ATS / Reg NMS**: order routing disclosure for those who route. diff --git a/cpzai/skills/order-execution/SKILL.md b/cpzai/skills/order-execution/SKILL.md index 2310ce3..5b8557b 100644 --- a/cpzai/skills/order-execution/SKILL.md +++ b/cpzai/skills/order-execution/SKILL.md @@ -192,7 +192,7 @@ At each stage, compare actual performance to expected performance. If live Sharp CPZAI's primary broker integration. Supports: - Stocks and ETFs (US markets) -- Market, limit, stop, stop-limit, trailing stop orders +- Market, limit, stop, stop-limit and trailing stop orders at the broker (through CPZAI's `place_order`: market, limit, stop and stop-limit day orders) - Paper and live accounts - Real-time order status via WebSocket - Fractional shares @@ -207,8 +207,8 @@ Available for users who need: ### Order Routing Best Practices -1. Always specify `time_in_force` (day, GTC, IOC, FOK) -2. Use `extended_hours: false` unless you specifically want pre/post-market fills +1. Through CPZAI's `place_order` an order is `market`, `limit`, `stop` or `stop_limit`, with `time_in_force: day` only; `stop` and `stop_limit` need `stop_price`, `limit` and `stop_limit` need `price`, and the size is a share quantity. GTC, IOC, FOK, extended hours, trailing stops and brackets are not available through it: describe them as broker features the user sets at the broker +2. Never resend an order after a timeout or an unclear answer: look for it in `list_orders` first (see /cpzai:trade) 3. For strategies, prefer limit orders with a small buffer above/below current price 4. Monitor order status — don't assume fills; handle rejections and partial fills diff --git a/cpzai/skills/portfolio-optimization/SKILL.md b/cpzai/skills/portfolio-optimization/SKILL.md index 9652fe1..17b4d34 100644 --- a/cpzai/skills/portfolio-optimization/SKILL.md +++ b/cpzai/skills/portfolio-optimization/SKILL.md @@ -53,7 +53,7 @@ Shrink the sample covariance matrix toward a structured target (e.g. constant co ``` Σ_shrunk = δ F + (1-δ) S ``` -Where F = structured target, S = sample covariance, δ = shrinkage intensity (estimated from data). Use `sklearn.covariance.LedoitWolf`. +Where F = structured target, S = sample covariance, δ = shrinkage intensity (estimated from data). `sklearn.covariance.LedoitWolf` uses one target only, the scaled identity (average variance × I), which pulls every correlation toward zero. For a constant-correlation target (Ledoit and Wolf 2004) or a single-factor target (Ledoit and Wolf 2003), build F and estimate δ yourself. **Resampled efficient frontier (Michaud):** 1. Bootstrap many samples from the return distribution @@ -97,8 +97,8 @@ Decompose covariance through a factor model: Where B = N×K factor loading matrix, F = K×K factor covariance, D = N×N diagonal specific variance. **Advantages:** -- Requires estimating K(K+1)/2 + 2N parameters instead of N(N+1)/2 -- For 500 stocks with 10 factors: ~5,500 parameters vs ~125,000 +- Requires estimating N×K loadings + K(K+1)/2 factor covariances + N specific variances instead of N(N+1)/2 +- For 500 stocks with 10 factors: 5,000 + 55 + 500 = 5,555 parameters vs 125,250 - More stable, better conditioned, fewer estimation errors **Construction:** @@ -207,7 +207,7 @@ Allocate so each asset contributes equally to portfolio risk. Find weights such that: `w_i × (Σw)_i / (w'Σw) = 1/N` for all i. -This means each asset's marginal contribution to portfolio volatility is identical. Solved numerically (no closed-form). +This means each asset's total risk contribution (its weight times its marginal contribution) is identical, so each carries 1/N of portfolio risk. Equal *marginal* contributions, `(Σw)_i` the same for every asset, is a different portfolio: the minimum-variance one. Solved numerically (no closed-form). ### Inverse Volatility (Simple Approximation) @@ -215,7 +215,7 @@ This means each asset's marginal contribution to portfolio volatility is identic w_i = (1/σ_i) / Σ(1/σ_j) ``` -Quick approximation that ignores correlations. Works well when correlations are roughly uniform. +Quick approximation that ignores correlations. It gives equal risk contributions exactly only when every pairwise correlation is the same; otherwise use ERC above. ### Leveraged Risk Parity diff --git a/cpzai/skills/risk-management/SKILL.md b/cpzai/skills/risk-management/SKILL.md index b737010..d375902 100644 --- a/cpzai/skills/risk-management/SKILL.md +++ b/cpzai/skills/risk-management/SKILL.md @@ -128,18 +128,18 @@ Allocate risk (not capital) across factors or strategies. **Marginal contribution to risk (MCTR):** ``` -MCTR_i = w_i × (Σw)_i / σ_portfolio +MCTR_i = ∂σ_p / ∂w_i = (Σw)_i / σ_p ``` -The change in portfolio risk from a small increase in position i. Useful for identifying which positions are driving total risk. +The change in portfolio volatility from a small increase in position i (σ_p = √(w'Σw)). -**Component risk:** +**Component risk and percent contribution:** ``` -CR_i = w_i × MCTR_i -Σ CR_i = σ²_portfolio +CR_i = w_i × MCTR_i = w_i (Σw)_i / σ_p Σ CR_i = σ_p +PCR_i = CR_i / σ_p = w_i (Σw)_i / (w'Σw) Σ PCR_i = 100% ``` -Each position's share of total portfolio variance. If one position contributes 40% of risk but only 10% of weight, it's dominating the portfolio's risk profile. +PCR_i is each position's share of total portfolio risk, and the shares add up to 100% (Euler's theorem: σ_p is homogeneous of degree one in w). If one position contributes 40% of risk but only 10% of weight, it's dominating the portfolio's risk profile. **Risk budget target:** set desired risk contribution per position/factor/strategy, then optimize weights to match the budget. diff --git a/cpzai/skills/strategy-development/SKILL.md b/cpzai/skills/strategy-development/SKILL.md index 1567879..135076b 100644 --- a/cpzai/skills/strategy-development/SKILL.md +++ b/cpzai/skills/strategy-development/SKILL.md @@ -156,7 +156,7 @@ Choosing which instruments to trade is as important as the signal itself. Every position gets 1/N of the portfolio. Simple, transparent, avoids concentration. ### Volatility Parity (Risk Parity) -Weight inversely proportional to volatility: `w_i = (1/σ_i) / Σ(1/σ_j)`. Equalizes risk contribution. +Weight inversely proportional to volatility: `w_i = (1/σ_i) / Σ(1/σ_j)`. Equalizes risk contribution only when all pairwise correlations are equal; otherwise it is an approximation, and equal risk contribution needs the ERC solve (see portfolio-optimization). ### Kelly Criterion Optimal sizing: `f = (p * b - q) / b` where p = win probability, b = win/loss ratio, q = 1-p. In practice, use fractional Kelly (0.25-0.5x) to reduce variance. diff --git a/cpzai/skills/volatility-and-derivatives/SKILL.md b/cpzai/skills/volatility-and-derivatives/SKILL.md index a63ecc1..c06feb2 100644 --- a/cpzai/skills/volatility-and-derivatives/SKILL.md +++ b/cpzai/skills/volatility-and-derivatives/SKILL.md @@ -57,7 +57,7 @@ Implied vol varies by strike price: **Equity skew:** OTM puts have higher implied vol than ATM or OTM calls. Reflects demand for downside protection and the empirical fact that equities crash more than they spike. **Skew metrics:** -- **25-delta risk reversal:** IV(25d put) - IV(25d call). Measures skew direction. Negative for equities (puts more expensive). +- **25-delta risk reversal:** IV(25d call) - IV(25d put), the market convention. Measures skew direction. Negative for equities (puts carry higher implied vol). - **25-delta butterfly:** (IV(25d put) + IV(25d call))/2 - IV(ATM). Measures smile curvature (wing richness). **What skew tells you:** From e75003e8b9ccc03a7e8a4c45db24827f0d745890 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:31:55 -0500 Subject: [PATCH 06/10] fix(commands): /trade stop price and no blind resend, /strategy-builder writes Strategy Lab's format, book commands page (cpzai#3013, #3014, #3034, #3037) --- CHANGELOG.md | 8 +++ cpzai/commands/orders.md | 2 +- cpzai/commands/portfolio-review.md | 2 +- cpzai/commands/positions.md | 2 +- cpzai/commands/risk-report.md | 2 +- cpzai/commands/strategy-builder.md | 29 +++++++---- cpzai/commands/trade.md | 27 +++++++--- tests/test_content.py | 84 ++++++++++++++++++++++++++++++ 8 files changed, 133 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0d496c..b0e80f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - 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). + ### Added - `tests/test_hooks.py` and `tests/test_content.py`, run by `tests/run-all.sh` and CI. diff --git a/cpzai/commands/orders.md b/cpzai/commands/orders.md index a1cfddd..619d1d9 100644 --- a/cpzai/commands/orders.md +++ b/cpzai/commands/orders.md @@ -34,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 d566c48..8935edc 100644 --- a/cpzai/commands/portfolio-review.md +++ b/cpzai/commands/portfolio-review.md @@ -34,7 +34,7 @@ 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_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 diff --git a/cpzai/commands/positions.md b/cpzai/commands/positions.md index ec4a64f..d2e51a0 100644 --- a/cpzai/commands/positions.md +++ b/cpzai/commands/positions.md @@ -28,7 +28,7 @@ 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_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 diff --git a/cpzai/commands/risk-report.md b/cpzai/commands/risk-report.md index a85fc69..3516f06 100644 --- a/cpzai/commands/risk-report.md +++ b/cpzai/commands/risk-report.md @@ -39,7 +39,7 @@ 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_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. Its figures are today's holdings replayed over `return_window`: quote `method_note` with them diff --git a/cpzai/commands/strategy-builder.md b/cpzai/commands/strategy-builder.md index 7cbd966..9f8eef9 100644 --- a/cpzai/commands/strategy-builder.md +++ b/cpzai/commands/strategy-builder.md @@ -50,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: - -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 +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". + +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 @@ -71,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/trade.md b/cpzai/commands/trade.md index 117636f..e3c5af4 100644 --- a/cpzai/commands/trade.md +++ b/cpzai/commands/trade.md @@ -1,6 +1,6 @@ --- 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__plugin_cpzai_cpzai__list_accounts - mcp__plugin_cpzai_cpzai__cash_summary @@ -24,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 @@ -68,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]) @@ -102,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/tests/test_content.py b/tests/test_content.py index 65ffb2a..4764d4e 100644 --- a/tests/test_content.py +++ b/tests/test_content.py @@ -111,5 +111,89 @@ def test_options_and_fundamentals_are_named_unavailable(self): 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) + + if __name__ == "__main__": unittest.main(verbosity=2) From 6f6070126397dbf97ed2f89d3618b16dbfc58c43 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 09:47:25 -0500 Subject: [PATCH 07/10] fix(hooks): the guard fails closed on malformed events and unknown names; the banner reads confirm like the guard and flags a missing python3 (review of #2908) --- CHANGELOG.md | 1 + cpzai/CONNECTORS.md | 4 ++- cpzai/scripts/pre_trade_guard.py | 45 +++++++++++++++++++++----------- cpzai/scripts/session-start.sh | 16 ++++++++++-- tests/test_hooks.py | 44 ++++++++++++++++++++++++++++--- 5 files changed, 88 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0e80f0..fa763cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - `/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. diff --git a/cpzai/CONNECTORS.md b/cpzai/CONNECTORS.md index 5e075c1..2961e71 100644 --- a/cpzai/CONNECTORS.md +++ b/cpzai/CONNECTORS.md @@ -115,7 +115,9 @@ allowed-tools: ### 2. PreToolUse safety hook -`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. +`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 `python3`; the session banner shows `guard=OFF` when python3 is missing. + +`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. 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. diff --git a/cpzai/scripts/pre_trade_guard.py b/cpzai/scripts/pre_trade_guard.py index 2bd1839..2af11a6 100755 --- a/cpzai/scripts/pre_trade_guard.py +++ b/cpzai/scripts/pre_trade_guard.py @@ -99,29 +99,44 @@ def describe(tool: str, inp: dict, default_env: str) -> str: return f"CPZAI: {tool} changes your CPZAI account. Approve to run it once." -def main() -> int: - raw = sys.stdin.read() +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 {} - except json.JSONDecodeError: + event = json.loads(raw) if raw.strip() else None + except (json.JSONDecodeError, ValueError): event = None if not isinstance(event, dict): - # Only CPZAI's guarded tools reach this hook; one we cannot read is asked about. - ask("CPZAI safety guard could not read this tool call. Review it before approving.") - return 0 - - name = event.get("tool_name") or event.get("toolName") or "" + 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 0 + 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 0 - - tool = m.group(1) - inp = event.get("tool_input") or event.get("toolInput") or {} + return None + inp = event.get("tool_input") if "tool_input" in event else event.get("toolInput") if not isinstance(inp, dict): inp = {} - ask(describe(tool, inp, option("DEFAULT_ENVIRONMENT", "paper") or "paper")) + 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 diff --git a/cpzai/scripts/session-start.sh b/cpzai/scripts/session-start.sh index 086066e..50b5256 100755 --- a/cpzai/scripts/session-start.sh +++ b/cpzai/scripts/session-start.sh @@ -8,8 +8,20 @@ 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: without python3 neither runs, and the banner says so. +if command -v python3 >/dev/null 2>&1; then + GUARD="on" +else + GUARD="OFF (python3 not found: orders are not asked about and nothing is logged)" + CONFIRM="false" +fi cat < 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 (python3 not found", out) + self.assertIn("confirm=false", out) + + class AuditLog(unittest.TestCase): def run_audit(self, event: dict) -> dict: with tempfile.TemporaryDirectory() as d: From f3f02983b67d769b46700a589320fcd20ff28325 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 10:35:10 -0500 Subject: [PATCH 08/10] fix(hooks): a guard that cannot run blocks the call (onFailure block), and the banner runs python3 instead of trusting command -v (re-review of #2908) --- cpzai/CONNECTORS.md | 2 +- cpzai/hooks/hooks.json | 3 ++- cpzai/scripts/session-start.sh | 9 ++++++--- tests/test_hooks.py | 23 ++++++++++++++++++++++- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/cpzai/CONNECTORS.md b/cpzai/CONNECTORS.md index 2961e71..94539c6 100644 --- a/cpzai/CONNECTORS.md +++ b/cpzai/CONNECTORS.md @@ -115,7 +115,7 @@ allowed-tools: ### 2. PreToolUse safety hook -`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 `python3`; the session banner shows `guard=OFF` when python3 is missing. +`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. diff --git a/cpzai/hooks/hooks.json b/cpzai/hooks/hooks.json index 6412606..656edf0 100644 --- a/cpzai/hooks/hooks.json +++ b/cpzai/hooks/hooks.json @@ -16,7 +16,8 @@ "hooks": [ { "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/pre_trade_guard.py" + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/pre_trade_guard.py", + "onFailure": "block" } ] } diff --git a/cpzai/scripts/session-start.sh b/cpzai/scripts/session-start.sh index 50b5256..6bb84ca 100755 --- a/cpzai/scripts/session-start.sh +++ b/cpzai/scripts/session-start.sh @@ -14,11 +14,14 @@ case "$RAW_CONFIRM" in false|0|no|off) CONFIRM="false" ;; *) CONFIRM="true" ;; esac -# The guard and the audit log are Python: without python3 neither runs, and the banner says so. -if command -v python3 >/dev/null 2>&1; then +# 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 (python3 not found: orders are not asked about and nothing is logged)" + GUARD="OFF (no working python3: CPZAI orders and strategy runs are blocked and nothing is logged)" CONFIRM="false" fi diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 5f99bbb..6a2e02a 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -155,9 +155,30 @@ def test_says_when_python3_is_missing(self): for tool in ("tr", "cat"): os.symlink(shutil.which(tool), os.path.join(d, tool)) out = self.banner(path=d) - self.assertIn("guard=OFF (python3 not found", out) + 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: From 3e53b1c0fedc810513b68a93d3b178f5303b64a1 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 10:39:16 -0500 Subject: [PATCH 09/10] fix(hooks): a failed state-changing call is logged as outcome unknown with is_interrupt and duration; wider redaction; audit.log 0600 (re-review of #3024) --- cpzai/scripts/audit_log.py | 67 +++++++++++++++++++++++++++++++------- tests/test_hooks.py | 41 +++++++++++++++++++++-- 2 files changed, 94 insertions(+), 14 deletions(-) diff --git a/cpzai/scripts/audit_log.py b/cpzai/scripts/audit_log.py index 8d6a0a8..d6e48de 100755 --- a/cpzai/scripts/audit_log.py +++ b/cpzai/scripts/audit_log.py @@ -6,12 +6,17 @@ primary audit source (cpzai#3024). Each record has: ts, event, tool when, PostToolUse or PostToolUseFailure, which tool - ok false when the call failed or the tool answered an - error or a refusal, true when it answered without - one, null when the answer says neither - input the full tool input, with any credential field - (key, secret, token, password) replaced by - "[redacted]"; never cut short + 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 @@ -28,17 +33,40 @@ import sys from pathlib import Path -SENSITIVE = re.compile(r"(key|secret|token|password|passphrase)", re.I) +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): - return {k: ("[redacted]" if SENSITIVE.search(str(k)) else redact(v)) for k, v in value.items()} + 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): @@ -80,13 +108,26 @@ 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": redact(inp)} + rec = {"ts": ts, "event": name, "tool": tool, "ok": None, "input": logged_input(short, inp)} if name == "PostToolUseFailure": - rec["ok"] = False 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") @@ -121,7 +162,11 @@ def main() -> int: # Not the raw event: it can hold a credential (create_connection). "raw_length": len(raw), } - with open(data_dir / "audit.log", "a") as f: + 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 diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 6a2e02a..4279ade 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -216,11 +216,46 @@ def test_an_accepted_order_is_logged_with_the_broker_order_id_and_status(self): self.assertIs(rec["ok"], True) self.assertEqual((rec["order_id"], rec["status"]), ("alp-123", "accepted")) - def test_a_call_that_failed_outright_is_logged(self): + # 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"}) - self.assertIs(rec["ok"], False) + "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} From eec3de949e13154d5f01a83e564e87486b40a738 Mon Sep 17 00:00:00 2001 From: Chris Preuss Date: Wed, 25 Nov 2026 10:41:09 -0500 Subject: [PATCH 10/10] fix(commands): sync, positions and portfolio review show paper and live balances apart, never one total (cpzai#3120) --- cpzai/commands/portfolio-review.md | 6 ++++-- cpzai/commands/positions.md | 6 ++++-- cpzai/commands/sync.md | 2 +- tests/test_content.py | 12 ++++++++++++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/cpzai/commands/portfolio-review.md b/cpzai/commands/portfolio-review.md index 8935edc..84d72bc 100644 --- a/cpzai/commands/portfolio-review.md +++ b/cpzai/commands/portfolio-review.md @@ -50,13 +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 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 | diff --git a/cpzai/commands/positions.md b/cpzai/commands/positions.md index d2e51a0..33d9bde 100644 --- a/cpzai/commands/positions.md +++ b/cpzai/commands/positions.md @@ -41,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/sync.md b/cpzai/commands/sync.md index 2c7d86b..7f22db4 100644 --- a/cpzai/commands/sync.md +++ b/cpzai/commands/sync.md @@ -48,7 +48,7 @@ Last sync: [Timestamp] ### 3. Updated Summary After sync completes, show the refreshed state: -- Total equity across all accounts (`cash_summary` totals; say which accounts have no balance) +- 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/tests/test_content.py b/tests/test_content.py index 4764d4e..5c4a116 100644 --- a/tests/test_content.py +++ b/tests/test_content.py @@ -195,5 +195,17 @@ def test_book_commands_page_until_a_short_page(self): 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)