@agent402-dev/pay-mcp 0.0.0-stage → 0.2.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.
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +76 -2
- package/dist/agent.d.ts +53 -0
- package/dist/agent.js +157 -0
- package/dist/history.d.ts +35 -0
- package/dist/history.js +36 -0
- package/dist/policy.d.ts +107 -0
- package/dist/policy.js +146 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +26 -0
- package/dist/tools.d.ts +12 -0
- package/dist/tools.js +83 -0
- package/dist/units.d.ts +5 -0
- package/dist/units.js +11 -0
- package/dist/wallet.d.ts +12 -0
- package/dist/wallet.js +58 -0
- package/package.json +53 -4
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
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @agent402-dev/pay-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **A402 (v1) is deprecated.** The token payment option is now **PREQ** (mint `aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX`). Official addresses: https://claude.ai/artifact/S6UafAfViJk3DJeMsDMAja
|
|
4
|
+
|
|
5
|
+
MCP server (stdio) that lets an AI agent call [x402](https://github.com/coinbase/x402) paid APIs on Solana and pay in **USDC** (or, if you allow it, **PREQ**) from **your own wallet on your machine**, only within the rules you set.
|
|
6
|
+
|
|
7
|
+
Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
|
|
8
|
+
Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
|
|
9
|
+
|
|
10
|
+
> It pays only what you allow and gives no opinion on any API or token. Not investment advice.
|
|
11
|
+
|
|
12
|
+
## Rules checked before signing
|
|
13
|
+
Nothing is signed unless every rule passes. **With no configuration, every payment is refused.**
|
|
14
|
+
|
|
15
|
+
| Rule | Variable | Default |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Allowed domains (host or host:port; https only, http only for localhost) | `X402_ALLOWED_DOMAINS` | empty → refuse all |
|
|
18
|
+
| Trusted recipients (payTo addresses) | `X402_TRUSTED_PAY_TO` | empty → refuse all |
|
|
19
|
+
| Allowed assets | `X402_ALLOWED_ASSETS` | `USDC` (PREQ only if listed) |
|
|
20
|
+
| Max USDC per payment (USD) | `X402_MAX_USD` | `0.05` |
|
|
21
|
+
| Max USDC per UTC day (USD) | `X402_MAX_USD_PER_DAY` | `1` |
|
|
22
|
+
| Max payments per UTC day | `X402_MAX_PAYMENTS_PER_DAY` | `20` |
|
|
23
|
+
| **Max PREQ per payment** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_ATOMIC` | **not set → PREQ payments refused** |
|
|
24
|
+
| **Max PREQ per UTC day** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_PER_DAY_ATOMIC` | **not set → PREQ payments refused** |
|
|
25
|
+
| Ask a human at or above this USDC amount (USD) | `X402_CONFIRM_ABOVE_USD` | off |
|
|
26
|
+
| Ask a human at or above this PREQ amount (PREQ smallest units) | `X402_CONFIRM_ABOVE_PREQ_ATOMIC` | off |
|
|
27
|
+
|
|
28
|
+
- **PREQ units.** The PREQ variables take the smallest unit (PREQ has 6 decimals). Example: `X402_MAX_PREQ_ATOMIC=200000000000` is 200,000 PREQ per payment. `wallet_status` and `payment_history` also show PREQ amounts in smallest units (`…Atomic` fields).
|
|
29
|
+
- USD limits apply to USDC only. PREQ has its own two limits, and **both must be set** before any PREQ payment is made.
|
|
30
|
+
- **PREQ mint.** Until the PREQ mainnet mint is filled into this package, listing `PREQ` in `X402_ALLOWED_ASSETS` stops the server at start with an error (you can set `X402_PREQ_MINT` yourself).
|
|
31
|
+
- **A402 (v1) is deprecated.** It is never allowed by default. If you list `A402` in `X402_ALLOWED_ASSETS` (with its own `X402_MAX_A402_ATOMIC` and `X402_MAX_A402_PER_DAY_ATOMIC`, in A402 smallest units; 1 A402 = 1,000,000), the server prints "A402 (v1) is deprecated and no longer supported; use PREQ." at start, and `wallet_status`, `x402_quote` and `x402_fetch` results carry the same warning.
|
|
32
|
+
- Human confirmation uses MCP elicitation. If your MCP client cannot ask, the payment is not made (`confirmation_required`).
|
|
33
|
+
- At most one signature per `x402_fetch` call. If the server answers 402 again after payment, it does not sign again.
|
|
34
|
+
- Redirects are followed manually and each hop must be an allowed domain; a disallowed hop is not contacted.
|
|
35
|
+
- Pass `quoteId` from `x402_quote` to `x402_fetch` to refuse if the amount, asset or recipient changed.
|
|
36
|
+
- Daily totals count every payment this server signed, whatever the result.
|
|
37
|
+
- Daily limits are counted from the local payment log file (`X402_HISTORY_PATH`). Deleting or moving that file resets the daily totals.
|
|
38
|
+
|
|
39
|
+
Other settings: `X402_KEYPAIR_PATH` (wallet key file, Solana CLI JSON; without it nothing is paid), `X402_NETWORK` (`mainnet` | `devnet`), `X402_RPC_URL`, `X402_PAY_WITH` (`USDC` | `PREQ`), `X402_HISTORY_PATH` (default `~/.agent402/payments.jsonl`).
|
|
40
|
+
|
|
41
|
+
## Connect
|
|
42
|
+
Claude Code (example — set your own allowlists and limits):
|
|
43
|
+
```bash
|
|
44
|
+
claude mcp add a402-pay \
|
|
45
|
+
-e X402_KEYPAIR_PATH=<path to a small, dedicated wallet key file> \
|
|
46
|
+
-e X402_ALLOWED_DOMAINS=<api.example.com> \
|
|
47
|
+
-e X402_TRUSTED_PAY_TO=<recipient address> \
|
|
48
|
+
-- npx -y @agent402-dev/pay-mcp
|
|
49
|
+
```
|
|
50
|
+
Claude Desktop (`claude_desktop_config.json`):
|
|
51
|
+
```json
|
|
52
|
+
{ "mcpServers": { "a402-pay": { "command": "npx", "args": ["-y", "@agent402-dev/pay-mcp"], "env": { "X402_KEYPAIR_PATH": "<key file>", "X402_ALLOWED_DOMAINS": "<api.example.com>", "X402_TRUSTED_PAY_TO": "<recipient address>" } } } }
|
|
53
|
+
```
|
|
54
|
+
Node 20+. Without `X402_ALLOWED_DOMAINS` and `X402_TRUSTED_PAY_TO` every payment is refused; without `X402_KEYPAIR_PATH` only `x402_quote` and `wallet_status` are useful.
|
|
55
|
+
|
|
56
|
+
## Tools
|
|
57
|
+
| Tool | What it does |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `x402_fetch` | Fetch a URL; pay only if the rules pass |
|
|
60
|
+
| `x402_quote` | Show payment requirements and which rules pass; never signs; returns `quoteId` |
|
|
61
|
+
| `wallet_status` | Address, balances, today's usage (count, USDC, PREQ), limits including both PREQ limits, allowlists |
|
|
62
|
+
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id |
|
|
63
|
+
|
|
64
|
+
The log never stores keys or signed payment payloads.
|
|
65
|
+
|
|
66
|
+
## Use a small, dedicated wallet
|
|
67
|
+
Put only what you are willing to spend in the payment wallet. Never point this at a wallet that holds other funds. The key file stays on your machine; only a partially signed payment transaction is sent.
|
|
68
|
+
|
|
69
|
+
## What it does not do
|
|
70
|
+
- It **does not judge, score or rate** tokens or APIs and gives no investment advice.
|
|
71
|
+
- It **does not operate a facilitator**, **does not hold funds**, **does not exchange** currencies, and **does not accept or send payments on anyone's behalf**. It signs payments from your own wallet, on your machine, under your rules.
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
Apache-2.0. See [LICENSE](https://github.com/agent402-dev/agent402-toolkit/blob/main/LICENSE) and [NOTICE](https://github.com/agent402-dev/agent402-toolkit/blob/main/NOTICE).
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
Factual information from public on-chain data. Not investment advice.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { History, PaymentResult } from './history.js';
|
|
2
|
+
import { type PayPolicy } from './policy.js';
|
|
3
|
+
import type { Wallet } from './wallet.js';
|
|
4
|
+
export type ConfirmAnswer = 'accept' | 'decline' | 'unsupported';
|
|
5
|
+
export interface AgentDeps {
|
|
6
|
+
policy: PayPolicy;
|
|
7
|
+
wallet: Wallet | null;
|
|
8
|
+
history: History;
|
|
9
|
+
fetch: typeof fetch;
|
|
10
|
+
/** Human confirmation (MCP elicitation). If the client does not support it, 'unsupported' → no payment */
|
|
11
|
+
confirm: (message: string) => Promise<ConfirmAnswer>;
|
|
12
|
+
now?: () => Date;
|
|
13
|
+
maxRedirects?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface RequestSpec {
|
|
16
|
+
url: string;
|
|
17
|
+
method?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface FetchOutcome {
|
|
22
|
+
result: PaymentResult | 'not_required';
|
|
23
|
+
httpStatus?: number;
|
|
24
|
+
reasons?: string[];
|
|
25
|
+
payment?: {
|
|
26
|
+
asset: string | null;
|
|
27
|
+
mint: string;
|
|
28
|
+
amount: string;
|
|
29
|
+
payTo: string;
|
|
30
|
+
network: string;
|
|
31
|
+
settlementTx?: string;
|
|
32
|
+
};
|
|
33
|
+
body?: unknown;
|
|
34
|
+
/** Policy evaluation result (the reason for each condition when rejected) */
|
|
35
|
+
options?: {
|
|
36
|
+
asset: string | null;
|
|
37
|
+
mint: string;
|
|
38
|
+
amount: string;
|
|
39
|
+
payTo: string;
|
|
40
|
+
ok: boolean;
|
|
41
|
+
reasons: string[];
|
|
42
|
+
}[];
|
|
43
|
+
/** Warnings (e.g. the deprecation notice when trying to pay with A402 (v1)) */
|
|
44
|
+
warnings?: string[];
|
|
45
|
+
}
|
|
46
|
+
export declare function createAgent(d: AgentDeps): {
|
|
47
|
+
quote: (spec: RequestSpec) => Promise<FetchOutcome & {
|
|
48
|
+
quoteId?: string;
|
|
49
|
+
}>;
|
|
50
|
+
payAndFetch: (spec: RequestSpec & {
|
|
51
|
+
quoteId?: string;
|
|
52
|
+
}) => Promise<FetchOutcome>;
|
|
53
|
+
};
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Payment decision and execution (core logic independent of MCP, separated for testing)
|
|
2
|
+
// Order: domain check → request (follows redirects itself, checking the domain each time) → on 402, evaluate the policy → (confirm the quote is unchanged) → (human confirmation) → sign once → re-request
|
|
3
|
+
// At most one signature per request. If another 402 comes after paying, it does not sign again
|
|
4
|
+
import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
|
|
5
|
+
import { A402_DEPRECATION_WARNING, choose, domainCheck, evaluate } from './policy.js';
|
|
6
|
+
import { withSmallest } from './units.js';
|
|
7
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
8
|
+
/** Adds the deprecation warning if the chosen asset is A402 (v1) (there is no path that silently pays with A402) */
|
|
9
|
+
const withDeprecation = (o) => o.payment?.asset === 'A402' ? { ...o, warnings: [...(o.warnings ?? []), A402_DEPRECATION_WARNING] } : o;
|
|
10
|
+
export function createAgent(d) {
|
|
11
|
+
const now = d.now ?? (() => new Date());
|
|
12
|
+
const quotes = new Map();
|
|
13
|
+
const QUOTE_TTL_MS = 5 * 60_000;
|
|
14
|
+
/** Follows redirects itself and checks the domain at each step */
|
|
15
|
+
async function send(spec, extraHeaders = {}, follow = true) {
|
|
16
|
+
let url = spec.url;
|
|
17
|
+
for (let hop = 0; hop <= (d.maxRedirects ?? 3); hop++) {
|
|
18
|
+
const dc = domainCheck(d.policy, url);
|
|
19
|
+
if (!dc.ok)
|
|
20
|
+
return { refused: hop === 0 ? dc.reason : `redirect_to_disallowed_domain: ${dc.reason}` };
|
|
21
|
+
const res = await d.fetch(url, { method: spec.method ?? 'GET', headers: { ...(spec.headers ?? {}), ...extraHeaders }, body: spec.body, redirect: 'manual' });
|
|
22
|
+
if (!follow || !REDIRECTS.has(res.status))
|
|
23
|
+
return { res, finalUrl: url };
|
|
24
|
+
const loc = res.headers.get('location');
|
|
25
|
+
if (!loc)
|
|
26
|
+
return { res, finalUrl: url };
|
|
27
|
+
url = new URL(loc, url).toString();
|
|
28
|
+
}
|
|
29
|
+
return { refused: 'too_many_redirects' };
|
|
30
|
+
}
|
|
31
|
+
const readBody = async (res) => {
|
|
32
|
+
const t = (await res.text()).slice(0, 20_000);
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(t);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return t;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const describe = (e) => ({ asset: e.asset, mint: e.requirement.asset, amount: e.requirement.amount, payTo: e.requirement.payTo, ok: e.ok, reasons: e.reasons });
|
|
41
|
+
const host = (u) => { try {
|
|
42
|
+
return new URL(u).host;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return '';
|
|
46
|
+
} };
|
|
47
|
+
const record = (e) => d.history.add({ at: now().toISOString(), ...e });
|
|
48
|
+
/** Receives a 402 and evaluates it with the policy (no signing) */
|
|
49
|
+
async function assess(spec) {
|
|
50
|
+
const sent = await send(spec);
|
|
51
|
+
if ('refused' in sent)
|
|
52
|
+
return { kind: 'refused', refused: sent.refused };
|
|
53
|
+
const { res, finalUrl } = sent;
|
|
54
|
+
if (res.status !== 402)
|
|
55
|
+
return { kind: 'not_required', res, finalUrl };
|
|
56
|
+
const h = res.headers.get('payment-required');
|
|
57
|
+
let pr;
|
|
58
|
+
try {
|
|
59
|
+
pr = decodePaymentRequiredHeader(h ?? '');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return { kind: 'refused', refused: 'invalid_payment_required_header' };
|
|
63
|
+
}
|
|
64
|
+
// If the 402 points to a resource at another address, that address must also be on the allowlist
|
|
65
|
+
if (pr.resource?.url) {
|
|
66
|
+
const rc = domainCheck(d.policy, pr.resource.url);
|
|
67
|
+
if (!rc.ok)
|
|
68
|
+
return { kind: 'refused', refused: `resource_on_disallowed_domain: ${rc.reason}` };
|
|
69
|
+
}
|
|
70
|
+
const evs = pr.accepts.map((r) => evaluate(d.policy, r, d.history.today(now())));
|
|
71
|
+
return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl };
|
|
72
|
+
}
|
|
73
|
+
async function quote(spec) {
|
|
74
|
+
const a = await assess(spec);
|
|
75
|
+
if (a.kind === 'refused')
|
|
76
|
+
return { result: 'refused', reasons: [a.refused] };
|
|
77
|
+
if (a.kind === 'not_required')
|
|
78
|
+
return { result: 'not_required', httpStatus: a.res.status };
|
|
79
|
+
const options = a.evs.map(describe);
|
|
80
|
+
if (!a.chosen)
|
|
81
|
+
return { result: 'refused', reasons: ['no_option_passes_policy'], options };
|
|
82
|
+
const quoteId = crypto.randomUUID();
|
|
83
|
+
const r = a.chosen.requirement;
|
|
84
|
+
quotes.set(quoteId, { url: spec.url, asset: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, at: now().getTime() });
|
|
85
|
+
return { result: 'not_required', quoteId, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network }, reasons: a.chosen.needsConfirmation ? ['will_ask_for_confirmation'] : [] };
|
|
86
|
+
}
|
|
87
|
+
async function payAndFetch(spec) {
|
|
88
|
+
const base = { url: spec.url, host: host(spec.url) };
|
|
89
|
+
const a = await assess(spec);
|
|
90
|
+
if (a.kind === 'refused') {
|
|
91
|
+
record({ ...base, result: 'refused', reasons: [a.refused], signed: false });
|
|
92
|
+
return { result: 'refused', reasons: [a.refused] };
|
|
93
|
+
}
|
|
94
|
+
if (a.kind === 'not_required')
|
|
95
|
+
return { result: 'not_required', httpStatus: a.res.status, body: await readBody(a.res) };
|
|
96
|
+
const options = a.evs.map(describe);
|
|
97
|
+
if (!a.chosen) {
|
|
98
|
+
const reasons = ['no_option_passes_policy', ...a.evs.flatMap((e) => e.reasons)];
|
|
99
|
+
record({ ...base, result: 'refused', reasons, signed: false });
|
|
100
|
+
return { result: 'refused', reasons, options };
|
|
101
|
+
}
|
|
102
|
+
const r = a.chosen.requirement;
|
|
103
|
+
const pay = { network: r.network, asset: a.chosen.asset ?? undefined, mint: r.asset, amount: r.amount, payTo: r.payTo };
|
|
104
|
+
const refuse = (result, reasons) => {
|
|
105
|
+
record({ ...base, ...pay, result, reasons, signed: false });
|
|
106
|
+
return { result, reasons, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network } };
|
|
107
|
+
};
|
|
108
|
+
// Same requirement as the quote? (reject if the amount or receiver changed between requests)
|
|
109
|
+
if (spec.quoteId) {
|
|
110
|
+
const q = quotes.get(spec.quoteId);
|
|
111
|
+
if (!q || q.url !== spec.url || now().getTime() - q.at > QUOTE_TTL_MS)
|
|
112
|
+
return refuse('refused', ['quote_not_found_or_expired']);
|
|
113
|
+
const changed = ['asset', 'amount', 'payTo', 'network'].filter((k) => q[k] !== r[k]);
|
|
114
|
+
if (changed.length)
|
|
115
|
+
return refuse('refused', [`requirements_changed_since_quote: ${changed.join(',')}`]);
|
|
116
|
+
}
|
|
117
|
+
if (!d.wallet)
|
|
118
|
+
return refuse('refused', ['no_wallet: set X402_KEYPAIR_PATH']);
|
|
119
|
+
if (a.chosen.needsConfirmation) {
|
|
120
|
+
const human = `Pay ${a.chosen.asset === 'USDC' ? `${a.chosen.usd} USDC` : withSmallest(r.amount, a.chosen.asset ?? 'tokens')} to ${r.payTo} for ${spec.url}?${a.chosen.asset === 'A402' ? ` (${A402_DEPRECATION_WARNING})` : ''}`;
|
|
121
|
+
const ans = await d.confirm(human).catch(() => 'unsupported');
|
|
122
|
+
if (ans === 'unsupported')
|
|
123
|
+
return refuse('confirmation_required', ['confirmation_required: this client cannot ask for confirmation (MCP elicitation); payment not made']);
|
|
124
|
+
if (ans === 'decline')
|
|
125
|
+
return refuse('declined_by_user', ['declined_by_user']);
|
|
126
|
+
}
|
|
127
|
+
// Sign (only once per request)
|
|
128
|
+
const header = await d.wallet.sign(a.pr.resource, r);
|
|
129
|
+
const sent = await send({ ...spec, url: a.finalUrl }, { 'payment-signature': header }, false);
|
|
130
|
+
if ('refused' in sent) {
|
|
131
|
+
record({ ...base, ...pay, result: 'failed', reasons: [sent.refused], signed: true });
|
|
132
|
+
return { result: 'failed', reasons: [sent.refused] };
|
|
133
|
+
}
|
|
134
|
+
const res = sent.res;
|
|
135
|
+
const body = await readBody(res);
|
|
136
|
+
if (res.ok) {
|
|
137
|
+
const pr = res.headers.get('payment-response');
|
|
138
|
+
let tx;
|
|
139
|
+
try {
|
|
140
|
+
tx = pr ? decodePaymentResponseHeader(pr).transaction : undefined;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
tx = undefined;
|
|
144
|
+
}
|
|
145
|
+
record({ ...base, ...pay, result: 'paid', httpStatus: res.status, settlementTx: tx, signed: true });
|
|
146
|
+
return { result: 'paid', httpStatus: res.status, body, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, settlementTx: tx } };
|
|
147
|
+
}
|
|
148
|
+
const reason = typeof body === 'object' && body && 'reason' in body ? String(body.reason) : `http_${res.status}`;
|
|
149
|
+
const result = res.status === 402 ? 'rejected_by_server' : res.headers.get('x-payment-status') === 'not-settled' || res.status === 409 ? 'failed' : 'unknown';
|
|
150
|
+
record({ ...base, ...pay, result, reasons: [reason], httpStatus: res.status, signed: true });
|
|
151
|
+
return { result, httpStatus: res.status, reasons: [reason], body };
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
quote: async (spec) => withDeprecation(await quote(spec)),
|
|
155
|
+
payAndFetch: async (spec) => withDeprecation(await payAndFetch(spec)),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type PaymentResult = 'paid' | 'refused' | 'declined_by_user' | 'confirmation_required' | 'rejected_by_server' | 'failed' | 'unknown';
|
|
2
|
+
export interface HistoryEntry {
|
|
3
|
+
at: string;
|
|
4
|
+
url: string;
|
|
5
|
+
host: string;
|
|
6
|
+
network?: string;
|
|
7
|
+
asset?: string;
|
|
8
|
+
mint?: string;
|
|
9
|
+
amount?: string;
|
|
10
|
+
payTo?: string;
|
|
11
|
+
result: PaymentResult;
|
|
12
|
+
/** Reason for rejection or failure */
|
|
13
|
+
reasons?: string[];
|
|
14
|
+
httpStatus?: number;
|
|
15
|
+
/** Settlement transaction id (PAYMENT-RESPONSE) */
|
|
16
|
+
settlementTx?: string;
|
|
17
|
+
/** Whether it signed (true if it signed a payment transaction in this request) */
|
|
18
|
+
signed: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface History {
|
|
21
|
+
add(e: HistoryEntry): void;
|
|
22
|
+
list(limit?: number): HistoryEntry[];
|
|
23
|
+
/** Today's (UTC) signed payment count, USDC total (USD), PREQ and A402 (v1) totals (base units), for limit checks */
|
|
24
|
+
today(now?: Date): {
|
|
25
|
+
count: number;
|
|
26
|
+
usd: number;
|
|
27
|
+
preq: bigint;
|
|
28
|
+
a402: bigint;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export declare function jsonlHistory(path: string, mints: () => {
|
|
32
|
+
USDC: string;
|
|
33
|
+
PREQ: string;
|
|
34
|
+
A402: string;
|
|
35
|
+
}): History;
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Payment history (JSONL, on the user's computer). Keys, payment signature headers and raw partially signed transactions are not stored.
|
|
2
|
+
// Stored: time, URL, host, asset, amount, receiver, result, reason, settlement tx id (public on-chain record)
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
const FORBIDDEN_KEYS = ['secret', 'privateKey', 'keypair', 'paymentSignature', 'transaction', 'payload'];
|
|
6
|
+
export function jsonlHistory(path, mints) {
|
|
7
|
+
const read = () => {
|
|
8
|
+
if (!existsSync(path))
|
|
9
|
+
return [];
|
|
10
|
+
return readFileSync(path, 'utf8').split('\n').filter(Boolean).map((l) => { try {
|
|
11
|
+
return JSON.parse(l);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
} }).filter((x) => !!x);
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
add(e) {
|
|
19
|
+
for (const k of FORBIDDEN_KEYS)
|
|
20
|
+
if (k in e)
|
|
21
|
+
throw new Error(`history: refusing to store field ${k}`);
|
|
22
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
23
|
+
appendFileSync(path, JSON.stringify(e) + '\n');
|
|
24
|
+
},
|
|
25
|
+
list(limit = 50) { return read().slice(-limit).reverse(); },
|
|
26
|
+
today(now = new Date()) {
|
|
27
|
+
const day = now.toISOString().slice(0, 10);
|
|
28
|
+
// A signed payment counts as spent regardless of result (succeeded, rejected, unknown), to be conservative
|
|
29
|
+
const xs = read().filter((e) => e.signed && e.at.slice(0, 10) === day);
|
|
30
|
+
const m = mints();
|
|
31
|
+
const usd = xs.filter((e) => e.mint === m.USDC && e.amount).reduce((s, e) => s + Number(e.amount) / 1e6, 0);
|
|
32
|
+
const sum = (mint) => (mint ? xs.filter((e) => e.mint === mint && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n) : 0n);
|
|
33
|
+
return { count: xs.length, usd, preq: sum(m.PREQ), a402: sum(m.A402) };
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
package/dist/policy.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { PaymentRequirements } from '@x402/core/types';
|
|
2
|
+
export declare const NETWORKS: {
|
|
3
|
+
readonly mainnet: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
4
|
+
readonly devnet: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* PREQ mainnet mint (Token-2022, 6 decimals). Same value as PREQ_MAINNET_MINT in pay-server src/preq.ts.
|
|
8
|
+
* Set after the PREQ launch on 2026-11-21. X402_PREQ_MINT can override it (e.g. for devnet rehearsals)
|
|
9
|
+
*/
|
|
10
|
+
export declare const PREQ_MAINNET_MINT = "aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX";
|
|
11
|
+
export declare const A402_DEPRECATION_WARNING = "A402 (v1) is deprecated and no longer supported; use PREQ.";
|
|
12
|
+
export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
|
|
13
|
+
/** Tokens other than USDC (limits managed in base units) */
|
|
14
|
+
export type TokenSymbol = Exclude<AssetSymbol, 'USDC'>;
|
|
15
|
+
export declare const TOKEN_SYMBOLS: TokenSymbol[];
|
|
16
|
+
/** Limits for one token (all in base units, 1 token = 1,000,000) */
|
|
17
|
+
export interface TokenLimits {
|
|
18
|
+
/** Per-payment cap. null = not set → payments in that token are rejected */
|
|
19
|
+
perPayment: bigint | null;
|
|
20
|
+
/** Daily (UTC) total cap. null = not set → payments in that token are rejected */
|
|
21
|
+
perDay: bigint | null;
|
|
22
|
+
/** Ask a human at or above this amount. null = never ask */
|
|
23
|
+
confirmAbove: bigint | null;
|
|
24
|
+
}
|
|
25
|
+
export interface PayPolicy {
|
|
26
|
+
network: string;
|
|
27
|
+
/** Empty string = no mint on that network (that asset matches no payment requirement) */
|
|
28
|
+
mints: Record<AssetSymbol, string>;
|
|
29
|
+
/** Domains allowed for paid calls (host or host:port, lowercase). Empty means reject all */
|
|
30
|
+
allowedDomains: string[];
|
|
31
|
+
/** Receiving addresses allowed for payment. Empty means reject all */
|
|
32
|
+
trustedPayTo: string[];
|
|
33
|
+
/** Assets allowed for payment (USDC only by default; PREQ must be enabled explicitly; A402 is deprecated) */
|
|
34
|
+
allowedAssets: AssetSymbol[];
|
|
35
|
+
/** Per-payment USDC cap (USD) */
|
|
36
|
+
maxUsdPerPayment: number;
|
|
37
|
+
maxPaymentsPerDay: number;
|
|
38
|
+
/** Daily USDC total cap (USD) */
|
|
39
|
+
maxUsdPerDay: number;
|
|
40
|
+
/** USDC payments at or above this amount (USD) need human confirmation. null = never ask */
|
|
41
|
+
confirmAboveUsd: number | null;
|
|
42
|
+
/** Per-token limits (base units). No defaults: both per-payment and daily must be set to pay in that token */
|
|
43
|
+
tokenLimits: Record<TokenSymbol, TokenLimits>;
|
|
44
|
+
prefer: AssetSymbol;
|
|
45
|
+
/** Warnings to show at start (e.g. when A402 (v1) is enabled) */
|
|
46
|
+
warnings: string[];
|
|
47
|
+
}
|
|
48
|
+
export interface PolicyEnv {
|
|
49
|
+
X402_NETWORK?: string;
|
|
50
|
+
X402_ALLOWED_DOMAINS?: string;
|
|
51
|
+
X402_TRUSTED_PAY_TO?: string;
|
|
52
|
+
X402_ALLOWED_ASSETS?: string;
|
|
53
|
+
X402_MAX_USD?: string;
|
|
54
|
+
X402_MAX_PAYMENTS_PER_DAY?: string;
|
|
55
|
+
X402_MAX_USD_PER_DAY?: string;
|
|
56
|
+
X402_CONFIRM_ABOVE_USD?: string;
|
|
57
|
+
X402_MAX_PREQ_ATOMIC?: string;
|
|
58
|
+
X402_MAX_PREQ_PER_DAY_ATOMIC?: string;
|
|
59
|
+
X402_CONFIRM_ABOVE_PREQ_ATOMIC?: string;
|
|
60
|
+
/** A402 (v1, deprecated): only meaningful when A402 is allowed explicitly */
|
|
61
|
+
X402_MAX_A402_ATOMIC?: string;
|
|
62
|
+
X402_MAX_A402_PER_DAY_ATOMIC?: string;
|
|
63
|
+
X402_CONFIRM_ABOVE_A402_ATOMIC?: string;
|
|
64
|
+
X402_PAY_WITH?: string;
|
|
65
|
+
/** Only to change or set mints, e.g. in rehearsals */
|
|
66
|
+
X402_USDC_MINT?: string;
|
|
67
|
+
X402_PREQ_MINT?: string;
|
|
68
|
+
X402_A402_MINT?: string;
|
|
69
|
+
}
|
|
70
|
+
/** Environment variable names for token limits */
|
|
71
|
+
export declare const tokenEnv: (t: TokenSymbol) => {
|
|
72
|
+
perPayment: string;
|
|
73
|
+
perDay: string;
|
|
74
|
+
confirmAbove: string;
|
|
75
|
+
};
|
|
76
|
+
export declare function policyFromEnv(env: PolicyEnv): PayPolicy;
|
|
77
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
78
|
+
export declare function domainCheck(p: PayPolicy, url: string): {
|
|
79
|
+
ok: true;
|
|
80
|
+
host: string;
|
|
81
|
+
} | {
|
|
82
|
+
ok: false;
|
|
83
|
+
reason: string;
|
|
84
|
+
};
|
|
85
|
+
export interface DayUsage {
|
|
86
|
+
count: number;
|
|
87
|
+
usd: number;
|
|
88
|
+
/** Total PREQ signed today (base units) */
|
|
89
|
+
preq: bigint;
|
|
90
|
+
/** Total A402 (v1) signed today (base units) */
|
|
91
|
+
a402: bigint;
|
|
92
|
+
}
|
|
93
|
+
export interface Evaluated {
|
|
94
|
+
requirement: PaymentRequirements;
|
|
95
|
+
asset: AssetSymbol | null;
|
|
96
|
+
ok: boolean;
|
|
97
|
+
reasons: string[];
|
|
98
|
+
/** Whether human confirmation is needed (meaningful only when ok) */
|
|
99
|
+
needsConfirmation: boolean;
|
|
100
|
+
/** USD amount if USDC */
|
|
101
|
+
usd: number | null;
|
|
102
|
+
}
|
|
103
|
+
export declare function symbolOf(p: PayPolicy, mint: string): AssetSymbol | null;
|
|
104
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
105
|
+
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage): Evaluated;
|
|
106
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
107
|
+
export declare function choose(p: PayPolicy, evs: Evaluated[]): Evaluated | null;
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
export const NETWORKS = {
|
|
2
|
+
mainnet: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
|
|
3
|
+
devnet: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* PREQ mainnet mint (Token-2022, 6 decimals). Same value as PREQ_MAINNET_MINT in pay-server src/preq.ts.
|
|
7
|
+
* Set after the PREQ launch on 2026-11-21. X402_PREQ_MINT can override it (e.g. for devnet rehearsals)
|
|
8
|
+
*/
|
|
9
|
+
export const PREQ_MAINNET_MINT = 'aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX';
|
|
10
|
+
export const A402_DEPRECATION_WARNING = 'A402 (v1) is deprecated and no longer supported; use PREQ.';
|
|
11
|
+
const DEFAULT_MINTS = {
|
|
12
|
+
[NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', PREQ: PREQ_MAINNET_MINT, A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
|
|
13
|
+
// No devnet PREQ mint; rehearsals pass one with X402_PREQ_MINT
|
|
14
|
+
[NETWORKS.devnet]: { USDC: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', PREQ: '', A402: '5R2rKmzsNk1S5mFPR99bU1anromo73brwNApghvXeb46' },
|
|
15
|
+
};
|
|
16
|
+
export const TOKEN_SYMBOLS = ['PREQ', 'A402'];
|
|
17
|
+
const ASSET_SYMBOLS = ['USDC', 'PREQ', 'A402'];
|
|
18
|
+
const list = (s) => (s ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
19
|
+
const num = (s, d) => (s && Number.isFinite(Number(s)) ? Number(s) : d);
|
|
20
|
+
/** Integer in base units (positive only). null if missing or invalid */
|
|
21
|
+
const atomic = (s) => (s && /^\d+$/.test(s.trim()) && BigInt(s.trim()) > 0n ? BigInt(s.trim()) : null);
|
|
22
|
+
const isAsset = (a) => ASSET_SYMBOLS.includes(a);
|
|
23
|
+
/** Environment variable names for token limits */
|
|
24
|
+
export const tokenEnv = (t) => ({
|
|
25
|
+
perPayment: `X402_MAX_${t}_ATOMIC`,
|
|
26
|
+
perDay: `X402_MAX_${t}_PER_DAY_ATOMIC`,
|
|
27
|
+
confirmAbove: `X402_CONFIRM_ABOVE_${t}_ATOMIC`,
|
|
28
|
+
});
|
|
29
|
+
export function policyFromEnv(env) {
|
|
30
|
+
const network = env.X402_NETWORK === 'devnet' ? NETWORKS.devnet : NETWORKS.mainnet;
|
|
31
|
+
const m = DEFAULT_MINTS[network];
|
|
32
|
+
const e = env;
|
|
33
|
+
const mints = { USDC: env.X402_USDC_MINT ?? m.USDC, PREQ: env.X402_PREQ_MINT ?? m.PREQ, A402: env.X402_A402_MINT ?? m.A402 };
|
|
34
|
+
const allowedAssets = (list(env.X402_ALLOWED_ASSETS).length ? list(env.X402_ALLOWED_ASSETS) : ['USDC']).filter(isAsset);
|
|
35
|
+
if (allowedAssets.includes('PREQ') && !mints.PREQ) {
|
|
36
|
+
throw new Error('PREQ mint is not set: PREQ payments cannot be enabled yet. Fill PREQ_MAINNET_MINT in @agent402-dev/pay-mcp src/policy.ts after the PREQ launch, or set X402_PREQ_MINT.');
|
|
37
|
+
}
|
|
38
|
+
const warnings = [];
|
|
39
|
+
if (allowedAssets.includes('A402') || env.X402_PAY_WITH === 'A402')
|
|
40
|
+
warnings.push(A402_DEPRECATION_WARNING);
|
|
41
|
+
// Tokens have no defaults: both per-payment and daily must be set to pay (USD limits do not apply to tokens)
|
|
42
|
+
const limitsFor = (t) => {
|
|
43
|
+
const n = tokenEnv(t);
|
|
44
|
+
const c = e[n.confirmAbove];
|
|
45
|
+
return { perPayment: atomic(e[n.perPayment]), perDay: atomic(e[n.perDay]), confirmAbove: c && /^\d+$/.test(c.trim()) ? BigInt(c.trim()) : null };
|
|
46
|
+
};
|
|
47
|
+
const prefer = env.X402_PAY_WITH && isAsset(env.X402_PAY_WITH) ? env.X402_PAY_WITH : 'USDC';
|
|
48
|
+
return {
|
|
49
|
+
network,
|
|
50
|
+
mints,
|
|
51
|
+
allowedDomains: list(env.X402_ALLOWED_DOMAINS).map((d) => d.toLowerCase()),
|
|
52
|
+
trustedPayTo: list(env.X402_TRUSTED_PAY_TO),
|
|
53
|
+
allowedAssets,
|
|
54
|
+
maxUsdPerPayment: num(env.X402_MAX_USD, 0.05),
|
|
55
|
+
maxPaymentsPerDay: num(env.X402_MAX_PAYMENTS_PER_DAY, 20),
|
|
56
|
+
maxUsdPerDay: num(env.X402_MAX_USD_PER_DAY, 1),
|
|
57
|
+
confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
|
|
58
|
+
tokenLimits: { PREQ: limitsFor('PREQ'), A402: limitsFor('A402') },
|
|
59
|
+
prefer,
|
|
60
|
+
warnings,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
64
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
65
|
+
export function domainCheck(p, url) {
|
|
66
|
+
let u;
|
|
67
|
+
try {
|
|
68
|
+
u = new URL(url);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return { ok: false, reason: 'invalid_url' };
|
|
72
|
+
}
|
|
73
|
+
const host = u.host.toLowerCase();
|
|
74
|
+
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && LOOPBACK.has(u.hostname)))
|
|
75
|
+
return { ok: false, reason: `insecure_url: only https (http only for localhost)` };
|
|
76
|
+
if (!p.allowedDomains.length)
|
|
77
|
+
return { ok: false, reason: 'domain_not_allowed: allowed domain list is empty (X402_ALLOWED_DOMAINS)' };
|
|
78
|
+
if (!p.allowedDomains.includes(host))
|
|
79
|
+
return { ok: false, reason: `domain_not_allowed: ${host}` };
|
|
80
|
+
return { ok: true, host };
|
|
81
|
+
}
|
|
82
|
+
export function symbolOf(p, mint) {
|
|
83
|
+
if (!mint)
|
|
84
|
+
return null;
|
|
85
|
+
return ASSET_SYMBOLS.find((s) => p.mints[s] && p.mints[s] === mint) ?? null;
|
|
86
|
+
}
|
|
87
|
+
const usedToday = (usage, t) => (t === 'PREQ' ? usage.preq : usage.a402);
|
|
88
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
89
|
+
export function evaluate(p, r, usage) {
|
|
90
|
+
const reasons = [];
|
|
91
|
+
const asset = symbolOf(p, r.asset);
|
|
92
|
+
if (r.scheme !== 'exact')
|
|
93
|
+
reasons.push(`unsupported_scheme: ${r.scheme}`);
|
|
94
|
+
if (r.network !== p.network)
|
|
95
|
+
reasons.push(`wrong_network: ${r.network}`);
|
|
96
|
+
if (!asset)
|
|
97
|
+
reasons.push(`asset_not_allowed: unknown mint ${r.asset}`);
|
|
98
|
+
else if (!p.allowedAssets.includes(asset))
|
|
99
|
+
reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)${asset === 'A402' ? ' — A402 (v1) is deprecated; use PREQ' : ''}`);
|
|
100
|
+
if (!p.trustedPayTo.length)
|
|
101
|
+
reasons.push('pay_to_not_trusted: trusted recipient list is empty (X402_TRUSTED_PAY_TO)');
|
|
102
|
+
else if (!p.trustedPayTo.includes(r.payTo))
|
|
103
|
+
reasons.push(`pay_to_not_trusted: ${r.payTo}`);
|
|
104
|
+
let amount;
|
|
105
|
+
try {
|
|
106
|
+
amount = BigInt(r.amount);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
amount = -1n;
|
|
110
|
+
}
|
|
111
|
+
if (amount <= 0n)
|
|
112
|
+
reasons.push('invalid_amount');
|
|
113
|
+
let usd = null;
|
|
114
|
+
if (asset === 'USDC' && amount > 0n) {
|
|
115
|
+
usd = Number(amount) / 1e6;
|
|
116
|
+
if (usd > p.maxUsdPerPayment)
|
|
117
|
+
reasons.push(`over_per_payment_limit: ${usd} USD > ${p.maxUsdPerPayment} USD`);
|
|
118
|
+
if (usage.usd + usd > p.maxUsdPerDay)
|
|
119
|
+
reasons.push(`over_daily_usd_limit: ${usage.usd} + ${usd} > ${p.maxUsdPerDay} USD`);
|
|
120
|
+
}
|
|
121
|
+
let needsTokenConfirm = false;
|
|
122
|
+
if (asset && asset !== 'USDC' && p.allowedAssets.includes(asset) && amount > 0n) {
|
|
123
|
+
const l = p.tokenLimits[asset];
|
|
124
|
+
const n = tokenEnv(asset);
|
|
125
|
+
const lc = asset.toLowerCase();
|
|
126
|
+
const unit = `${asset} smallest units`;
|
|
127
|
+
if (l.perPayment === null)
|
|
128
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perPayment} (max ${asset} per payment, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
129
|
+
else if (amount > l.perPayment)
|
|
130
|
+
reasons.push(`over_per_payment_limit: ${amount} > ${l.perPayment} (${unit})`);
|
|
131
|
+
if (l.perDay === null)
|
|
132
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perDay} (max ${asset} per UTC day, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
133
|
+
else if (usedToday(usage, asset) + amount > l.perDay)
|
|
134
|
+
reasons.push(`over_daily_${lc}_limit: ${usedToday(usage, asset)} + ${amount} > ${l.perDay} (${unit})`);
|
|
135
|
+
needsTokenConfirm = l.confirmAbove !== null && amount >= l.confirmAbove;
|
|
136
|
+
}
|
|
137
|
+
if (usage.count >= p.maxPaymentsPerDay)
|
|
138
|
+
reasons.push(`over_daily_count_limit: ${p.maxPaymentsPerDay}`);
|
|
139
|
+
const needsConfirmation = (asset === 'USDC' && p.confirmAboveUsd !== null && usd !== null && usd >= p.confirmAboveUsd) || needsTokenConfirm;
|
|
140
|
+
return { requirement: r, asset, ok: reasons.length === 0, reasons, needsConfirmation, usd };
|
|
141
|
+
}
|
|
142
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
143
|
+
export function choose(p, evs) {
|
|
144
|
+
const ok = evs.filter((e) => e.ok);
|
|
145
|
+
return ok.find((e) => e.asset === p.prefer) ?? ok[0] ?? null;
|
|
146
|
+
}
|
package/dist/server.d.ts
ADDED
package/dist/server.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @agent402-dev/pay-mcp (stdio). Configured with environment variables: policy.ts PolicyEnv and the following:
|
|
3
|
+
// X402_KEYPAIR_PATH payment wallet key file (Solana CLI JSON). Without it, no payments (x402_quote only)
|
|
4
|
+
// X402_RPC_URL RPC used to build payment transactions (public RPC if unset)
|
|
5
|
+
// X402_HISTORY_PATH payment history JSONL (default ~/.agent402/payments.jsonl)
|
|
6
|
+
// Allowlists (X402_ALLOWED_DOMAINS, X402_TRUSTED_PAY_TO) default to empty = reject everything
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
10
|
+
import { jsonlHistory } from './history.js';
|
|
11
|
+
import { policyFromEnv } from './policy.js';
|
|
12
|
+
import { createPayServer } from './tools.js';
|
|
13
|
+
import { loadWallet } from './wallet.js';
|
|
14
|
+
// If PREQ is allowed but its mint is empty, stop here with an error (policyFromEnv)
|
|
15
|
+
const policy = policyFromEnv(process.env);
|
|
16
|
+
// If A402 (v1) is enabled explicitly, print the deprecation warning (stderr; stdout is for MCP)
|
|
17
|
+
for (const w of policy.warnings)
|
|
18
|
+
console.error(`[a402-pay] WARNING: ${w}`);
|
|
19
|
+
const wallet = process.env.X402_KEYPAIR_PATH
|
|
20
|
+
? await loadWallet(process.env.X402_KEYPAIR_PATH, policy, process.env.X402_RPC_URL).catch((e) => {
|
|
21
|
+
console.error(`[a402-pay] could not load wallet, starting without payments: ${e.message}`);
|
|
22
|
+
return null;
|
|
23
|
+
})
|
|
24
|
+
: null;
|
|
25
|
+
const history = jsonlHistory(process.env.X402_HISTORY_PATH ?? join(homedir(), '.agent402', 'payments.jsonl'), () => policy.mints);
|
|
26
|
+
await createPayServer({ policy, wallet, history, fetch }).connect(new StdioServerTransport());
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import type { History } from './history.js';
|
|
3
|
+
import { type PayPolicy } from './policy.js';
|
|
4
|
+
import type { Wallet } from './wallet.js';
|
|
5
|
+
export interface PayServerDeps {
|
|
6
|
+
policy: PayPolicy;
|
|
7
|
+
wallet: Wallet | null;
|
|
8
|
+
history: History;
|
|
9
|
+
fetch: typeof fetch;
|
|
10
|
+
now?: () => Date;
|
|
11
|
+
}
|
|
12
|
+
export declare function createPayServer(d: PayServerDeps): McpServer;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @agent402-dev/pay-mcp's 4 tools: x402_fetch, x402_quote, wallet_status, payment_history
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
import { createAgent } from './agent.js';
|
|
5
|
+
import { tokenEnv } from './policy.js';
|
|
6
|
+
import { formatUnits } from './units.js';
|
|
7
|
+
const out = (obj, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }], ...(isError ? { isError } : {}) });
|
|
8
|
+
const bigintSafe = (o) => JSON.parse(JSON.stringify(o, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
|
|
9
|
+
/** Adds a unit description and display value to each { asset: 'USDC'|'PREQ'|'A402', amount: '<base units>' } in the result (token amounts always with units) */
|
|
10
|
+
function withUnits(o) {
|
|
11
|
+
if (Array.isArray(o))
|
|
12
|
+
return o.map(withUnits);
|
|
13
|
+
if (!o || typeof o !== 'object')
|
|
14
|
+
return o;
|
|
15
|
+
const r = {};
|
|
16
|
+
for (const [k, v] of Object.entries(o))
|
|
17
|
+
r[k] = withUnits(v);
|
|
18
|
+
if ((r.asset === 'USDC' || r.asset === 'PREQ' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
|
|
19
|
+
r.amountUnit = `${r.asset} smallest unit (1 ${r.asset} = 1,000,000)`;
|
|
20
|
+
r.amountDisplay = formatUnits(r.amount, r.asset);
|
|
21
|
+
}
|
|
22
|
+
return r;
|
|
23
|
+
}
|
|
24
|
+
const atomicLimit = (v, envName, sym) => v === null ? `not set (${envName}) — ${sym} payments refused` : v;
|
|
25
|
+
/** Token limits in wallet_status (e.g. maxPreqPerPaymentAtomic, maxPreqPerPaymentDisplay …) */
|
|
26
|
+
function tokenLimitFields(p, t) {
|
|
27
|
+
const l = p.tokenLimits[t];
|
|
28
|
+
const n = tokenEnv(t);
|
|
29
|
+
const k = t === 'PREQ' ? 'Preq' : 'A402';
|
|
30
|
+
return {
|
|
31
|
+
[`max${k}PerPaymentAtomic`]: atomicLimit(l.perPayment, n.perPayment, t),
|
|
32
|
+
[`max${k}PerDayAtomic`]: atomicLimit(l.perDay, n.perDay, t),
|
|
33
|
+
...(l.perPayment !== null ? { [`max${k}PerPaymentDisplay`]: formatUnits(l.perPayment, t) } : {}),
|
|
34
|
+
...(l.perDay !== null ? { [`max${k}PerDayDisplay`]: formatUnits(l.perDay, t) } : {}),
|
|
35
|
+
[`confirmAbove${k}Atomic`]: l.confirmAbove,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function createPayServer(d) {
|
|
39
|
+
const server = new McpServer({ name: 'a402-pay', version: '0.2.0' });
|
|
40
|
+
const confirm = async (message) => {
|
|
41
|
+
if (!server.server.getClientCapabilities()?.elicitation)
|
|
42
|
+
return 'unsupported';
|
|
43
|
+
const r = await server.server.elicitInput({
|
|
44
|
+
message,
|
|
45
|
+
requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean', title: 'Pay', description: 'Approve this payment' } }, required: ['confirm'] },
|
|
46
|
+
});
|
|
47
|
+
return r.action === 'accept' && r.content?.confirm === true ? 'accept' : 'decline';
|
|
48
|
+
};
|
|
49
|
+
const agent = createAgent({ ...d, confirm });
|
|
50
|
+
const req = { url: z.string().url(), method: z.enum(['GET', 'POST']).optional(), headers: z.record(z.string(), z.string()).optional(), body: z.string().max(100_000).optional() };
|
|
51
|
+
server.tool('x402_fetch', 'Fetch a URL and, if it answers HTTP 402 (x402), pay from the configured wallet only when every rule passes before signing: allowed domain (X402_ALLOWED_DOMAINS), trusted recipient (X402_TRUSTED_PAY_TO), allowed asset (USDC by default; PREQ only if listed; A402 (v1) is deprecated), per-payment and daily limits, and human confirmation above the configured amount. Signs at most once per call. Pass quoteId from x402_quote to refuse if the requirements changed. The wallet key never leaves this machine.', { ...req, quoteId: z.string().optional() }, async (a) => { const r = await agent.payAndFetch(a); return out(withUnits(r), !['paid', 'not_required'].includes(r.result)); });
|
|
52
|
+
server.tool('x402_quote', 'Show the x402 payment requirements of a URL and whether each option passes the payment rules. Never signs or pays. Returns a quoteId that x402_fetch can use to pin the amount, asset and recipient.', req, async (a) => { const r = await agent.quote(a); return out(withUnits(r), r.result === 'refused'); });
|
|
53
|
+
server.tool('wallet_status', 'Payment wallet address, network, USDC and PREQ balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
|
|
54
|
+
const { preq, a402, ...today } = d.history.today(d.now?.());
|
|
55
|
+
const balances = d.wallet ? await d.wallet.balances() : null;
|
|
56
|
+
// A402 (v1) is deprecated: shown only if allowed explicitly or if spent today
|
|
57
|
+
const showA402 = d.policy.allowedAssets.includes('A402') || a402 > 0n;
|
|
58
|
+
return out(bigintSafe({
|
|
59
|
+
address: d.wallet?.address ?? null,
|
|
60
|
+
network: d.policy.network,
|
|
61
|
+
// Balances in token units (e.g. "10 PREQ")
|
|
62
|
+
balances: balances ? Object.fromEntries(Object.entries(balances).map(([k, v]) => [k, /^[\d.]+$/.test(v) ? `${v} ${k}` : v])) : null,
|
|
63
|
+
today: {
|
|
64
|
+
...today, usdUnit: 'USD (USDC)',
|
|
65
|
+
preq, preqUnit: 'PREQ smallest unit (1 PREQ = 1,000,000)', preqDisplay: formatUnits(preq, 'PREQ'),
|
|
66
|
+
...(showA402 ? { a402, a402Unit: 'A402 smallest unit (1 A402 = 1,000,000)', a402Display: formatUnits(a402, 'A402') } : {}),
|
|
67
|
+
},
|
|
68
|
+
signedThisSession: d.wallet?.signedCount ?? 0,
|
|
69
|
+
limits: {
|
|
70
|
+
maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
|
|
71
|
+
confirmAboveUsd: d.policy.confirmAboveUsd,
|
|
72
|
+
...tokenLimitFields(d.policy, 'PREQ'),
|
|
73
|
+
...(showA402 ? tokenLimitFields(d.policy, 'A402') : {}),
|
|
74
|
+
units: '…Usd = US dollars (USDC); …Atomic = token smallest unit (1 PREQ = 1,000,000)',
|
|
75
|
+
},
|
|
76
|
+
allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
|
|
77
|
+
...(d.policy.warnings.length ? { warnings: d.policy.warnings } : {}),
|
|
78
|
+
...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
|
|
79
|
+
}));
|
|
80
|
+
});
|
|
81
|
+
server.tool('payment_history', 'Recent payment records from the local JSONL log (time, URL, asset, amount, recipient, result, settlement transaction id). Keys and signed payment payloads are never stored.', { limit: z.number().int().min(1).max(500).optional() }, async ({ limit }) => out(withUnits(d.history.list(limit ?? 20))));
|
|
82
|
+
return server;
|
|
83
|
+
}
|
package/dist/units.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const DECIMALS = 6;
|
|
2
|
+
/** Base-unit integer → "140,000 PREQ" */
|
|
3
|
+
export declare function formatUnits(atomic: string | bigint, symbol: string): string;
|
|
4
|
+
/** "140,000 PREQ (140000000000 smallest units)" */
|
|
5
|
+
export declare const withSmallest: (atomic: string | bigint, symbol: string) => string;
|
package/dist/units.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Amount display: USDC and PREQ (and the deprecated A402) all have 6 decimals. Token amounts are always shown with units
|
|
2
|
+
export const DECIMALS = 6;
|
|
3
|
+
/** Base-unit integer → "140,000 PREQ" */
|
|
4
|
+
export function formatUnits(atomic, symbol) {
|
|
5
|
+
const s = atomic.toString().padStart(DECIMALS + 1, '0');
|
|
6
|
+
const int = s.slice(0, -DECIMALS).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
7
|
+
const frac = s.slice(-DECIMALS).replace(/0+$/, '');
|
|
8
|
+
return `${int}${frac ? '.' + frac : ''} ${symbol}`;
|
|
9
|
+
}
|
|
10
|
+
/** "140,000 PREQ (140000000000 smallest units)" */
|
|
11
|
+
export const withSmallest = (atomic, symbol) => `${formatUnits(atomic, symbol)} (${atomic} smallest units)`;
|
package/dist/wallet.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { PaymentRequired, PaymentRequirements } from '@x402/core/types';
|
|
2
|
+
import { type PayPolicy } from './policy.js';
|
|
3
|
+
export interface Wallet {
|
|
4
|
+
address: string;
|
|
5
|
+
network: string;
|
|
6
|
+
/** Signs one requirement that passed the policy check → PAYMENT-SIGNATURE header value */
|
|
7
|
+
sign(resource: PaymentRequired['resource'], requirement: PaymentRequirements): Promise<string>;
|
|
8
|
+
/** Number of signatures made in this process */
|
|
9
|
+
readonly signedCount: number;
|
|
10
|
+
balances(): Promise<Record<string, string>>;
|
|
11
|
+
}
|
|
12
|
+
export declare function loadWallet(keyPath: string, policy: PayPolicy, rpcUrl?: string): Promise<Wallet>;
|
package/dist/wallet.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Payment wallet: signs x402 exact payment transactions with a key file on the user's computer (official @x402 client).
|
|
2
|
+
// The key is never sent to the server; only the partially signed transaction goes in the PAYMENT-SIGNATURE header. This module signs only one requirement that passed the policy check
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { createKeyPairSignerFromBytes } from '@solana/kit';
|
|
5
|
+
import { encodePaymentSignatureHeader } from '@x402/core/http';
|
|
6
|
+
import { x402Client } from '@x402/fetch';
|
|
7
|
+
import { toClientSvmSigner } from '@x402/svm';
|
|
8
|
+
import { ExactSvmScheme } from '@x402/svm/exact/client';
|
|
9
|
+
import { TOKEN_SYMBOLS } from './policy.js';
|
|
10
|
+
export async function loadWallet(keyPath, policy, rpcUrl) {
|
|
11
|
+
const bytes = Uint8Array.from(JSON.parse(readFileSync(keyPath, 'utf8')));
|
|
12
|
+
const signer = await createKeyPairSignerFromBytes(bytes);
|
|
13
|
+
bytes.fill(0);
|
|
14
|
+
let signed = 0;
|
|
15
|
+
const tokenAllow = TOKEN_SYMBOLS.flatMap((t) => {
|
|
16
|
+
const max = policy.tokenLimits[t].perPayment;
|
|
17
|
+
return policy.allowedAssets.includes(t) && policy.mints[t] && max !== null
|
|
18
|
+
? [{ network: policy.network, asset: policy.mints[t], maxAmountPerPayment: max.toString() }]
|
|
19
|
+
: [];
|
|
20
|
+
});
|
|
21
|
+
// The official client's spending limit is set to the same value (a second safety net)
|
|
22
|
+
const client = x402Client.fromConfig({
|
|
23
|
+
schemes: [{ network: policy.network, client: new ExactSvmScheme(toClientSvmSigner(signer), rpcUrl ? { rpcUrl } : undefined) }],
|
|
24
|
+
spendControls: {
|
|
25
|
+
maxAmountPerPayment: `$${policy.maxUsdPerPayment}`,
|
|
26
|
+
// Tokens (PREQ, A402 (v1)) are allowed in the official client only when allowed and a per-payment cap is set (without a cap the official client rejects too)
|
|
27
|
+
...(tokenAllow.length ? { allowedAssets: tokenAllow } : {}),
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
const rpc = rpcUrl ?? (policy.network.includes('EtWTRAB') ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');
|
|
31
|
+
return {
|
|
32
|
+
address: signer.address,
|
|
33
|
+
network: policy.network,
|
|
34
|
+
get signedCount() { return signed; },
|
|
35
|
+
async sign(resource, requirement) {
|
|
36
|
+
const payload = await client.createPaymentPayload({ x402Version: 2, resource, accepts: [requirement] });
|
|
37
|
+
signed++;
|
|
38
|
+
return encodePaymentSignatureHeader(payload);
|
|
39
|
+
},
|
|
40
|
+
async balances() {
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [sym, mint] of Object.entries(policy.mints)) {
|
|
43
|
+
// Skip assets without a mint and A402 (v1) when not allowed
|
|
44
|
+
if (!mint || (sym === 'A402' && !policy.allowedAssets.includes('A402')))
|
|
45
|
+
continue;
|
|
46
|
+
try {
|
|
47
|
+
const r = await fetch(rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getTokenAccountsByOwner', params: [signer.address, { mint }, { encoding: 'jsonParsed' }] }) });
|
|
48
|
+
const j = (await r.json());
|
|
49
|
+
out[sym] = j.result?.value[0]?.account.data.parsed.info.tokenAmount.uiAmountString ?? '0';
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
out[sym] = 'unavailable';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent402-dev/pay-mcp",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
"description": "MCP server that lets an AI agent pay x402 APIs (USDC, PREQ) from the user's own wallet on the user's machine, within limits and allowlists. With no configuration, every payment is refused.",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"mcp",
|
|
6
|
+
"x402",
|
|
7
|
+
"solana",
|
|
8
|
+
"usdc",
|
|
9
|
+
"agent",
|
|
10
|
+
"payments"
|
|
11
|
+
],
|
|
12
|
+
"mcpName": "io.github.agent402-dev/a402-pay-mcp",
|
|
13
|
+
"bin": {
|
|
14
|
+
"agent402-pay-mcp": "./dist/server.js"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
"./*": {
|
|
18
|
+
"types": "./dist/*.d.ts",
|
|
19
|
+
"default": "./dist/*.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
24
|
+
"@solana/kit": "8.6.0",
|
|
25
|
+
"@x402/core": "2.31.0",
|
|
26
|
+
"@x402/fetch": "2.31.0",
|
|
27
|
+
"@x402/svm": "2.31.0",
|
|
28
|
+
"zod": "^4.6.7"
|
|
29
|
+
},
|
|
30
|
+
"version": "0.2.0",
|
|
31
|
+
"author": "Agent402",
|
|
32
|
+
"license": "Apache-2.0",
|
|
33
|
+
"type": "module",
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=20"
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/agent402-dev/agent402-toolkit.git",
|
|
40
|
+
"directory": "packages/pay-mcp"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-mcp#readme",
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/agent402-dev/agent402-toolkit/issues"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"files": [
|
|
50
|
+
"dist",
|
|
51
|
+
"README.md",
|
|
52
|
+
"LICENSE",
|
|
53
|
+
"NOTICE"
|
|
54
|
+
]
|
|
55
|
+
}
|