claude-code-inspector 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md ADDED
@@ -0,0 +1,241 @@
1
+ # CC Inspector
2
+
3
+ > 🌐 他の言語で読む:[English](README.md) | [简体中文](README.zh.md) | [日本語](README.ja.md)
4
+
5
+ CC Inspector は、Claude Code API リクエストを監視・記録するための開発者向けツールです。プロキシを通じて `/v1/messages` リクエストをインターセプトし、詳細なリクエスト/レスポンスデータを記録し、リアルタイム可視化ダッシュボードを提供します。
6
+
7
+ ## インストール
8
+
9
+ ### npm 経由でインストール(推奨)
10
+
11
+ ```bash
12
+ npm install -g claude-code-inspector
13
+ ```
14
+
15
+ ### ソースコードからインストール
16
+
17
+ ```bash
18
+ git clone https://github.com/devtalker/claude-code-inspector.git
19
+ cd claude-code-inspector
20
+ npm install
21
+ ```
22
+
23
+ ## 機能
24
+
25
+ - **リクエストプロキシ**:Claude Code API リクエストをインターセプトし、アップストリームサーバーに転送
26
+ - **リアルタイムログ**:すべてのリクエストヘッダー、ボディ、レスポンス、ストリーミングイベントを記録
27
+ - **ダッシュボード**:リクエストステータス、トークン使用量、レイテンシ、コストを可視化
28
+ - **WebSocket プッシュ**:新しいリクエストと更新をフロントエンドにリアルタイムプッシュ
29
+ - **データ永続化**:すべてのリクエストログを SQLite に保存
30
+ - **エクスポート機能**:リクエストデータを JSON または CSV 形式でエクスポート
31
+ - **トークン統計**:入力/出力トークンとキャッシュ使用量を自動計算
32
+ - **コスト見積もり**:モデル価格に基づいてリクエストあたりのコストを計算
33
+
34
+ ## 技術スタック
35
+
36
+ - **フレームワーク**:Next.js 16 + React 19
37
+ - **言語**:TypeScript
38
+ - **データベース**:SQLite (better-sqlite3)
39
+ - **WebSocket**:ws
40
+ - **スタイリング**:Tailwind CSS 4
41
+ - **テスト**:Vitest
42
+
43
+ ## クイックスタート
44
+
45
+ ### 方法 1: npm パッケージを使用(推奨)
46
+
47
+ インストール後、`cc-inspector` コマンドでサービスを起動します:
48
+
49
+ ```bash
50
+ # サービスを起動
51
+ cc-inspector
52
+ ```
53
+
54
+ 起動後にアクセス:
55
+ - **ダッシュボード**:http://localhost:3000/dashboard
56
+ - **ホーム**:http://localhost:3000
57
+
58
+ ### 方法 2: ソースコードから実行
59
+
60
+ **要件:**
61
+ - Node.js 18+
62
+ - npm / yarn / pnpm
63
+
64
+ **依存関係のインストール:**
65
+
66
+ ```bash
67
+ npm install
68
+ ```
69
+
70
+ **開発サーバーの起動:**
71
+
72
+ ```bash
73
+ npm run dev
74
+ ```
75
+
76
+ アクセス:
77
+ - **ダッシュボード**:http://localhost:3000/dashboard
78
+ - **ホーム**:http://localhost:3000
79
+
80
+ ### 環境変数の設定
81
+
82
+ CC Inspector は、リクエストを転送する LLM サービスプロバイダーを知る必要があります。2 つの設定方法があります:
83
+
84
+ **方法 1: Claude Code グローバル設定で設定(npm パッケージユーザーに推奨)**
85
+
86
+ `~/.claude/settings.json` を編集:
87
+
88
+ ```json
89
+ {
90
+ "env": {
91
+ "UPSTREAM_BASE_URL": "https://api.anthropic.com",
92
+ "UPSTREAM_API_KEY": "your-api-key"
93
+ }
94
+ }
95
+ ```
96
+
97
+ **方法 2: `.env.local` ファイルを作成(ソースコード実行ユーザー向け)**
98
+
99
+ ```bash
100
+ # .env.local
101
+ UPSTREAM_BASE_URL=https://api.anthropic.com # アップストリーム API ベース URL
102
+ UPSTREAM_API_KEY=your-api-key # アップストリーム API キー
103
+ ```
104
+
105
+ > 注意:`UPSTREAM_BASE_URL` が設定されていない場合、プログラムは自動的に `ANTHROPIC_BASE_URL` の値を使用します。
106
+
107
+ ### Claude Code のプロキシ設定
108
+
109
+ CC Inspector を起動した後、Claude Code が Anthropic API に直接送信する代わりに、プロキシサーバーにリクエストを送信するように設定する必要があります。
110
+
111
+ Claude Code で以下のコマンドを実行して baseURL を設定:
112
+
113
+ ```bash
114
+ /mcp set anthropic_base_url http://localhost:3000/api/proxy
115
+ ```
116
+
117
+ または、`~/.claude/settings.json` を手動で編集:
118
+
119
+ ```json
120
+ {
121
+ "anthropic_base_url": "http://localhost:3000/api/proxy"
122
+ }
123
+ ```
124
+
125
+ 設定後、Claude Code からのすべての API リクエストは CC Inspector を経由し、その後アップストリーム API に転送されます。
126
+
127
+ **設定の確認:**
128
+
129
+ 1. CC Inspector を起動:`cc-inspector` または `npm run dev`
130
+ 2. ダッシュボードにアクセス:http://localhost:3000/dashboard
131
+ 3. Claude Code で任意のリクエストを実行
132
+ 4. ダッシュボードに新しいリクエストレコードが表示されるはずです
133
+
134
+ ## プロジェクト構成
135
+
136
+ ```
137
+ claude-code-inspector/
138
+ ├── app/ # Next.js App Router
139
+ │ ├── dashboard/ # 監視ダッシュボードページ
140
+ │ ├── api/ # API ルート
141
+ │ │ ├── proxy/ # プロキシエンドポイント
142
+ │ │ ├── requests/ # リクエストログ API
143
+ │ │ └── events/ # SSE イベント API
144
+ │ └── v1/messages/ # 元のメッセージエンドポイント
145
+ ├── lib/ # コアロジックライブラリ
146
+ │ ├── proxy/ # プロキシフォワーダー
147
+ │ │ ├── handlers.ts # リクエストハンドラー
148
+ │ │ ├── forwarder.ts # フォワーダー
149
+ │ │ └── ws-server.ts # WebSocket サーバー
150
+ │ └── recorder/ # データレコーダー
151
+ │ ├── index.ts # レコーダーエントリー
152
+ │ ├── store.ts # SQLite ストレージ
153
+ │ └── schema.ts # データベーススキーマ
154
+ ├── components/ # React コンポーネント
155
+ │ ├── JsonViewer.tsx # JSON ビューワー
156
+ │ └── JsonModal.tsx # JSON モーダル
157
+ ├── db/ # SQLite データベースファイル
158
+ └── server.ts # カスタムサーバー(WebSocket + Next.js)
159
+ ```
160
+
161
+ ## API エンドポイント
162
+
163
+ | エンドポイント | メソッド | 説明 |
164
+ |--------------|--------|------|
165
+ | `/api/proxy` | POST | リクエストをプロキシし、アップストリームに転送 |
166
+ | `/api/requests` | GET | 最近のリクエストログを取得 |
167
+ | `/api/requests/:id` | GET | 単一リクエストの詳細を取得 |
168
+ | `/api/requests/export` | GET | リクエストデータをエクスポート(JSON/CSV) |
169
+ | `/api/events` | GET | SSE イベントストリーム |
170
+ | `/api/ws` | WebSocket | リアルタイムプッシュ接続 |
171
+
172
+ ## データモデル
173
+
174
+ リクエストログには以下のフィールドが含まれます:
175
+
176
+ - `id`: 一意のリクエスト識別子
177
+ - `session_id`: セッション識別子
178
+ - `endpoint`: リクエストエンドポイント
179
+ - `method`: HTTP メソッド
180
+ - `request_headers/body`: リクエストヘッダーとボディ
181
+ - `response_status/body/headers`: レスポンスステータス、ボディ、ヘッダー
182
+ - `streaming_events`: SSE ストリーミングイベント
183
+ - `input_tokens/output_tokens`: 入力/出力トークン
184
+ - `cache_read_tokens/cache_creation_tokens`: キャッシュ読み取り/作成トークン
185
+ - `latency_ms`: リクエストレイテンシ(ミリ秒)
186
+ - `first_token_ms`: 初回トークン時間(ミリ秒)
187
+ - `model`: 使用されたモデル
188
+ - `cost_usd`: 推定コスト(USD)
189
+ - `error_message`: エラーメッセージ(ある場合)
190
+
191
+ ## スクリプト
192
+
193
+ **ソースコード実行ユーザー:**
194
+
195
+ ```bash
196
+ # 開発
197
+ npm run dev # 開発サーバーを起動
198
+
199
+ # ビルドと実行
200
+ npm run build # 本番バージョンをビルド
201
+ npm run start # 本番サーバーを起動
202
+
203
+ # テストとチェック
204
+ npm run test # テストを実行
205
+ npm run lint # ESLint チェック
206
+ ```
207
+
208
+ **npm パッケージユーザー:**
209
+
210
+ ```bash
211
+ cc-inspector # サービスを起動
212
+ ```
213
+
214
+ ## データベース
215
+
216
+ データは `db/inspector.sqlite` に保存され、以下のテーブルを含みます:
217
+
218
+ - `request_logs`: リクエストログテーブル
219
+ - `settings`: 設定テーブル
220
+
221
+ ## 注意事項
222
+
223
+ 1. **WebSocket**:本番環境では `wss://` 接続を使用してください
224
+ 2. **プロキシモード**:Claude Code がプロキシエンドポイントを使用するように設定されていることを確認してください
225
+ 3. **トークン計算**:コスト見積もりは公式価格に基づく参考値です
226
+
227
+ ## 開発
228
+
229
+ ### テストの実行
230
+
231
+ ```bash
232
+ npm run test
233
+ ```
234
+
235
+ ### デバッグ
236
+
237
+ サーバーログはすべてのリクエストと WebSocket 接続情報を出力します。コンソール出力を確認するか、`db/inspector.sqlite` を使用してデータベースを直接クエリしてください。
238
+
239
+ ## ライセンス
240
+
241
+ MIT
package/README.md CHANGED
@@ -1,63 +1,89 @@
1
1
  # CC Inspector
2
2
 
3
- CC Inspector 是一个用于监控和记录 Claude Code API 请求的开发者工具。它通过代理拦截 `/v1/messages` 请求,记录详细的请求/响应数据,并提供实时可视化面板。
3
+ > 🌐 Read in other languages: [English](README.md) | [简体中文](README.zh.md) | [日本語](README.ja.md)
4
4
 
5
- ## 功能特性
5
+ CC Inspector is a developer tool for monitoring and logging Claude Code API requests. It intercepts `/v1/messages` requests through a proxy, records detailed request/response data, and provides a real-time visualization dashboard.
6
6
 
7
- - **请求代理**: 拦截并转发 Claude Code API 请求到上游服务器
8
- - **实时日志**: 记录所有请求的 headers、body、response 和 streaming events
9
- - **监控面板**: 可视化展示请求状态、tokens 使用量、延迟和成本
10
- - **WebSocket 推送**: 实时推送新请求和更新到前端
11
- - **数据持久化**: 使用 SQLite 存储所有请求日志
12
- - **导出功能**: 支持 JSON 和 CSV 格式导出请求数据
13
- - **Token 统计**: 自动计算 input/output tokens 和缓存使用量
14
- - **成本估算**: 根据模型自动计算每次请求的成本
7
+ ## Installation
15
8
 
16
- ## 技术栈
9
+ ### Install via npm (Recommended)
17
10
 
18
- - **框架**: Next.js 16 + React 19
19
- - **语言**: TypeScript
20
- - **数据库**: SQLite (better-sqlite3)
11
+ ```bash
12
+ npm install -g claude-code-inspector
13
+ ```
14
+
15
+ ### Install from Source
16
+
17
+ ```bash
18
+ git clone https://github.com/devtalker/claude-code-inspector.git
19
+ cd claude-code-inspector
20
+ npm install
21
+ ```
22
+
23
+ ## Features
24
+
25
+ - **Request Proxy**: Intercept and forward Claude Code API requests to upstream servers
26
+ - **Real-time Logging**: Record all request headers, body, response, and streaming events
27
+ - **Dashboard**: Visualize request status, token usage, latency, and costs
28
+ - **WebSocket Push**: Real-time push of new requests and updates to the frontend
29
+ - **Data Persistence**: Store all request logs in SQLite
30
+ - **Export Functionality**: Export request data in JSON or CSV format
31
+ - **Token Statistics**: Automatically calculate input/output tokens and cache usage
32
+ - **Cost Estimation**: Calculate cost per request based on model pricing
33
+
34
+ ## Tech Stack
35
+
36
+ - **Framework**: Next.js 16 + React 19
37
+ - **Language**: TypeScript
38
+ - **Database**: SQLite (better-sqlite3)
21
39
  - **WebSocket**: ws
22
- - **样式**: Tailwind CSS 4
23
- - **测试**: Vitest
40
+ - **Styling**: Tailwind CSS 4
41
+ - **Testing**: Vitest
42
+
43
+ ## Quick Start
44
+
45
+ ### Option 1: Using npm Package (Recommended)
24
46
 
25
- ## 快速开始
47
+ After installation, start the service using the `cc-inspector` command:
26
48
 
27
- ### 环境要求
49
+ ```bash
50
+ # Start the service
51
+ cc-inspector
52
+ ```
28
53
 
54
+ After the service starts, access:
55
+ - **Dashboard**: http://localhost:3000/dashboard
56
+ - **Home**: http://localhost:3000
57
+
58
+ ### Option 2: Running from Source
59
+
60
+ **Requirements:**
29
61
  - Node.js 18+
30
62
  - npm / yarn / pnpm
31
63
 
32
- ### 安装依赖
64
+ **Install dependencies:**
33
65
 
34
66
  ```bash
35
67
  npm install
36
68
  ```
37
69
 
38
- ### 启动开发服务器
70
+ **Start development server:**
39
71
 
40
72
  ```bash
41
73
  npm run dev
42
74
  ```
43
75
 
44
- 访问以下地址:
76
+ Access:
45
77
  - **Dashboard**: http://localhost:3000/dashboard
46
- - **首页**: http://localhost:3000
78
+ - **Home**: http://localhost:3000
47
79
 
48
- ### 配置 LLM 服务 API
80
+ ### Configure Environment Variables
49
81
 
50
- CC Inspector 需要知道将请求转发到哪个 LLM 服务提供商。配置方式有两种:
82
+ CC Inspector needs to know which LLM service provider to forward requests to. There are two configuration methods:
51
83
 
52
- **方式 1:在项目根目录创建 `.env.local` 文件**
84
+ **Option 1: Configure in Claude Code global settings (Recommended for npm package users)**
53
85
 
54
- ```bash
55
- # .env.local
56
- UPSTREAM_BASE_URL=https://api.anthropic.com # 上游 API 基础 URL
57
- UPSTREAM_API_KEY=your-api-key # 上游 API Key
58
- ```
59
-
60
- **方式 2:在 Claude Code 全局配置中设置 (`~/.claude/settings.json`)**
86
+ Edit `~/.claude/settings.json`:
61
87
 
62
88
  ```json
63
89
  {
@@ -68,19 +94,27 @@ UPSTREAM_API_KEY=your-api-key # 上游 API Key
68
94
  }
69
95
  ```
70
96
 
71
- > 注意:如果未设置 `UPSTREAM_BASE_URL`,程序会自动使用 `ANTHROPIC_BASE_URL` 的值。
97
+ **Option 2: Create `.env.local` file (For source running users)**
72
98
 
73
- ### 配置 Claude Code 使用代理
99
+ ```bash
100
+ # .env.local
101
+ UPSTREAM_BASE_URL=https://api.anthropic.com # Upstream API base URL
102
+ UPSTREAM_API_KEY=your-api-key # Upstream API Key
103
+ ```
104
+
105
+ > Note: If `UPSTREAM_BASE_URL` is not set, the program will automatically use the value of `ANTHROPIC_BASE_URL`.
74
106
 
75
- CC Inspector 启动后,需要让 Claude Code 将请求发送到代理服务器而不是直接发送到 Anthropic API。
107
+ ### Configure Claude Code to Use Proxy
76
108
 
77
- Claude Code 中执行以下命令配置 baseURL:
109
+ After starting CC Inspector, you need to configure Claude Code to send requests to the proxy server instead of directly to Anthropic API.
110
+
111
+ Run the following command in Claude Code to configure baseURL:
78
112
 
79
113
  ```bash
80
114
  /mcp set anthropic_base_url http://localhost:3000/api/proxy
81
115
  ```
82
116
 
83
- 或者手动编辑 `~/.claude/settings.json`:
117
+ Or manually edit `~/.claude/settings.json`:
84
118
 
85
119
  ```json
86
120
  {
@@ -88,111 +122,119 @@ CC Inspector 启动后,需要让 Claude Code 将请求发送到代理服务器
88
122
  }
89
123
  ```
90
124
 
91
- 配置完成后,Claude Code 的所有 API 请求都会先经过 CC Inspector,然后转发到上游 API
125
+ After configuration, all API requests from Claude Code will go through CC Inspector and then be forwarded to the upstream API.
92
126
 
93
- **验证配置:**
127
+ **Verify Configuration:**
94
128
 
95
- 1. 启动 CC Inspector:`npm run dev`
96
- 2. 访问 Dashboardhttp://localhost:3000/dashboard
97
- 3. Claude Code 中发起任意请求
98
- 4. Dashboard 应显示新请求的记录
129
+ 1. Start CC Inspector: `cc-inspector` or `npm run dev`
130
+ 2. Access Dashboard: http://localhost:3000/dashboard
131
+ 3. Make any request in Claude Code
132
+ 4. Dashboard should display the new request record
99
133
 
100
- ## 项目结构
134
+ ## Project Structure
101
135
 
102
136
  ```
103
- cc-inspector/
137
+ claude-code-inspector/
104
138
  ├── app/ # Next.js App Router
105
- │ ├── dashboard/ # 监控面板页面
106
- │ ├── api/ # API 路由
107
- │ │ ├── proxy/ # 代理端点
108
- │ │ ├── requests/ # 请求日志 API
109
- │ │ └── events/ # SSE 事件 API
110
- │ └── v1/messages/ # 原始消息端点
111
- ├── lib/ # 核心逻辑库
112
- │ ├── proxy/ # 代理转发器
113
- │ │ ├── handlers.ts # 请求处理器
114
- │ │ ├── forwarder.ts # 转发器
115
- │ │ └── ws-server.ts # WebSocket 服务器
116
- │ └── recorder/ # 数据记录器
117
- │ ├── index.ts # 记录器入口
118
- │ ├── store.ts # SQLite 存储
119
- │ └── schema.ts # 数据库 Schema
120
- ├── components/ # React 组件
121
- │ ├── JsonViewer.tsx # JSON 查看器
122
- │ └── JsonModal.tsx # JSON 模态框
123
- ├── db/ # SQLite 数据库文件
124
- └── server.ts # 自定义服务器(WebSocket + Next.js
139
+ │ ├── dashboard/ # Monitoring dashboard page
140
+ │ ├── api/ # API routes
141
+ │ │ ├── proxy/ # Proxy endpoint
142
+ │ │ ├── requests/ # Request logs API
143
+ │ │ └── events/ # SSE events API
144
+ │ └── v1/messages/ # Original messages endpoint
145
+ ├── lib/ # Core logic library
146
+ │ ├── proxy/ # Proxy forwarder
147
+ │ │ ├── handlers.ts # Request handlers
148
+ │ │ ├── forwarder.ts # Forwarder
149
+ │ │ └── ws-server.ts # WebSocket server
150
+ │ └── recorder/ # Data recorder
151
+ │ ├── index.ts # Recorder entry
152
+ │ ├── store.ts # SQLite storage
153
+ │ └── schema.ts # Database schema
154
+ ├── components/ # React components
155
+ │ ├── JsonViewer.tsx # JSON viewer
156
+ │ └── JsonModal.tsx # JSON modal
157
+ ├── db/ # SQLite database files
158
+ └── server.ts # Custom server (WebSocket + Next.js)
125
159
  ```
126
160
 
127
- ## API 端点
128
-
129
- | 端点 | 方法 | 描述 |
130
- |------|------|------|
131
- | `/api/proxy` | POST | 代理转发请求到上游 |
132
- | `/api/requests` | GET | 获取最近的请求日志 |
133
- | `/api/requests/:id` | GET | 获取单个请求详情 |
134
- | `/api/requests/export` | GET | 导出请求数据(JSON/CSV |
135
- | `/api/events` | GET | SSE 事件流 |
136
- | `/api/ws` | WebSocket | 实时推送连接 |
137
-
138
- ## 数据模型
139
-
140
- 请求日志包含以下字段:
141
-
142
- - `id`: 请求唯一标识
143
- - `session_id`: 会话标识
144
- - `endpoint`: 请求端点
145
- - `method`: HTTP 方法
146
- - `request_headers/body`: 请求头和请求体
147
- - `response_status/body/headers`: 响应状态、响应体和响应头
148
- - `streaming_events`: SSE 流式事件
149
- - `input_tokens/output_tokens`: 输入/输出 tokens
150
- - `cache_read_tokens/cache_creation_tokens`: 缓存读取/创建 tokens
151
- - `latency_ms`: 请求延迟(毫秒)
152
- - `first_token_ms`: token 时间(毫秒)
153
- - `model`: 使用的模型
154
- - `cost_usd`: 估算成本(美元)
155
- - `error_message`: 错误信息(如有)
156
-
157
- ## 脚本命令
161
+ ## API Endpoints
162
+
163
+ | Endpoint | Method | Description |
164
+ |----------|--------|-------------|
165
+ | `/api/proxy` | POST | Proxy and forward requests to upstream |
166
+ | `/api/requests` | GET | Get recent request logs |
167
+ | `/api/requests/:id` | GET | Get single request details |
168
+ | `/api/requests/export` | GET | Export request data (JSON/CSV) |
169
+ | `/api/events` | GET | SSE event stream |
170
+ | `/api/ws` | WebSocket | Real-time push connection |
171
+
172
+ ## Data Model
173
+
174
+ Request logs include the following fields:
175
+
176
+ - `id`: Unique request identifier
177
+ - `session_id`: Session identifier
178
+ - `endpoint`: Request endpoint
179
+ - `method`: HTTP method
180
+ - `request_headers/body`: Request headers and body
181
+ - `response_status/body/headers`: Response status, body, and headers
182
+ - `streaming_events`: SSE streaming events
183
+ - `input_tokens/output_tokens`: Input/output tokens
184
+ - `cache_read_tokens/cache_creation_tokens`: Cache read/creation tokens
185
+ - `latency_ms`: Request latency (milliseconds)
186
+ - `first_token_ms`: First token time (milliseconds)
187
+ - `model`: Model used
188
+ - `cost_usd`: Estimated cost (USD)
189
+ - `error_message`: Error message (if any)
190
+
191
+ ## Scripts
192
+
193
+ **For source running users:**
158
194
 
159
195
  ```bash
160
- # 开发
161
- npm run dev # 启动开发服务器
196
+ # Development
197
+ npm run dev # Start development server
162
198
 
163
- # 构建和运行
164
- npm run build # 构建生产版本
165
- npm run start # 启动生产服务器
199
+ # Build and run
200
+ npm run build # Build production version
201
+ npm run start # Start production server
166
202
 
167
- # 测试和检查
168
- npm run test # 运行测试
169
- npm run lint # ESLint 检查
203
+ # Testing and checking
204
+ npm run test # Run tests
205
+ npm run lint # ESLint check
206
+ ```
207
+
208
+ **For npm package users:**
209
+
210
+ ```bash
211
+ cc-inspector # Start service
170
212
  ```
171
213
 
172
- ## 数据库
214
+ ## Database
173
215
 
174
- 数据存储在 `db/inspector.sqlite`,包含以下表:
216
+ Data is stored in `db/inspector.sqlite`, containing the following tables:
175
217
 
176
- - `request_logs`: 请求日志
177
- - `settings`: 配置设置
218
+ - `request_logs`: Request logs
219
+ - `settings`: Configuration settings
178
220
 
179
- ## 注意事项
221
+ ## Notes
180
222
 
181
- 1. **WebSocket**: 生产环境建议使用 `wss://` 连接
182
- 2. **代理模式**: 确保 Claude Code 配置为使用代理端点
183
- 3. **Token 计算**: 成本估算基于官方定价,仅供参考
223
+ 1. **WebSocket**: Use `wss://` connection in production environment
224
+ 2. **Proxy Mode**: Ensure Claude Code is configured to use the proxy endpoint
225
+ 3. **Token Calculation**: Cost estimation is based on official pricing and is for reference only
184
226
 
185
- ## 开发
227
+ ## Development
186
228
 
187
- ### 运行测试
229
+ ### Run Tests
188
230
 
189
231
  ```bash
190
232
  npm run test
191
233
  ```
192
234
 
193
- ### 调试
235
+ ### Debugging
194
236
 
195
- 服务器日志会输出所有请求和 WebSocket 连接信息。查看控制台输出或使用 `db/inspector.sqlite` 直接查询数据库。
237
+ Server logs output all request and WebSocket connection information. Check console output or query the database directly using `db/inspector.sqlite`.
196
238
 
197
239
  ## License
198
240
 
package/README.zh.md ADDED
@@ -0,0 +1,241 @@
1
+ # CC Inspector
2
+
3
+ > 🌐 其他语言版本:[English](README.md) | [简体中文](README.zh.md) | [日本語](README.ja.md)
4
+
5
+ CC Inspector 是一个用于监控和记录 Claude Code API 请求的开发者工具。它通过代理拦截 `/v1/messages` 请求,记录详细的请求/响应数据,并提供实时可视化仪表板。
6
+
7
+ ## 安装
8
+
9
+ ### 通过 npm 安装(推荐)
10
+
11
+ ```bash
12
+ npm install -g claude-code-inspector
13
+ ```
14
+
15
+ ### 从源代码安装
16
+
17
+ ```bash
18
+ git clone https://github.com/devtalker/claude-code-inspector.git
19
+ cd claude-code-inspector
20
+ npm install
21
+ ```
22
+
23
+ ## 功能特性
24
+
25
+ - **请求代理**:拦截并转发 Claude Code API 请求到上游服务器
26
+ - **实时日志**:记录所有请求的头部、正文、响应和流式事件
27
+ - **仪表板**:可视化请求状态、Token 使用量、延迟和成本
28
+ - **WebSocket 推送**:实时推送新请求和更新到前端
29
+ - **数据持久化**:使用 SQLite 存储所有请求日志
30
+ - **导出功能**:支持 JSON 或 CSV 格式导出请求数据
31
+ - **Token 统计**:自动计算输入/输出 Token 和缓存使用量
32
+ - **成本估算**:根据模型定价计算每个请求的成本
33
+
34
+ ## 技术栈
35
+
36
+ - **框架**:Next.js 16 + React 19
37
+ - **语言**:TypeScript
38
+ - **数据库**:SQLite (better-sqlite3)
39
+ - **WebSocket**:ws
40
+ - **样式**:Tailwind CSS 4
41
+ - **测试**:Vitest
42
+
43
+ ## 快速开始
44
+
45
+ ### 方式一:使用 npm 包(推荐)
46
+
47
+ 安装后,使用 `cc-inspector` 命令启动服务:
48
+
49
+ ```bash
50
+ # 启动服务
51
+ cc-inspector
52
+ ```
53
+
54
+ 启动后访问:
55
+ - **仪表板**:http://localhost:3000/dashboard
56
+ - **首页**:http://localhost:3000
57
+
58
+ ### 方式二:从源代码运行
59
+
60
+ **环境要求:**
61
+ - Node.js 18+
62
+ - npm / yarn / pnpm
63
+
64
+ **安装依赖:**
65
+
66
+ ```bash
67
+ npm install
68
+ ```
69
+
70
+ **启动开发服务器:**
71
+
72
+ ```bash
73
+ npm run dev
74
+ ```
75
+
76
+ 访问:
77
+ - **仪表板**:http://localhost:3000/dashboard
78
+ - **首页**:http://localhost:3000
79
+
80
+ ### 配置环境变量
81
+
82
+ CC Inspector 需要知道将请求转发到哪个 LLM 服务提供商。有两种配置方式:
83
+
84
+ **方式一:在 Claude Code 全局配置中设置(推荐 npm 包用户)**
85
+
86
+ 编辑 `~/.claude/settings.json`:
87
+
88
+ ```json
89
+ {
90
+ "env": {
91
+ "UPSTREAM_BASE_URL": "https://api.anthropic.com",
92
+ "UPSTREAM_API_KEY": "your-api-key"
93
+ }
94
+ }
95
+ ```
96
+
97
+ **方式二:创建 `.env.local` 文件(适合源代码运行用户)**
98
+
99
+ ```bash
100
+ # .env.local
101
+ UPSTREAM_BASE_URL=https://api.anthropic.com # 上游 API 基础 URL
102
+ UPSTREAM_API_KEY=your-api-key # 上游 API 密钥
103
+ ```
104
+
105
+ > 注意:如果未设置 `UPSTREAM_BASE_URL`,程序将自动使用 `ANTHROPIC_BASE_URL` 的值。
106
+
107
+ ### 配置 Claude Code 使用代理
108
+
109
+ 启动 CC Inspector 后,需要配置 Claude Code 将请求发送到代理服务器,而不是直接发送到 Anthropic API。
110
+
111
+ 在 Claude Code 中运行以下命令配置 baseURL:
112
+
113
+ ```bash
114
+ /mcp set anthropic_base_url http://localhost:3000/api/proxy
115
+ ```
116
+
117
+ 或者手动编辑 `~/.claude/settings.json`:
118
+
119
+ ```json
120
+ {
121
+ "anthropic_base_url": "http://localhost:3000/api/proxy"
122
+ }
123
+ ```
124
+
125
+ 配置完成后,所有来自 Claude Code 的 API 请求都会先经过 CC Inspector,然后被转发到上游 API。
126
+
127
+ **验证配置:**
128
+
129
+ 1. 启动 CC Inspector:`cc-inspector` 或 `npm run dev`
130
+ 2. 访问仪表板:http://localhost:3000/dashboard
131
+ 3. 在 Claude Code 中发起任意请求
132
+ 4. 仪表板应显示新的请求记录
133
+
134
+ ## 项目结构
135
+
136
+ ```
137
+ claude-code-inspector/
138
+ ├── app/ # Next.js App Router
139
+ │ ├── dashboard/ # 监控仪表板页面
140
+ │ ├── api/ # API 路由
141
+ │ │ ├── proxy/ # 代理端点
142
+ │ │ ├── requests/ # 请求日志 API
143
+ │ │ └── events/ # SSE 事件 API
144
+ │ └── v1/messages/ # 原始消息端点
145
+ ├── lib/ # 核心逻辑库
146
+ │ ├── proxy/ # 代理转发器
147
+ │ │ ├── handlers.ts # 请求处理器
148
+ │ │ ├── forwarder.ts # 转发器
149
+ │ │ └── ws-server.ts # WebSocket 服务器
150
+ │ └── recorder/ # 数据记录器
151
+ │ ├── index.ts # 记录器入口
152
+ │ ├── store.ts # SQLite 存储
153
+ │ └── schema.ts # 数据库模式
154
+ ├── components/ # React 组件
155
+ │ ├── JsonViewer.tsx # JSON 查看器
156
+ │ └── JsonModal.tsx # JSON 模态框
157
+ ├── db/ # SQLite 数据库文件
158
+ └── server.ts # 自定义服务器(WebSocket + Next.js)
159
+ ```
160
+
161
+ ## API 端点
162
+
163
+ | 端点 | 方法 | 描述 |
164
+ |------|------|------|
165
+ | `/api/proxy` | POST | 代理并转发请求到上游 |
166
+ | `/api/requests` | GET | 获取最近的请求日志 |
167
+ | `/api/requests/:id` | GET | 获取单个请求详情 |
168
+ | `/api/requests/export` | GET | 导出请求数据(JSON/CSV) |
169
+ | `/api/events` | GET | SSE 事件流 |
170
+ | `/api/ws` | WebSocket | 实时推送连接 |
171
+
172
+ ## 数据模型
173
+
174
+ 请求日志包含以下字段:
175
+
176
+ - `id`: 唯一请求标识符
177
+ - `session_id`: 会话标识符
178
+ - `endpoint`: 请求端点
179
+ - `method`: HTTP 方法
180
+ - `request_headers/body`: 请求头部和正文
181
+ - `response_status/body/headers`: 响应状态、正文和头部
182
+ - `streaming_events`: SSE 流式事件
183
+ - `input_tokens/output_tokens`: 输入/输出 Token
184
+ - `cache_read_tokens/cache_creation_tokens`: 缓存读取/创建 Token
185
+ - `latency_ms`: 请求延迟(毫秒)
186
+ - `first_token_ms`: 首 Token 时间(毫秒)
187
+ - `model`: 使用的模型
188
+ - `cost_usd`: 估算成本(美元)
189
+ - `error_message`: 错误消息(如有)
190
+
191
+ ## 脚本命令
192
+
193
+ **源代码运行用户:**
194
+
195
+ ```bash
196
+ # 开发
197
+ npm run dev # 启动开发服务器
198
+
199
+ # 构建和运行
200
+ npm run build # 构建生产版本
201
+ npm run start # 启动生产服务器
202
+
203
+ # 测试和检查
204
+ npm run test # 运行测试
205
+ npm run lint # ESLint 检查
206
+ ```
207
+
208
+ **npm 包用户:**
209
+
210
+ ```bash
211
+ cc-inspector # 启动服务
212
+ ```
213
+
214
+ ## 数据库
215
+
216
+ 数据存储在 `db/inspector.sqlite` 中,包含以下表:
217
+
218
+ - `request_logs`: 请求日志表
219
+ - `settings`: 配置设置表
220
+
221
+ ## 注意事项
222
+
223
+ 1. **WebSocket**:生产环境请使用 `wss://` 连接
224
+ 2. **代理模式**:确保 Claude Code 已配置使用代理端点
225
+ 3. **Token 计算**:成本估算基于官方定价,仅供参考
226
+
227
+ ## 开发
228
+
229
+ ### 运行测试
230
+
231
+ ```bash
232
+ npm run test
233
+ ```
234
+
235
+ ### 调试
236
+
237
+ 服务器日志会输出所有请求和 WebSocket 连接信息。检查控制台输出或使用 `db/inspector.sqlite` 直接查询数据库。
238
+
239
+ ## 许可证
240
+
241
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { createServer } = require('http');
4
+ const next = require('next');
5
+ const { WebSocketServer } = require('ws');
6
+ const { parse } = require('url');
7
+
8
+ const port = parseInt(process.env.PORT || '3000', 10);
9
+ const dev = process.env.NODE_ENV !== 'production';
10
+
11
+ // 禁用 Turbopack,使用 Webpack
12
+ if (dev) {
13
+ delete process.env.TURBOPACK;
14
+ }
15
+
16
+ const app = next({ dev });
17
+ const handle = app.getRequestHandler();
18
+
19
+ app.prepare().then(() => {
20
+ const upgradeHandler = app.getUpgradeHandler();
21
+ const server = createServer((req, res) => {
22
+ const parsedUrl = parse(req.url, true);
23
+ handle(req, res, parsedUrl);
24
+ });
25
+
26
+ // 注册 WebSocket upgrade 处理器
27
+ server.on('upgrade', async (req, socket, head) => {
28
+ console.log('[SERVER] Upgrade request received for URL:', req.url);
29
+ try {
30
+ await upgradeHandler(req, socket, head);
31
+ console.log('[SERVER] Upgrade handler completed successfully');
32
+ } catch (error) {
33
+ console.error('[SERVER] Upgrade handler error:', error);
34
+ }
35
+ });
36
+
37
+ // WebSocket 服务器
38
+ const wss = new WebSocketServer({ server, path: '/api/ws' });
39
+
40
+ wss.on('connection', (ws) => {
41
+ console.log('Client connected. Total clients:', wss.clients.size);
42
+
43
+ ws.on('close', () => {
44
+ console.log('Client disconnected. Total clients:', wss.clients.size);
45
+ });
46
+
47
+ ws.on('error', (error) => {
48
+ console.error('WebSocket error:', error);
49
+ });
50
+ });
51
+
52
+ server.listen(port, () => {
53
+ console.log(`> Ready on http://localhost:${port}`);
54
+ console.log(`> WebSocket available on ws://localhost:${port}/api/ws`);
55
+ console.log(`> Dashboard: http://localhost:${port}/dashboard`);
56
+ });
57
+ });
package/package.json CHANGED
@@ -1,10 +1,22 @@
1
1
  {
2
2
  "name": "claude-code-inspector",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "private": false,
5
+ "bin": {
6
+ "cc-inspector": "./bin/cli.js"
7
+ },
5
8
  "publishConfig": {
6
9
  "registry": "https://registry.npmjs.org"
7
10
  },
11
+ "files": [
12
+ "app",
13
+ "lib",
14
+ "components",
15
+ "bin",
16
+ "public",
17
+ "next.config.ts",
18
+ "server.ts"
19
+ ],
8
20
  "scripts": {
9
21
  "dev": "tsx server.ts",
10
22
  "build": "next build",
@@ -1,31 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- push:
5
- branches: [main, master]
6
- pull_request:
7
- branches: [main, master]
8
-
9
- jobs:
10
- build-and-test:
11
- runs-on: ubuntu-latest
12
-
13
- steps:
14
- - uses: actions/checkout@v4
15
-
16
- - name: Setup Node.js
17
- uses: actions/setup-node@v4
18
- with:
19
- node-version: '20'
20
- cache: 'yarn'
21
-
22
- - name: Install dependencies
23
- run: yarn install --frozen-lockfile
24
- env:
25
- PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
26
-
27
- - name: Build
28
- run: yarn build
29
-
30
- - name: Run tests
31
- run: yarn test
@@ -1,33 +0,0 @@
1
- name: Publish npm Package
2
-
3
- on:
4
- release:
5
- types: [published]
6
-
7
- jobs:
8
- publish:
9
- runs-on: ubuntu-latest
10
-
11
- steps:
12
- - uses: actions/checkout@v4
13
-
14
- - name: Setup Node.js
15
- uses: actions/setup-node@v4
16
- with:
17
- node-version: '20'
18
- cache: 'yarn'
19
- registry-url: 'https://registry.npmjs.org'
20
-
21
- - name: Install dependencies
22
- run: yarn install --frozen-lockfile
23
-
24
- - name: Build
25
- run: yarn build
26
-
27
- - name: Run tests
28
- run: yarn test
29
-
30
- - name: Publish to npm
31
- run: npm publish --access public
32
- env:
33
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/dev.sh DELETED
@@ -1,19 +0,0 @@
1
- #!/bin/bash
2
-
3
- # 快速开发脚本 - 使用生产构建避免自动刷新
4
-
5
- echo "=== 构建生产版本 ==="
6
- npm run build
7
-
8
- if [ $? -ne 0 ]; then
9
- echo "构建失败!"
10
- exit 1
11
- fi
12
-
13
- echo ""
14
- echo "=== 启动生产服务器 ==="
15
- echo "访问 http://localhost:3000/dashboard"
16
- echo "按 Ctrl+C 停止服务器"
17
- echo ""
18
-
19
- NODE_ENV=production npm start
package/eslint.config.mjs DELETED
@@ -1,18 +0,0 @@
1
- import { defineConfig, globalIgnores } from "eslint/config";
2
- import nextVitals from "eslint-config-next/core-web-vitals";
3
- import nextTs from "eslint-config-next/typescript";
4
-
5
- const eslintConfig = defineConfig([
6
- ...nextVitals,
7
- ...nextTs,
8
- // Override default ignores of eslint-config-next.
9
- globalIgnores([
10
- // Default ignores of eslint-config-next:
11
- ".next/**",
12
- "out/**",
13
- "build/**",
14
- "next-env.d.ts",
15
- ]),
16
- ]);
17
-
18
- export default eslintConfig;
@@ -1,7 +0,0 @@
1
- const config = {
2
- plugins: {
3
- "@tailwindcss/postcss": {},
4
- },
5
- };
6
-
7
- export default config;
package/tsconfig.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "lib": ["dom", "dom.iterable", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "strict": true,
8
- "noEmit": true,
9
- "esModuleInterop": true,
10
- "module": "esnext",
11
- "moduleResolution": "bundler",
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
- "jsx": "react-jsx",
15
- "incremental": true,
16
- "plugins": [
17
- {
18
- "name": "next"
19
- }
20
- ],
21
- "paths": {
22
- "@/*": ["./*"]
23
- }
24
- },
25
- "include": [
26
- "next-env.d.ts",
27
- "**/*.ts",
28
- "**/*.tsx",
29
- ".next/types/**/*.ts",
30
- ".next/dev/types/**/*.ts",
31
- "**/*.mts"
32
- ],
33
- "exclude": ["node_modules"]
34
- }
@@ -1,11 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "module": "ESNext",
5
- "moduleResolution": "Node",
6
- "isolatedModules": false,
7
- "noEmit": false,
8
- "outDir": ".next/server"
9
- },
10
- "include": ["server.ts"]
11
- }
package/vitest.config.ts DELETED
@@ -1,14 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
- import path from 'path';
3
-
4
- export default defineConfig({
5
- test: {
6
- globals: true,
7
- environment: 'node',
8
- },
9
- resolve: {
10
- alias: {
11
- '@': path.resolve(__dirname, './'),
12
- },
13
- },
14
- });