verify402-mcp 0.0.0-stage → 1.0.2

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/.env.example ADDED
@@ -0,0 +1,20 @@
1
+ # Bridge configuration.
2
+ #
3
+ # The bridge runs without any of these. With no EVM_PRIVATE_KEY it exposes only
4
+ # the free preflight_gate. Set a key only when you want the five paid checks.
5
+ #
6
+ # EVM_PRIVATE_KEY is a dedicated hot wallet that pays for calls in USDC. Use a
7
+ # wallet with only the money you are willing to spend. NEVER commit the real
8
+ # .env and never use a main wallet.
9
+ EVM_PRIVATE_KEY= # optional; omit for the free gate only
10
+ VERIFY402_URL=https://verify402.onrender.com
11
+ # spend controls (paid tools only)
12
+ MAX_PAYMENT_USD=0.25 # cap on ONE payment, enforced at signature time
13
+ MAX_DAILY_USD=0.50 # cap on the whole UTC day, survives restarts; omit to disable
14
+ SPEND_LEDGER_PATH= # optional override for the ledger file (default .spend-ledger.json)
15
+
16
+ # payment allowlist (paid tools only; these are the defaults)
17
+ VERIFY402_NETWORKS=eip155:8453
18
+ VERIFY402_PAY_TO=0xAeEF086DD4e436c69d6d0F684b4c9F43392df9cb
19
+ # VERIFY402_RESOURCE_PREFIX=https://verify402.onrender.com
20
+ # For local testnet, set VERIFY402_NETWORKS=eip155:84532 and the payee the local server names.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ verify402
2
+ Copyright 2026 verify402 (https://github.com/a32116150-ctrl/verify402)
3
+
4
+ This product includes software developed by the verify402 project.
5
+
6
+ The verify402 name and logo identify this project. They are not licensed for
7
+ use as trademarks to endorse or promote derived products, except as allowed by
8
+ Section 6 of the Apache License, Version 2.0.
package/README.md CHANGED
@@ -1,3 +1,174 @@
1
- # Temporary Holding Version
1
+ # verify402-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP server for **verify402**: a free, fail-closed **preflight gate** before an
4
+ agent signs a payment or a chain transaction, plus five paid on-chain checks
5
+ paid per call over x402.
6
+
7
+ Works with Claude Desktop, Cursor, OpenCode, and any MCP client that speaks
8
+ stdio. The free gate needs **no wallet**. The paid tools use a dedicated hot
9
+ wallet that pays in USDC; the bridge never signs or sends a trade.
10
+
11
+ ## Tools
12
+
13
+ | tool | price | what it answers |
14
+ |---|---|---|
15
+ | `preflight_gate` | **free** | "Should I sign this payment request or transaction?" — PASS / CAUTION / BLOCK with reasons, `checked` / `notChecked`, and a short-lived receipt |
16
+ | `verify_arbitrage` | $0.05 | "Is this cross-venue arbitrage opportunity real, right now?" |
17
+ | `check_token_safety` | $0.10 | "Is this token safe to buy?" — TRUST / CAUTION / AVOID with evidence |
18
+ | `get_best_route` | $0.03 | "What would the chain actually pay for this swap?" — best route + every quoted venue |
19
+ | `verify_quote_fairness` | $0.05 | "A broker/bot offered me this number — is it honest?" fair / overpaying / too_good_to_be_true |
20
+ | `get_trade_depth` | $0.05 | "How big can I trade here before the round trip eats me?" — per-size impact, round-trip cost, capacity |
21
+
22
+ `preflight_gate` is the front door. Call it before signing any crypto
23
+ transaction or x402 payment request. If `sign_allowed` is false, **do not
24
+ sign**. If `requires_ack` is true, surface the reasons to the operator. The
25
+ receipt expires (default 90s); call again instead of reusing it.
26
+
27
+ The gate is advisory at this layer: the bridge does not hold the agent's
28
+ transaction key and cannot stop an agent that ignores the answer. Enforcement
29
+ belongs in the executor that signs — verify the receipt, then sign. See
30
+ [`examples/preflight-guard.mjs`](https://github.com/a32116150-ctrl/verify402/blob/master/examples/preflight-guard.mjs)
31
+ for a deny-by-default reference that refuses to call the signer without a
32
+ verified receipt.
33
+
34
+ ## Run
35
+
36
+ The package is distributed as a versioned GitHub release tarball. No npm
37
+ account is required.
38
+
39
+ ```bash
40
+ npx -y \
41
+ --package=https://github.com/a32116150-ctrl/verify402/releases/download/mcp-v1.0.2/verify402-mcp-1.0.2.tgz \
42
+ verify402-mcp --help
43
+ ```
44
+
45
+ **Warm the cache first.** The first `npx` run installs the MCP SDK and `viem`;
46
+ some clients kill a server that takes more than 30 seconds to start. Run the
47
+ `--help` command once before adding it to an MCP client. After that, startup is
48
+ fast.
49
+
50
+ From source:
51
+
52
+ ```bash
53
+ git clone https://github.com/a32116150-ctrl/verify402
54
+ cd verify402/mcp-bridge
55
+ npm ci
56
+ node index.mjs --help
57
+ ```
58
+
59
+ ## Free gate only (no key)
60
+
61
+ Omit `EVM_PRIVATE_KEY`. The server registers only `preflight_gate` and logs
62
+ `free preflight_gate only`. Nothing can be charged.
63
+
64
+ ## Paid tools (dedicated hot wallet)
65
+
66
+ Set a wallet with USDC on the payment network. Use a wallet with only the money
67
+ you are willing to spend — never a main wallet. The key stays in your MCP client
68
+ configuration or environment; the package never contains it.
69
+
70
+ ```
71
+ EVM_PRIVATE_KEY=0x... # optional; omit for free-only
72
+ VERIFY402_URL=https://verify402.onrender.com
73
+ MAX_PAYMENT_USD=0.25 # hard cap on ONE payment, enforced at signature time
74
+ MAX_DAILY_USD=0.50 # optional cap for the UTC day, persisted
75
+ SPEND_LEDGER_PATH= # optional ledger path (default .spend-ledger.json)
76
+ VERIFY402_NETWORKS=eip155:8453 # paid calls only; comma-separated EVM networks
77
+ VERIFY402_PAY_TO=0xAeEF086DD4e436c69d6d0F684b4c9F43392df9cb
78
+ # VERIFY402_RESOURCE_PREFIX=https://verify402.onrender.com
79
+ ```
80
+
81
+ The paid client refuses a 402 that names another network or payee, a resource
82
+ outside the configured server, or a non-paid route. It also refuses redirects.
83
+ The amount cap and the USDC-only default-asset allowlist are enforced inside
84
+ the x402 client, before a signature exists.
85
+
86
+ ### Claude Desktop / Cursor
87
+
88
+ `claude_desktop_config.json`, or `.cursor/mcp.json`:
89
+
90
+ ```json
91
+ {
92
+ "mcpServers": {
93
+ "verify402": {
94
+ "command": "npx",
95
+ "args": [
96
+ "-y",
97
+ "--package=https://github.com/a32116150-ctrl/verify402/releases/download/mcp-v1.0.2/verify402-mcp-1.0.2.tgz",
98
+ "verify402-mcp"
99
+ ],
100
+ "env": {
101
+ "VERIFY402_URL": "https://verify402.onrender.com"
102
+ }
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ For paid tools, add `"EVM_PRIVATE_KEY": "0x..."`, `"MAX_PAYMENT_USD": "0.25"`
109
+ and optionally `"MAX_DAILY_USD": "0.50"` to `env`. The free gate works without
110
+ them.
111
+
112
+ ### OpenCode V2
113
+
114
+ `opencode.jsonc`, or the global `~/.config/opencode/opencode.jsonc`:
115
+
116
+ ```jsonc
117
+ {
118
+ "$schema": "https://opencode.ai/config.json",
119
+ "mcp": {
120
+ "servers": {
121
+ "verify402": {
122
+ "type": "local",
123
+ "command": [
124
+ "npx",
125
+ "-y",
126
+ "--package=https://github.com/a32116150-ctrl/verify402/releases/download/mcp-v1.0.2/verify402-mcp-1.0.2.tgz",
127
+ "verify402-mcp"
128
+ ],
129
+ "environment": {
130
+ "VERIFY402_URL": "https://verify402.onrender.com"
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ ```
137
+
138
+ For paid tools, add `"EVM_PRIVATE_KEY": "{env:EVM_PRIVATE_KEY}"` to
139
+ `environment` and export the key in the environment that starts OpenCode. Keep
140
+ the secret out of the config file.
141
+
142
+ ## Safety
143
+
144
+ - The bridge signs **x402 payments only**. It never signs or broadcasts a trade.
145
+ - Before signing, the paid client requires the 402 to come from the configured
146
+ server and a known paid route, on an allowlisted EVM network, to the
147
+ verify402 payee. It accepts only recognized default assets (USDC), caps the
148
+ amount at `MAX_PAYMENT_USD`, and refuses redirects.
149
+ - The allowlist can be narrowed or pointed at another deployment with
150
+ `VERIFY402_NETWORKS`, `VERIFY402_PAY_TO`, and `VERIFY402_RESOURCE_PREFIX`.
151
+ Defaults are Base mainnet and the public verify402 payee.
152
+ - `MAX_PAYMENT_USD` is enforced inside the x402 client, before a signature
153
+ exists; removing it is a security regression.
154
+ - `preflight_gate` is a check, not a guarantee. Read `notChecked`: it does not
155
+ screen recipient reputation or sanctions, audit contracts, simulate full
156
+ balance deltas, or protect against MEV. It catches the measurable signing
157
+ mistakes, not every scam.
158
+ - Use the [reference executor](https://github.com/a32116150-ctrl/verify402/blob/master/examples/preflight-guard.mjs)
159
+ when you want enforcement rather than advice.
160
+
161
+ ## Development
162
+
163
+ ```bash
164
+ npm pack --dry-run
165
+ ```
166
+
167
+ ## License
168
+
169
+ Apache License 2.0. See `LICENSE` and `NOTICE`.
170
+
171
+ You may use, modify, and distribute this package, including in commercial agent
172
+ systems and bots. If you redistribute it or a product containing it, keep the
173
+ copyright notice, the license text, and the `NOTICE` file. The `verify402` name
174
+ and logo are not licensed for endorsement.
package/budget.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // Per-day client-side budget for the verify402 MCP bridge.
2
+ //
3
+ // MAX_PAYMENT_USD caps ONE payment. That answered "how much can one talked-
4
+ //into prompt drain?" but an operator on MoltJobs (vegachiefofstaff) asked the
5
+ // sharper question and was right: nothing stopped a long-running task from
6
+ // opening a fresh client and resetting the cap. This module adds the missing
7
+ // layer, enforced client-side with a persisted ledger:
8
+ //
9
+ // MAX_DAILY_USD (optional, off by default) caps the TOTAL spent per UTC day,
10
+ // across process restarts, via a small JSON ledger file. A attempted charge
11
+ // is recorded BEFORE the payment is constructed: for a spending guard the
12
+ // conservative direction is to over-count, never to under-count.
13
+ //
14
+ // Disabled when MAX_DAILY_USD is unset/0 — the bridge then behaves exactly as
15
+ // before, which is also what pure-local testing wants.
16
+
17
+ import fs from "fs";
18
+ import path from "path";
19
+ import { fileURLToPath } from "url";
20
+
21
+ export const DEFAULT_PRICES = {
22
+ "/verify": 0.05,
23
+ "/safety": 0.10,
24
+ "/route": 0.03,
25
+ "/quotecheck": 0.05,
26
+ "/depth": 0.05,
27
+ };
28
+
29
+ const dayKey = () => new Date().toISOString().slice(0, 10);
30
+
31
+ function loadLedger(file) {
32
+ try {
33
+ const j = JSON.parse(fs.readFileSync(file, "utf8"));
34
+ if (typeof j.totalUsd === "number" && j.day === dayKey()) return j;
35
+ } catch { /* fresh day or fresh file */ }
36
+ return { day: dayKey(), totalUsd: 0 };
37
+ }
38
+
39
+ export function createDailyBudget({ maxDailyUsd, ledgerPath, pricesOverride } = {}) {
40
+ const cap = Number(maxDailyUsd || 0);
41
+ if (!(cap > 0)) return { enabled: false, assert: () => ({ charged: 0, totalUsd: null, remaining: null }) };
42
+
43
+ const file = ledgerPath || path.join(path.dirname(fileURLToPath(import.meta.url)), ".spend-ledger.json");
44
+ const prices = { ...DEFAULT_PRICES, ...(pricesOverride || {}) };
45
+
46
+ function assert(route) {
47
+ let price = prices[route];
48
+ if (price == null) price = prices.default ?? 0;
49
+ const ledger = loadLedger(file);
50
+ const next = Math.round((ledger.totalUsd + price) * 1e6) / 1e6;
51
+ if (next > cap + 1e-9) {
52
+ throw new Error(
53
+ `daily budget exhausted: $${ledger.totalUsd} of $${cap} spent today; refusing ${route} ($${price}). ` +
54
+ `Raise MAX_DAILY_USD in the bridge .env or wait for the next UTC day.`,
55
+ );
56
+ }
57
+ ledger.totalUsd = next;
58
+ ledger.lastRoute = route;
59
+ ledger.lastAt = new Date().toISOString();
60
+ fs.writeFileSync(file, JSON.stringify(ledger, null, 2));
61
+ return { charged: price, totalUsd: next, remaining: Math.max(0, cap - next) };
62
+ }
63
+
64
+ return { enabled: true, cap, file, assert };
65
+ }
package/index.mjs ADDED
@@ -0,0 +1,353 @@
1
+ #!/usr/bin/env node
2
+ // verify402 MCP bridge.
3
+ //
4
+ // Makes verify402 consumable by any MCP client (Claude Desktop, OpenCode, any
5
+ // agent framework) as native tools. The free preflight gate works with no
6
+ // wallet. The five paid checks use an x402 payment handshake from the wallet in
7
+ // EVM_PRIVATE_KEY and return the verdict.
8
+ //
9
+ // ARCHITECTURE (per docs.x402.org/guides/mcp-server-with-x402):
10
+ //
11
+ // MCP client ──▶ this bridge (MCP server + x402 payer) ──▶ verify402.com
12
+ //
13
+ // 1. tool call 3. 402 + PAYMENT-REQUIRED
14
+ // 2. paid GET/POST 4. sign payment (wallet in env)
15
+ // 5. retry with proof → verdict
16
+ //
17
+ // PAYMENT POLICY (load-bearing, do not remove): before a signature exists,
18
+ // x402Client's spend controls enforce the USD cap and the default-asset
19
+ // (USDC) allowlist; payment-policy.mjs then enforces the network allowlist,
20
+ // the verify402 payee, and a known paid resource on the configured server.
21
+ // Redirects are refused. An MCP server that signs anything any remote 402
22
+ // asks for is a blank cheque. This one is not.
23
+
24
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
25
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
+ import axios from "axios";
27
+ import { x402Client, wrapAxiosWithPayment } from "@x402/axios";
28
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
29
+ import { privateKeyToAccount } from "viem/accounts";
30
+ import { config } from "dotenv";
31
+ import { z } from "zod";
32
+
33
+ config();
34
+
35
+ const EVM_PRIVATE_KEY = process.env.EVM_PRIVATE_KEY;
36
+ const SERVER_URL = process.env.VERIFY402_URL || "https://verify402.onrender.com";
37
+ // Preflight is free, so it does not go through the paying client. Keeping the
38
+ // two clients separate means a misconfigured 402 on a free route can never
39
+ // turn into a signature.
40
+ const freeApi = axios.create({ baseURL: SERVER_URL, timeout: 30_000, maxRedirects: 0 });
41
+ // Spend guard: the x402 client refuses to SIGN any payment above this, before
42
+ // a signature exists. Enforced inside x402Client (applySpendControls), not by
43
+ // our own request code - so it cannot be bypassed by a caller.
44
+ const MAX_PAYMENT_USD = Number(process.env.MAX_PAYMENT_USD || 0.25);
45
+
46
+ // Free-only mode is deliberate: an agent can install the bridge and call the
47
+ // free preflight gate without handing it a private key. The paid tools are
48
+ // registered only when a wallet is configured.
49
+ const PAID_ENABLED = Boolean(EVM_PRIVATE_KEY);
50
+
51
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
52
+ console.log(`verify402-mcp — MCP server for verify402
53
+
54
+ Usage:
55
+ verify402-mcp start the stdio MCP server
56
+ verify402-mcp --help show this help
57
+ verify402-mcp --version print the version
58
+
59
+ Environment:
60
+ VERIFY402_URL verify402 base URL (default https://verify402.onrender.com)
61
+ EVM_PRIVATE_KEY optional; omit for the free preflight_gate only
62
+ MAX_PAYMENT_USD cap on one x402 payment (default 0.25)
63
+ MAX_DAILY_USD optional cap for the UTC day, persisted in a small ledger
64
+ SPEND_LEDGER_PATH optional ledger path (default .spend-ledger.json)
65
+ VERIFY402_NETWORKS comma-separated EVM networks for paid calls (default eip155:8453)
66
+ VERIFY402_PAY_TO EVM payee the 402 must name (default the verify402 payee)
67
+ VERIFY402_RESOURCE_PREFIX resource origin/prefix the 402 must match (default VERIFY402_URL)
68
+
69
+ The free gate is preflight_gate. The paid tools are verify_arbitrage,
70
+ check_token_safety, get_best_route, verify_quote_fairness and get_trade_depth.
71
+ The bridge signs x402 payments only; it never signs or sends a trade.
72
+ `);
73
+ process.exit(0);
74
+ }
75
+ if (process.argv.includes("--version") || process.argv.includes("-v")) {
76
+ console.log("1.0.2");
77
+ process.exit(0);
78
+ }
79
+
80
+ // ---------------------------------------------------------------- payment ---
81
+ async function createPaidClient() {
82
+ if (!Number.isFinite(MAX_PAYMENT_USD) || MAX_PAYMENT_USD <= 0) {
83
+ throw new Error("MAX_PAYMENT_USD must be a positive number");
84
+ }
85
+ const policy = createPaymentPolicy({
86
+ networks: process.env.VERIFY402_NETWORKS || DEFAULT_NETWORKS,
87
+ payTo: process.env.VERIFY402_PAY_TO || DEFAULT_PAY_TO,
88
+ resourcePrefix: process.env.VERIFY402_RESOURCE_PREFIX || SERVER_URL,
89
+ paidRoutes: Object.keys(DEFAULT_PRICES),
90
+ });
91
+ const account = privateKeyToAccount(EVM_PRIVATE_KEY);
92
+ const client = x402Client.fromConfig({
93
+ schemes: [], // registered below, one per allowlisted network
94
+ spendControls: { maxAmountPerPayment: `$${MAX_PAYMENT_USD}` },
95
+ policies: [(version, requirements) => policy.filter(version, requirements)],
96
+ });
97
+ for (const network of policy.allowedNetworks) {
98
+ client.register(network, new ExactEvmScheme(account));
99
+ }
100
+ client.onBeforePaymentCreation((context) => policy.checkBeforeSign(context));
101
+ console.error(
102
+ `paid policy: networks=${policy.allowedNetworks.join(",")} ` +
103
+ `payee=${policy.allowedPayTo} resources=${policy.resourcePrefix} ` +
104
+ `{${policy.paidRoutes.join(",")}}`,
105
+ );
106
+ const axiosInstance = axios.create({ baseURL: SERVER_URL, timeout: 120_000, maxRedirects: 0 });
107
+ return wrapAxiosWithPayment(axiosInstance, client);
108
+ }
109
+
110
+ // ------------------------------------------------------------------ budget --
111
+ // The second, broader guard: MAX_PAYMENT_USD caps ONE payment; MAX_DAILY_USD
112
+ // (optional) caps the whole UTC day across restarts, persisted in a tiny
113
+ // ledger file. Attempted charges are counted conservatively (before payment).
114
+ import { createDailyBudget, DEFAULT_PRICES } from "./budget.mjs";
115
+ import { createPaymentPolicy, DEFAULT_NETWORKS, DEFAULT_PAY_TO } from "./payment-policy.mjs";
116
+ const dailyBudget = createDailyBudget({
117
+ maxDailyUsd: process.env.MAX_DAILY_USD,
118
+ });
119
+
120
+ async function guardedPaidCall(route, run) {
121
+ if (dailyBudget.enabled) dailyBudget.assert(route);
122
+ return run();
123
+ }
124
+
125
+ // ------------------------------------------------------------------ tools ---
126
+ const DESCRIPTIONS = {
127
+ preflight_gate:
128
+ "Call this BEFORE signing any crypto transaction or x402 payment request. " +
129
+ "Returns PASS / CAUTION / BLOCK with typed reasons, the checks that actually ran, " +
130
+ "the checks that did not, and a short-lived receipt bound to the exact intent + block. " +
131
+ "If sign_allowed is false, DO NOT SIGN. If requires_ack is true, surface the reasons to the " +
132
+ "operator before signing. The receipt expires (default 90s): call again rather than reuse it. " +
133
+ "Free. Pass `from` (the wallet that will sign) to enable simulation and balance checks.",
134
+ verify_arbitrage:
135
+ "Ask verify402 whether a cross-venue arbitrage opportunity is REAL, right now. " +
136
+ "Quotes come from Uniswap's canonical QuoterV2 and each DEX router at one pinned block. " +
137
+ "The honest answer is usually 'no_edge' - that IS the product. Costs $0.05 per call.",
138
+ check_token_safety:
139
+ "Ask verify402 whether a token is safe to buy BEFORE the agent risks capital. " +
140
+ "Returns TRUST/CAUTION/AVOID with evidence: live contract facts, market liquidity, " +
141
+ "a USD-sized sell probe against every venue (honeypot test), round-trip cost at your " +
142
+ "intended size, and phantom-price detection. Costs $0.10 per call.",
143
+ get_best_route:
144
+ "Ask verify402 what the chain would ACTUALLY pay for a swap: the full execution book " +
145
+ "(every venue, direct and WETH-routed) at one pinned block, best first. Costs $0.03 per call.",
146
+ verify_quote_fairness:
147
+ "Audit a swap quote someone else gave you (aggregator, broker, bot) BEFORE signing. " +
148
+ "Returns fair / overpaying / too_good_to_be_true with the full chain book as evidence. " +
149
+ "Ask this before accepting ANY number you did not produce yourself. Costs $0.05 per call.",
150
+ get_trade_depth:
151
+ "Position sizing: measure how much of a token the chain ACTUALLY lets you trade - " +
152
+ "entry and exit across every venue at a ladder of USD sizes, per-size impact and " +
153
+ "round-trip cost, plus the largest size under your cost tolerance. Ask BEFORE choosing " +
154
+ "a position size. Costs $0.05 per call.",
155
+ };
156
+
157
+ async function main() {
158
+ const paidApi = PAID_ENABLED ? await createPaidClient() : null;
159
+
160
+ const server = new McpServer({ name: "verify402", version: "1.0.2" });
161
+
162
+ server.tool(
163
+ "preflight_gate",
164
+ DESCRIPTIONS.preflight_gate,
165
+ {
166
+ kind: z.enum(["payment", "transaction"]).describe("payment = an x402 402 challenge; transaction = a chain transaction"),
167
+ chainId: z.number().optional().describe("EVM chain id: 1 Ethereum, 42161 Arbitrum, 8453 Base. For payment, cross-checks the network."),
168
+ from: z.string().optional().describe("The wallet that will sign. Strongly recommended: enables simulation and balance checks."),
169
+ payment: z.object({
170
+ scheme: z.string().optional().describe('x402 scheme, normally "exact"'),
171
+ network: z.string().describe('CAIP-2 network, e.g. "eip155:8453" or "solana:..."'),
172
+ asset: z.string().describe("Token address or mint, e.g. canonical USDC on that network"),
173
+ amount: z.string().describe("RAW amount in the asset's smallest unit, as a string"),
174
+ payTo: z.string().describe("Recipient address from the 402 challenge"),
175
+ resource: z.string().optional().describe("The resource URL the payment is for"),
176
+ maxTimeoutSeconds: z.number().optional().describe("maxTimeoutSeconds from the 402 challenge"),
177
+ extra: z.object({
178
+ validAfter: z.number().optional(),
179
+ validBefore: z.number().optional(),
180
+ facilitator: z.string().optional(),
181
+ }).optional().describe("x402 extra fields: validAfter / validBefore / facilitator"),
182
+ }).optional().describe("Required when kind=payment"),
183
+ to: z.string().optional().describe("Transaction target (required when kind=transaction)"),
184
+ data: z.string().optional().describe("0x calldata for the transaction"),
185
+ value: z.string().optional().describe("Native value in wei, as a decimal string"),
186
+ policy: z.object({
187
+ maxAmountUsd: z.number().optional().describe("Reject payments above this USD value"),
188
+ maxValueWei: z.string().optional().describe("Reject native value above this wei amount"),
189
+ maxValueEth: z.number().optional().describe("Reject native value above this ETH amount"),
190
+ allowedNetworks: z.array(z.string()).optional().describe("Allowlist of CAIP-2 networks"),
191
+ allowedPayTo: z.array(z.string()).optional().describe("Allowlist of payment recipients"),
192
+ allowedTo: z.array(z.string()).optional().describe("Allowlist of transaction targets"),
193
+ allowedSpenders: z.array(z.string()).optional().describe("Allowlist of approval spenders"),
194
+ allowedAssets: z.array(z.string()).optional().describe("Allowlist of payment assets"),
195
+ allowedFacilitators: z.array(z.string()).optional().describe("Allowlist of x402 facilitators"),
196
+ expectedResource: z.string().optional().describe("The exact resource URL the agent intends to pay for"),
197
+ forbidUnlimitedApproval: z.boolean().optional().describe("Turn an unlimited approve into a BLOCK"),
198
+ maxTimeoutSeconds: z.number().optional().describe("Reject challenges with a longer timeout"),
199
+ }).optional().describe("Operator policy. Omit for structural checks only."),
200
+ ttlSeconds: z.number().optional().describe("Receipt lifetime in seconds, 15-300 (default 90)"),
201
+ },
202
+ async (args) => {
203
+ const payload = {
204
+ kind: args.kind,
205
+ chainId: args.chainId,
206
+ from: args.from,
207
+ payment: args.payment,
208
+ to: args.to,
209
+ data: args.data,
210
+ value: args.value,
211
+ policy: args.policy,
212
+ ttlSeconds: args.ttlSeconds,
213
+ };
214
+ try {
215
+ const res = await freeApi.post("/preflight", payload);
216
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
217
+ } catch (e) {
218
+ const status = e.response?.status;
219
+ const body = e.response?.data;
220
+ return {
221
+ isError: true,
222
+ content: [{
223
+ type: "text",
224
+ text: `preflight failed${status ? ` (${status})` : ""}: ${JSON.stringify(body ?? e.message)}. Do not sign without a verifiable receipt.`,
225
+ }],
226
+ };
227
+ }
228
+ },
229
+ );
230
+
231
+ // Paid tools require a wallet. Without EVM_PRIVATE_KEY the server still
232
+ // exposes the free gate, so "install it and try it" never asks for a key.
233
+ if (paidApi) {
234
+ server.tool(
235
+ "verify_arbitrage",
236
+ DESCRIPTIONS.verify_arbitrage,
237
+ {
238
+ target: z.string().describe('Token to buy and sell back, e.g. "WETH"'),
239
+ chainId: z.number().optional().describe("1 Ethereum, 42161 Arbitrum, 8453 Base (default 1)"),
240
+ base: z.string().optional().describe('Token to trade from, e.g. "USDC" (default USDC)'),
241
+ size: z.number().optional().describe("Trade size in whole base units, e.g. 100000 (default 100000)"),
242
+ },
243
+ async (args) => {
244
+ const res = await guardedPaidCall("/verify", () => paidApi.post("/verify", {
245
+ chainId: args.chainId ?? 1,
246
+ target: String(args.target ?? "WETH").toUpperCase(),
247
+ base: String(args.base ?? "USDC").toUpperCase(),
248
+ size: args.size ?? 100000,
249
+ }));
250
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
251
+ },
252
+ );
253
+
254
+ server.tool(
255
+ "check_token_safety",
256
+ DESCRIPTIONS.check_token_safety,
257
+ {
258
+ tokenAddress: z.string().describe("ERC-20 contract address, or a known symbol like WETH"),
259
+ chainId: z.number().optional().describe("1 Ethereum, 42161 Arbitrum, 8453 Base (default 1)"),
260
+ intendedUsd: z.number().optional().describe("Size the agent plans to buy, in USD (default 500)"),
261
+ offeredPriceUsd: z.number().optional().describe("Optional price per token someone offered you"),
262
+ },
263
+ async (args) => {
264
+ const res = await guardedPaidCall("/safety", () => paidApi.post("/safety", {
265
+ chainId: args.chainId ?? 1,
266
+ tokenAddress: String(args.tokenAddress ?? "").trim(),
267
+ intendedUsd: args.intendedUsd ?? 500,
268
+ offeredPriceUsd: args.offeredPriceUsd ?? null,
269
+ }));
270
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
271
+ },
272
+ );
273
+
274
+ server.tool(
275
+ "get_best_route",
276
+ DESCRIPTIONS.get_best_route,
277
+ {
278
+ tokenIn: z.string().describe("Token symbol (e.g. USDC) or 0x address"),
279
+ tokenOut: z.string().describe("Token symbol (e.g. WETH) or 0x address"),
280
+ amountIn: z.string().describe("RAW base units of tokenIn, wei-scale, as a string"),
281
+ chainId: z.number().optional().describe("1 Ethereum, 42161 Arbitrum, 8453 Base (default 1)"),
282
+ },
283
+ async (args) => {
284
+ const res = await guardedPaidCall("/route", () => paidApi.post("/route", {
285
+ chainId: args.chainId ?? 1,
286
+ tokenIn: args.tokenIn,
287
+ tokenOut: args.tokenOut,
288
+ amountIn: args.amountIn,
289
+ }));
290
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
291
+ },
292
+ );
293
+
294
+ server.tool(
295
+ "verify_quote_fairness",
296
+ DESCRIPTIONS.verify_quote_fairness,
297
+ {
298
+ tokenIn: z.string().describe("Token you are selling (symbol or 0x address)"),
299
+ tokenOut: z.string().describe("Token you would receive (symbol or 0x address)"),
300
+ amountIn: z.string().describe("RAW units of tokenIn, as in the offer"),
301
+ quotedOut: z.string().describe("RAW units of tokenOut you were OFFERED"),
302
+ venueClaimed: z.string().optional().describe("Optional: who gave you the offer"),
303
+ chainId: z.number().optional().describe("1 Ethereum, 42161 Arbitrum, 8453 Base (default 1)"),
304
+ },
305
+ async (args) => {
306
+ const res = await guardedPaidCall("/quotecheck", () => paidApi.post("/quotecheck", {
307
+ chainId: args.chainId ?? 1,
308
+ tokenIn: args.tokenIn,
309
+ tokenOut: args.tokenOut,
310
+ amountIn: args.amountIn,
311
+ quotedOut: args.quotedOut,
312
+ venueClaimed: args.venueClaimed ?? null,
313
+ }));
314
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
315
+ },
316
+ );
317
+
318
+ server.tool(
319
+ "get_trade_depth",
320
+ DESCRIPTIONS.get_trade_depth,
321
+ {
322
+ tokenAddress: z.string().describe("Token you plan to buy (symbol or 0x address)"),
323
+ chainId: z.number().optional().describe("1 Ethereum, 42161 Arbitrum, 8453 Base (default 1)"),
324
+ baseSymbol: z.string().optional().describe("What you pay with (default USDC)"),
325
+ sizesUsd: z.array(z.number()).optional().describe("Ladder of sizes in USD, max 6 (default 100, 1000, 10000, 100000)"),
326
+ maxRoundTripPct: z.number().optional().describe("Your round-trip cost tolerance, default 1%"),
327
+ },
328
+ async (args) => {
329
+ const res = await guardedPaidCall("/depth", () => paidApi.post("/depth", {
330
+ chainId: args.chainId ?? 1,
331
+ tokenAddress: args.tokenAddress,
332
+ baseSymbol: args.baseSymbol ?? "USDC",
333
+ sizesUsd: args.sizesUsd ?? null,
334
+ maxRoundTripPct: args.maxRoundTripPct ?? 1.0,
335
+ }));
336
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
337
+ },
338
+ );
339
+ } // end paid tools
340
+
341
+ const transport = new StdioServerTransport();
342
+ await server.connect(transport);
343
+ console.error(
344
+ paidApi
345
+ ? `verify402 MCP bridge connected -> ${SERVER_URL} (paid tools on, max payment $${MAX_PAYMENT_USD})`
346
+ : `verify402 MCP bridge connected -> ${SERVER_URL} (free preflight_gate only; set EVM_PRIVATE_KEY for paid tools)`,
347
+ );
348
+ }
349
+
350
+ main().catch((e) => {
351
+ console.error("bridge failed:", e.message);
352
+ process.exit(1);
353
+ });
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "verify402-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "mcpName": "io.github.a32116150-ctrl/verify402-mcp",
5
+ "description": "MCP server for verify402: a free, fail-closed preflight gate before signing, plus five paid on-chain checks paid per call via x402.",
6
+ "type": "module",
7
+ "bin": {
8
+ "verify402-mcp": "index.mjs"
9
+ },
10
+ "main": "index.mjs",
11
+ "files": [
12
+ "index.mjs",
13
+ "budget.mjs",
14
+ "payment-policy.mjs",
15
+ "README.md",
16
+ ".env.example",
17
+ "LICENSE",
18
+ "NOTICE"
19
+ ],
20
+ "scripts": {
21
+ "start": "node index.mjs",
22
+ "test": "node --test test/payment-policy.test.mjs"
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "keywords": [
28
+ "mcp",
29
+ "model-context-protocol",
30
+ "x402",
31
+ "ai-agents",
32
+ "crypto",
33
+ "preflight",
34
+ "payments",
35
+ "base",
36
+ "solana",
37
+ "trading-bot"
38
+ ],
39
+ "license": "Apache-2.0",
40
+ "author": "verify402 (https://github.com/a32116150-ctrl/verify402)",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/a32116150-ctrl/verify402.git",
44
+ "directory": "mcp-bridge"
45
+ },
46
+ "homepage": "https://verify402.onrender.com/mcp",
47
+ "bugs": {
48
+ "url": "https://github.com/a32116150-ctrl/verify402/issues"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "dependencies": {
54
+ "@modelcontextprotocol/sdk": "^1.12.1",
55
+ "@x402/axios": "^2.28.0",
56
+ "@x402/evm": "^2.28.0",
57
+ "axios": "^1.13.2",
58
+ "dotenv": "^16.4.5",
59
+ "viem": "^2.39.0",
60
+ "zod": "^4.6.7"
61
+ }
62
+ }
@@ -0,0 +1,162 @@
1
+ // Payment policy for the paid x402 client.
2
+ //
3
+ // The bridge is a payer, not a blank cheque for any remote 402. Before a
4
+ // signature exists, the policy requires:
5
+ //
6
+ // - the network to be explicitly allowlisted (default Base mainnet);
7
+ // - payTo to be the verify402 payee (default the EVM payTo);
8
+ // - the 402 resource to be on the configured server and a known paid route.
9
+ //
10
+ // The amount cap and the default-asset (USDC) allowlist are enforced by
11
+ // x402Client's spendControls, which run before this policy. Redirects are
12
+ // refused by the axios client in index.mjs.
13
+ //
14
+ // Free-only mode never imports or constructs this policy.
15
+
16
+ export const DEFAULT_NETWORKS = ["eip155:8453"];
17
+ export const DEFAULT_PAY_TO = "0xAeEF086DD4e436c69d6d0F684b4c9F43392df9cb";
18
+ export const DEFAULT_PAID_ROUTES = ["/verify", "/safety", "/route", "/quotecheck", "/depth"];
19
+
20
+ function parseNetworks(raw) {
21
+ const values = Array.isArray(raw) ? raw : String(raw ?? "").split(",");
22
+ const networks = values.map((value) => String(value).trim()).filter(Boolean);
23
+ if (networks.length === 0) {
24
+ throw new Error("VERIFY402_NETWORKS must list at least one eip155:<chainId> network");
25
+ }
26
+ for (const network of networks) {
27
+ if (!/^eip155:\d+$/.test(network)) {
28
+ throw new Error(`VERIFY402_NETWORKS: ${network} is not an eip155:<chainId> network`);
29
+ }
30
+ }
31
+ return [...new Set(networks)];
32
+ }
33
+
34
+ function normalizePayTo(raw) {
35
+ const value = String(raw ?? "").trim();
36
+ if (!/^0x[0-9a-fA-F]{40}$/.test(value)) {
37
+ throw new Error("VERIFY402_PAY_TO must be a 20-byte 0x EVM address");
38
+ }
39
+ return value.toLowerCase();
40
+ }
41
+
42
+ function normalizePrefix(raw) {
43
+ const value = String(raw ?? "").trim().replace(/\/+$/, "");
44
+ let url;
45
+ try {
46
+ url = new URL(value);
47
+ } catch {
48
+ throw new Error(`VERIFY402_RESOURCE_PREFIX is not a URL: ${value || "(empty)"}`);
49
+ }
50
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
51
+ throw new Error(`VERIFY402_RESOURCE_PREFIX must be http(s): ${value}`);
52
+ }
53
+ return {
54
+ value,
55
+ origin: url.origin,
56
+ pathPrefix: url.pathname.replace(/\/+$/, ""),
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Build the paid-call policy. Throws on invalid configuration so a paid-mode
62
+ * start fails closed instead of silently accepting a wider policy.
63
+ */
64
+ export function createPaymentPolicy({
65
+ networks = DEFAULT_NETWORKS,
66
+ payTo = DEFAULT_PAY_TO,
67
+ resourcePrefix,
68
+ paidRoutes = DEFAULT_PAID_ROUTES,
69
+ } = {}) {
70
+ const allowedNetworks = parseNetworks(networks);
71
+ const allowed = new Set(allowedNetworks);
72
+ const allowedPayTo = normalizePayTo(payTo);
73
+ const prefix = normalizePrefix(resourcePrefix);
74
+ const routes = new Set(paidRoutes.map(String));
75
+
76
+ return {
77
+ allowedNetworks,
78
+ allowedPayTo,
79
+ resourcePrefix: prefix.value,
80
+ paidRoutes: [...routes],
81
+
82
+ /**
83
+ * x402Client policy: runs after spend controls and before the selector.
84
+ * Returning an empty array would also fail, but a typed error is easier to
85
+ * debug and is surfaced to the caller as a refused payment.
86
+ */
87
+ filter(_x402Version, requirements) {
88
+ const passing = requirements.filter((requirement) => {
89
+ const network = String(requirement?.network ?? "");
90
+ const requirementPayTo = String(requirement?.payTo ?? "").toLowerCase();
91
+ return allowed.has(network) && requirementPayTo === allowedPayTo;
92
+ });
93
+ if (passing.length === 0) {
94
+ throw new Error(
95
+ `402 offered no payment on an allowed network/payee ` +
96
+ `(allowed networks: ${allowedNetworks.join(", ")}; payee: ${allowedPayTo})`,
97
+ );
98
+ }
99
+ return passing;
100
+ },
101
+
102
+ /**
103
+ * x402Client onBeforePaymentCreation hook: runs after selection and before
104
+ * the scheme creates a signature. Returning `{ abort: true }` fails closed.
105
+ */
106
+ checkBeforeSign(context) {
107
+ const rawResource = context?.paymentRequired?.resource;
108
+ const resourceUrl = typeof rawResource === "string" ? rawResource : rawResource?.url;
109
+ if (!resourceUrl) {
110
+ return { abort: true, reason: "402 has no resource URL" };
111
+ }
112
+
113
+ let url;
114
+ try {
115
+ url = new URL(String(resourceUrl));
116
+ } catch {
117
+ return { abort: true, reason: `402 resource is not a URL: ${String(resourceUrl)}` };
118
+ }
119
+
120
+ if (url.origin !== prefix.origin) {
121
+ return {
122
+ abort: true,
123
+ reason: `402 resource origin ${url.origin} is not the configured ${prefix.origin}`,
124
+ };
125
+ }
126
+
127
+ const pathOk =
128
+ prefix.pathPrefix === "" ||
129
+ url.pathname === prefix.pathPrefix ||
130
+ url.pathname.startsWith(`${prefix.pathPrefix}/`);
131
+ if (!pathOk) {
132
+ return {
133
+ abort: true,
134
+ reason: `402 resource ${url.href} is outside ${prefix.value}`,
135
+ };
136
+ }
137
+
138
+ if (!routes.has(url.pathname)) {
139
+ return {
140
+ abort: true,
141
+ reason: `402 resource path ${url.pathname} is not a paid verify402 route`,
142
+ };
143
+ }
144
+
145
+ const requirement = context?.selectedRequirements;
146
+ if (!requirement) {
147
+ return { abort: true, reason: "402 selected no payment requirement" };
148
+ }
149
+ if (
150
+ !allowed.has(String(requirement.network)) ||
151
+ String(requirement.payTo ?? "").toLowerCase() !== allowedPayTo
152
+ ) {
153
+ return {
154
+ abort: true,
155
+ reason: "selected payment requirement changed after selection",
156
+ };
157
+ }
158
+
159
+ return;
160
+ },
161
+ };
162
+ }