@forum-labs/payfetch 1.0.0

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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +467 -0
  3. package/dist/bin/payfetch-mcp.d.ts +2 -0
  4. package/dist/bin/payfetch-mcp.js +9 -0
  5. package/dist/bin/payfetch.d.ts +2 -0
  6. package/dist/bin/payfetch.js +126 -0
  7. package/dist/src/config.d.ts +35 -0
  8. package/dist/src/config.js +170 -0
  9. package/dist/src/core/budget.d.ts +62 -0
  10. package/dist/src/core/budget.js +236 -0
  11. package/dist/src/core/constants.d.ts +66 -0
  12. package/dist/src/core/constants.js +115 -0
  13. package/dist/src/core/fs.d.ts +14 -0
  14. package/dist/src/core/fs.js +104 -0
  15. package/dist/src/core/integrity.d.ts +23 -0
  16. package/dist/src/core/integrity.js +150 -0
  17. package/dist/src/core/ledger.d.ts +149 -0
  18. package/dist/src/core/ledger.js +357 -0
  19. package/dist/src/core/notes.d.ts +22 -0
  20. package/dist/src/core/notes.js +24 -0
  21. package/dist/src/core/pipeline.d.ts +143 -0
  22. package/dist/src/core/pipeline.js +795 -0
  23. package/dist/src/core/policy.d.ts +57 -0
  24. package/dist/src/core/policy.js +224 -0
  25. package/dist/src/core/transport.d.ts +93 -0
  26. package/dist/src/core/transport.js +364 -0
  27. package/dist/src/guards/index.d.ts +4 -0
  28. package/dist/src/guards/index.js +3 -0
  29. package/dist/src/guards/internal.d.ts +17 -0
  30. package/dist/src/guards/internal.js +74 -0
  31. package/dist/src/guards/safety.d.ts +2 -0
  32. package/dist/src/guards/safety.js +94 -0
  33. package/dist/src/guards/trust.d.ts +2 -0
  34. package/dist/src/guards/trust.js +79 -0
  35. package/dist/src/guards/types.d.ts +59 -0
  36. package/dist/src/guards/types.js +20 -0
  37. package/dist/src/index.d.ts +58 -0
  38. package/dist/src/index.js +151 -0
  39. package/dist/src/mcp/server.d.ts +6 -0
  40. package/dist/src/mcp/server.js +125 -0
  41. package/dist/src/mcp/tools.d.ts +46 -0
  42. package/dist/src/mcp/tools.js +321 -0
  43. package/dist/src/payer/mpp.d.ts +7 -0
  44. package/dist/src/payer/mpp.js +13 -0
  45. package/dist/src/payer/parse402.d.ts +6 -0
  46. package/dist/src/payer/parse402.js +169 -0
  47. package/dist/src/payer/signer_cdp.d.ts +14 -0
  48. package/dist/src/payer/signer_cdp.js +64 -0
  49. package/dist/src/payer/signer_local.d.ts +8 -0
  50. package/dist/src/payer/signer_local.js +14 -0
  51. package/dist/src/payer/types.d.ts +99 -0
  52. package/dist/src/payer/types.js +10 -0
  53. package/dist/src/payer/x402.d.ts +23 -0
  54. package/dist/src/payer/x402.js +165 -0
  55. package/dist/src/report/report.d.ts +162 -0
  56. package/dist/src/report/report.js +220 -0
  57. package/mcpb/manifest.json +104 -0
  58. package/package.json +72 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Forum Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,467 @@
1
+ # payfetch
2
+
3
+ payfetch lets an AI agent fetch a URL and, when the server answers HTTP 402 (the
4
+ x402 payment protocol), pay for it automatically, but only within a spending policy
5
+ you control. It is non-custodial: you bring your own wallet, the key stays on your
6
+ machine, and no MCP tool can raise the limits. It ships as a local stdio MCP server
7
+ with a small library and CLI alongside it.
8
+
9
+ The reference x402 clients pay whatever a 402 asks for. payfetch is the opposite:
10
+ the policy and safety surface is the point. Per-call, per-day, and per-host spend
11
+ caps; host allow and deny lists; a human-approval threshold; optional pre-payment
12
+ trust and safety checks; and an append-only local receipt for every attempt,
13
+ whether it paid, was denied, was a dry run, or failed.
14
+
15
+ - Website: https://forum-labs.com
16
+ - Source: https://github.com/forum-labs/payfetch
17
+
18
+ ## Status and scope
19
+
20
+ - Version 1.0.0. Policy schema `p3f.policy.v1`, client schema `p3f-1.0.0`.
21
+ - x402 only, Base USDC, the `exact` scheme. Solana-settled x402, the `upto` scheme,
22
+ and MPP are parsed and then refused with a reason recorded in your receipts.
23
+ - Requires Node 22 or newer. Windows is not supported.
24
+ - USD is treated as USDC at 1.00. Budgets are denominated in USD and settle in USDC,
25
+ so a depeg makes the caps wrong by the depeg factor.
26
+
27
+ ## Install
28
+
29
+ The package ships compiled JavaScript, so there is no build step and no `tsx` for
30
+ consumers. Run it on demand with `npx`:
31
+
32
+ ```bash
33
+ # Operator CLI (status, verify, clear-autodeny, report):
34
+ npx @forum-labs/payfetch status
35
+
36
+ # MCP server (what an MCP client launches):
37
+ npx -p @forum-labs/payfetch payfetch-mcp
38
+ ```
39
+
40
+ The package exposes two binaries: `payfetch` (the operator CLI) and `payfetch-mcp`
41
+ (the stdio MCP server). Because there are two, the server is launched with
42
+ `npx -p @forum-labs/payfetch payfetch-mcp`; the `-p` flag selects the named binary.
43
+
44
+ ## Quickstart
45
+
46
+ ### 1. Configure a wallet (pick exactly one signer)
47
+
48
+ payfetch refuses to start if zero or more than one signer source is set. It never
49
+ guesses which wallet to spend from.
50
+
51
+ Raw private key, the simplest option. Use a dedicated low-balance wallet:
52
+
53
+ ```bash
54
+ export PAYFETCH_PRIVATE_KEY=0xabc...
55
+ ```
56
+
57
+ Key file, which must be mode 600 (payfetch refuses to start otherwise):
58
+
59
+ ```bash
60
+ printf '0xabc...' > ~/.payfetch-wallet.key && chmod 600 ~/.payfetch-wallet.key
61
+ export PAYFETCH_KEY_FILE=~/.payfetch-wallet.key
62
+ ```
63
+
64
+ Coinbase CDP server wallet, where the keys are managed by CDP under your account
65
+ instead of being pasted into an environment variable:
66
+
67
+ ```bash
68
+ export PAYFETCH_CDP_API_KEY_ID=...
69
+ export PAYFETCH_CDP_API_KEY_SECRET=...
70
+ export PAYFETCH_CDP_WALLET_SECRET=...
71
+ export PAYFETCH_CDP_ACCOUNT_NAME=payfetch # optional; stable name across restarts
72
+ ```
73
+
74
+ ### 2. Wire it into an MCP client
75
+
76
+ Claude Desktop, in `claude_desktop_config.json`:
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "payfetch": {
82
+ "command": "npx",
83
+ "args": ["-y", "-p", "@forum-labs/payfetch", "payfetch-mcp"],
84
+ "env": {
85
+ "PAYFETCH_PRIVATE_KEY": "0xabc...",
86
+ "PAYFETCH_TEST_MODE": "1"
87
+ }
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ Claude Code:
94
+
95
+ ```bash
96
+ claude mcp add payfetch \
97
+ --env PAYFETCH_PRIVATE_KEY=0xabc... \
98
+ --env PAYFETCH_TEST_MODE=1 \
99
+ -- npx -y -p @forum-labs/payfetch payfetch-mcp
100
+ ```
101
+
102
+ The examples set `PAYFETCH_TEST_MODE=1` so your first runs settle on Base Sepolia
103
+ and never touch mainnet. Drop it when you are ready to spend real USDC.
104
+
105
+ ### 3. First paid fetch
106
+
107
+ Quote before you pay. `payment_quote` returns the terms, the selected quote, the
108
+ trust-check result, your remaining budgets, and the policy decision (`would_pay` or
109
+ `would_deny`). It signs nothing and reserves nothing:
110
+
111
+ ```json
112
+ { "url": "https://api.example.com/paid-endpoint" }
113
+ ```
114
+
115
+ Dry run the whole pipeline. `paid_fetch` with `"dryRun": true` runs the exact code
116
+ path a real payment takes, up to but not including the signature.
117
+
118
+ Pay for real with `paid_fetch`:
119
+
120
+ ```json
121
+ { "url": "https://api.example.com/paid-endpoint", "maxAmountUsd": 0.25 }
122
+ ```
123
+
124
+ `maxAmountUsd` tightens the per-call cap for this one call. It can only lower the
125
+ limit, never raise it. If the price is above your approval threshold, a human is
126
+ asked to confirm (see Approvals). The result carries the response body, the payment
127
+ outcome and transaction reference, any warnings, and a `receiptId`.
128
+
129
+ ## The spending policy
130
+
131
+ Policy lives in `{dataDir}/config.json` (the data dir defaults to `~/.payfetch`).
132
+ On first run payfetch writes the defaults there so you can read and edit exactly
133
+ what you are running. A missing file falls back to the defaults. An invalid file
134
+ fails closed: every paying tool returns `policy_config_invalid` until you fix it, so
135
+ a typo never silently restores a cap you lowered. The file is re-read when its mtime
136
+ changes.
137
+
138
+ Only you can change the policy. No MCP tool mutates it and no tool clears an
139
+ auto-deny. Agent-supplied parameters such as `maxAmountUsd` can only tighten, never
140
+ loosen. Every denied `paid_fetch` result repeats this back to the agent so a
141
+ prompt-injected model cannot mistake the boundary for something negotiable.
142
+
143
+ ### Caps
144
+
145
+ - `caps.perCallUsd` (default 1.00): maximum for a single payment.
146
+ - `caps.dailyUsd` (default 2.00): maximum per UTC day.
147
+ - `caps.perHostDailyUsd` (default 1.00): maximum per host per UTC day.
148
+ - `caps.totalUsd` (default null): optional lifetime cap.
149
+
150
+ Caps are hard and reserve before paying. A signed authorization is held against the
151
+ budget until it provably expires, so budgets can over-count but never under-count.
152
+ At most one payment attempt happens per request, so a retry loop cannot drain the
153
+ wallet.
154
+
155
+ There is deliberately no default lifetime cap. The dedicated wallet's balance
156
+ already bounds lifetime spend on-chain (see Security), so a software lifetime ceiling
157
+ would be one more field to forget. Set `totalUsd` only if you want a software
158
+ ceiling on top of a larger-balance wallet.
159
+
160
+ ### Allow and deny lists
161
+
162
+ `mode` is `open` by default. Set it to `allowlist` to pay only hosts listed in
163
+ `allow`. Patterns in `deny` are always refused and win over `allow`. A pattern like
164
+ `*.example.com` matches subdomains, not the apex.
165
+
166
+ ### Approvals
167
+
168
+ A payment whose price is strictly above `approval.thresholdUsd` (default 0.10)
169
+ triggers approval. An approval authorizes one payment only. There is no "always
170
+ allow", and it never widens future authority.
171
+
172
+ - `elicit` (default): the client prompts a human with the host, resource, amount,
173
+ network and asset, guard results, and today's remaining budgets. They approve once
174
+ or deny. The prompt times out after 120 seconds and is then treated as a denial.
175
+ Some MCP clients cannot service an elicitation prompt (Claude Desktop cancels it
176
+ immediately; Claude Code supports it). payfetch tells apart a real human "deny"
177
+ from a client that simply cannot ask, and it never treats "cannot ask" as a silent
178
+ denial. When a payment is blocked only because the client cannot elicit, the tool
179
+ result says so and names the ways to allow it.
180
+ - `queue`: the payment is not executed. The result returns an `approvalId`. A human
181
+ with approval authority resolves it with the `approve_pending` tool. An approved
182
+ entry is a grant to re-run: the follow-up `paid_fetch` runs the full pipeline again
183
+ and matches on host and exact amount. It expires after one hour, and drifted terms
184
+ require a fresh approval.
185
+ - `deny`: anything above the threshold is refused, for unattended fleets.
186
+
187
+ For clients that cannot prompt a human, two config-only settings let above-threshold
188
+ payments through without a dialog. Both are explicit operator authorization, not the
189
+ agent's, and neither is reachable from a tool. `approval.preApprovedUpToUsd` (default
190
+ null) auto-approves above-threshold payments up to a ceiling.
191
+ `approval.preApprovedHosts` (default empty) auto-approves specific hosts. Both still
192
+ pass through every cap and every guard.
193
+
194
+ Approval never bypasses caps. An approved payment that fails budget reservation is
195
+ still denied.
196
+
197
+ `approve_pending` with `{"action":"list"}` is always allowed and shows the queue.
198
+ Approving or denying an entry requires `PAYFETCH_APPROVER=1` in the server's
199
+ environment; without it the tool returns `approver_not_enabled`. An agent must not
200
+ approve its own payments, so the server refuses to start if `PAYFETCH_APPROVER=1` is
201
+ combined with a queue-capable approval mode.
202
+
203
+ ### Receipts
204
+
205
+ Every outcome, including free fetches, dry runs, denials, and unknown-settlement
206
+ cases, appends one immutable JSON line to the ledger:
207
+
208
+ ```
209
+ {dataDir}/ledger/{yyyy-mm}.jsonl # append-only, monthly rotation, fsync on payments
210
+ {dataDir}/state.json # disposable cache, rebuildable from the ledger
211
+ {dataDir}/downloads/{receiptId} # response bodies when responseMode is "file"
212
+ ```
213
+
214
+ A receipt records the URL, method, and host; the outcome and deny code; the pipeline
215
+ steps traversed; the selected quote and a tally of rejected quotes; guard results;
216
+ approval info; the payment (payer address, nonce, validBefore, settled amount,
217
+ transaction reference, and whether it confirmed); the budgets at decision time; and
218
+ an HTTP summary. Key material, signatures, full payment payloads, response bodies,
219
+ and request header values are never stored. Response bodies are recorded as a
220
+ SHA-256 hash plus a byte count. URL query strings are stored, because this is your
221
+ own audit trail on your own disk; guard calls, by contrast, strip the query (see
222
+ Security). Nothing is rewritten. Corrections append `p3f.adjust.v1` records.
223
+
224
+ Query receipts with the `list_receipts` tool (filter by time, host, or outcome) or
225
+ `spend_status` (today's totals, holds, and recent payments). After repeated
226
+ paid-but-bad outcomes a host is auto-denied for 7 days; clear it out of band with
227
+ `payfetch clear-autodeny <host>`, never from a tool.
228
+
229
+ ## Trust and safety checks
230
+
231
+ payfetch can consult two checks before it pays. Both call paid Forum Labs APIs at
232
+ `https://api.forum-labs.com`, and both are self-dealing that is disclosed here rather
233
+ than buried: the guards call our own products. The default guard budget is 0, so by
234
+ default the client uses only those products' free tier. Any paid guard usage is
235
+ opt-in, budgeted with `guards.*.dailyBudgetUsd > 0`, and produces a receipt like any
236
+ other spend.
237
+
238
+ The trust check is on by default in advisory mode. Before paying, it asks whether the
239
+ target endpoint has a reliable history. In advisory mode it warns; in enforce mode it
240
+ blocks on the configured verdicts (`unreliable` by default). New endpoints without
241
+ enough history come back `unrated` and pass by default, so the check does not
242
+ strangle them. This check is the client's only outbound call to us; see Security for
243
+ exactly what it sends and how to turn it off.
244
+
245
+ The safety check is off by default. When enabled it screens a token mint you pass in
246
+ (`tokenAddress`) against the Forum Labs token safety API and blocks on a `danger`
247
+ verdict, or on a `serial_rugger` deployer verdict in `deep` mode. `deep` is always a
248
+ paid screen, so it needs `dailyBudgetUsd > 0`.
249
+
250
+ ## Security and disclosure
251
+
252
+ Read this before pointing payfetch at a funded wallet.
253
+
254
+ ### The wallet balance is your real limit
255
+
256
+ The primary control on how much a bug or a prompt-injected agent can spend is the
257
+ balance of the wallet you point payfetch at, not the software caps. A wallet's
258
+ balance is a hard on-chain bound: payfetch cannot spend a dollar that is not in the
259
+ wallet, whatever the config says or the agent is told to do. So the first thing to
260
+ get right is the wallet.
261
+
262
+ Create a fresh wallet, fund it with only the amount you are willing to lose entirely
263
+ (a few dollars for a trial, a capped top-up for production), and give payfetch that
264
+ wallet. Never your main wallet. Refill it deliberately rather than by standing order.
265
+
266
+ The caps, lists, approval threshold, and guards are the fine-grained layer on top.
267
+ They shape rate, per-target exposure, and detection within that balance. They are
268
+ real and enforced, but the wallet balance is the circuit breaker and the caps are
269
+ the scalpel. Set both.
270
+
271
+ ### Key custody
272
+
273
+ Your key is never transmitted to us, never logged, and never written to the receipt
274
+ ledger. The ledger stores addresses and amounts, not keys, and that is asserted by a
275
+ test. Keys are read from the environment in-process to sign EIP-3009 payment
276
+ authorizations. A signed authorization is bounded to one asset, one amount, one
277
+ recipient, and one time window. If you use `PAYFETCH_KEY_FILE`, payfetch refuses to
278
+ start when the file is group- or world-readable, so `chmod 600` it.
279
+
280
+ ### What the trust guard sends, and the off switch
281
+
282
+ While the trust guard is on, it makes one call to the Forum Labs trust API on every
283
+ paid fetch. That call is the client's only egress to us. It sends the target endpoint
284
+ with the query string stripped, plus a random per-install id. The query is stripped
285
+ because a target URL's query can carry your own secrets; server-side we store a hash
286
+ of the input, never the raw target, and the install id is used for aggregate counting
287
+ only, never per-install profiling or resale. The install id is a random 32-hex value
288
+ generated on first run and stored in your state file; delete the state file and it
289
+ regenerates.
290
+
291
+ Turn the guard off with `guards.trust.enabled: false`. With it off, payfetch makes no
292
+ external call at all: no guard result, no network request, nothing dialed. That is
293
+ the complete off switch, and the honest cost of it is that operators who disable the
294
+ guard are invisible to our adoption instrument.
295
+
296
+ ### Optional outcome reporting (off by default)
297
+
298
+ Reporting is off by default and changes nothing unless you turn it on. When you report
299
+ an outcome, currently only per-incident with `payfetch report <receiptId>`, the client
300
+ reports the outcome of a completed payment attempt (paid and delivered, or paid and
301
+ not delivered), signed by your payment wallet and tied to the on-chain settlement, to
302
+ the trust API. This is a fact about the seller's conduct that you are reporting. It is
303
+ never a record of what you looked at. Lookups (guard checks, quotes, dry runs) are
304
+ never retained per consumer.
305
+
306
+ A report sends exactly these fields and nothing else: the endpoint `{method, url}`
307
+ with the query stripped; the `outcome`, derived from the receipt and never
308
+ agent-supplied; structural `checks` (`settlementConfirmed`, a coarse HTTP status
309
+ class, `contentTypeOk`, `nonEmpty`); the `termsHash` you paid under; the seller's
310
+ `payTo` address, which is already on-chain; a coarse `amountBand` rather than the
311
+ exact amount; the UTC day rather than an exact timestamp; and your payment wallet
312
+ address plus an EIP-712 signature over the payload. A report never carries the query
313
+ string, request headers or bodies, the response body, the receiptId, the exact
314
+ amount, or the exact timestamp. The install id never rides on the report path, so the
315
+ report wallet and the guard install id are never joined.
316
+
317
+ A settled x402 payment is already public (payer, payee, amount, and time are on the
318
+ chain). What a report adds is the outcome bit. On very-low-traffic endpoints a seller
319
+ may be able to infer that a report came from you, since the anonymity set is small; we
320
+ mitigate with day granularity and bucketed publication, and we state the residual here
321
+ rather than hide it. In this version the trust API verifies the signature
322
+ (`recover(sig) === payer`), so a stranger cannot report on your behalf, but it does
323
+ not yet prove the settlement, so reports are shown as unverified until they are
324
+ settlement-matched in a later version. We will not monetize, publish, or attempt to
325
+ deanonymize reporter wallets.
326
+
327
+ ### SSRF and private targets
328
+
329
+ Unless you set `allowPrivateTargets: true`, payfetch refuses non-http(s) schemes and
330
+ any host that resolves to loopback, RFC1918, link-local `169.254/16`, CGNAT, or ULA.
331
+ A paying-fetch must not become the tool that exfiltrates `169.254.169.254`. DNS is
332
+ pinned, so the vetted IP is the one dialed; every redirect hop is re-checked; and an
333
+ `https` to `http` downgrade aborts.
334
+
335
+ ### What payfetch does not protect against
336
+
337
+ Fetched content is untrusted input to your agent. A malicious page can tell the agent
338
+ to fetch or pay somewhere else. payfetch bounds the damage with the dedicated wallet's
339
+ balance and the caps, lists, approval threshold, receipts, and SSRF block, but it
340
+ cannot make the agent wise. It cannot stop an injected agent from spending within
341
+ policy, so keep the wallet balance small. For untrusted-content workloads, tighten the
342
+ defaults:
343
+
344
+ ```jsonc
345
+ {
346
+ "mode": "allowlist",
347
+ "allow": ["api.trusted-vendor.com"],
348
+ "caps": { "perCallUsd": 0.05, "dailyUsd": 0.50, "perHostDailyUsd": 0.25 },
349
+ "approval": { "thresholdUsd": 0.0, "mode": "elicit", "elicitFallback": "deny" },
350
+ "guards": { "trust": { "enabled": true, "mode": "enforce" } }
351
+ }
352
+ ```
353
+
354
+ `thresholdUsd: 0.0` sends every payment to a human. `mode: "enforce"` blocks on an
355
+ `unreliable` verdict instead of only warning.
356
+
357
+ Two more limits worth stating plainly. There is no on-chain settlement verification
358
+ yet: settlement facts come from the server's payment-response header, so a lying
359
+ server can misreport. Both error directions over-count, which is the safe direction,
360
+ and on-chain verification is planned. And the ledger is single-instance: one lockfile,
361
+ one process, one machine. A fleet needs a policy plane that is not built here.
362
+
363
+ ## Configuration reference
364
+
365
+ Defaults, from `{dataDir}/config.json`, schema `p3f.policy.v1`:
366
+
367
+ | Field | Default | Meaning |
368
+ |---|---|---|
369
+ | `mode` | `"open"` | `"allowlist"` pays only hosts in `allow`. |
370
+ | `allow` | `[]` | Host patterns permitted in allowlist mode. |
371
+ | `deny` | `[]` | Host patterns always refused (wins over `allow`). |
372
+ | `caps.perCallUsd` | `1.00` | Max per single payment. |
373
+ | `caps.dailyUsd` | `2.00` | Max per UTC day. |
374
+ | `caps.perHostDailyUsd` | `1.00` | Max per host per UTC day. |
375
+ | `caps.totalUsd` | `null` | Optional lifetime cap. |
376
+ | `approval.thresholdUsd` | `0.10` | Above this, a human approves. |
377
+ | `approval.mode` | `"elicit"` | `elicit`, `queue`, or `deny`. |
378
+ | `approval.elicitFallback` | `"deny"` | Used when the client cannot elicit. Fail-closed. |
379
+ | `approval.preApprovedUpToUsd` | `null` | No-dialog ceiling for above-threshold payments. |
380
+ | `approval.preApprovedHosts` | `[]` | Hosts pre-approved to auto-pay above threshold. |
381
+ | `guards.trust.enabled` | `true` | The default-on trust check. |
382
+ | `guards.trust.mode` | `"advisory"` | `advisory` warns; `enforce` blocks. |
383
+ | `guards.trust.blockVerdicts` | `["unreliable"]` | Verdicts that block or warn. |
384
+ | `guards.trust.blockUnrated` | `false` | `unrated` passes by default. |
385
+ | `guards.trust.onUnavailable` | `"block"` | Enforce-mode behavior when the guard cannot answer. |
386
+ | `guards.trust.dailyBudgetUsd` | `0` | 0 means free tier only. |
387
+ | `guards.safety.enabled` | `false` | Token safety screen; needs `tokenAddress`. |
388
+ | `guards.safety.depth` | `"basic"` | `deep` is always paid. |
389
+ | `guards.safety.blockVerdicts` | `["danger"]` | Token verdicts that block. |
390
+ | `guards.safety.blockDeployerVerdicts` | `["serial_rugger"]` | Deployer verdicts, deep only. |
391
+ | `guards.safety.onUnavailable` | `"block"` | Enforce behavior when the safety guard is dead. |
392
+ | `guards.safety.onDegraded` | `"block"` | Enforce behavior on a degraded screen. |
393
+ | `allowPrivateTargets` | `false` | SSRF guard. Keep `false`. |
394
+ | `autoDeny.enabled` | `true` | Per-host circuit breaker. |
395
+
396
+ Environment variables read by both the server and the CLI:
397
+
398
+ | Variable | Meaning |
399
+ |---|---|
400
+ | `PAYFETCH_PRIVATE_KEY` | 0x-hex EVM private key. One of three signer sources. |
401
+ | `PAYFETCH_KEY_FILE` | Path to a mode-600 file holding a 0x-hex key. |
402
+ | `PAYFETCH_CDP_API_KEY_ID` / `_SECRET`, `PAYFETCH_CDP_WALLET_SECRET` | Coinbase CDP server-wallet credentials (all three required together). |
403
+ | `PAYFETCH_CDP_ACCOUNT_NAME` | Optional named CDP EVM account. Defaults to a stable name. |
404
+ | `PAYFETCH_DATA_DIR` | Ledger, state, and config root. Default `~/.payfetch`. |
405
+ | `PAYFETCH_TEST_MODE` | Any value marks receipts `test:true` and refuses Base mainnet quotes (Sepolia only). |
406
+ | `PAYFETCH_APPROVER` | `1` grants approval authority. Refused with a queue-capable mode. |
407
+ | `PAYFETCH_VIA` | Optional `via=` attribution slug sent on guard calls only. |
408
+
409
+ ## Test mode
410
+
411
+ Set `PAYFETCH_TEST_MODE` to any value. Then every receipt is stamped `test: true` and
412
+ excluded from metrics, and Base mainnet quotes are refused so a self-test can never
413
+ touch mainnet spend. Only Base Sepolia settles. Use it to run the end-to-end Base
414
+ Sepolia path before spending real USDC.
415
+
416
+ ## CLI
417
+
418
+ The `payfetch` CLI reads the same environment as the MCP server.
419
+
420
+ ```bash
421
+ # Reset a host's auto-deny circuit breaker (an operator action, not a tool).
422
+ npx @forum-labs/payfetch clear-autodeny api.example.com
423
+
424
+ # Print today's spend status as JSON.
425
+ npx @forum-labs/payfetch status
426
+
427
+ # Verify the ledger tamper-evidence sidecar (exits non-zero on any integrity gap).
428
+ npx @forum-labs/payfetch verify
429
+
430
+ # Report a paid outcome for a receipt (opt-in, off by default). Prints the exact
431
+ # wallet-signed payload, asks for confirmation, then submits. Never an MCP tool, so
432
+ # the agent can neither file nor suppress a report. Use --yes to skip the prompt.
433
+ npx @forum-labs/payfetch report <receiptId>
434
+ ```
435
+
436
+ `status` builds the engine and takes the single-writer lock. If the MCP server is
437
+ already running, use the `spend_status` tool instead, or stop the server first.
438
+
439
+ ## Manual .mcpb install
440
+
441
+ Directory submission is not offered for payment connectors, so payfetch is packaged
442
+ for manual install. Build the bundle:
443
+
444
+ ```bash
445
+ npm run build:mcpb # produces dist-mcpb/payfetch.mcpb
446
+ ```
447
+
448
+ This runs `tsc`, then esbuild-bundles the built server entry and its runtime
449
+ dependencies into a single self-contained ESM file, and packs it with the mcpb tool.
450
+ The result is a small `.mcpb` zip holding `manifest.json` alongside the bundled
451
+ server. No `node_modules` is shipped, so Claude Desktop installs it without running
452
+ `npm install`. In Claude Desktop, go to Settings, Extensions, Install from file,
453
+ choose the `.mcpb`, then fill in exactly one signer option. The bundling logic is in
454
+ `mcpb/build.mjs` and the manifest is `mcpb/manifest.json`.
455
+
456
+ ## From source
457
+
458
+ ```bash
459
+ npm install # dev dependencies, including tsx for the from-source flow
460
+ npm run typecheck # tsc --noEmit
461
+ npm test # vitest, hermetic, no network
462
+ npm run build # emit dist/, the compiled JS the package ships
463
+ ```
464
+
465
+ ## License
466
+
467
+ MIT. See [LICENSE](LICENSE). Copyright (c) 2026 Forum Labs.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { scrubSecrets } from "../src/config.js";
3
+ import { runStdioServer } from "../src/mcp/server.js";
4
+ runStdioServer().catch((err) => {
5
+ const message = scrubSecrets(String(err?.message ?? err), []);
6
+ const line = message.startsWith("payfetch") ? message : `payfetch-mcp: fatal: ${message}`;
7
+ process.stderr.write(`${line}\n`);
8
+ process.exit(1);
9
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ import { buildFromEnv, resolveDataDir, scrubSecrets, ConfigError, } from "../src/config.js";
3
+ import { SCAFFOLD_BASE_URL } from "../src/core/constants.js";
4
+ import { realFs } from "../src/core/fs.js";
5
+ import { Ledger, LedgerLockedError } from "../src/core/ledger.js";
6
+ import { clearAutoDeny, createPayfetch } from "../src/index.js";
7
+ import { runReport } from "../src/report/report.js";
8
+ function usage(message) {
9
+ if (message)
10
+ process.stderr.write(`payfetch: ${message}\n`);
11
+ process.stderr.write("usage:\n" +
12
+ " payfetch clear-autodeny <host> reset a host's auto-deny (SPEC §5.4)\n" +
13
+ " payfetch status print today's spend status (JSON)\n" +
14
+ " payfetch verify verify the ledger integrity sidecar (SPEC §8/§14)\n" +
15
+ " payfetch report <receiptId> report a paid outcome (opt-in; --yes skips prompt)\n");
16
+ process.exit(message ? 1 : 0);
17
+ }
18
+ function promptYesNo(prompt) {
19
+ return new Promise((resolve) => {
20
+ process.stdout.write(prompt);
21
+ process.stdin.resume();
22
+ process.stdin.once("data", (buf) => {
23
+ process.stdin.pause();
24
+ const answer = buf.toString().trim().toLowerCase();
25
+ resolve(answer === "y" || answer === "yes");
26
+ });
27
+ });
28
+ }
29
+ async function cmdClearAutoDeny(host) {
30
+ if (!host)
31
+ usage("clear-autodeny requires a <host> argument");
32
+ const dataDir = resolveDataDir(process.env);
33
+ const cleared = clearAutoDeny(dataDir, host);
34
+ process.stdout.write(`${JSON.stringify({ host, cleared }, null, 2)}\n`);
35
+ }
36
+ async function cmdStatus() {
37
+ let pf;
38
+ try {
39
+ pf = createPayfetch(buildFromEnv(process.env));
40
+ }
41
+ catch (err) {
42
+ if (err instanceof LedgerLockedError) {
43
+ process.stderr.write("payfetch: the MCP server appears to be running (ledger is locked). " +
44
+ "Use the spend_status tool, or stop the server first.\n");
45
+ process.exit(1);
46
+ }
47
+ throw err;
48
+ }
49
+ try {
50
+ const status = await pf.status();
51
+ process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
52
+ }
53
+ finally {
54
+ pf.close();
55
+ }
56
+ }
57
+ async function cmdVerify() {
58
+ const dataDir = resolveDataDir(process.env);
59
+ const ledger = new Ledger(realFs, dataDir, () => Date.now());
60
+ try {
61
+ ledger.acquireLock();
62
+ }
63
+ catch (err) {
64
+ if (err instanceof LedgerLockedError) {
65
+ process.stderr.write("payfetch: the MCP server appears to be running (ledger is locked). " +
66
+ "Stop the server first to verify the ledger.\n");
67
+ process.exit(1);
68
+ }
69
+ throw err;
70
+ }
71
+ let ok;
72
+ try {
73
+ const report = ledger.verifyIntegrity();
74
+ ok = report.ok;
75
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
76
+ }
77
+ finally {
78
+ ledger.releaseLock();
79
+ }
80
+ if (!ok)
81
+ process.exit(1);
82
+ }
83
+ async function cmdReport(rest) {
84
+ const receiptId = rest.find((a) => !a.startsWith("-"));
85
+ if (!receiptId)
86
+ usage("report requires a <receiptId> argument");
87
+ const autoYes = rest.includes("--yes") || rest.includes("-y");
88
+ const signer = buildFromEnv(process.env).deps.signer;
89
+ const dataDir = resolveDataDir(process.env);
90
+ const receipts = new Ledger(realFs, dataDir, () => Date.now()).readAllReceipts();
91
+ const outcome = await runReport({
92
+ readReceipts: () => receipts,
93
+ receiptId: receiptId,
94
+ signer,
95
+ fetchImpl: (input, init) => fetch(input, init),
96
+ baseUrl: SCAFFOLD_BASE_URL,
97
+ confirm: async () => autoYes ? true : await promptYesNo("Submit this report? [y/N] "),
98
+ out: (line) => process.stdout.write(`${line}\n`),
99
+ err: (line) => process.stderr.write(`${line}\n`),
100
+ });
101
+ if (outcome.kind === "not_found" ||
102
+ outcome.kind === "not_reportable" ||
103
+ outcome.kind === "submit_failed") {
104
+ process.exit(1);
105
+ }
106
+ }
107
+ async function main() {
108
+ const [cmd, ...rest] = process.argv.slice(2);
109
+ switch (cmd) {
110
+ case "clear-autodeny":
111
+ return cmdClearAutoDeny(rest[0]);
112
+ case "status":
113
+ return cmdStatus();
114
+ case "verify":
115
+ return cmdVerify();
116
+ case "report":
117
+ return cmdReport(rest);
118
+ default:
119
+ usage(cmd ? `unknown subcommand: ${cmd}` : "no subcommand given");
120
+ }
121
+ }
122
+ main().catch((err) => {
123
+ const raw = scrubSecrets(String(err?.message ?? err), []);
124
+ process.stderr.write(err instanceof ConfigError ? `${raw}\n` : `payfetch: ${raw}\n`);
125
+ process.exit(1);
126
+ });
@@ -0,0 +1,35 @@
1
+ import type { PayfetchDeps } from "./payer/types.js";
2
+ import type { CreatePayfetchOpts } from "./index.js";
3
+ export declare const ENV: {
4
+ readonly PRIVATE_KEY: "PAYFETCH_PRIVATE_KEY";
5
+ readonly KEY_FILE: "PAYFETCH_KEY_FILE";
6
+ readonly CDP_API_KEY_ID: "PAYFETCH_CDP_API_KEY_ID";
7
+ readonly CDP_API_KEY_SECRET: "PAYFETCH_CDP_API_KEY_SECRET";
8
+ readonly CDP_WALLET_SECRET: "PAYFETCH_CDP_WALLET_SECRET";
9
+ readonly CDP_ACCOUNT_NAME: "PAYFETCH_CDP_ACCOUNT_NAME";
10
+ readonly DATA_DIR: "PAYFETCH_DATA_DIR";
11
+ readonly TEST_MODE: "PAYFETCH_TEST_MODE";
12
+ readonly APPROVER: "PAYFETCH_APPROVER";
13
+ readonly VIA: "PAYFETCH_VIA";
14
+ };
15
+ export declare const DEFAULT_DATA_DIR_NAME = ".payfetch";
16
+ export declare const APPROVER_ENABLED_VALUE = "1";
17
+ export type EnvRecord = Record<string, string | undefined>;
18
+ export type ConfigIo = {
19
+ readText: (path: string) => string;
20
+ statMode: (path: string) => number | null;
21
+ homedir: () => string;
22
+ fetch: typeof fetch;
23
+ now: () => number;
24
+ random: () => Uint8Array;
25
+ log: PayfetchDeps["log"];
26
+ };
27
+ export declare function realConfigIo(): ConfigIo;
28
+ export declare class ConfigError extends Error {
29
+ constructor(message: string);
30
+ }
31
+ export declare function scrubSecrets(text: string, secrets: string[]): string;
32
+ export type SignerSource = "private_key" | "key_file" | "cdp";
33
+ export declare function selectSignerSource(env: EnvRecord): SignerSource;
34
+ export declare function resolveDataDir(env: EnvRecord, homedir?: () => string): string;
35
+ export declare function buildFromEnv(env: EnvRecord, io?: ConfigIo): CreatePayfetchOpts;