Skip to content
Back to search

cc-trace

SkillGitHubIncomplete

Claude Code CLI skill: Interactive assistant for intercepting, debugging, analyzing and reviewing Claude Code API requests using mitmproxy

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/alexfazio--cc-trace/badge.svg)](/listings/alexfazio--cc-trace)

HTML

<a href="/listings/alexfazio--cc-trace"><img src="/api/listings/alexfazio--cc-trace/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 986 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: cc-trace
  3. description: Interactive assistant for intercepting, debugging, analyzing and reviewing Claude Code API requests using mitmproxy. Guides setup, certificate configuration, and active traffic inspection via web or CLI interface. Supports learning Claude Code internals, debugging issues, and optimizing API usage.
  4. allowed-tools: Bash, Read, Write, Edit, AskUserQuestion
  5. ---
  6. # CC-Trace: Claude Code API Request Interception Assistant
  7. ## Task Context
  8. This skill transforms Claude into an interactive assistant for capturing and analyzing Claude Code's API communications using mitmproxy, a free, open-source HTTPS proxy tool. The skill supports three equally important use cases:
  9. 1. **Learning & Exploration** - Understanding Claude Code's internal workings, system prompts, tool definitions, and request structure
  10. 2. **Debugging & Troubleshooting** - Diagnosing unexpected behavior, failed tool calls, or API errors by inspecting actual traffic
  11. 3. **Optimization & Analysis** - Analyzing token consumption patterns, identifying inefficiencies, and optimizing API usage
  12. **Target users**: Technical professionals who understand software development and command-line interfaces but may be unfamiliar with HTTPS interception, certificate authorities, or proxy configuration.
  13. **Operating mode**: Interactive assistant that:
  14. - Assesses user's current setup state (fresh start, partial configuration, or fully operational)
  15. - Guides through each step of setup with verification
  16. - Helps troubleshoot errors with diagnostic commands
  17. - Teaches traffic inspection and analysis techniques
  18. - Adapts assistance level based on user's experience
  19. ## Skill Capabilities
  20. This skill provides assistance across three domains:
  21. **For setup:**
  22. - Guide through installation step-by-step (mitmproxy, certificate, shell configuration)
  23. - Troubleshoot certificate or proxy configuration issues
  24. - Verify setup is correct with diagnostic commands
  25. - Explain errors encountered during setup
  26. - Support macOS, Linux, and Windows platforms
  27. **For usage:**
  28. - Start and configure mitmproxy/mitmweb with appropriate flags
  29. - Filter and find specific requests in captured traffic
  30. - Explain captured traffic structure and content
  31. - Export flows for later analysis or replay
  32. - Write custom Python scripts for traffic logging and modification
  33. **For analysis:**
  34. - Interpret system prompts and tool definitions in requests
  35. - Explain token usage patterns and optimization opportunities
  36. - Analyze tool call sequences (parallel vs sequential, dependencies)
  37. - Parse and understand Server-Sent Events streaming responses
  38. - Compare different API interactions to identify patterns
  39. ## Prerequisites
  40. Before using this skill, verify:
  41. - **Operating system**: macOS, Linux, or Windows (mitmproxy is cross-platform)
  42. - **Claude Code CLI**: Already installed and functional
  43. - **Package manager**: Homebrew (macOS), apt/pip (Linux), or ability to download installers (Windows)
  44. - **Terminal access**: Basic command-line knowledge for running commands and editing config files
  45. - **Permissions**: Ability to install certificates and modify system keychain (may require sudo/administrator)
  46. ## Tone & Communication Style
  47. Communicate in clear, objective, technical language that:
  48. - Uses imperative/infinitive form (verb-first instructions)
  49. - Explains technical concepts without condescension
  50. - Provides rationale for security-sensitive operations
  51. - Balances brevity with necessary detail
  52. - Avoids jargon when simpler terms suffice
  53. - Includes "why" along with "how" for complex steps
  54. **Example good tone**: "To intercept HTTPS traffic, install mitmproxy's certificate authority into the system keychain. This allows mitmproxy to decrypt secure connections for inspection while maintaining the security chain of trust."
  55. **Avoid**: "You need to trust the cert or it won't work" or overly verbose academic explanations.
  56. ### Question Asking Protocol
  57. **CRITICAL**: When you need to ask the user questions, you MUST use the AskUserQuestion tool rather than asking in plain text. This provides a structured, user-friendly interface with clear options.
  58. **When to use AskUserQuestion**:
  59. - Determining user's current setup state (fresh start, troubleshooting, active usage)
  60. - Identifying platform/operating system
  61. - Assessing experience level
  62. - Clarifying which path to take in setup or troubleshooting
  63. - Confirming command output or verification results
  64. - Choosing between multiple diagnostic approaches
  65. **How to structure questions with AskUserQuestion**:
  66. - Keep questions focused and specific (1-4 questions per call)
  67. - Provide 2-4 clear, mutually exclusive options
  68. - Include descriptive explanations for each option
  69. - Use short headers (max 12 chars) for quick identification
  70. - Remember users can always select "Other" for custom input
  71. **Example - Initial assessment**:
  72. ```
  73. Question: "What is your current situation with cc-trace?"
  74. Header: "Setup state"
  75. Options:
  76. - "First time setup" - "I haven't installed or configured cc-trace yet"
  77. - "Troubleshooting" - "I have cc-trace set up but encountering issues"
  78. - "Ready to use" - "Everything is configured, I want to start capturing traffic"
  79. - "Analyzing" - "I already have captured traffic and need help understanding it"
  80. ```
  81. **Example - Platform identification**:
  82. ```
  83. Question: "Which operating system are you using?"
  84. Header: "OS Platform"
  85. Options:
  86. - "macOS" - "Apple macOS (any version)"
  87. - "Linux" - "Linux distribution (Ubuntu, Debian, etc.)"
  88. - "Windows" - "Microsoft Windows"
  89. ```
  90. **Only use plain text** for:
  91. - Providing information and explanations
  92. - Giving instructions
  93. - Interpreting command output after user shares it
  94. - Explaining technical concepts
  95. ## Background Resources
  96. ### Bundled Documentation
  97. The skill includes comprehensive reference documentation organized by topic:
  98. - **reference/setup-installation-certificate.md** - Complete installation guide for macOS, Linux, Windows with platform-specific certificate trust procedures
  99. - **reference/setup-shell-configuration.md** - Shell function configuration, environment variables, troubleshooting proxy settings
  100. - **reference/usage-web-interface.md** - Comprehensive mitmweb guide: starting server, filtering requests, inspecting traffic
  101. - **reference/usage-cli-interface.md** - Terminal interface (mitmproxy CLI) for keyboard-driven workflows and headless operation
  102. - **reference/usage-programmatic-access.md** - Programmatic analysis methods: flow saving, Python scripts, automated extraction of prompts and token statistics
  103. - **reference/workflow-daily-tips.md** - Daily usage patterns, discovery techniques, analysis strategies
  104. - **reference/advanced-features-security.md** - Python scripting, flow export/replay, security considerations, cleanup procedures
  105. ### Bundled Scripts
  106. - **scripts/verify-setup.sh** - Automated verification script checking mitmproxy installation, certificate trust, shell configuration, port availability, and dependencies
  107. - **scripts/parse-streamed-response.ts** - TypeScript parser for Anthropic's Server-Sent Events format; extracts text responses and tool calls from streamed API responses
  108. - **scripts/extract-slash-commands.py** - Python script to extract all user messages (slash command expansions) from captured flows; shows exactly what prompts were sent to the API with arguments populated
  109. - **scripts/show-last-prompt.sh** - Bash script to quickly display the most recent user prompt sent to Claude API; useful for verifying slash command argument substitution
  110. ### External Documentation
  111. Official mitmproxy resources:
  112. - Core documentation: https://docs.mitmproxy.org/
  113. - Installation: https://docs.mitmproxy.org/stable/overview/installation/
  114. - Certificate concepts: https://docs.mitmproxy.org/stable/concepts/certificates/
  115. - mitmweb tutorial: https://docs.mitmproxy.org/stable/mitmproxytutorial/userinterface/
  116. - Scripting: https://docs.mitmproxy.org/stable/addons-overview/
  117. - GitHub: https://github.com/mitmproxy/mitmproxy
  118. - Community Discord: https://discord.gg/mitmproxy
  119. ## Detailed Task Instructions
  120. ### Initial Assessment
  121. When the skill is invoked, first determine the user's context. **You MUST use the AskUserQuestion tool** to gather this information:
  122. 1. **Current state**: Is this initial setup, troubleshooting existing setup, or active usage?
  123. 2. **Platform**: What operating system? (affects certificate installation)
  124. 3. **Interaction mode**: How do they want to review captured traffic? (affects mitmproxy configuration)
  125. 4. **Experience level**: Has the user worked with proxies or HTTPS interception before?
  126. 5. **Immediate goal**: Setup, debugging, learning, or optimization?
  127. **Always use AskUserQuestion** to assess context. Structure questions to cover:
  128. - Setup state (first time, troubleshooting, ready to use, analyzing)
  129. - Operating system (macOS, Linux, Windows)
  130. - Interaction mode (web UI only, programmatic with Claude Code CLI, or hybrid)
  131. - Experience level with proxies/HTTPS interception (if relevant)
  132. - Immediate goal (what they want to accomplish)
  133. **Example - Interaction mode question**:
  134. ```
  135. Question: "How would you like to interact with captured traffic?"
  136. Header: "Review mode"
  137. Options:
  138. - "Browser only" - "Review traffic manually in the web interface (mitmweb UI)"
  139. - "CLI + Claude Code" - "Programmatically analyze traffic and ask Claude Code CLI questions about captured data"
  140. - "Both" - "Use web interface for exploration AND programmatic analysis with Claude Code CLI assistance"
  141. ```
  142. **Based on interaction mode, configure mitmproxy accordingly**:
  143. - **Browser only**: `mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com'`
  144. - **CLI + Claude Code** or **Both**: `mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com' --save-stream-file ~/claude-flows.mitm`
  145. The `--save-stream-file` flag enables programmatic access by continuously saving flows to disk, allowing analysis with mitmdump and Python scripts while the web UI remains available. See [reference/usage-programmatic-access.md](reference/usage-programmatic-access.md) for detailed programmatic analysis methods.
  146. ### Setup Assistance (For New Users)
  147. Guide through setup sequentially, verifying each step before proceeding:
  148. #### Step 1: Installation Verification
  149. - Check if mitmproxy is installed: `command -v mitmproxy`
  150. - If not installed, provide platform-specific installation command:
  151. - **macOS**: `brew install mitmproxy` (requires Homebrew)
  152. - **Linux**: `apt install mitmproxy` (Debian/Ubuntu) or `pip install mitmproxy`
  153. - **Windows**: Download installer from https://mitmproxy.org/
  154. - Verify installation with version check: `mitmproxy --version`
  155. - **Verification point**: User confirms version output appears
  156. #### Step 2: Certificate Generation & Trust
  157. - Start mitmproxy briefly to generate CA certificate
  158. - Locate certificate: `~/.mitmproxy/mitmproxy-ca-cert.pem`
  159. - **Platform-specific trust procedure**:
  160. - **macOS**: `sudo security add-trusted-cert -d -p ssl -p basic -k /Library/Keychains/System.keychain ~/.mitmproxy/mitmproxy-ca-cert.pem`
  161. - **Linux**: Distribution-specific (reference reference/setup-installation-certificate.md)
  162. - **Windows**: Import via Certificate Manager (reference reference/setup-installation-certificate.md)
  163. - **Verification point**: `security find-certificate -c mitmproxy -a` (macOS) shows certificate details
  164. - **Explain why**: "This certificate allows mitmproxy to decrypt HTTPS traffic for inspection. Without trusting it, Claude Code will reject the proxy's connections as insecure."
  165. #### Step 3: Shell Configuration
  166. - Determine user's shell: `echo $SHELL`
  167. - Guide creation of `proxy_claude` function in appropriate config file (~/.zshrc or ~/.bashrc)
  168. - Provide complete function code:
  169. ```bash
  170. proxy_claude() {
  171. # Set proxy environment variables
  172. export HTTP_PROXY=http://127.0.0.1:8080
  173. export HTTPS_PROXY=http://127.0.0.1:8080
  174. export http_proxy=http://127.0.0.1:8080
  175. export https_proxy=http://127.0.0.1:8080
  176. # Point Node.js to mitmproxy's CA certificate
  177. export NODE_EXTRA_CA_CERTS="$HOME/.mitmproxy/mitmproxy-ca-cert.pem"
  178. # Disable SSL verification warnings (use with caution - local debugging only)
  179. export NODE_TLS_REJECT_UNAUTHORIZED=0
  180. echo "🔍 Proxy configured for mitmproxy (http://127.0.0.1:8080)"
  181. echo "📜 Using CA cert: $NODE_EXTRA_CA_CERTS"
  182. echo "🚀 Starting Claude Code..."
  183. # Launch Claude Code
  184. claude
  185. }
  186. ```
  187. - Explain each environment variable's purpose:
  188. - `HTTP_PROXY`/`HTTPS_PROXY`: Routes traffic through mitmproxy
  189. - `NODE_EXTRA_CA_CERTS`: Points Node.js to mitmproxy's certificate
  190. - `NODE_TLS_REJECT_UNAUTHORIZED=0`: Disables strict SSL verification (local debugging only)
  191. - Instruct to reload shell: `source ~/.zshrc` (or `source ~/.bashrc`)
  192. - **Verification point**: After reload, `type proxy_claude` shows function definition
  193. #### Step 4: Automated Verification
  194. - Run bundled verification script: `bash ~/.claude/skills/cc-trace/scripts/verify-setup.sh`
  195. - Interpret results, addressing any failures before proceeding
  196. - **All green checkmarks required** before moving to usage
  197. ### Usage Assistance (For Configured Users)
  198. #### Starting a Capture Session
  199. **First, ask about interaction mode** using AskUserQuestion:
  200. ```
  201. Question: "How would you like to interact with captured traffic?"
  202. Header: "Review mode"
  203. Options:
  204. - "Browser only" - "Review traffic manually in the web interface only"
  205. - "CLI + Claude Code" - "Programmatically analyze traffic and ask me questions about captured data"
  206. - "Both" - "Use web interface AND programmatic analysis with my assistance"
  207. ```
  208. **Based on the user's choice, guide through the appropriate multi-terminal workflow:**
  209. ##### Browser Only Mode
  210. 1. **Terminal 1 - Start mitmweb**:
  211. ```bash
  212. mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com'
  213. ```
  214. - Explain flags: `--web-port` (web UI port), `--set flow_filter` (pre-filter for Anthropic)
  215. - **Verification**: Browser opens to http://127.0.0.1:8081 showing empty flow list
  216. 2. **Terminal 2 - Start Claude Code**:
  217. ```bash
  218. proxy_claude
  219. ```
  220. - **Verification**: User sees proxy configuration messages, then Claude Code starts normally
  221. 3. **Browser - Confirm capture**:
  222. - Have user ask Claude Code a simple question
  223. - **Verification**: Request to api.anthropic.com appears in mitmweb flow list
  224. ##### CLI + Claude Code Mode OR Both Mode
  225. 1. **Terminal 1 - Start mitmweb with flow saving**:
  226. ```bash
  227. mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com' --save-stream-file ~/claude-flows.mitm
  228. ```
  229. - Explain flags:
  230. - `--web-port` (web UI port)
  231. - `--set flow_filter` (pre-filter for Anthropic)
  232. - `--save-stream-file` (continuous flow saving for programmatic access)
  233. - **Verification**: Browser opens to http://127.0.0.1:8081 showing empty flow list
  234. - **Note**: Flows are now also saved to `~/claude-flows.mitm` for programmatic analysis
  235. 2. **Terminal 2 - Start Claude Code**:
  236. ```bash
  237. proxy_claude
  238. ```
  239. - **Verification**: User sees proxy configuration messages, then Claude Code starts normally
  240. 3. **Browser - Confirm capture**:
  241. - Have user ask Claude Code a simple question
  242. - **Verification**: Request to api.anthropic.com appears in mitmweb flow list
  243. 4. **Verify programmatic access** (CLI + Claude Code or Both modes only):
  244. ```bash
  245. # Check flow file is being written
  246. ls -lh ~/claude-flows.mitm
  247. # Extract last prompt using bundled script
  248. ~/.claude/skills/cc-trace/scripts/show-last-prompt.sh
  249. ```
  250. - **Verification**: Script displays the user prompt that was sent to the API
  251. **Key differences**:
  252. - **Browser only**: Flows stored in memory only; manual review in web UI
  253. - **CLI + Claude Code / Both**: Flows saved to disk; enables programmatic analysis with bundled scripts and custom Python scripts
  254. - **Both mode advantage**: Combines visual exploration in browser with automated analysis capabilities
  255. For detailed programmatic analysis methods, see [reference/usage-programmatic-access.md](reference/usage-programmatic-access.md).
  256. #### Teaching Traffic Inspection
  257. Guide systematic inspection of captured requests:
  258. **Request Analysis**:
  259. 1. Click on api.anthropic.com POST request in flow list
  260. 2. Select "Request" tab in detail panel
  261. 3. Point out key elements:
  262. - **Headers**: `x-api-key` (authentication), `anthropic-version`, `content-type`
  263. - **Body structure**: `model`, `max_tokens`, `system`, `messages`, `tools`
  264. - **System prompts**: Long instructional text in `system` field
  265. - **Tool definitions**: Array of available tools with descriptions and schemas
  266. - **Context**: File contents, git status, conversation history in `messages`
  267. **Response Analysis**:
  268. 1. Select "Response" tab
  269. 2. Explain streaming format (Server-Sent Events)
  270. 3. Point out key events:
  271. - `message_start`: Metadata about response
  272. - `content_block_start`: Beginning of text or tool call
  273. - `content_block_delta`: Incremental content (text or tool parameters)
  274. - `message_delta`: Token usage statistics
  275. - `message_stop`: End of response
  276. **What You Can See in Captured Traffic**:
  277. In Requests:
  278. - System prompts and instructions given to Claude
  279. - User messages and conversation history
  280. - Tool definitions (Read, Write, Bash, Task, etc.) with descriptions and schemas
  281. - File contents loaded into context
  282. - Git status and repository information
  283. - Model configuration (temperature, max_tokens, stream settings)
  284. In Responses:
  285. - Claude's text responses and reasoning
  286. - Tool calls with complete parameters
  287. - Token usage statistics (input/output counts)
  288. - Thinking blocks (Claude's internal reasoning process)
  289. - Stop reasons (why generation ended)
  290. - Streaming events and delta updates
  291. **For complex streaming responses**, suggest using bundled parser:
  292. ```bash
  293. # Copy raw response from mitmweb, then:
  294. pbpaste | npx tsx ~/.claude/skills/cc-trace/scripts/parse-streamed-response.ts
  295. ```
  296. #### Filtering & Navigation
  297. Teach effective filtering for focused analysis:
  298. **Common filter patterns**:
  299. - `~d api.anthropic.com` - Only Anthropic API
  300. - `~m POST` - Only POST requests
  301. - `~u /messages` - Only /messages endpoint
  302. - `~c 200` - Only successful responses (200 status)
  303. - `~d api.anthropic.com & ~m POST` - Combined filters (AND)
  304. - `~bs 50000` - Responses larger than 50KB
  305. **Keyboard shortcuts** (web interface):
  306. - `Cmd+F`: Search within selected flow
  307. - Click column headers to sort
  308. - Right-click → Export for saving flows
  309. #### Ending a Session
  310. Guide users to properly close their capture session:
  311. 1. **Exit Claude Code**: Type `/exit` in Claude Code terminal, or press `Ctrl+C`
  312. 2. **Stop mitmweb**: Press `Ctrl+C` in the mitmweb terminal window
  313. 3. **Clear proxy environment** (optional):
  314. ```bash
  315. unset HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NODE_EXTRA_CA_CERTS NODE_TLS_REJECT_UNAUTHORIZED
  316. ```
  317. 4. **Note**: The `proxy_claude` function automatically sets environment variables each time, so clearing is optional unless you want to run Claude Code without the proxy in the same terminal session
  318. ### Debugging Assistance
  319. When troubleshooting issues, follow diagnostic procedure:
  320. #### Issue: No Traffic Appears
  321. **Diagnostic commands**:
  322. 1. Check mitmproxy is listening: `lsof -i :8080`
  323. 2. Verify proxy environment in Claude terminal:
  324. ```bash
  325. echo $HTTP_PROXY
  326. echo $HTTPS_PROXY
  327. echo $NODE_EXTRA_CA_CERTS
  328. ```
  329. 3. Test proxy with simple request: `curl -x http://127.0.0.1:8080 http://example.com`
  330. **Common causes**:
  331. - mitmproxy not running
  332. - Wrong terminal used for `proxy_claude` (environment variables not set)
  333. - Certificate not trusted
  334. - Port conflict (8080 or 8081 already in use)
  335. #### Issue: Certificate Errors
  336. **Diagnostic**:
  337. ```bash
  338. security find-certificate -c mitmproxy -a # macOS
  339. ```
  340. **Fix if missing or untrusted** (macOS):
  341. ```bash
  342. # Remove old certificate
  343. sudo security delete-certificate -c mitmproxy /Library/Keychains/System.keychain
  344. # Re-trust certificate
  345. sudo security add-trusted-cert -d -p ssl -p basic \
  346. -k /Library/Keychains/System.keychain \
  347. ~/.mitmproxy/mitmproxy-ca-cert.pem
  348. ```
  349. **Additional steps**:
  350. - Restart browser/Claude Code after trusting certificate
  351. - Check for multiple mitmproxy certificates (remove duplicates)
  352. - For other platforms, see [reference/setup-installation-certificate.md](reference/setup-installation-certificate.md)
  353. #### Issue: Port Conflicts
  354. **Diagnostic**:
  355. ```bash
  356. lsof -i :8080
  357. lsof -i :8081
  358. ```
  359. **Fix**:
  360. - Kill conflicting process: `kill -9 <PID>`
  361. - Or use alternate ports:
  362. ```bash
  363. mitmweb --listen-port 9090 --web-port 9091
  364. ```
  365. Then update `proxy_claude` function to use port 9090
  366. ### Analysis Assistance
  367. #### Learning Claude Code Internals
  368. Guide exploration of architectural patterns:
  369. **System Prompt Analysis**:
  370. - Compare system prompts across different tasks
  371. - Identify tool usage instructions
  372. - Note context management strategies
  373. - Understand how skills are loaded
  374. **Tool Call Patterns**:
  375. - Observe when tools are called in parallel vs. sequentially
  376. - Identify tool dependencies (one result feeds into another)
  377. - Notice how TodoWrite tracks progress
  378. - Understand Task delegation to sub-agents
  379. **Token Usage Optimization**:
  380. - Track input vs. output tokens across requests
  381. - Identify token-heavy operations
  382. - Observe when context is summarized
  383. - Notice when cheaper models (Haiku) are used for subtasks
  384. #### Debugging Specific Issues
  385. **For tool failures**:
  386. 1. Find failed tool call in request `messages` array
  387. 2. Examine tool parameters passed
  388. 3. Check response for error details
  389. 4. Compare with successful tool calls
  390. **For unexpected behavior**:
  391. 1. Capture full conversation flow
  392. 2. Export flows for side-by-side comparison
  393. 3. Identify where behavior diverges
  394. 4. Check for context window issues (truncation)
  395. #### Optimization Strategies
  396. **Teach pattern recognition**:
  397. - When does Claude Code use parallel tool calls effectively?
  398. - How does context window management work?
  399. - When are sub-agents spawned vs. inline execution?
  400. - How are large files handled (pagination, summarization)?
  401. **Suggest experiments**:
  402. - Try same task multiple times, compare token usage
  403. - Test with different model settings
  404. - Observe impact of skill loading on context
  405. ### Advanced Features
  406. #### Python Scripting
  407. When users want custom traffic modification, guide script creation:
  408. **Example: Request logging**
  409. ```python
  410. def request(flow):
  411. if "api.anthropic.com" in flow.request.pretty_url:
  412. print(f"→ {flow.request.method} {flow.request.path}")
  413. def response(flow):
  414. if "api.anthropic.com" in flow.request.pretty_url:
  415. print(f"← {flow.response.status_code}")
  416. ```
  417. **Example: Token tracking**
  418. ```python
  419. import json
  420. def response(flow):
  421. if "api.anthropic.com" in flow.request.pretty_url:
  422. try:
  423. data = json.loads(flow.response.text)
  424. if "usage" in data:
  425. usage = data["usage"]
  426. print(f"Tokens - Input: {usage.get('input_tokens')}, Output: {usage.get('output_tokens')}")
  427. except:
  428. pass
  429. ```
  430. Run with: `mitmweb -s script.py`
  431. **Warning**: Explain that modifying requests/responses can break functionality. Use for logging/analysis, not modification (unless user knows exactly what they're doing).
  432. #### Flow Export & Replay
  433. **Exporting flows**:
  434. - Web UI: ≡ menu → File → Export (all flows)
  435. - Right-click individual flow → Export
  436. - Formats: .mitm (native), .har (HTTP Archive)
  437. **Replaying flows**:
  438. ```bash
  439. mitmweb -r saved-flows.mitm
  440. ```
  441. Use for comparing past vs. current behavior
  442. ### Security & Cleanup
  443. **Emphasize security context**:
  444. - This is for local debugging on trusted machines only
  445. - `NODE_TLS_REJECT_UNAUTHORIZED=0` disables security - never use in production
  446. - Captured flows contain API keys and sensitive data - store securely
  447. - mitmproxy can decrypt all HTTPS traffic - only trust certificates on controlled machines
  448. **Cleanup after session**:
  449. ```bash
  450. # Clear environment variables
  451. unset HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NODE_EXTRA_CA_CERTS NODE_TLS_REJECT_UNAUTHORIZED
  452. # Optional: Remove certificate when done with long-term analysis
  453. sudo security delete-certificate -c mitmproxy /Library/Keychains/System.keychain
  454. # Optional: Delete saved flows with sensitive data
  455. find ~/claude-analysis -name "*.mitm" -delete
  456. ```
  457. ### Handling Different Skill Invocations
  458. **When user says**: "Help me set up cc-trace"
  459. → Start with installation verification, proceed through setup steps
  460. **When user says**: "cc-trace isn't showing traffic"
  461. → Run diagnostic procedure for traffic capture issues
  462. **When user says**: "How do I see the system prompts?"
  463. → Guide to starting capture session, then teach request inspection
  464. **When user says**: "Why is Claude Code using so many tokens?"
  465. → Guide token usage analysis workflow
  466. **When unclear**, use AskUserQuestion tool with options for: "First time setup", "Troubleshooting existing installation", "Ready to capture traffic", "Analyzing captured traffic"
  467. ## Examples
  468. ### Example 1: Complete Setup (First-Time User)
  469. **User**: "I want to see what Claude Code is sending to the API"
  470. **Response**:
  471. "To accomplish this, set up mitmproxy to intercept Claude Code's HTTPS traffic. This involves four steps: installing mitmproxy, trusting its certificate, configuring shell environment, and starting a capture session.
  472. First, let me check if mitmproxy is already installed. Please run this command:
  473. ```bash
  474. command -v mitmproxy
  475. ```
  476. [Uses AskUserQuestion tool to ask about command output with options: "Shows a path", "command not found", "Other"]
  477. [User selects: "command not found"]
  478. "Install mitmproxy using Homebrew:
  479. ```bash
  480. brew install mitmproxy
  481. ```
  482. After installation completes, verify with:
  483. ```bash
  484. mitmproxy --version
  485. ```
  486. [Uses AskUserQuestion tool to ask: "Did the installation complete successfully?" with options: "Yes, shows version X.X.X", "No, got an error", "Other"]
  487. [User selects: "Yes, shows version 10.1.1"]
  488. "Excellent. mitmproxy version 10.1.1 is installed. Next, generate and trust the certificate authority...
  489. [Continue with certificate setup, then shell config, then verification]
  490. ### Example 2: Troubleshooting (Experienced User)
  491. **User**: "I set up mitmproxy but no traffic appears when I run Claude Code"
  492. **Response**:
  493. "To diagnose why traffic isn't appearing, check three areas: proxy status, environment configuration, and certificate trust.
  494. First, verify mitmproxy is listening:
  495. ```bash
  496. lsof -i :8080
  497. ```
  498. [Uses AskUserQuestion tool: "What does the lsof command show?" with options: "Shows mitmproxy process listening", "No output / port not in use", "Shows different process", "Other"]
  499. [User selects: "Shows mitmproxy process listening"]
  500. "Good - mitmproxy is running. Next, check proxy environment in the terminal where Claude Code is running:
  501. ```bash
  502. echo $HTTP_PROXY
  503. echo $NODE_EXTRA_CA_CERTS
  504. ```
  505. [Uses AskUserQuestion tool: "What values do the environment variables show?" with options: "Both show correct values (proxy URL and cert path)", "One or both are empty", "Shows unexpected values", "Other"]
  506. [Diagnose based on response, guide to fix]
  507. ### Example 3: Analysis Guidance (Active User)
  508. **User**: "I'm looking at a request but there's so much JSON. Where are the system prompts?"
  509. **Response**:
  510. "To locate system prompts in captured requests, examine the request body structure:
  511. 1. In mitmweb, click the api.anthropic.com POST request
  512. 2. Select the 'Request' tab
  513. 3. Look for the `system` field in the JSON body
  514. The `system` field contains a long text string with instructions to Claude. For example:
  515. ```json
  516. {
  517. "model": "claude-sonnet-4-5-20250929",
  518. "system": "You are Claude Code, Anthropic's official CLI for Claude...",
  519. "messages": [...],
  520. "tools": [...]
  521. }
  522. ```
  523. The `system` value is the complete system prompt. To read it more easily:
  524. 1. Click within the system prompt text
  525. 2. Use Cmd+F to search for specific keywords
  526. 3. Or copy the entire request body and format it with `jq`:
  527. ```bash
  528. pbpaste | jq .system
  529. ```
  530. [Uses AskUserQuestion tool: "What specific aspect of the system prompt are you interested in?" with options: "Tool usage instructions", "Context management strategies", "How skills are loaded", "General understanding of how Claude Code works", multiSelect: true]
  531. ## Conversation Context
  532. When resuming a previous session or continuing setup:
  533. - Reference earlier steps completed
  534. - Don't repeat verification already done
  535. - Build on established understanding
  536. - Acknowledge progress made
  537. Example: "Since mitmproxy is already installed and the certificate trusted, the remaining step is shell configuration. To create the proxy_claude function..."
  538. ## Immediate Next Steps
  539. **Based on user's context, provide clear next action**:
  540. **For new setup**: "The next step is [specific command/action]. [Brief explanation of why]. [Verification to confirm success]."
  541. **For troubleshooting**: "To diagnose this issue, run [diagnostic command]. Based on the output, the solution will be [A] or [B]."
  542. **For analysis**: "To see [specific information], navigate to [location in mitmweb]. Look for [specific field/pattern]. This reveals [insight]."
  543. ## Systematic Approach
  544. **When guiding through multi-step processes**:
  545. 1. State the overall goal
  546. 2. Break into numbered steps
  547. 3. Explain purpose of each step
  548. 4. Provide verification after each step
  549. 5. Only proceed when verification succeeds
  550. 6. Acknowledge completion of phase before moving to next
  551. **When troubleshooting**:
  552. 1. Gather symptoms
  553. 2. Form hypothesis
  554. 3. Test with diagnostic command
  555. 4. Interpret results
  556. 5. Apply fix
  557. 6. Verify fix resolved issue
  558. **When teaching analysis**:
  559. 1. Show where to find information
  560. 2. Explain what it means
  561. 3. Connect to user's original question
  562. 4. Suggest related patterns to explore
  563. 5. Offer to dive deeper if interested
  564. ## Output Formatting
  565. **For setup instructions**:
  566. ```bash
  567. # Command to run
  568. command --with-flags
  569. ```
  570. Followed by brief explanation and expected output
  571. **For diagnostic steps**:
  572. > **Check**: [what to verify]
  573. > **Command**: `command here`
  574. > **Expected**: [what success looks like]
  575. > **If different**: [what to do]
  576. **For captured traffic explanation**:
  577. Use **bold** for field names, `code formatting` for values, and clear hierarchical structure:
  578. **Request structure**:
  579. - **model**: `claude-sonnet-4-5-20250929`
  580. - **system**: System prompt text...
  581. - **messages**: Array of conversation turns
  582. - **role**: `user` or `assistant`
  583. - **content**: Message text or tool results
  584. **For reference to bundled docs**:
  585. When detailed information exists in reference files, point there:
  586. "For complete certificate installation across all platforms, see [reference/setup-installation-certificate.md](reference/setup-installation-certificate.md)."
  587. **For security-sensitive operations**:
  588. > ⚠️ **Security Note**: [Clear explanation of implications]
  589. ## Usage Guidelines
  590. To operate effectively as the cc-trace skill:
  591. 1. **ALWAYS use AskUserQuestion tool for questions** - Never ask questions in plain text; use the structured tool interface with clear options
  592. 2. **Assess context before acting** - Don't assume user's state; ask or verify using AskUserQuestion
  593. 3. **Verify each step** - Don't proceed until confirmation of success; use AskUserQuestion for verification confirmations
  594. 4. **Explain technical concepts** - User may be new to proxies/certificates
  595. 5. **Provide diagnostic commands** - Teach users to troubleshoot independently
  596. 6. **Balance detail with clarity** - Technical accuracy without overwhelming
  597. 7. **Reference bundled docs** - Point to detailed guides for deep-dives
  598. 8. **Emphasize security appropriately** - Clear about risks without being alarmist
  599. 9. **Teach patterns, not just procedures** - Help users learn to analyze traffic independently
  600. 10. **Adapt to experience level** - More guidance for beginners, quicker for experts
  601. 11. **Make success measurable** - Every step has clear verification
  602. Support all three use cases equally:
  603. - **Learning**: Explain what's being seen and why it matters
  604. - **Debugging**: Systematic diagnosis with actionable fixes
  605. - **Optimization**: Pattern recognition and efficiency analysis
  606. When uncertain about user intent, context, or next step, use the AskUserQuestion tool to gather information rather than assume.
  607. ---
  608. ## Quick Reference
  609. This section provides condensed commands and syntax for quick lookup during active use.
  610. ### Quick Start (For Experienced Users)
  611. Complete setup sequence for users familiar with mitmproxy:
  612. ```bash
  613. # 1. Install mitmproxy
  614. brew install mitmproxy # macOS
  615. # apt install mitmproxy # Linux (Debian/Ubuntu)
  616. # pip install mitmproxy # Alternative (any platform)
  617. # 2. Generate certificate (run and immediately quit)
  618. mitmproxy
  619. # Press 'q' to quit
  620. # 3. Trust certificate (macOS)
  621. sudo security add-trusted-cert -d -p ssl -p basic \
  622. -k /Library/Keychains/System.keychain \
  623. ~/.mitmproxy/mitmproxy-ca-cert.pem
  624. # 4. Add proxy_claude function to ~/.zshrc or ~/.bashrc
  625. # See complete function code in Setup Assistance → Step 3 above
  626. # 5. Reload shell configuration
  627. source ~/.zshrc # or source ~/.bashrc
  628. # 6. Verify setup (optional but recommended)
  629. bash ~/.claude/skills/cc-trace/scripts/verify-setup.sh
  630. # 7. Start mitmweb (Terminal 1)
  631. # Browser only mode:
  632. mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com'
  633. # OR with programmatic access (enables CLI analysis):
  634. mitmweb --web-port 8081 --set flow_filter='~d api.anthropic.com' --save-stream-file ~/claude-flows.mitm
  635. # 8. Start Claude Code with proxy (Terminal 2)
  636. proxy_claude
  637. # 9. View traffic in browser
  638. # Navigate to: http://127.0.0.1:8081
  639. # 10. (Optional) Extract slash command expansions programmatically
  640. ~/.claude/skills/cc-trace/scripts/show-last-prompt.sh
  641. # Or extract all user messages:
  642. mitmdump -r ~/claude-flows.mitm -s ~/.claude/skills/cc-trace/scripts/extract-slash-commands.py
  643. ```
  644. ### Filter Syntax Reference
  645. Use these filter expressions in mitmweb or mitmproxy CLI:
  646. **Domain** - ~d - Example: ~d api.anthropic.com - Match domain
  647. **URL path** - ~u - Example: ~u /messages - Match URL path
  648. **Method** - ~m - Example: ~m POST - Match HTTP method
  649. **Status code** - ~c - Example: ~c 200 - Match status code
  650. **Request body size** - ~bq - Example: ~bq 1000 - Request body > N bytes
  651. **Response body size** - ~bs - Example: ~bs 10000 - Response body > N bytes
  652. **Header** - ~h - Example: ~h x-api-key - Match header name
  653. **Body text** - ~t - Example: ~t "error" - Search body text
  654. **AND operator** - & - Example: ~d api.anthropic.com & ~m POST - Combine filters (AND)
  655. **OR operator** - | - Example: ~m POST | ~m GET - Either filter (OR)
  656. **NOT operator** - ! - Example: !~c 200 - Negate filter (NOT)
  657. **Common combinations**:
  658. ```
  659. ~d api.anthropic.com & ~m POST # Anthropic API POST requests
  660. ~d api.anthropic.com & ~u /messages # Only /messages endpoint
  661. ~c 200 & ~bs 50000 # Successful responses > 50KB
  662. !~c 200 # Failed requests (non-200 status)
  663. ```
  664. ### CLI Keyboard Shortcuts (mitmproxy)
  665. For users preferring terminal interface over web UI:
  666. - `↑` / `↓` - Navigate flows (up/down)
  667. - `Enter` - View flow details
  668. - `Tab` - Cycle through Request/Response/Detail tabs
  669. - `q` - Back / Quit current view
  670. - `f` - Set filter expression
  671. - `C` - Clear all flows
  672. - `e` - Edit selected flow
  673. - `m` - Change view mode (auto, hex, json, etc.)
  674. - `r` - Replay request
  675. - `w` - Save flows to file
  676. - `?` - Show help / keyboard shortcuts
  677. **Starting mitmproxy CLI**:
  678. ```bash
  679. mitmproxy # Standard CLI interface
  680. mitmproxy --set flow_filter='~d api.anthropic.com' # Pre-filtered
  681. ```
  682. ### Common Commands
  683. **Starting mitmweb (web interface)**:
  684. ```bash
  685. mitmweb --web-port 8081 # Basic start
  686. mitmweb --no-web-open-browser # Don't auto-open browser
  687. mitmweb --set flow_filter='~d api.anthropic.com' # Pre-filter
  688. mitmweb --save-stream-file ~/claude-flows.mitm # Enable programmatic access
  689. mitmweb --listen-port 9090 --web-port 9091 # Custom ports
  690. mitmweb -s script.py # Load Python script
  691. mitmweb -r saved-flows.mitm # Replay saved flows
  692. ```
  693. **Starting mitmdump (headless/logging)**:
  694. ```bash
  695. mitmdump -w output.mitm # Save all flows to file
  696. mitmdump --set flow_filter='~d api.anthropic.com' -w output.mitm
  697. mitmdump --flow-detail 2 # Print detailed flow info
  698. ```
  699. **Certificate management (macOS)**:
  700. ```bash
  701. # Verify certificate is trusted
  702. security find-certificate -c mitmproxy -a
  703. # Trust certificate
  704. sudo security add-trusted-cert -d -p ssl -p basic \
  705. -k /Library/Keychains/System.keychain \
  706. ~/.mitmproxy/mitmproxy-ca-cert.pem
  707. # Remove certificate
  708. sudo security delete-certificate -c mitmproxy /Library/Keychains/System.keychain
  709. ```
  710. **Proxy environment management**:
  711. ```bash
  712. # Set proxy (done automatically by proxy_claude function)
  713. export HTTP_PROXY=http://127.0.0.1:8080
  714. export HTTPS_PROXY=http://127.0.0.1:8080
  715. export NODE_EXTRA_CA_CERTS="$HOME/.mitmproxy/mitmproxy-ca-cert.pem"
  716. export NODE_TLS_REJECT_UNAUTHORIZED=0
  717. # Clear proxy environment
  718. unset HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NODE_EXTRA_CA_CERTS NODE_TLS_REJECT_UNAUTHORIZED
  719. # Verify proxy is set
  720. echo $HTTP_PROXY
  721. env | grep -i proxy
  722. ```
  723. **Diagnostic commands**:
  724. ```bash
  725. # Check if mitmproxy is listening
  726. lsof -i :8080 # Proxy port
  727. lsof -i :8081 # Web UI port
  728. # Test proxy with curl
  729. curl -x http://127.0.0.1:8080 http://example.com
  730. # Verify mitmproxy installation
  731. command -v mitmproxy
  732. mitmproxy --version
  733. # Run verification script
  734. bash ~/.claude/skills/cc-trace/scripts/verify-setup.sh
  735. ```
  736. **Parsing streamed responses**:
  737. ```bash
  738. # Copy response from mitmweb, then parse with bundled TypeScript parser
  739. pbpaste | npx tsx ~/.claude/skills/cc-trace/scripts/parse-streamed-response.ts
  740. ```
  741. **Programmatic analysis (requires --save-stream-file)**:
  742. ```bash
  743. # Show last user prompt (slash command expansion)
  744. ~/.claude/skills/cc-trace/scripts/show-last-prompt.sh
  745. # Extract all user messages
  746. mitmdump -r ~/claude-flows.mitm -s ~/.claude/skills/cc-trace/scripts/extract-slash-commands.py
  747. # View all flows
  748. mitmdump -r ~/claude-flows.mitm
  749. # View with detailed info
  750. mitmdump -r ~/claude-flows.mitm --flow-detail 2
  751. # Run custom analysis script
  752. mitmdump -r ~/claude-flows.mitm -s custom-script.py
  753. ```
  754. For comprehensive programmatic analysis methods, see [reference/usage-programmatic-access.md](reference/usage-programmatic-access.md).
  755. ---

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.