lowdown-proxy 0.1.16 → 0.1.18

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,277 +1,302 @@
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 | command string |
104
- | `--source` | `organic` \| `seeded` \| `synthetic` (internal/testing only) | `organic` |
105
- | `--watch-log` | App log file to watch; repeat for several files (see [App logs in tool results](#app-logs-in-tool-results)) | none |
106
- | `--log-pattern` | Regular expression for log lines to report | error, exception, fatal, uncaught, unhandled, failed |
107
-
108
- ## Environment variables
109
-
110
- Required for recording. The proxy works as a pure pass-through without them.
111
-
112
- ```bash
113
- export LOWDOWN_SUPABASE_URL="https://xxxx.supabase.co"
114
- export LOWDOWN_SUPABASE_KEY="..."
115
- ```
116
-
117
- ## Public API
118
-
119
- No auth required.
120
-
121
- ```bash
122
- # Get reputation of a tool
123
- curl https://lowdown-proxy.vercel.app/api/reputation/brave-search
124
-
125
- # With node identity — returns richer data
126
- curl https://lowdown-proxy.vercel.app/api/reputation/brave-search \
127
- -H "x-lowdown-node-id: ld_your_node_id"
128
-
129
- # Check your node's contribution
130
- curl https://lowdown-proxy.vercel.app/api/node/ld_your_node_id
131
-
132
- # Record an interaction
133
- curl -X POST https://lowdown-proxy.vercel.app/api/interactions \
134
- -H "Content-Type: application/json" \
135
- -d '{"actor":"agent:my-bot","target":"mcp:modelcontextprotocol/brave-search","target_type":"tool","task_type":"web_search","outcome":"success"}'
136
- ```
137
-
138
- Basic response (no node):
139
-
140
- ```json
141
- {
142
- "target": "brave-search",
143
- "interactions": 30,
144
- "success_rate": 0.933,
145
- "confidence": "medium"
146
- }
147
- ```
148
-
149
- Contributor response (with node):
150
-
151
- ```json
152
- {
153
- "target": "brave-search",
154
- "interactions": 30,
155
- "success_rate": 0.933,
156
- "confidence": "medium",
157
- "task_breakdown": { ... },
158
- "recent_trends": [ ... ]
159
- }
160
- ```
161
-
162
- Fuzzy matching supported — short names like `brave-search`, `fetch`, `github` resolve automatically.
163
-
164
- ### Scanner observations
165
-
166
- 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`.
167
-
168
- ```bash
169
- curl https://lowdown-proxy.vercel.app/api/reputation/mcp:io.github.user/server
170
- ```
171
-
172
- ```json
173
- {
174
- "target": "mcp:io.github.user/server",
175
- "interactions": 0,
176
- "success_rate": null,
177
- "scanner": {
178
- "target": "mcp:io.github.user/server",
179
- "last_observed_at": "2026-10-07T19:17:00+00:00",
180
- "observations_30d": 28,
181
- "latest": { "reached_level": 2, "http_status": 200, "latency_ms": 312, "tool_count": 7 },
182
- "schema_versions_30d": 1,
183
- "status_distribution_30d": { "200": 28 }
184
- }
185
- }
186
- ```
187
-
188
- HTTP statuses are reported as observed — a `401` is a `401`, not "dead".
189
-
190
- ## Why Lowdown
191
-
192
- 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.
193
-
194
- 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.
195
-
196
- The loop is simple:
197
- - **Read**: query observed history before selecting a tool
198
- - **Use**: run the tool through the proxy
199
- - **Write**: the result is automatically recorded for the next agent
200
-
201
- No ratings. No human curation. Just signal from actual use.
202
-
203
- > Observations are interaction data, not independent quality judgments.
204
-
205
- ## How the network works
206
-
207
- ```
208
- Run proxy → node_id auto-created → interactions contributed → deeper Lowdown data
209
- ```
210
-
211
- Every proxy instance is a node.
212
-
213
- Nodes contribute interaction data to the shared network.
214
- Contributors get access to richer query results.
215
-
216
- No tokens.
217
- No points.
218
- No reviews to write.
219
-
220
- Just run the proxy and share what your agents experience.
221
-
222
- ## Design principles
223
-
224
- - **Zero config**: run the proxy, everything else is automatic.
225
- - **Pass-through first**: recording never blocks or degrades MCP communication.
226
- - **Facts only**: v0 records success/failure and latency. Quality judgments are out of scope.
227
- - **Provenance always tagged**: every record carries `organic` / `seeded` / `synthetic` so bootstrap data and real traffic are always distinguishable.
228
-
229
- ## Status
230
-
231
- 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).
232
- See [DESIGN.md](./DESIGN.md) for what's in scope and what's been ruled out.
233
-
234
- ## License
235
-
236
- MIT
237
-
238
- ---
239
-
240
- ## 한국어
241
-
242
- 한 번도 거래한 적 없는 상대를 에이전트가 무조건 신뢰할 필요는 없습니다.
243
-
244
- `lowdown-proxy`는 AI 에이전트, 도구, 서비스 사이의 상호작용을 기록하고,
245
- 그 이력을 누구나 조회할 수 있게 만듭니다. 도구를 선택하거나, API를 호출하거나,
246
- 다른 에이전트에게 작업을 위임하기 전에 물어볼 수 있습니다:
247
- *네트워크는 이 상대에 대해 무엇을 봤는가?*
248
-
249
- MCP 서버를 감싸는 stdio 프록시가 첫 번째 진입점입니다.
250
- 평판 레이어는 MCP에 국한되지 않고 모든 에이전트, 도구, 서비스에 열려 있습니다.
251
-
252
- 기록된 데이터는 다른 에이전트가 판단할 때 참고할 수 있는 최소한의 공통 근거가 됩니다.
253
-
254
- ### 네트워크 구조
255
-
256
- ```
257
- 프록시 실행 → node_id 자동 생성 → interaction 기여 → 더 깊은 Lowdown 조회
258
- ```
259
-
260
- 프록시를 실행하는 것 자체가 노드 참여입니다. 기여할수록 더 상세한 데이터를 조회할 수 있습니다.
261
-
262
- ### Scanner 관찰 데이터
263
-
264
- 공식 MCP Registry에 등록된 원격 MCP 서버는 응답에 `scanner` 블록이 함께 옵니다. Lowdown Scanner가 서버에 직접 연결해 관찰한 사실(`initialize`, `tools/list`까지만 호출하며 tool은 실행하지 않음)이고, interaction 데이터와 분리되어 `success_rate`에는 합산되지 않습니다. HTTP 상태는 해석 없이 관찰된 값 그대로 보여줍니다.
265
-
266
- ### 앱 로그를 도구 결과에 붙이기
267
-
268
- 도구 호출은 성공했는데 그 뒤의 앱(씬, 게임, 개발 서버)이 실패하는 경우가 있습니다. 진짜 에러는 앱의 로그 파일에만 찍혀서 에이전트는 모릅니다. `--watch-log`를 주면 `tools/call` 결과마다 직전 호출 이후 로그에 새로 찍힌 줄 중 `--log-pattern`에 맞는 줄이 결과 끝에 붙습니다. 에이전트가 따로 호출할 것은 없습니다. 로그 내용은 로컬에만 머물고 Lowdown에 기록되지 않습니다.
269
-
270
- ### 설계 원칙 (요약)
271
-
272
- - **설정 없음**: 프록시를 실행하면 모든 것이 자동으로 처리됩니다.
273
- - **패스스루 우선**: 기록 로직이 실패하거나 느려도 실제 MCP 통신은 절대 막지 않습니다.
274
- - **사실만 기록**: v0는 성공/실패/지연시간만 기록합니다. 품질 판단은 범위 밖입니다.
275
- - **출처 구분**: 모든 기록은 `organic` / `seeded` / `synthetic`으로 태깅됩니다.
276
-
1
+ # lowdown-proxy
2
+
3
+ [![Listed on mcpservers.org](https://mcpservers.org/badge.svg)](https://mcpservers.org/servers/petshopbros/lowdown-proxy)
4
+
5
+ Agents should not have to trust anyone they've never interacted with.
6
+
7
+ `lowdown-proxy` records interactions between AI agents, tools, and services — and makes
8
+ that history queryable by anyone. Before choosing a tool, calling an API, or delegating
9
+ to another agent, you can ask: *what has the network seen from this one?*
10
+
11
+ 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.
12
+
13
+ See [DESIGN.md](./DESIGN.md) for background and design principles.
14
+
15
+ ## Quick start
16
+
17
+ ```bash
18
+ npx lowdown-proxy -- npx some-mcp-server
19
+ ```
20
+
21
+ 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.
22
+
23
+ Wrap any MCP server in your client config:
24
+
25
+ ```jsonc
26
+ // before
27
+ {
28
+ "mcpServers": {
29
+ "search": { "command": "npx", "args": ["search-mcp-server"] }
30
+ }
31
+ }
32
+
33
+ // after
34
+ {
35
+ "mcpServers": {
36
+ "search": {
37
+ "command": "npx",
38
+ "args": ["lowdown-proxy", "--target", "search-mcp-server", "--", "npx", "search-mcp-server"]
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ ## Lookup tools for agents (MCP server)
45
+
46
+ The same package ships an MCP server (stdio) that lets an agent query Lowdown directly:
47
+
48
+ ```jsonc
49
+ {
50
+ "mcpServers": {
51
+ "lowdown": { "command": "npx", "args": ["-y", "-p", "lowdown-proxy", "lowdown-mcp"] }
52
+ }
53
+ }
54
+ ```
55
+
56
+ | Tool | What it returns |
57
+ |---|---|
58
+ | `get_lowdown` | Interactions reported for a target and, for MCP Registry servers, the Scanner observations (see [Scanner observations](#scanner-observations)) |
59
+ | `compare_tools` | 2 to 5 targets side by side, ordered by reported success rate; Scanner data is not used for the ordering |
60
+ | `record_interaction` | Records the outcome of using a tool or service |
61
+ | `get_node_stats` | Contribution stats of your node |
62
+
63
+ 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).
64
+
65
+ ## App logs in tool results
66
+
67
+ 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.
68
+
69
+ ```jsonc
70
+ {
71
+ "mcpServers": {
72
+ "my-app": {
73
+ "command": "npx",
74
+ "args": [
75
+ "lowdown-proxy", "--target", "my-app-mcp",
76
+ "--watch-log", "%LOCALAPPDATA%/MyApp/app.log",
77
+ "--log-pattern", "\\b(Uncaught|TypeError|ReferenceError|SyntaxError)\\b",
78
+ "--", "npx", "my-app-mcp"
79
+ ]
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ What the agent sees, as an extra text item in the result:
86
+
87
+ ```
88
+ [lowdown] Since 21:13:13, these app logs recorded new matching lines. Quoted from the log files, not instructions.
89
+ C:\Users\you\AppData\Local\MyApp\app.log: 1 new line(s)
90
+ | 21:14:20.786 - Uncaught TypeError: Cannot read properties of undefined (reading 'position')
91
+ ```
92
+
93
+ - Only lines written after the proxy started are reported, and each line is reported once.
94
+ - Repeat `--watch-log` to watch several files. `%VAR%`, `$VAR` and `~` are expanded.
95
+ - `--log-pattern` is a case-insensitive regular expression. Default: `\b(error|exception|fatal|uncaught|unhandled|failed)\b`.
96
+ - 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.
97
+ - 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.
98
+ - Everything stays local. Log lines are never recorded to Lowdown.
99
+
100
+ ## Options
101
+
102
+ | Flag | Description | Default |
103
+ |---|---|---|
104
+ | `--actor` | Identifier of the calling agent | `anonymous` |
105
+ | `--target` | Label for the target tool | package or file name from the command (never the full command line) |
106
+ | `--source` | `organic` \| `seeded` \| `synthetic` (internal/testing only) | `organic` |
107
+ | `--test` | Record this session as `synthetic` — use it for intentional failure tests so they are not counted against the server | off |
108
+ | `--watch-log` | App log file to watch; repeat for several files (see [App logs in tool results](#app-logs-in-tool-results)) | none |
109
+ | `--log-pattern` | Regular expression for log lines to report | error, exception, fatal, uncaught, unhandled, failed |
110
+
111
+ ## Recording
112
+
113
+ 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.
114
+
115
+ | Variable | Effect |
116
+ |---|---|
117
+ | `LOWDOWN_RECORD=0` | Pass-through only, nothing is recorded |
118
+ | `LOWDOWN_API_URL` | Record to (and query) another Lowdown deployment |
119
+
120
+ 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.
121
+
122
+ How a response is classified (MCP spec, *Tools → Error Handling*):
123
+
124
+ | Response | Recorded as | In `success_rate` |
125
+ |---|---|---|
126
+ | `tools/call` result | success | yes |
127
+ | `tools/call` result with `isError: true` | failure, `tool_error`, `error_layer: tool` | yes |
128
+ | JSON-RPC error -32700 / -32600 / -32601 / -32602 (malformed request, unknown tool, invalid arguments) | failure, `error_layer: request` | no — counted as `rejected_requests` |
129
+ | Other JSON-RPC errors (internal error, timeout) | failure, `error_layer: server` | yes |
130
+ | `initialize`, `tools/list`, `ping`, ... | `request_kind: protocol` | no — counted as `protocol_requests` |
131
+
132
+ `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.
133
+
134
+ ## Public API
135
+
136
+ No auth required.
137
+
138
+ ```bash
139
+ # What Lowdown has recorded about an MCP Registry server
140
+ curl https://lowdown-proxy.vercel.app/api/reputation/mcp:ai.agent-bev/bev-door
141
+
142
+ # A short name works when it matches one server; otherwise candidate names are returned
143
+ curl https://lowdown-proxy.vercel.app/api/reputation/bev-door
144
+
145
+ # With node identity: adds task_breakdown and recent_trends for reported interactions
146
+ curl https://lowdown-proxy.vercel.app/api/reputation/mcp:ai.agent-bev/bev-door \
147
+ -H "x-lowdown-node-id: ld_your_node_id"
148
+
149
+ # Check your node's contribution
150
+ curl https://lowdown-proxy.vercel.app/api/node/ld_your_node_id
151
+
152
+ # Record an interaction (replace the example values with your own)
153
+ curl -X POST https://lowdown-proxy.vercel.app/api/interactions \
154
+ -H "Content-Type: application/json" \
155
+ -d '{"actor":"agent:my-bot","target":"mcp:io.github.user/server","target_type":"tool","task_type":"web_search","outcome":"success"}'
156
+ ```
157
+
158
+ Registry names contain `/`; it can be written as is or encoded as `%2F`.
159
+
160
+ Response for that server on 2026-10-20 (trimmed: the full response has 14 daily entries, the observed tool names, and the observation method):
161
+
162
+ ```json
163
+ {
164
+ "target": "mcp:ai.agent-bev/bev-door",
165
+ "resolved_target": "mcp:ai.agent-bev/bev-door",
166
+ "message": "MCP Registry declaration recorded; observed daily by Lowdown Scanner since 2026-10-06; no agent-reported interactions.",
167
+ "registry": {
168
+ "listed": true,
169
+ "declared_version": "0.2.5",
170
+ "status": "active",
171
+ "remote_hosts": ["mcp.bev-buyer.ai"],
172
+ "recorded_since_baseline": true,
173
+ "changes_30d": []
174
+ },
175
+ "scanner": {
176
+ "last_observed_at": "2026-10-19T06:19:57.397+00:00",
177
+ "latest": { "reached_level": 2, "http_status": 200, "tool_count": 9, "server_version": "0.2.5" },
178
+ "in_sample": true,
179
+ "first_observed_at": "2026-10-06T19:59:59.739+00:00",
180
+ "daily_30d": [
181
+ { "day": "2026-10-18", "reached_level": 2, "http_status": 200, "tool_count": 9, "tools_changed": false },
182
+ { "day": "2026-10-19", "reached_level": 2, "http_status": 200, "tool_count": 9, "tools_changed": false }
183
+ ],
184
+ "missing_days": [],
185
+ "declared_vs_observed": {
186
+ "declared_version": "0.2.5",
187
+ "observed_server_version": "0.2.5",
188
+ "declared_hosts": ["mcp.bev-buyer.ai"],
189
+ "observed_hosts": ["mcp.bev-buyer.ai"]
190
+ }
191
+ },
192
+ "interactions": 0,
193
+ "success_rate": null,
194
+ "confidence": "none"
195
+ }
196
+ ```
197
+
198
+ - `registry`: what the official MCP Registry declares for the server, as recorded by Lowdown since 2026-10-19, with changes in the last 30 days. It answers for any Registry entry, observed or not.
199
+ - `scanner`: what Lowdown Scanner observed when it connected (`initialize` and `tools/list` only; it never calls a tool): one entry per day for the last 30 days, days without an observation and the recorded reason, the tool names returned by `tools/list`, and declared values next to observed ones. HTTP statuses are reported as observed: a `401` is a `401`, not "dead". A server outside the observed sample returns `observed: false`, which says nothing about its status.
200
+ - Interaction fields: `interactions` is every reported record for the target; `rated_interactions` is the denominator of `success_rate`, and `confidence` is based on it. Scanner observations are never counted in `success_rate`.
201
+
202
+ These are recorded facts with their sources, not scores or rankings. The full schema is in [`openapi.json`](https://lowdown-proxy.vercel.app/openapi.json).
203
+
204
+ ## Why Lowdown
205
+
206
+ 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.
207
+
208
+ 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.
209
+
210
+ The loop is simple:
211
+ - **Read**: query observed history before selecting a tool
212
+ - **Use**: run the tool through the proxy
213
+ - **Write**: the result is automatically recorded for the next agent
214
+
215
+ No ratings. No human curation. Just signal from actual use.
216
+
217
+ > Observations are interaction data, not independent quality judgments.
218
+
219
+ ## How the network works
220
+
221
+ ```
222
+ Run proxy → node_id auto-created → interactions contributed → deeper Lowdown data
223
+ ```
224
+
225
+ Every proxy instance is a node.
226
+
227
+ Nodes contribute interaction data to the shared network.
228
+ Contributors get access to richer query results.
229
+
230
+ No tokens.
231
+ No points.
232
+ No reviews to write.
233
+
234
+ Just run the proxy and share what your agents experience.
235
+
236
+ ## Design principles
237
+
238
+ - **Zero config**: run the proxy, everything else is automatic.
239
+ - **Pass-through first**: recording never blocks or degrades MCP communication.
240
+ - **Facts only**: v0 records success/failure and latency. Quality judgments are out of scope.
241
+ - **Provenance always tagged**: every record carries `organic` / `seeded` / `synthetic` so bootstrap data and real traffic are always distinguishable.
242
+
243
+ ## Status
244
+
245
+ Running continuously since September 2026. Since October 6, 2026 the Scanner has observed a fixed sample of MCP Registry entries every day: 2,000 entries through October 18, and from October 19 a 5,000-entry sample that keeps all of the first 2,000. The daily report and raw data are public at [PetShopBros/lowdown-data](https://github.com/PetShopBros/lowdown-data).
246
+ See [DESIGN.md](./DESIGN.md) for what's in scope and what's been ruled out.
247
+
248
+ ## License
249
+
250
+ MIT
251
+
252
+ ---
253
+
254
+ ## 한국어
255
+
256
+ 한 번도 거래한 적 없는 상대를 에이전트가 무조건 신뢰할 필요는 없습니다.
257
+
258
+ `lowdown-proxy`는 AI 에이전트, 도구, 서비스 사이의 상호작용을 기록하고,
259
+ 그 이력을 누구나 조회할 수 있게 만듭니다. 도구를 선택하거나, API를 호출하거나,
260
+ 다른 에이전트에게 작업을 위임하기 전에 물어볼 수 있습니다:
261
+ *네트워크는 이 상대에 대해 무엇을 봤는가?*
262
+
263
+ MCP 서버를 감싸는 stdio 프록시가 첫 번째 진입점입니다.
264
+ 평판 레이어는 MCP에 국한되지 않고 모든 에이전트, 도구, 서비스에 열려 있습니다.
265
+
266
+ 기록된 데이터는 다른 에이전트가 판단할 때 참고할 수 있는 최소한의 공통 근거가 됩니다.
267
+
268
+ ### 네트워크 구조
269
+
270
+ ```
271
+ 프록시 실행 → node_id 자동 생성 → interaction 기여 → 더 깊은 Lowdown 조회
272
+ ```
273
+
274
+ 프록시를 실행하는 것 자체가 노드 참여입니다. 기여할수록 더 상세한 데이터를 조회할 수 있습니다.
275
+
276
+ ### Scanner 관찰 데이터
277
+
278
+ 공식 MCP Registry에 등록된 원격 MCP 서버는 응답에 `scanner` 블록이 함께 옵니다. Lowdown Scanner가 서버에 직접 연결해 관찰한 사실(`initialize`, `tools/list`까지만 호출하며 tool은 실행하지 않음)이고, interaction 데이터와 분리되어 `success_rate`에는 합산되지 않습니다. HTTP 상태는 해석 없이 관찰된 값 그대로 보여줍니다.
279
+
280
+ ### 앱 로그를 도구 결과에 붙이기
281
+
282
+ 도구 호출은 성공했는데 그 뒤의 앱(씬, 게임, 개발 서버)이 실패하는 경우가 있습니다. 진짜 에러는 앱의 로그 파일에만 찍혀서 에이전트는 모릅니다. `--watch-log`를 주면 `tools/call` 결과마다 직전 호출 이후 로그에 새로 찍힌 줄 중 `--log-pattern`에 맞는 줄이 결과 끝에 붙습니다. 에이전트가 따로 호출할 것은 없습니다. 로그 내용은 로컬에만 머물고 Lowdown에 기록되지 않습니다.
283
+
284
+ ### 기록 방식 (0.1.17~)
285
+
286
+ 프록시는 공개 API(`POST /api/interactions`)로 기록합니다. DB 키가 필요 없고 `LOWDOWN_SUPABASE_URL` / `LOWDOWN_SUPABASE_KEY`는 더 이상 쓰지 않습니다. `LOWDOWN_RECORD=0`이면 기록 없이 패스스루만 합니다.
287
+
288
+ - `tools/call` 결과의 `isError: true`는 실패(`tool_error`)로 기록합니다.
289
+ - 잘못된 요청(-32700/-32600/-32601/-32602: 형식 오류, 없는 도구, 잘못된 인자)은 서버 실패와 분리해 `rejected_requests`로 셉니다. `success_rate`에는 들어가지 않습니다.
290
+ - `initialize`, `tools/list` 같은 비도구 요청은 `protocol_requests`로 따로 셉니다.
291
+ - `success_rate`는 `organic` 기록만 계산합니다. `seeded` / `synthetic`은 `by_source`로 따로 보여줍니다. 일부러 실패시키는 테스트는 `--test`로 실행하면 `synthetic`으로 남습니다.
292
+ - 각 기록에는 그 시점의 `server_version`(initialize), `schema_hash`(tools/list, Scanner와 같은 계산), `recorder_version`이 함께 남습니다. 인자와 결과 내용은 기록하지 않습니다.
293
+ - `--target`을 주지 않으면 명령줄 전체가 아니라 패키지·파일 이름 하나만 라벨로 씁니다.
294
+
295
+ ### 설계 원칙 (요약)
296
+
297
+ - **설정 없음**: 프록시를 실행하면 모든 것이 자동으로 처리됩니다.
298
+ - **패스스루 우선**: 기록 로직이 실패하거나 느려도 실제 MCP 통신은 절대 막지 않습니다.
299
+ - **사실만 기록**: v0는 성공/실패/지연시간만 기록합니다. 품질 판단은 범위 밖입니다.
300
+ - **출처 구분**: 모든 기록은 `organic` / `seeded` / `synthetic`으로 태깅됩니다.
301
+
277
302
  자세한 배경과 설계 원칙은 [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,14 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { runProxy } from "./proxy.js";
3
3
  import { LogWatcher } from "./log-watch.js";
4
+ import { defaultTargetLabel } from "./classify.js";
4
5
  // 사용법:
5
6
  // npx lowdown-proxy → 인자 없음: Lowdown 조회용 MCP 서버(stdio) 시작 (Registry 설치 경로)
6
- // 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...]
7
8
  // → MCP 서버를 감싸는 기록 프록시
9
+ // --test : 이 세션의 기록을 synthetic 으로 남긴다(일부러 실패시키는 테스트가 서버 실패로 집계되지 않게).
10
+ // --target 이 없으면 명령줄 전체가 아니라 패키지/파일 이름 하나만 라벨로 쓴다(인자의 키·경로가 공개 기록에 남지 않게).
8
11
  function parseArgs(argv) {
9
12
  const dashIndex = argv.indexOf("--");
10
13
  if (dashIndex === -1) {
11
- 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" +
12
15
  "예시: lowdown-proxy -- npx some-mcp-server\n" +
13
16
  "인자 없이 실행하면 Lowdown 조회용 MCP 서버가 시작됩니다.");
14
17
  process.exit(1);
@@ -25,10 +28,16 @@ function parseArgs(argv) {
25
28
  };
26
29
  const getAll = (name) => flags.flatMap((f, i) => (f === name && flags[i + 1] ? [flags[i + 1]] : []));
27
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);
28
37
  return {
29
38
  actor: getFlag("--actor", "anonymous"),
30
- targetLabel: getFlag("--target", commandParts.join(" ")),
31
- source: getFlag("--source", "organic"),
39
+ targetLabel: getFlag("--target", defaultTargetLabel(commandParts[0], commandParts.slice(1))),
40
+ source,
32
41
  command: commandParts[0],
33
42
  args: commandParts.slice(1),
34
43
  logWatcher: watchLogs.length ? new LogWatcher(watchLogs, getFlag("--log-pattern", "")) : undefined,
@@ -19,12 +19,12 @@ const server = new McpServer({
19
19
  version: PKG_VERSION,
20
20
  });
21
21
  // ── 1. get_lowdown ──────────────────────────────────────────────
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, " +
25
- "HTTP status, tool count, and tool-schema changes over the last 30 days. " +
26
- "Scanner data is observation, not a score. A target outside the observed sample returns `observed: false`, " +
27
- "which says nothing about its status.", {
22
+ server.tool("get_lowdown", "Look up what Lowdown has recorded about an MCP server, agent, tool, or service before choosing or connecting to it. " +
23
+ "For MCP Registry servers it returns, in order: a `registry` block (what the official MCP Registry declares, and changes in the last 30 days); " +
24
+ "a `scanner` block (daily Lowdown Scanner observations of initialize and tools/list over the last 30 days, one entry per day, days without an observation and why, " +
25
+ "the tool names observed, and declared versus observed version and hosts); and interactions reported by agents (count, outcomes, success rate). " +
26
+ "The success rate counts organic tool calls and agent reports only; protocol requests, rejected requests, and seeded or synthetic records are counted separately. " +
27
+ "These are recorded facts, not scores. A server outside the observed sample returns `observed: false` in `scanner`, which says nothing about its status.", {
28
28
  target: z.string().describe("MCP Registry name with the mcp: prefix (e.g. 'mcp:io.github.user/server'), a short name, or an id such as 'agent:some-agent-id'"),
29
29
  }, async ({ target }) => {
30
30
  const res = await fetch(`${BASE_URL}/api/reputation/${encodeURIComponent(target)}`, { headers: { "x-lowdown-source": "organic", "x-lowdown-node-id": NODE_ID } });
@@ -35,7 +35,9 @@ server.tool("get_lowdown", "Look up what Lowdown has recorded about an agent, to
35
35
  });
36
36
  // ── 2. record_interaction ───────────────────────────────────────
37
37
  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.", {
38
+ "Helps build the shared reputation dataset for the community. " +
39
+ "If the call was an intentional negative test (e.g. deliberately invalid input), set source to 'synthetic' " +
40
+ "so it is not counted as a failure of the target.", {
39
41
  actor: z.string().describe("Your agent/system identifier"),
40
42
  target: z.string().describe("Identifier of what you used"),
41
43
  target_type: z.enum(["agent", "tool", "service", "human"]),
@@ -45,12 +47,18 @@ server.tool("record_interaction", "Record an interaction with an agent, tool, or
45
47
  .optional()
46
48
  .describe("Required when outcome is failure. Distinguish tool failure vs argument error."),
47
49
  latency_ms: z.number().optional().describe("How long it took in milliseconds"),
48
- source: z.enum(["organic", "seeded", "synthetic"]).optional(),
50
+ source: z.enum(["organic", "seeded", "synthetic"]).optional()
51
+ .describe("organic (default) for real use; synthetic for tests, including intentional failure tests"),
49
52
  }, async ({ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source }) => {
50
53
  const res = await fetch(`${BASE_URL}/api/interactions`, {
51
54
  method: "POST",
52
55
  headers: { "Content-Type": "application/json" },
53
- body: JSON.stringify({ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source }),
56
+ body: JSON.stringify({
57
+ actor, target, target_type, task_type, outcome, failure_type, latency_ms, source,
58
+ request_kind: "reported",
59
+ node_id: NODE_ID,
60
+ recorder_version: PKG_VERSION,
61
+ }),
54
62
  });
55
63
  const data = await res.json();
56
64
  return {
@@ -61,7 +69,7 @@ server.tool("record_interaction", "Record an interaction with an agent, tool, or
61
69
  server.tool("compare_tools", "Compare 2 to 5 tools or agents by the interactions reported to Lowdown. " +
62
70
  "Candidates are ordered by reported success rate (candidates without data last), with interaction count and confidence. " +
63
71
  "Scanner observations are not used for the ordering. " +
64
- "A suggestion is included only when the first candidate has at least 5 reported interactions.", {
72
+ "A suggestion is included only when the first candidate has at least 5 rated interactions.", {
65
73
  candidates: z.array(z.string()).min(2).max(5).describe("List of tool/agent identifiers to compare"),
66
74
  task_type: z.string().optional().describe("Filter by task type if you want task-specific comparison"),
67
75
  }, async ({ candidates, task_type }) => {
@@ -98,19 +106,19 @@ server.tool("compare_tools", "Compare 2 to 5 tools or agents by the interactions
98
106
  .map((r, i) => {
99
107
  const rate = r.success_rate !== null ? `${(Number(r.success_rate) * 100).toFixed(0)}%` : "no data";
100
108
  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}`;
109
+ return `${i + 1}. ${r.target} — success: ${rate}, rated interactions: ${ratedCount(r)}, confidence: ${r.confidence}${latency}`;
102
110
  })
103
111
  .join("\n");
104
112
  // recommendation + reason 자동 생성
105
113
  const best = ranked[0];
106
114
  let recommendation = null;
107
- if (best?.interactions >= 5 && best?.success_rate !== null) {
115
+ if (ratedCount(best) >= 5 && best?.success_rate !== null && best?.success_rate !== undefined) {
108
116
  const rate = `${(Number(best.success_rate) * 100).toFixed(0)}%`;
109
117
  const latencyNote = best.avg_latency_ms ? ` with avg latency ${best.avg_latency_ms}ms` : "";
110
118
  const taskNote = task_type ? ` for ${task_type}` : "";
111
119
  recommendation = {
112
120
  target: best.target,
113
- reason: `Highest success rate${taskNote} (${rate}) across ${best.interactions} observations${latencyNote}.`,
121
+ reason: `Highest success rate${taskNote} (${rate}) across ${ratedCount(best)} rated interactions${latencyNote}.`,
114
122
  };
115
123
  }
116
124
  return {
@@ -133,6 +141,10 @@ server.tool("get_node_stats", "Get your node's contribution stats and network po
133
141
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
134
142
  };
135
143
  });
144
+ // success_rate 의 분모(organic 도구 호출·보고). 0.1.17 이전 API 응답에는 없으므로 interactions 로 대체.
145
+ function ratedCount(r) {
146
+ return Number(r?.rated_interactions ?? r?.interactions ?? 0);
147
+ }
136
148
  // ── 서버 시작 ───────────────────────────────────────────────────
137
149
  const transport = new StdioServerTransport();
138
150
  await server.connect(transport);
package/dist/proxy.js CHANGED
@@ -1,45 +1,36 @@
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
5
  import { annotateToolResult } from "./log-watch.js";
6
+ import { classifyResponse, schemaHash, serverVersionOf } from "./classify.js";
6
7
  /**
7
8
  * lowdown-proxy 핵심 로직.
8
9
  *
9
10
  * 설계 원칙 (lowdown-brief.md 참고):
10
11
  * - 패스스루가 최우선. 기록 로직이 통신을 막거나 지연시켜선 안 된다.
11
12
  * - "무슨 일이 일어났는가"만 기록한다(Interaction 레이어). 품질 판단(Opinion)은 v0 범위 밖.
12
- * - tool_execution 성공(JSON-RPC 에러 없음)과 실제 결과 품질은 다른 문제 — v0는 전자만 다룬다.
13
+ * - 판정 기준은 classify.ts: tools/call 의 isError 는 실패, 잘못된 요청(-32602 등)은 서버 실패와 분리,
14
+ * tools/call 이 아닌 요청은 protocol 로 남기고 성공률에 넣지 않는다.
15
+ * - 각 행에 그 시점의 server_version(initialize)·schema_hash(tools/list)를 찍는다.
13
16
  */
14
17
  export function runProxy(opts) {
15
18
  const nodeId = getNodeId();
19
+ const record = opts.record ?? ((r) => recordInteraction(r));
16
20
  const child = spawn(opts.command, opts.args, {
17
21
  stdio: ["pipe", "pipe", "inherit"], // stderr는 그대로 상위로 흘려보냄(디버깅용)
18
22
  shell: process.platform === "win32",
19
23
  });
20
24
  const pending = new Map();
25
+ const state = {};
21
26
  // ── Client(부모 프로세스의 stdin) → Server(child.stdin) ──
22
- // 요청을 가로채서 tools/call이면 pending에 기록해두고, 그대로 통과시킴
23
27
  const clientReader = createInterface({ input: process.stdin });
24
28
  clientReader.on("line", (line) => {
25
29
  // 항상 먼저 그대로 전달 — 파싱 실패해도 패스스루는 깨지면 안 됨
26
30
  child.stdin.write(line + "\n");
27
- try {
28
- const msg = JSON.parse(line);
29
- if (msg?.id !== undefined && msg?.method) {
30
- pending.set(msg.id, {
31
- method: msg.method,
32
- toolName: msg.method === "tools/call" ? msg.params?.name : undefined,
33
- startedAt: Date.now(),
34
- });
35
- }
36
- }
37
- catch {
38
- // JSON이 아니거나 파싱 실패 — 무시하고 패스스루만 유지
39
- }
31
+ trackRequest(pending, line);
40
32
  });
41
33
  // ── Server(child.stdout) → Client(부모 프로세스의 stdout) ──
42
- // 응답을 가로채서 pending과 매칭되면 interaction 기록, 그대로 통과시킴
43
34
  const serverReader = createInterface({ input: child.stdout });
44
35
  serverReader.on("line", (line) => {
45
36
  let out = line;
@@ -57,48 +48,9 @@ export function runProxy(opts) {
57
48
  }
58
49
  }
59
50
  process.stdout.write(out + "\n");
60
- try {
61
- const msg = JSON.parse(line);
62
- if (msg?.id !== undefined && pending.has(msg.id)) {
63
- const call = pending.get(msg.id);
64
- pending.delete(msg.id);
65
- const latency_ms = Date.now() - call.startedAt;
66
- const outcome = msg.error
67
- ? "failure"
68
- : "success";
69
- let failure_type;
70
- if (msg.error) {
71
- const code = msg.error?.code;
72
- const message = msg.error?.message ?? "";
73
- if (code === -32602)
74
- failure_type = "invalid_arguments";
75
- else if (message.toLowerCase().includes("timeout"))
76
- failure_type = "timeout";
77
- else if (code === -32603)
78
- failure_type = "server_error";
79
- else if (code === -32000)
80
- failure_type = "tool_error";
81
- else
82
- failure_type = "unknown";
83
- }
84
- const record = {
85
- actor: opts.actor,
86
- target: opts.targetLabel,
87
- target_type: "tool",
88
- task_type: call.toolName ?? call.method,
89
- outcome,
90
- failure_type,
91
- latency_ms,
92
- source: opts.source,
93
- node_id: nodeId,
94
- };
95
- // fire-and-forget — 응답 전달을 기다리게 하지 않음
96
- void recordInteraction(record);
97
- }
98
- }
99
- catch {
100
- // 무시, 패스스루 유지
101
- }
51
+ const rec = buildRecord(pending, state, line, { ...opts, nodeId });
52
+ if (rec)
53
+ void Promise.resolve(record(rec)).catch(() => { }); // fire-and-forget
102
54
  });
103
55
  child.on("exit", (code) => {
104
56
  process.exit(code ?? 0);
@@ -106,3 +58,60 @@ export function runProxy(opts) {
106
58
  process.on("SIGINT", () => child.kill("SIGINT"));
107
59
  process.on("SIGTERM", () => child.kill("SIGTERM"));
108
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,6 +1,6 @@
1
1
  {
2
2
  "name": "lowdown-proxy",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "mcpName": "io.github.PetShopBros/lowdown-proxy",
5
5
  "description": "Record and query AI agent/tool/service interactions. Shared interaction history for the multi-agent ecosystem.",
6
6
  "type": "module",
@@ -13,11 +13,12 @@
13
13
  "dist"
14
14
  ],
15
15
  "scripts": {
16
- "build": "tsc",
16
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
17
17
  "dev": "tsx src/cli.ts",
18
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"
19
+ "scanner:test": "node --test scanner/lib.test.ts scanner/registry-diff.test.ts scanner/first-seen.test.ts scanner/archive.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"
21
22
  },
22
23
  "keywords": [
23
24
  "mcp",
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
- }