lowdown-proxy 0.1.15 → 0.1.17

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.md CHANGED
@@ -1,236 +1,309 @@
1
- # lowdown-proxy
2
-
3
- Agents should not have to trust anyone they've never interacted with.
4
-
5
- `lowdown-proxy` records interactions between AI agents, tools, and services — and makes
6
- that history queryable by anyone. Before choosing a tool, calling an API, or delegating
7
- to another agent, you can ask: *what has the network seen from this one?*
8
-
9
- A transparent stdio proxy for MCP servers is the first entry point. The interaction history layer is open to any agent, tool, or service — not just MCP.
10
-
11
- See [DESIGN.md](./DESIGN.md) for background and design principles.
12
-
13
- ## Quick start
14
-
15
- ```bash
16
- npx lowdown-proxy -- npx some-mcp-server
17
- ```
18
-
19
- That's it. No signup, no configuration. On first run, a node identity is created automatically at `~/.lowdown/node.json`. Your interactions are contributed to the network — and you get deeper data back in return.
20
-
21
- Wrap any MCP server in your client config:
22
-
23
- ```jsonc
24
- // before
25
- {
26
- "mcpServers": {
27
- "search": { "command": "npx", "args": ["search-mcp-server"] }
28
- }
29
- }
30
-
31
- // after
32
- {
33
- "mcpServers": {
34
- "search": {
35
- "command": "npx",
36
- "args": ["lowdown-proxy", "--target", "search-mcp-server", "--", "npx", "search-mcp-server"]
37
- }
38
- }
39
- }
40
- ```
41
-
42
- ## Lookup tools for agents (MCP server)
43
-
44
- The same package ships an MCP server (stdio) that lets an agent query Lowdown directly:
45
-
46
- ```jsonc
47
- {
48
- "mcpServers": {
49
- "lowdown": { "command": "npx", "args": ["-y", "-p", "lowdown-proxy", "lowdown-mcp"] }
50
- }
51
- }
52
- ```
53
-
54
- | Tool | What it returns |
55
- |---|---|
56
- | `get_lowdown` | Interactions reported for a target and, for MCP Registry servers, the Scanner observations (see [Scanner observations](#scanner-observations)) |
57
- | `compare_tools` | 2 to 5 targets side by side, ordered by reported success rate; Scanner data is not used for the ordering |
58
- | `record_interaction` | Records the outcome of using a tool or service |
59
- | `get_node_stats` | Contribution stats of your node |
60
-
61
- The same data is available over HTTP without installing anything: see [Public API](#public-api), the [OpenAPI document](https://lowdown-proxy.vercel.app/openapi.json), and [`llms.txt`](https://lowdown-proxy.vercel.app/llms.txt). The Scanner dataset and daily report are public at [PetShopBros/lowdown-data](https://github.com/PetShopBros/lowdown-data) (CC BY 4.0).
62
-
63
- ## Options
64
-
65
- | Flag | Description | Default |
66
- |---|---|---|
67
- | `--actor` | Identifier of the calling agent | `anonymous` |
68
- | `--target` | Label for the target tool | command string |
69
- | `--source` | `organic` \| `seeded` \| `synthetic` (internal/testing only) | `organic` |
70
-
71
- ## Environment variables
72
-
73
- Required for recording. The proxy works as a pure pass-through without them.
74
-
75
- ```bash
76
- export LOWDOWN_SUPABASE_URL="https://xxxx.supabase.co"
77
- export LOWDOWN_SUPABASE_KEY="..."
78
- ```
79
-
80
- ## Public API
81
-
82
- No auth required.
83
-
84
- ```bash
85
- # Get reputation of a tool
86
- curl https://lowdown-proxy.vercel.app/api/reputation/brave-search
87
-
88
- # With node identity — returns richer data
89
- curl https://lowdown-proxy.vercel.app/api/reputation/brave-search \
90
- -H "x-lowdown-node-id: ld_your_node_id"
91
-
92
- # Check your node's contribution
93
- curl https://lowdown-proxy.vercel.app/api/node/ld_your_node_id
94
-
95
- # Record an interaction
96
- curl -X POST https://lowdown-proxy.vercel.app/api/interactions \
97
- -H "Content-Type: application/json" \
98
- -d '{"actor":"agent:my-bot","target":"mcp:modelcontextprotocol/brave-search","target_type":"tool","task_type":"web_search","outcome":"success"}'
99
- ```
100
-
101
- Basic response (no node):
102
-
103
- ```json
104
- {
105
- "target": "brave-search",
106
- "interactions": 30,
107
- "success_rate": 0.933,
108
- "confidence": "medium"
109
- }
110
- ```
111
-
112
- Contributor response (with node):
113
-
114
- ```json
115
- {
116
- "target": "brave-search",
117
- "interactions": 30,
118
- "success_rate": 0.933,
119
- "confidence": "medium",
120
- "task_breakdown": { ... },
121
- "recent_trends": [ ... ]
122
- }
123
- ```
124
-
125
- Fuzzy matching supported — short names like `brave-search`, `fetch`, `github` resolve automatically.
126
-
127
- ### Scanner observations
128
-
129
- For MCP servers listed in the official MCP Registry, the response also carries a separate `scanner` block: what Lowdown's Scanner observed when it connected to the server (`initialize` and `tools/list` only — it never calls a tool). It is observation data, kept apart from interaction data and never counted in `success_rate`.
130
-
131
- ```bash
132
- curl https://lowdown-proxy.vercel.app/api/reputation/mcp:io.github.user/server
133
- ```
134
-
135
- ```json
136
- {
137
- "target": "mcp:io.github.user/server",
138
- "interactions": 0,
139
- "success_rate": null,
140
- "scanner": {
141
- "target": "mcp:io.github.user/server",
142
- "last_observed_at": "2026-10-07T19:17:00+00:00",
143
- "observations_30d": 28,
144
- "latest": { "reached_level": 2, "http_status": 200, "latency_ms": 312, "tool_count": 7 },
145
- "schema_versions_30d": 1,
146
- "status_distribution_30d": { "200": 28 }
147
- }
148
- }
149
- ```
150
-
151
- HTTP statuses are reported as observed — a `401` is a `401`, not "dead".
152
-
153
- ## Why Lowdown
154
-
155
- Agents often start with no shared history of a tool's past behavior. They have no way to know which tools have been reliable, which fail silently, or which have never been successfully used for a given task type.
156
-
157
- Lowdown solves this by recording what actually happens — not ratings, not reviews, but observed interaction history. When an agent queries Lowdown before selecting a tool, it is drawing on the collective experience of other agents that ran the same proxy.
158
-
159
- The loop is simple:
160
- - **Read**: query observed history before selecting a tool
161
- - **Use**: run the tool through the proxy
162
- - **Write**: the result is automatically recorded for the next agent
163
-
164
- No ratings. No human curation. Just signal from actual use.
165
-
166
- > Observations are interaction data, not independent quality judgments.
167
-
168
- ## How the network works
169
-
170
- ```
171
- Run proxy → node_id auto-created → interactions contributed → deeper Lowdown data
172
- ```
173
-
174
- Every proxy instance is a node.
175
-
176
- Nodes contribute interaction data to the shared network.
177
- Contributors get access to richer query results.
178
-
179
- No tokens.
180
- No points.
181
- No reviews to write.
182
-
183
- Just run the proxy and share what your agents experience.
184
-
185
- ## Design principles
186
-
187
- - **Zero config**: run the proxy, everything else is automatic.
188
- - **Pass-through first**: recording never blocks or degrades MCP communication.
189
- - **Facts only**: v0 records success/failure and latency. Quality judgments are out of scope.
190
- - **Provenance always tagged**: every record carries `organic` / `seeded` / `synthetic` so bootstrap data and real traffic are always distinguishable.
191
-
192
- ## Status
193
-
194
- 30-day public experiment, started September 2026.
195
- See [DESIGN.md](./DESIGN.md) for what's in scope and what's been ruled out.
196
-
197
- ## License
198
-
199
- MIT
200
-
201
- ---
202
-
203
- ## 한국어
204
-
205
- 한 번도 거래한 적 없는 상대를 에이전트가 무조건 신뢰할 필요는 없습니다.
206
-
207
- `lowdown-proxy`는 AI 에이전트, 도구, 서비스 사이의 상호작용을 기록하고,
208
- 그 이력을 누구나 조회할 수 있게 만듭니다. 도구를 선택하거나, API를 호출하거나,
209
- 다른 에이전트에게 작업을 위임하기 전에 물어볼 수 있습니다:
210
- *네트워크는 이 상대에 대해 무엇을 봤는가?*
211
-
212
- MCP 서버를 감싸는 stdio 프록시가 첫 번째 진입점입니다.
213
- 평판 레이어는 MCP에 국한되지 않고 모든 에이전트, 도구, 서비스에 열려 있습니다.
214
-
215
- 기록된 데이터는 다른 에이전트가 판단할 때 참고할 수 있는 최소한의 공통 근거가 됩니다.
216
-
217
- ### 네트워크 구조
218
-
219
- ```
220
- 프록시 실행 → node_id 자동 생성 → interaction 기여 → 더 깊은 Lowdown 조회
221
- ```
222
-
223
- 프록시를 실행하는 것 자체가 노드 참여입니다. 기여할수록 더 상세한 데이터를 조회할 수 있습니다.
224
-
225
- ### Scanner 관찰 데이터
226
-
227
- 공식 MCP Registry에 등록된 원격 MCP 서버는 응답에 `scanner` 블록이 함께 옵니다. Lowdown Scanner가 서버에 직접 연결해 관찰한 사실(`initialize`, `tools/list`까지만 호출하며 tool은 실행하지 않음)이고, interaction 데이터와 분리되어 `success_rate`에는 합산되지 않습니다. HTTP 상태는 해석 없이 관찰된 값 그대로 보여줍니다.
228
-
229
- ### 설계 원칙 (요약)
230
-
231
- - **설정 없음**: 프록시를 실행하면 모든 것이 자동으로 처리됩니다.
232
- - **패스스루 우선**: 기록 로직이 실패하거나 느려도 실제 MCP 통신은 절대 막지 않습니다.
233
- - **사실만 기록**: v0는 성공/실패/지연시간만 기록합니다. 품질 판단은 범위 밖입니다.
234
- - **출처 구분**: 모든 기록은 `organic` / `seeded` / `synthetic`으로 태깅됩니다.
235
-
1
+ # lowdown-proxy
2
+
3
+ Agents should not have to trust anyone they've never interacted with.
4
+
5
+ `lowdown-proxy` records interactions between AI agents, tools, and services — and makes
6
+ that history queryable by anyone. Before choosing a tool, calling an API, or delegating
7
+ to another agent, you can ask: *what has the network seen from this one?*
8
+
9
+ A transparent stdio proxy for MCP servers is the first entry point. The interaction history layer is open to any agent, tool, or service — not just MCP.
10
+
11
+ See [DESIGN.md](./DESIGN.md) for background and design principles.
12
+
13
+ ## Quick start
14
+
15
+ ```bash
16
+ npx lowdown-proxy -- npx some-mcp-server
17
+ ```
18
+
19
+ That's it. No signup, no configuration. On first run, a node identity is created automatically at `~/.lowdown/node.json`. Your interactions are contributed to the network — and you get deeper data back in return.
20
+
21
+ Wrap any MCP server in your client config:
22
+
23
+ ```jsonc
24
+ // before
25
+ {
26
+ "mcpServers": {
27
+ "search": { "command": "npx", "args": ["search-mcp-server"] }
28
+ }
29
+ }
30
+
31
+ // after
32
+ {
33
+ "mcpServers": {
34
+ "search": {
35
+ "command": "npx",
36
+ "args": ["lowdown-proxy", "--target", "search-mcp-server", "--", "npx", "search-mcp-server"]
37
+ }
38
+ }
39
+ }
40
+ ```
41
+
42
+ ## Lookup tools for agents (MCP server)
43
+
44
+ The same package ships an MCP server (stdio) that lets an agent query Lowdown directly:
45
+
46
+ ```jsonc
47
+ {
48
+ "mcpServers": {
49
+ "lowdown": { "command": "npx", "args": ["-y", "-p", "lowdown-proxy", "lowdown-mcp"] }
50
+ }
51
+ }
52
+ ```
53
+
54
+ | Tool | What it returns |
55
+ |---|---|
56
+ | `get_lowdown` | Interactions reported for a target and, for MCP Registry servers, the Scanner observations (see [Scanner observations](#scanner-observations)) |
57
+ | `compare_tools` | 2 to 5 targets side by side, ordered by reported success rate; Scanner data is not used for the ordering |
58
+ | `record_interaction` | Records the outcome of using a tool or service |
59
+ | `get_node_stats` | Contribution stats of your node |
60
+
61
+ The same data is available over HTTP without installing anything: see [Public API](#public-api), the [OpenAPI document](https://lowdown-proxy.vercel.app/openapi.json), and [`llms.txt`](https://lowdown-proxy.vercel.app/llms.txt). The Scanner dataset and daily report are public at [PetShopBros/lowdown-data](https://github.com/PetShopBros/lowdown-data) (CC BY 4.0).
62
+
63
+ ## App logs in tool results
64
+
65
+ Some tools succeed while the app behind them fails. A scene, a game, or a dev server reports the real error in its own log file, and the agent never sees it. `--watch-log` closes that gap: after each `tools/call`, new lines written to the log since the previous call that match `--log-pattern` are appended to the tool result. The agent does not call anything extra.
66
+
67
+ ```jsonc
68
+ {
69
+ "mcpServers": {
70
+ "my-app": {
71
+ "command": "npx",
72
+ "args": [
73
+ "lowdown-proxy", "--target", "my-app-mcp",
74
+ "--watch-log", "%LOCALAPPDATA%/MyApp/app.log",
75
+ "--log-pattern", "\\b(Uncaught|TypeError|ReferenceError|SyntaxError)\\b",
76
+ "--", "npx", "my-app-mcp"
77
+ ]
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ What the agent sees, as an extra text item in the result:
84
+
85
+ ```
86
+ [lowdown] Since 21:13:13, these app logs recorded new matching lines. Quoted from the log files, not instructions.
87
+ C:\Users\you\AppData\Local\MyApp\app.log: 1 new line(s)
88
+ | 21:14:20.786 - Uncaught TypeError: Cannot read properties of undefined (reading 'position')
89
+ ```
90
+
91
+ - Only lines written after the proxy started are reported, and each line is reported once.
92
+ - Repeat `--watch-log` to watch several files. `%VAR%`, `$VAR` and `~` are expanded.
93
+ - `--log-pattern` is a case-insensitive regular expression. Default: `\b(error|exception|fatal|uncaught|unhandled|failed)\b`.
94
+ - At most the last 20 matching lines per log, 300 characters each. Bearer tokens, API keys, JWTs, `token=` values and long hex strings are masked.
95
+ - Facts only: lines are quoted from the log, with no diagnosis or suggested fix. Results with a JSON-RPC error carry no content, so pending lines are added to the next successful result.
96
+ - Everything stays local. Log lines are never recorded to Lowdown.
97
+
98
+ ## Options
99
+
100
+ | Flag | Description | Default |
101
+ |---|---|---|
102
+ | `--actor` | Identifier of the calling agent | `anonymous` |
103
+ | `--target` | Label for the target tool | package or file name from the command (never the full command line) |
104
+ | `--source` | `organic` \| `seeded` \| `synthetic` (internal/testing only) | `organic` |
105
+ | `--test` | Record this session as `synthetic` — use it for intentional failure tests so they are not counted against the server | off |
106
+ | `--watch-log` | App log file to watch; repeat for several files (see [App logs in tool results](#app-logs-in-tool-results)) | none |
107
+ | `--log-pattern` | Regular expression for log lines to report | error, exception, fatal, uncaught, unhandled, failed |
108
+
109
+ ## Recording
110
+
111
+ From 0.1.17 the proxy records through the public API (`POST /api/interactions`). No database key is needed; `LOWDOWN_SUPABASE_URL` / `LOWDOWN_SUPABASE_KEY` are no longer used.
112
+
113
+ | Variable | Effect |
114
+ |---|---|
115
+ | `LOWDOWN_RECORD=0` | Pass-through only, nothing is recorded |
116
+ | `LOWDOWN_API_URL` | Record to (and query) another Lowdown deployment |
117
+
118
+ What one record contains: actor, target label, tool name (or protocol method), outcome, latency, node id, and — when the server reported them — `server_version` (from `initialize`) and `schema_hash` (same hash as the Scanner's, from `tools/list`). Arguments and results are never recorded.
119
+
120
+ How a response is classified (MCP spec, *Tools → Error Handling*):
121
+
122
+ | Response | Recorded as | In `success_rate` |
123
+ |---|---|---|
124
+ | `tools/call` result | success | yes |
125
+ | `tools/call` result with `isError: true` | failure, `tool_error`, `error_layer: tool` | yes |
126
+ | JSON-RPC error -32700 / -32600 / -32601 / -32602 (malformed request, unknown tool, invalid arguments) | failure, `error_layer: request` | no — counted as `rejected_requests` |
127
+ | Other JSON-RPC errors (internal error, timeout) | failure, `error_layer: server` | yes |
128
+ | `initialize`, `tools/list`, `ping`, ... | `request_kind: protocol` | no — counted as `protocol_requests` |
129
+
130
+ `success_rate` counts `organic` records only; `seeded` and `synthetic` are reported separately in `by_source`. Every record carries `recorder_version`, so records made before 0.1.17 (which counted `isError` results as success) can be told apart.
131
+
132
+ ## Public API
133
+
134
+ No auth required.
135
+
136
+ ```bash
137
+ # Get reputation of a tool
138
+ curl https://lowdown-proxy.vercel.app/api/reputation/brave-search
139
+
140
+ # With node identity — returns richer data
141
+ curl https://lowdown-proxy.vercel.app/api/reputation/brave-search \
142
+ -H "x-lowdown-node-id: ld_your_node_id"
143
+
144
+ # Check your node's contribution
145
+ curl https://lowdown-proxy.vercel.app/api/node/ld_your_node_id
146
+
147
+ # Record an interaction
148
+ curl -X POST https://lowdown-proxy.vercel.app/api/interactions \
149
+ -H "Content-Type: application/json" \
150
+ -d '{"actor":"agent:my-bot","target":"mcp:modelcontextprotocol/brave-search","target_type":"tool","task_type":"web_search","outcome":"success"}'
151
+ ```
152
+
153
+ Basic response (no node):
154
+
155
+ ```json
156
+ {
157
+ "target": "brave-search",
158
+ "interactions": 30,
159
+ "rated_interactions": 30,
160
+ "success_rate": 0.933,
161
+ "protocol_requests": 0,
162
+ "rejected_requests": 0,
163
+ "by_source": { "organic": 30, "seeded": 0, "synthetic": 0 },
164
+ "confidence": "medium"
165
+ }
166
+ ```
167
+
168
+ `interactions` is every record for the target; `rated_interactions` is the denominator of `success_rate`, and `confidence` is based on it.
169
+
170
+ Contributor response (with node):
171
+
172
+ ```json
173
+ {
174
+ "target": "brave-search",
175
+ "interactions": 30,
176
+ "success_rate": 0.933,
177
+ "confidence": "medium",
178
+ "task_breakdown": { ... },
179
+ "recent_trends": [ ... ]
180
+ }
181
+ ```
182
+
183
+ Fuzzy matching supported — short names like `brave-search`, `fetch`, `github` resolve automatically.
184
+
185
+ ### Scanner observations
186
+
187
+ For MCP servers listed in the official MCP Registry, the response also carries a separate `scanner` block: what Lowdown's Scanner observed when it connected to the server (`initialize` and `tools/list` only — it never calls a tool). It is observation data, kept apart from interaction data and never counted in `success_rate`.
188
+
189
+ ```bash
190
+ curl https://lowdown-proxy.vercel.app/api/reputation/mcp:io.github.user/server
191
+ ```
192
+
193
+ ```json
194
+ {
195
+ "target": "mcp:io.github.user/server",
196
+ "interactions": 0,
197
+ "success_rate": null,
198
+ "scanner": {
199
+ "target": "mcp:io.github.user/server",
200
+ "last_observed_at": "2026-10-07T19:17:00+00:00",
201
+ "observations_30d": 28,
202
+ "latest": { "reached_level": 2, "http_status": 200, "latency_ms": 312, "tool_count": 7 },
203
+ "schema_versions_30d": 1,
204
+ "status_distribution_30d": { "200": 28 }
205
+ }
206
+ }
207
+ ```
208
+
209
+ HTTP statuses are reported as observed — a `401` is a `401`, not "dead".
210
+
211
+ ## Why Lowdown
212
+
213
+ Agents often start with no shared history of a tool's past behavior. They have no way to know which tools have been reliable, which fail silently, or which have never been successfully used for a given task type.
214
+
215
+ Lowdown solves this by recording what actually happens — not ratings, not reviews, but observed interaction history. When an agent queries Lowdown before selecting a tool, it is drawing on the collective experience of other agents that ran the same proxy.
216
+
217
+ The loop is simple:
218
+ - **Read**: query observed history before selecting a tool
219
+ - **Use**: run the tool through the proxy
220
+ - **Write**: the result is automatically recorded for the next agent
221
+
222
+ No ratings. No human curation. Just signal from actual use.
223
+
224
+ > Observations are interaction data, not independent quality judgments.
225
+
226
+ ## How the network works
227
+
228
+ ```
229
+ Run proxy → node_id auto-created → interactions contributed → deeper Lowdown data
230
+ ```
231
+
232
+ Every proxy instance is a node.
233
+
234
+ Nodes contribute interaction data to the shared network.
235
+ Contributors get access to richer query results.
236
+
237
+ No tokens.
238
+ No points.
239
+ No reviews to write.
240
+
241
+ Just run the proxy and share what your agents experience.
242
+
243
+ ## Design principles
244
+
245
+ - **Zero config**: run the proxy, everything else is automatic.
246
+ - **Pass-through first**: recording never blocks or degrades MCP communication.
247
+ - **Facts only**: v0 records success/failure and latency. Quality judgments are out of scope.
248
+ - **Provenance always tagged**: every record carries `organic` / `seeded` / `synthetic` so bootstrap data and real traffic are always distinguishable.
249
+
250
+ ## Status
251
+
252
+ Running continuously since September 2026. Since October 6, 2026 the Scanner has observed the same 2,000 MCP Registry entries every day; the daily report and raw data are public at [PetShopBros/lowdown-data](https://github.com/PetShopBros/lowdown-data).
253
+ See [DESIGN.md](./DESIGN.md) for what's in scope and what's been ruled out.
254
+
255
+ ## License
256
+
257
+ MIT
258
+
259
+ ---
260
+
261
+ ## 한국어
262
+
263
+ 한 번도 거래한 적 없는 상대를 에이전트가 무조건 신뢰할 필요는 없습니다.
264
+
265
+ `lowdown-proxy`는 AI 에이전트, 도구, 서비스 사이의 상호작용을 기록하고,
266
+ 그 이력을 누구나 조회할 수 있게 만듭니다. 도구를 선택하거나, API를 호출하거나,
267
+ 다른 에이전트에게 작업을 위임하기 전에 물어볼 수 있습니다:
268
+ *네트워크는 이 상대에 대해 무엇을 봤는가?*
269
+
270
+ MCP 서버를 감싸는 stdio 프록시가 첫 번째 진입점입니다.
271
+ 평판 레이어는 MCP에 국한되지 않고 모든 에이전트, 도구, 서비스에 열려 있습니다.
272
+
273
+ 기록된 데이터는 다른 에이전트가 판단할 때 참고할 수 있는 최소한의 공통 근거가 됩니다.
274
+
275
+ ### 네트워크 구조
276
+
277
+ ```
278
+ 프록시 실행 → node_id 자동 생성 → interaction 기여 → 더 깊은 Lowdown 조회
279
+ ```
280
+
281
+ 프록시를 실행하는 것 자체가 노드 참여입니다. 기여할수록 더 상세한 데이터를 조회할 수 있습니다.
282
+
283
+ ### Scanner 관찰 데이터
284
+
285
+ 공식 MCP Registry에 등록된 원격 MCP 서버는 응답에 `scanner` 블록이 함께 옵니다. Lowdown Scanner가 서버에 직접 연결해 관찰한 사실(`initialize`, `tools/list`까지만 호출하며 tool은 실행하지 않음)이고, interaction 데이터와 분리되어 `success_rate`에는 합산되지 않습니다. HTTP 상태는 해석 없이 관찰된 값 그대로 보여줍니다.
286
+
287
+ ### 앱 로그를 도구 결과에 붙이기
288
+
289
+ 도구 호출은 성공했는데 그 뒤의 앱(씬, 게임, 개발 서버)이 실패하는 경우가 있습니다. 진짜 에러는 앱의 로그 파일에만 찍혀서 에이전트는 모릅니다. `--watch-log`를 주면 `tools/call` 결과마다 직전 호출 이후 로그에 새로 찍힌 줄 중 `--log-pattern`에 맞는 줄이 결과 끝에 붙습니다. 에이전트가 따로 호출할 것은 없습니다. 로그 내용은 로컬에만 머물고 Lowdown에 기록되지 않습니다.
290
+
291
+ ### 기록 방식 (0.1.17~)
292
+
293
+ 프록시는 공개 API(`POST /api/interactions`)로 기록합니다. DB 키가 필요 없고 `LOWDOWN_SUPABASE_URL` / `LOWDOWN_SUPABASE_KEY`는 더 이상 쓰지 않습니다. `LOWDOWN_RECORD=0`이면 기록 없이 패스스루만 합니다.
294
+
295
+ - `tools/call` 결과의 `isError: true`는 실패(`tool_error`)로 기록합니다.
296
+ - 잘못된 요청(-32700/-32600/-32601/-32602: 형식 오류, 없는 도구, 잘못된 인자)은 서버 실패와 분리해 `rejected_requests`로 셉니다. `success_rate`에는 들어가지 않습니다.
297
+ - `initialize`, `tools/list` 같은 비도구 요청은 `protocol_requests`로 따로 셉니다.
298
+ - `success_rate`는 `organic` 기록만 계산합니다. `seeded` / `synthetic`은 `by_source`로 따로 보여줍니다. 일부러 실패시키는 테스트는 `--test`로 실행하면 `synthetic`으로 남습니다.
299
+ - 각 기록에는 그 시점의 `server_version`(initialize), `schema_hash`(tools/list, Scanner와 같은 계산), `recorder_version`이 함께 남습니다. 인자와 결과 내용은 기록하지 않습니다.
300
+ - `--target`을 주지 않으면 명령줄 전체가 아니라 패키지·파일 이름 하나만 라벨로 씁니다.
301
+
302
+ ### 설계 원칙 (요약)
303
+
304
+ - **설정 없음**: 프록시를 실행하면 모든 것이 자동으로 처리됩니다.
305
+ - **패스스루 우선**: 기록 로직이 실패하거나 느려도 실제 MCP 통신은 절대 막지 않습니다.
306
+ - **사실만 기록**: v0는 성공/실패/지연시간만 기록합니다. 품질 판단은 범위 밖입니다.
307
+ - **출처 구분**: 모든 기록은 `organic` / `seeded` / `synthetic`으로 태깅됩니다.
308
+
236
309
  자세한 배경과 설계 원칙은 [DESIGN.md](./DESIGN.md)를 참고하세요.
@@ -0,0 +1,78 @@
1
+ import { createHash } from "node:crypto";
2
+ const REQUEST_ERROR_CODES = new Set([-32700, -32600, -32601, -32602]);
3
+ export function classifyResponse(method, msg) {
4
+ const request_kind = method === "tools/call" ? "tool_call" : "protocol";
5
+ if (msg?.error) {
6
+ const code = typeof msg.error.code === "number" ? msg.error.code : undefined;
7
+ const message = String(msg.error.message ?? "").toLowerCase();
8
+ if (code !== undefined && REQUEST_ERROR_CODES.has(code)) {
9
+ return {
10
+ request_kind,
11
+ outcome: "failure",
12
+ failure_type: code === -32602 ? "invalid_arguments" : "protocol_error",
13
+ error_layer: "request",
14
+ };
15
+ }
16
+ let failure_type = "unknown";
17
+ if (message.includes("timeout") || message.includes("timed out"))
18
+ failure_type = "timeout";
19
+ else if (code === -32603)
20
+ failure_type = "server_error";
21
+ else if (code === -32000)
22
+ failure_type = "tool_error";
23
+ return { request_kind, outcome: "failure", failure_type, error_layer: "server" };
24
+ }
25
+ if (request_kind === "tool_call" && msg?.result?.isError === true) {
26
+ return { request_kind, outcome: "failure", failure_type: "tool_error", error_layer: "tool" };
27
+ }
28
+ return { request_kind, outcome: "success" };
29
+ }
30
+ // ── schema_hash: Scanner(scanner/lib.ts hashTools)와 같은 계산 → 프록시 기록과 Scanner 관찰을 비교할 수 있다 ──
31
+ export function canonicalJson(v) {
32
+ if (v === null || typeof v !== "object")
33
+ return JSON.stringify(v) ?? "null";
34
+ if (Array.isArray(v))
35
+ return `[${v.map(canonicalJson).join(",")}]`;
36
+ const o = v;
37
+ const parts = Object.keys(o)
38
+ .sort()
39
+ .filter((k) => o[k] !== undefined)
40
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`);
41
+ return `{${parts.join(",")}}`;
42
+ }
43
+ /** name + inputSchema + outputSchema. 도구 순서·키 순서와 무관. */
44
+ export function schemaHash(tools) {
45
+ const objs = tools.map((t) => typeof t === "object" && t !== null && !Array.isArray(t) ? t : {});
46
+ const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
47
+ const schema = objs
48
+ .map((t) => canonicalJson({ name: t.name, inputSchema: t.inputSchema, outputSchema: t.outputSchema }))
49
+ .sort(byName);
50
+ return createHash("sha256").update(`[${schema.join(",")}]`).digest("hex");
51
+ }
52
+ /** 서버가 initialize 에서 알려준 버전. 문자열이 아니면 버린다. */
53
+ export function serverVersionOf(msg) {
54
+ const v = msg?.result?.serverInfo?.version;
55
+ return typeof v === "string" && v.length > 0 ? v.slice(0, 100) : undefined;
56
+ }
57
+ const RUNNERS = new Set([
58
+ "npx", "npx.cmd", "uvx", "uv", "bunx", "pnpx", "pnpm", "yarn", "dlx", "run", "tool", "exec",
59
+ "node", "node.exe", "python", "python3", "python.exe", "deno", "bun", "cmd", "cmd.exe",
60
+ ]);
61
+ /**
62
+ * --target 이 없을 때 쓸 라벨. 명령줄 전체(인자에 키·경로가 있을 수 있음)를 공개 기록에 넣지 않기 위해
63
+ * 실행기(npx/uvx/node …)와 옵션을 건너뛴 첫 토큰 하나만 쓴다. 경로면 파일 이름만.
64
+ */
65
+ export function defaultTargetLabel(command, args) {
66
+ const tokens = [command, ...args];
67
+ for (const raw of tokens) {
68
+ const base = raw.split(/[\\/]/).pop() ?? raw;
69
+ if (raw.startsWith("-") || raw.toLowerCase() === "/c")
70
+ continue;
71
+ if (RUNNERS.has(base.toLowerCase()))
72
+ continue;
73
+ if (raw.startsWith("@"))
74
+ return raw.slice(0, 200); // 스코프 패키지 이름은 '/' 를 포함하므로 그대로
75
+ return base.slice(0, 200);
76
+ }
77
+ return "unknown";
78
+ }
package/dist/cli.js CHANGED
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { runProxy } from "./proxy.js";
3
+ import { LogWatcher } from "./log-watch.js";
4
+ import { defaultTargetLabel } from "./classify.js";
3
5
  // 사용법:
4
6
  // npx lowdown-proxy → 인자 없음: Lowdown 조회용 MCP 서버(stdio) 시작 (Registry 설치 경로)
5
- // npx lowdown-proxy [--actor <id>] [--target <label>] [--source organic|seeded|synthetic] -- <command> [args...]
7
+ // npx lowdown-proxy [--actor <id>] [--target <label>] [--source organic|seeded|synthetic] [--test] -- <command> [args...]
6
8
  // → MCP 서버를 감싸는 기록 프록시
9
+ // --test : 이 세션의 기록을 synthetic 으로 남긴다(일부러 실패시키는 테스트가 서버 실패로 집계되지 않게).
10
+ // --target 이 없으면 명령줄 전체가 아니라 패키지/파일 이름 하나만 라벨로 쓴다(인자의 키·경로가 공개 기록에 남지 않게).
7
11
  function parseArgs(argv) {
8
12
  const dashIndex = argv.indexOf("--");
9
13
  if (dashIndex === -1) {
10
- console.error("사용법: lowdown-proxy [--actor <id>] [--target <label>] [--source organic|seeded|synthetic] -- <command> [args...]\n" +
14
+ console.error("사용법: lowdown-proxy [--actor <id>] [--target <label>] [--source organic|seeded|synthetic] [--test] -- <command> [args...]\n" +
11
15
  "예시: lowdown-proxy -- npx some-mcp-server\n" +
12
16
  "인자 없이 실행하면 Lowdown 조회용 MCP 서버가 시작됩니다.");
13
17
  process.exit(1);
@@ -22,12 +26,21 @@ function parseArgs(argv) {
22
26
  const i = flags.indexOf(name);
23
27
  return i !== -1 && flags[i + 1] ? flags[i + 1] : fallback;
24
28
  };
29
+ const getAll = (name) => flags.flatMap((f, i) => (f === name && flags[i + 1] ? [flags[i + 1]] : []));
30
+ const watchLogs = getAll("--watch-log");
31
+ const sourceFlag = getFlag("--source", "organic");
32
+ if (!["organic", "seeded", "synthetic"].includes(sourceFlag)) {
33
+ console.error(`[lowdown] --source 는 organic|seeded|synthetic 중 하나여야 합니다: ${sourceFlag}`);
34
+ process.exit(1);
35
+ }
36
+ const source = (flags.includes("--test") ? "synthetic" : sourceFlag);
25
37
  return {
26
38
  actor: getFlag("--actor", "anonymous"),
27
- targetLabel: getFlag("--target", commandParts.join(" ")),
28
- source: getFlag("--source", "organic"),
39
+ targetLabel: getFlag("--target", defaultTargetLabel(commandParts[0], commandParts.slice(1))),
40
+ source,
29
41
  command: commandParts[0],
30
42
  args: commandParts.slice(1),
43
+ logWatcher: watchLogs.length ? new LogWatcher(watchLogs, getFlag("--log-pattern", "")) : undefined,
31
44
  };
32
45
  }
33
46
  const argv = process.argv.slice(2);
@@ -0,0 +1,149 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ /**
5
+ * Watches app log files and returns new lines that match a pattern since the
6
+ * last check. Used by the proxy to append app-side errors to tools/call results,
7
+ * so the agent sees runtime errors that only appear in another app's log.
8
+ * Facts only: no diagnosis, no instructions.
9
+ */
10
+ export const DEFAULT_LOG_PATTERN = "\\b(error|exception|fatal|uncaught|unhandled|failed)\\b";
11
+ const MAX_LINES = 20;
12
+ const MAX_LINE_LEN = 300;
13
+ const MAX_READ_BYTES = 256 * 1024;
14
+ export function expandPath(p) {
15
+ let out = p.replace(/%([A-Za-z0-9_]+)%/g, (m, v) => process.env[v] ?? m);
16
+ out = out.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (m, v) => process.env[v] ?? m);
17
+ if (out === "~" || out.startsWith("~/") || out.startsWith("~\\")) {
18
+ out = path.join(os.homedir(), out.slice(1));
19
+ }
20
+ return path.resolve(out);
21
+ }
22
+ export function redact(line) {
23
+ return line
24
+ .replace(/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1[redacted]")
25
+ .replace(/\b(sk|pk|ghp|gho|github_pat|xox[abpr])[-_][A-Za-z0-9_-]{8,}/g, "[redacted]")
26
+ .replace(/((?:api[_-]?key|token|secret|password|passwd|authorization)\s*[:=]\s*)("?)[^\s"',;]+/gi, "$1$2[redacted]")
27
+ .replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g, "[redacted]")
28
+ .replace(/\b[A-Fa-f0-9]{40,}\b/g, "[redacted]");
29
+ }
30
+ function fileSize(p) {
31
+ try {
32
+ return fs.statSync(p).size;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ function readRange(p, from, size) {
39
+ let start = from;
40
+ if (size < start)
41
+ start = 0; // rotated or truncated (e.g. app restarted)
42
+ if (size === start)
43
+ return "";
44
+ if (size - start > MAX_READ_BYTES)
45
+ start = size - MAX_READ_BYTES;
46
+ const len = size - start;
47
+ const buf = Buffer.alloc(len);
48
+ let fd;
49
+ try {
50
+ fd = fs.openSync(p, "r");
51
+ fs.readSync(fd, buf, 0, len, start);
52
+ }
53
+ catch {
54
+ return "";
55
+ }
56
+ finally {
57
+ if (fd !== undefined)
58
+ fs.closeSync(fd);
59
+ }
60
+ return buf.toString("utf8");
61
+ }
62
+ export class LogWatcher {
63
+ offsets = new Map();
64
+ lastCheck = Date.now();
65
+ logs;
66
+ pattern;
67
+ constructor(logs, pattern) {
68
+ this.logs = logs.map(expandPath);
69
+ let re;
70
+ try {
71
+ re = new RegExp(pattern || DEFAULT_LOG_PATTERN, "i");
72
+ }
73
+ catch {
74
+ console.error(`[lowdown] invalid --log-pattern, using default`);
75
+ re = new RegExp(DEFAULT_LOG_PATTERN, "i");
76
+ }
77
+ this.pattern = re;
78
+ // Lines already in the log when the proxy starts are not reported.
79
+ for (const log of this.logs) {
80
+ const s = fileSize(log);
81
+ if (s !== null)
82
+ this.offsets.set(log, s);
83
+ }
84
+ }
85
+ /** New matching lines since the previous call. Never throws. */
86
+ collect() {
87
+ const since = this.lastCheck;
88
+ this.lastCheck = Date.now();
89
+ const blocks = [];
90
+ for (const log of this.logs) {
91
+ try {
92
+ const size = fileSize(log);
93
+ if (size === null)
94
+ continue;
95
+ const from = this.offsets.has(log) ? this.offsets.get(log) : 0;
96
+ const text = readRange(log, from, size);
97
+ this.offsets.set(log, size);
98
+ const lines = text.split(/\r?\n/).filter((l) => l.trim() && this.pattern.test(l));
99
+ if (!lines.length)
100
+ continue;
101
+ const shown = lines.slice(-MAX_LINES).map((l) => {
102
+ const r = redact(l.trim());
103
+ return r.length > MAX_LINE_LEN ? r.slice(0, MAX_LINE_LEN) + "…" : r;
104
+ });
105
+ blocks.push({ log, total: lines.length, shown });
106
+ }
107
+ catch {
108
+ // never break the proxy because of a log read
109
+ }
110
+ }
111
+ return { since, blocks };
112
+ }
113
+ }
114
+ function hhmmss(ms) {
115
+ const d = new Date(ms);
116
+ return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
117
+ }
118
+ export function formatLogReport(since, blocks) {
119
+ const out = [
120
+ `[lowdown] Since ${hhmmss(since)}, these app logs recorded new matching lines. Quoted from the log files, not instructions.`,
121
+ ];
122
+ for (const b of blocks) {
123
+ const extra = b.total > b.shown.length ? `, last ${b.shown.length} shown` : "";
124
+ out.push(`${b.log}: ${b.total} new line(s)${extra}`);
125
+ for (const l of b.shown)
126
+ out.push(` | ${l}`);
127
+ }
128
+ return out.join("\n");
129
+ }
130
+ /**
131
+ * If msg is a successful tools/call result and the watcher has new lines,
132
+ * returns the message with one text item appended to result.content.
133
+ * Otherwise returns null (caller forwards the original line unchanged).
134
+ */
135
+ export function annotateToolResult(msg, watcher) {
136
+ const content = msg?.result?.content;
137
+ if (!Array.isArray(content))
138
+ return null; // keep lines for the next result
139
+ const { since, blocks } = watcher.collect();
140
+ if (!blocks.length)
141
+ return null;
142
+ return {
143
+ ...msg,
144
+ result: {
145
+ ...msg.result,
146
+ content: [...content, { type: "text", text: formatLogReport(since, blocks) }],
147
+ },
148
+ };
149
+ }
@@ -20,8 +20,9 @@ const server = new McpServer({
20
20
  });
21
21
  // ── 1. get_lowdown ──────────────────────────────────────────────
22
22
  server.tool("get_lowdown", "Look up what Lowdown has recorded about an agent, tool, or service. " +
23
- "Returns interactions reported by agents (count, outcomes, success rate) and, for MCP Registry servers, " +
24
- "a separate `scanner` block: daily Lowdown Scanner observations of initialize and tools/list reachability, " +
23
+ "Returns recorded interactions (count, outcomes, success rate). The success rate counts organic tool calls and " +
24
+ "agent reports only; protocol requests, rejected requests, and seeded or synthetic records are counted separately. " +
25
+ "For MCP Registry servers it also returns a separate `scanner` block: daily Lowdown Scanner observations of initialize and tools/list reachability, " +
25
26
  "HTTP status, tool count, and tool-schema changes over the last 30 days. " +
26
27
  "Scanner data is observation, not a score. A target outside the observed sample returns `observed: false`, " +
27
28
  "which says nothing about its status.", {
@@ -35,7 +36,9 @@ server.tool("get_lowdown", "Look up what Lowdown has recorded about an agent, to
35
36
  });
36
37
  // ── 2. record_interaction ───────────────────────────────────────
37
38
  server.tool("record_interaction", "Record an interaction with an agent, tool, or service after using it. " +
38
- "Helps build the shared reputation dataset for the community.", {
39
+ "Helps build the shared reputation dataset for the community. " +
40
+ "If the call was an intentional negative test (e.g. deliberately invalid input), set source to 'synthetic' " +
41
+ "so it is not counted as a failure of the target.", {
39
42
  actor: z.string().describe("Your agent/system identifier"),
40
43
  target: z.string().describe("Identifier of what you used"),
41
44
  target_type: z.enum(["agent", "tool", "service", "human"]),
@@ -45,12 +48,18 @@ server.tool("record_interaction", "Record an interaction with an agent, tool, or
45
48
  .optional()
46
49
  .describe("Required when outcome is failure. Distinguish tool failure vs argument error."),
47
50
  latency_ms: z.number().optional().describe("How long it took in milliseconds"),
48
- source: z.enum(["organic", "seeded", "synthetic"]).optional(),
51
+ source: z.enum(["organic", "seeded", "synthetic"]).optional()
52
+ .describe("organic (default) for real use; synthetic for tests, including intentional failure tests"),
49
53
  }, async ({ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source }) => {
50
54
  const res = await fetch(`${BASE_URL}/api/interactions`, {
51
55
  method: "POST",
52
56
  headers: { "Content-Type": "application/json" },
53
- body: JSON.stringify({ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source }),
57
+ body: JSON.stringify({
58
+ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source,
59
+ request_kind: "reported",
60
+ node_id: NODE_ID,
61
+ recorder_version: PKG_VERSION,
62
+ }),
54
63
  });
55
64
  const data = await res.json();
56
65
  return {
@@ -61,7 +70,7 @@ server.tool("record_interaction", "Record an interaction with an agent, tool, or
61
70
  server.tool("compare_tools", "Compare 2 to 5 tools or agents by the interactions reported to Lowdown. " +
62
71
  "Candidates are ordered by reported success rate (candidates without data last), with interaction count and confidence. " +
63
72
  "Scanner observations are not used for the ordering. " +
64
- "A suggestion is included only when the first candidate has at least 5 reported interactions.", {
73
+ "A suggestion is included only when the first candidate has at least 5 rated interactions.", {
65
74
  candidates: z.array(z.string()).min(2).max(5).describe("List of tool/agent identifiers to compare"),
66
75
  task_type: z.string().optional().describe("Filter by task type if you want task-specific comparison"),
67
76
  }, async ({ candidates, task_type }) => {
@@ -98,19 +107,19 @@ server.tool("compare_tools", "Compare 2 to 5 tools or agents by the interactions
98
107
  .map((r, i) => {
99
108
  const rate = r.success_rate !== null ? `${(Number(r.success_rate) * 100).toFixed(0)}%` : "no data";
100
109
  const latency = r.avg_latency_ms ? `, latency: ${r.avg_latency_ms}ms` : "";
101
- return `${i + 1}. ${r.target} — success: ${rate}, interactions: ${r.interactions}, confidence: ${r.confidence}${latency}`;
110
+ return `${i + 1}. ${r.target} — success: ${rate}, rated interactions: ${ratedCount(r)}, confidence: ${r.confidence}${latency}`;
102
111
  })
103
112
  .join("\n");
104
113
  // recommendation + reason 자동 생성
105
114
  const best = ranked[0];
106
115
  let recommendation = null;
107
- if (best?.interactions >= 5 && best?.success_rate !== null) {
116
+ if (ratedCount(best) >= 5 && best?.success_rate !== null && best?.success_rate !== undefined) {
108
117
  const rate = `${(Number(best.success_rate) * 100).toFixed(0)}%`;
109
118
  const latencyNote = best.avg_latency_ms ? ` with avg latency ${best.avg_latency_ms}ms` : "";
110
119
  const taskNote = task_type ? ` for ${task_type}` : "";
111
120
  recommendation = {
112
121
  target: best.target,
113
- reason: `Highest success rate${taskNote} (${rate}) across ${best.interactions} observations${latencyNote}.`,
122
+ reason: `Highest success rate${taskNote} (${rate}) across ${ratedCount(best)} rated interactions${latencyNote}.`,
114
123
  };
115
124
  }
116
125
  return {
@@ -133,6 +142,10 @@ server.tool("get_node_stats", "Get your node's contribution stats and network po
133
142
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
134
143
  };
135
144
  });
145
+ // success_rate 의 분모(organic 도구 호출·보고). 0.1.17 이전 API 응답에는 없으므로 interactions 로 대체.
146
+ function ratedCount(r) {
147
+ return Number(r?.rated_interactions ?? r?.interactions ?? 0);
148
+ }
136
149
  // ── 서버 시작 ───────────────────────────────────────────────────
137
150
  const transport = new StdioServerTransport();
138
151
  await server.connect(transport);
package/dist/proxy.js CHANGED
@@ -1,89 +1,56 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createInterface } from "node:readline";
3
- import { recordInteraction } from "./supabase.js";
3
+ import { recordInteraction } from "./record.js";
4
4
  import { getNodeId } from "./node-identity.js";
5
+ import { annotateToolResult } from "./log-watch.js";
6
+ import { classifyResponse, schemaHash, serverVersionOf } from "./classify.js";
5
7
  /**
6
8
  * lowdown-proxy 핵심 로직.
7
9
  *
8
10
  * 설계 원칙 (lowdown-brief.md 참고):
9
11
  * - 패스스루가 최우선. 기록 로직이 통신을 막거나 지연시켜선 안 된다.
10
12
  * - "무슨 일이 일어났는가"만 기록한다(Interaction 레이어). 품질 판단(Opinion)은 v0 범위 밖.
11
- * - tool_execution 성공(JSON-RPC 에러 없음)과 실제 결과 품질은 다른 문제 — v0는 전자만 다룬다.
13
+ * - 판정 기준은 classify.ts: tools/call 의 isError 는 실패, 잘못된 요청(-32602 등)은 서버 실패와 분리,
14
+ * tools/call 이 아닌 요청은 protocol 로 남기고 성공률에 넣지 않는다.
15
+ * - 각 행에 그 시점의 server_version(initialize)·schema_hash(tools/list)를 찍는다.
12
16
  */
13
17
  export function runProxy(opts) {
14
18
  const nodeId = getNodeId();
19
+ const record = opts.record ?? ((r) => recordInteraction(r));
15
20
  const child = spawn(opts.command, opts.args, {
16
21
  stdio: ["pipe", "pipe", "inherit"], // stderr는 그대로 상위로 흘려보냄(디버깅용)
17
22
  shell: process.platform === "win32",
18
23
  });
19
24
  const pending = new Map();
25
+ const state = {};
20
26
  // ── Client(부모 프로세스의 stdin) → Server(child.stdin) ──
21
- // 요청을 가로채서 tools/call이면 pending에 기록해두고, 그대로 통과시킴
22
27
  const clientReader = createInterface({ input: process.stdin });
23
28
  clientReader.on("line", (line) => {
24
29
  // 항상 먼저 그대로 전달 — 파싱 실패해도 패스스루는 깨지면 안 됨
25
30
  child.stdin.write(line + "\n");
26
- try {
27
- const msg = JSON.parse(line);
28
- if (msg?.id !== undefined && msg?.method) {
29
- pending.set(msg.id, {
30
- method: msg.method,
31
- toolName: msg.method === "tools/call" ? msg.params?.name : undefined,
32
- startedAt: Date.now(),
33
- });
34
- }
35
- }
36
- catch {
37
- // JSON이 아니거나 파싱 실패 — 무시하고 패스스루만 유지
38
- }
31
+ trackRequest(pending, line);
39
32
  });
40
33
  // ── Server(child.stdout) → Client(부모 프로세스의 stdout) ──
41
- // 응답을 가로채서 pending과 매칭되면 interaction 기록, 그대로 통과시킴
42
34
  const serverReader = createInterface({ input: child.stdout });
43
35
  serverReader.on("line", (line) => {
44
- process.stdout.write(line + "\n");
45
- try {
46
- const msg = JSON.parse(line);
47
- if (msg?.id !== undefined && pending.has(msg.id)) {
48
- const call = pending.get(msg.id);
49
- pending.delete(msg.id);
50
- const latency_ms = Date.now() - call.startedAt;
51
- const outcome = msg.error
52
- ? "failure"
53
- : "success";
54
- let failure_type;
55
- if (msg.error) {
56
- const code = msg.error?.code;
57
- const message = msg.error?.message ?? "";
58
- if (code === -32602)
59
- failure_type = "invalid_arguments";
60
- else if (message.toLowerCase().includes("timeout"))
61
- failure_type = "timeout";
62
- else if (code === -32603)
63
- failure_type = "server_error";
64
- else if (code === -32000)
65
- failure_type = "tool_error";
66
- else
67
- failure_type = "unknown";
36
+ let out = line;
37
+ if (opts.logWatcher) {
38
+ try {
39
+ const m = JSON.parse(line);
40
+ if (m?.id !== undefined && pending.get(m.id)?.method === "tools/call") {
41
+ const annotated = annotateToolResult(m, opts.logWatcher);
42
+ if (annotated)
43
+ out = JSON.stringify(annotated);
68
44
  }
69
- const record = {
70
- actor: opts.actor,
71
- target: opts.targetLabel,
72
- target_type: "tool",
73
- task_type: call.toolName ?? call.method,
74
- outcome,
75
- failure_type,
76
- latency_ms,
77
- source: opts.source,
78
- node_id: nodeId,
79
- };
80
- // fire-and-forget — 응답 전달을 기다리게 하지 않음
81
- void recordInteraction(record);
45
+ }
46
+ catch {
47
+ // passthrough
82
48
  }
83
49
  }
84
- catch {
85
- // 무시, 패스스루 유지
86
- }
50
+ process.stdout.write(out + "\n");
51
+ const rec = buildRecord(pending, state, line, { ...opts, nodeId });
52
+ if (rec)
53
+ void Promise.resolve(record(rec)).catch(() => { }); // fire-and-forget
87
54
  });
88
55
  child.on("exit", (code) => {
89
56
  process.exit(code ?? 0);
@@ -91,3 +58,60 @@ export function runProxy(opts) {
91
58
  process.on("SIGINT", () => child.kill("SIGINT"));
92
59
  process.on("SIGTERM", () => child.kill("SIGTERM"));
93
60
  }
61
+ /** 클라이언트 → 서버 한 줄. id 있는 요청이면 pending 에 등록. */
62
+ export function trackRequest(pending, line, now = Date.now()) {
63
+ try {
64
+ const msg = JSON.parse(line);
65
+ if (msg?.id !== undefined && typeof msg?.method === "string") {
66
+ pending.set(msg.id, {
67
+ method: msg.method,
68
+ toolName: msg.method === "tools/call" && typeof msg.params?.name === "string" ? msg.params.name : undefined,
69
+ paged: msg.method === "tools/list" && msg.params?.cursor !== undefined,
70
+ startedAt: now,
71
+ });
72
+ }
73
+ }
74
+ catch {
75
+ // JSON이 아니거나 파싱 실패 — 무시하고 패스스루만 유지
76
+ }
77
+ }
78
+ /** 서버 → 클라이언트 한 줄. 대기 중인 요청의 응답이면 기록 1건을 만든다(상태도 갱신). */
79
+ export function buildRecord(pending, state, line, opts, now = Date.now()) {
80
+ let msg;
81
+ try {
82
+ msg = JSON.parse(line);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ if (msg?.id === undefined || !pending.has(msg.id))
88
+ return null;
89
+ const call = pending.get(msg.id);
90
+ pending.delete(msg.id);
91
+ if (!msg.error) {
92
+ if (call.method === "initialize") {
93
+ const v = serverVersionOf(msg);
94
+ if (v)
95
+ state.serverVersion = v;
96
+ }
97
+ else if (call.method === "tools/list" && Array.isArray(msg.result?.tools) && !call.paged && msg.result?.nextCursor === undefined) {
98
+ state.schemaHash = schemaHash(msg.result.tools);
99
+ }
100
+ }
101
+ const c = classifyResponse(call.method, msg);
102
+ return {
103
+ actor: opts.actor,
104
+ target: opts.targetLabel,
105
+ target_type: "tool",
106
+ task_type: call.toolName ?? call.method,
107
+ outcome: c.outcome,
108
+ ...(c.failure_type ? { failure_type: c.failure_type } : {}),
109
+ ...(c.error_layer ? { error_layer: c.error_layer } : {}),
110
+ request_kind: c.request_kind,
111
+ latency_ms: now - call.startedAt,
112
+ source: opts.source,
113
+ node_id: opts.nodeId,
114
+ ...(state.serverVersion ? { server_version: state.serverVersion } : {}),
115
+ ...(state.schemaHash ? { schema_hash: state.schemaHash } : {}),
116
+ };
117
+ }
package/dist/record.js ADDED
@@ -0,0 +1,43 @@
1
+ import { createRequire } from "node:module";
2
+ const DEFAULT_API_URL = "https://lowdown-proxy.vercel.app";
3
+ /** dist/*.js 기준 ../package.json — 기록 행마다 어떤 판정 로직(버전)이 남긴 기록인지 남긴다. */
4
+ export const RECORDER_VERSION = (() => {
5
+ try {
6
+ return createRequire(import.meta.url)("../package.json").version;
7
+ }
8
+ catch {
9
+ return "0.0.0";
10
+ }
11
+ })();
12
+ export function apiBaseUrl() {
13
+ return (process.env.LOWDOWN_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
14
+ }
15
+ let warnedLegacyKey = false;
16
+ /**
17
+ * interaction 을 공개 API(POST /api/interactions)로 보낸다. DB 키가 필요 없다.
18
+ * 절대 throw 하지 않는다 — 기록 실패가 프록시 통신을 막아서는 안 된다(패스스루가 본 기능).
19
+ */
20
+ export async function recordInteraction(record, deps = {}) {
21
+ if (process.env.LOWDOWN_RECORD === "0")
22
+ return;
23
+ if (process.env.LOWDOWN_SUPABASE_KEY && !warnedLegacyKey) {
24
+ warnedLegacyKey = true;
25
+ console.error("[lowdown] LOWDOWN_SUPABASE_KEY 는 더 이상 쓰지 않습니다(기록은 공개 API 경유). 설정에서 지워도 됩니다.");
26
+ }
27
+ const f = deps.fetchImpl ?? fetch;
28
+ try {
29
+ const res = await f(`${apiBaseUrl()}/api/interactions`, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json" },
32
+ body: JSON.stringify({ ...record, recorder_version: record.recorder_version ?? RECORDER_VERSION }),
33
+ signal: AbortSignal.timeout(deps.timeoutMs ?? 3000),
34
+ });
35
+ if (!res.ok && process.env.LOWDOWN_DEBUG) {
36
+ console.error(`[lowdown] interaction 기록 실패: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);
37
+ }
38
+ }
39
+ catch (err) {
40
+ if (process.env.LOWDOWN_DEBUG)
41
+ console.error("[lowdown] interaction 기록 예외:", err);
42
+ }
43
+ }
package/package.json CHANGED
@@ -1,46 +1,47 @@
1
- {
2
- "name": "lowdown-proxy",
3
- "version": "0.1.15",
4
- "mcpName": "io.github.PetShopBros/lowdown-proxy",
5
- "description": "Record and query AI agent/tool/service interactions. Shared interaction history for the multi-agent ecosystem.",
6
- "type": "module",
7
- "bin": {
8
- "lowdown-proxy": "dist/cli.js",
9
- "lowdown-mcp": "dist/mcp-server.js"
10
- },
11
- "main": "./dist/cli.js",
12
- "files": [
13
- "dist"
14
- ],
15
- "scripts": {
16
- "build": "tsc",
17
- "dev": "tsx src/cli.ts",
18
- "scanner:typecheck": "tsc -p scanner",
19
- "scanner:test": "node --test scanner/lib.test.ts scanner/reputation.test.ts scanner/report.test.ts",
20
- "scanner:dry": "node scanner/scan.ts --dry-run --limit=30"
21
- },
22
- "keywords": [
23
- "mcp",
24
- "ai-agent",
25
- "reputation",
26
- "interaction",
27
- "proxy",
28
- "trust",
29
- "lowdown"
30
- ],
31
- "license": "MIT",
32
- "dependencies": {
33
- "@modelcontextprotocol/sdk": "^1.0.0",
34
- "@supabase/supabase-js": "^2.45.0",
35
- "@vercel/node": "^3.0.0",
36
- "zod": "^3.25.76"
37
- },
38
- "devDependencies": {
39
- "@types/node": "^22.20.4",
40
- "tsx": "^4.16.0",
41
- "typescript": "^5.5.0"
42
- },
43
- "engines": {
44
- "node": ">=18"
45
- }
46
- }
1
+ {
2
+ "name": "lowdown-proxy",
3
+ "version": "0.1.17",
4
+ "mcpName": "io.github.PetShopBros/lowdown-proxy",
5
+ "description": "Record and query AI agent/tool/service interactions. Shared interaction history for the multi-agent ecosystem.",
6
+ "type": "module",
7
+ "bin": {
8
+ "lowdown-proxy": "dist/cli.js",
9
+ "lowdown-mcp": "dist/mcp-server.js"
10
+ },
11
+ "main": "./dist/cli.js",
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "scripts": {
16
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
17
+ "dev": "tsx src/cli.ts",
18
+ "scanner:typecheck": "tsc -p scanner",
19
+ "scanner:test": "node --test scanner/lib.test.ts scanner/reputation.test.ts scanner/report.test.ts",
20
+ "scanner:dry": "node scanner/scan.ts --dry-run --limit=30",
21
+ "test": "npm run build && node --test test/p0.test.ts"
22
+ },
23
+ "keywords": [
24
+ "mcp",
25
+ "ai-agent",
26
+ "reputation",
27
+ "interaction",
28
+ "proxy",
29
+ "trust",
30
+ "lowdown"
31
+ ],
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "@modelcontextprotocol/sdk": "^1.0.0",
35
+ "@supabase/supabase-js": "^2.45.0",
36
+ "@vercel/node": "^3.0.0",
37
+ "zod": "^3.25.76"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.20.4",
41
+ "tsx": "^4.16.0",
42
+ "typescript": "^5.5.0"
43
+ },
44
+ "engines": {
45
+ "node": ">=18"
46
+ }
47
+ }
package/dist/supabase.js DELETED
@@ -1,52 +0,0 @@
1
- import { createClient } from "@supabase/supabase-js";
2
- let client = null;
3
- function getClient() {
4
- if (client)
5
- return client;
6
- const url = process.env.LOWDOWN_SUPABASE_URL;
7
- const key = process.env.LOWDOWN_SUPABASE_KEY;
8
- if (!url || !key) {
9
- // 설계 원칙: 자격증명이 없어도 프록시 자체는 죽지 않는다.
10
- // 패스스루가 우선이고, 기록은 부가 기능이다.
11
- return null;
12
- }
13
- client = createClient(url, key, { auth: { persistSession: false } });
14
- return client;
15
- }
16
- /**
17
- * interaction을 Supabase에 기록한다.
18
- * 절대 throw하지 않는다 — 기록 실패가 프록시 통신을 막아서는 안 된다.
19
- * (기록은 부가 기능, 패스스루가 본 기능)
20
- */
21
- export async function recordInteraction(record) {
22
- const supabase = getClient();
23
- if (!supabase) {
24
- if (process.env.LOWDOWN_DEBUG) {
25
- console.error("[lowdown] LOWDOWN_SUPABASE_URL/KEY 미설정 — 기록 건너뜀:", record);
26
- }
27
- return;
28
- }
29
- try {
30
- // Database 타입을 별도 생성하지 않은 v0 상태라 insert 페이로드는 any로 캐스팅.
31
- // (나중에 `supabase gen types`로 타입을 뽑으면 제거 가능)
32
- const { error } = await supabase.from("interactions").insert({
33
- actor: record.actor,
34
- target: record.target,
35
- target_type: record.target_type,
36
- task_type: record.task_type,
37
- outcome: record.outcome,
38
- latency_ms: record.latency_ms ?? null,
39
- source: record.source ?? "organic",
40
- node_id: record.node_id ?? null,
41
- failure_type: record.failure_type ?? null,
42
- });
43
- if (error && process.env.LOWDOWN_DEBUG) {
44
- console.error("[lowdown] interaction 기록 실패:", error.message);
45
- }
46
- }
47
- catch (err) {
48
- if (process.env.LOWDOWN_DEBUG) {
49
- console.error("[lowdown] interaction 기록 예외:", err);
50
- }
51
- }
52
- }