@agent402-dev/pay-mcp 0.0.0-stage → 0.1.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 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,6 @@
1
+ A402 Check — token check engine
2
+ Copyright 2026 Agent402
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Results produced by this software are factual information from public on-chain data and are not investment advice.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @agent402-dev/pay-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 (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, **A402**) from **your own wallet on your machine**, only within the rules you set.
4
+
5
+ Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
6
+ Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
7
+
8
+ > It pays only what you allow and gives no opinion on any API or token. Not investment advice.
9
+ > 허용한 만큼만 결제하며 API나 토큰에 대한 의견을 주지 않습니다. 투자 권유가 아닙니다.
10
+
11
+ ## Rules checked before signing
12
+ Nothing is signed unless every rule passes. **With no configuration, every payment is refused.**
13
+
14
+ | Rule | Variable | Default |
15
+ |---|---|---|
16
+ | Allowed domains (host or host:port; https only, http only for localhost) | `X402_ALLOWED_DOMAINS` | empty → refuse all |
17
+ | Trusted recipients (payTo addresses) | `X402_TRUSTED_PAY_TO` | empty → refuse all |
18
+ | Allowed assets | `X402_ALLOWED_ASSETS` | `USDC` (A402 only if listed) |
19
+ | Max USDC per payment (USD) | `X402_MAX_USD` | `0.05` |
20
+ | Max USDC per UTC day (USD) | `X402_MAX_USD_PER_DAY` | `1` |
21
+ | Max payments per UTC day | `X402_MAX_PAYMENTS_PER_DAY` | `20` |
22
+ | **Max A402 per payment** (A402 smallest units; 1 A402 = 1,000,000) | `X402_MAX_A402_ATOMIC` | **not set → A402 payments refused** |
23
+ | **Max A402 per UTC day** (A402 smallest units; 1 A402 = 1,000,000) | `X402_MAX_A402_PER_DAY_ATOMIC` | **not set → A402 payments refused** |
24
+ | Ask a human at or above this USDC amount (USD) | `X402_CONFIRM_ABOVE_USD` | off |
25
+ | Ask a human at or above this A402 amount (A402 smallest units) | `X402_CONFIRM_ABOVE_A402_ATOMIC` | off |
26
+
27
+ - **A402 units.** The A402 variables take the smallest unit (A402 has 6 decimals). Example: `X402_MAX_A402_ATOMIC=200000000000` is 200,000 A402 per payment. `wallet_status` and `payment_history` also show A402 amounts in smallest units (`…Atomic` fields).
28
+ - USD limits apply to USDC only. A402 has its own two limits, and **both must be set** before any A402 payment is made.
29
+ - Human confirmation uses MCP elicitation. If your MCP client cannot ask, the payment is not made (`confirmation_required`).
30
+ - At most one signature per `x402_fetch` call. If the server answers 402 again after payment, it does not sign again.
31
+ - Redirects are followed manually and each hop must be an allowed domain; a disallowed hop is not contacted.
32
+ - Pass `quoteId` from `x402_quote` to `x402_fetch` to refuse if the amount, asset or recipient changed.
33
+ - Daily totals count every payment this server signed, whatever the result.
34
+ - Daily limits are counted from the local payment log file (`X402_HISTORY_PATH`). Deleting or moving that file resets the daily totals.
35
+
36
+ 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` | `A402`), `X402_HISTORY_PATH` (default `~/.agent402/payments.jsonl`).
37
+
38
+ ## Connect
39
+ Claude Code (example — set your own allowlists and limits):
40
+ ```bash
41
+ claude mcp add a402-pay \
42
+ -e X402_KEYPAIR_PATH=<path to a small, dedicated wallet key file> \
43
+ -e X402_ALLOWED_DOMAINS=<api.example.com> \
44
+ -e X402_TRUSTED_PAY_TO=<recipient address> \
45
+ -- npx -y @agent402-dev/pay-mcp
46
+ ```
47
+ Claude Desktop (`claude_desktop_config.json`):
48
+ ```json
49
+ { "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>" } } } }
50
+ ```
51
+ 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.
52
+
53
+ ## Tools
54
+ | Tool | What it does |
55
+ |---|---|
56
+ | `x402_fetch` | Fetch a URL; pay only if the rules pass |
57
+ | `x402_quote` | Show payment requirements and which rules pass; never signs; returns `quoteId` |
58
+ | `wallet_status` | Address, balances, today's usage (count, USDC, A402), limits including both A402 limits, allowlists |
59
+ | `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id |
60
+
61
+ The log never stores keys or signed payment payloads.
62
+
63
+ ## Use a small, dedicated wallet
64
+ 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.
65
+
66
+ ## What it does not do
67
+ - It **does not judge, score or rate** tokens or APIs and gives no investment advice.
68
+ - 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.
69
+
70
+ ## License
71
+ 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).
72
+
73
+ ---
74
+ Factual information from public on-chain data. Not investment advice. / 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
@@ -0,0 +1,51 @@
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
+ /** 사람 확인 (MCP elicitation). 클라이언트가 지원하지 않으면 'unsupported' → 결제 안 함 */
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
+ /** 정책 평가 결과 (거절일 때 각 조건의 이유) */
35
+ options?: {
36
+ asset: string | null;
37
+ mint: string;
38
+ amount: string;
39
+ payTo: string;
40
+ ok: boolean;
41
+ reasons: string[];
42
+ }[];
43
+ }
44
+ export declare function createAgent(d: AgentDeps): {
45
+ quote: (spec: RequestSpec) => Promise<FetchOutcome & {
46
+ quoteId?: string;
47
+ }>;
48
+ payAndFetch: (spec: RequestSpec & {
49
+ quoteId?: string;
50
+ }) => Promise<FetchOutcome>;
51
+ };
package/dist/agent.js ADDED
@@ -0,0 +1,152 @@
1
+ // 결제 판단·실행 (MCP 와 무관한 핵심 로직 — 테스트 가능하게 분리)
2
+ // 순서: 도메인 확인 → 요청(리다이렉트는 직접 따라가며 매번 도메인 확인) → 402 면 정책 평가 → (견적 고정 확인) → (사람 확인) → 서명 1회 → 재요청
3
+ // 서명은 이 요청에서 최대 1번. 결제 뒤 다시 402 가 오면 다시 서명하지 않음
4
+ import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
5
+ import { choose, domainCheck, evaluate } from './policy.js';
6
+ import { withSmallest } from './units.js';
7
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
8
+ export function createAgent(d) {
9
+ const now = d.now ?? (() => new Date());
10
+ const quotes = new Map();
11
+ const QUOTE_TTL_MS = 5 * 60_000;
12
+ /** 리다이렉트를 직접 따라가며 매 단계 도메인 확인 */
13
+ async function send(spec, extraHeaders = {}, follow = true) {
14
+ let url = spec.url;
15
+ for (let hop = 0; hop <= (d.maxRedirects ?? 3); hop++) {
16
+ const dc = domainCheck(d.policy, url);
17
+ if (!dc.ok)
18
+ return { refused: hop === 0 ? dc.reason : `redirect_to_disallowed_domain: ${dc.reason}` };
19
+ const res = await d.fetch(url, { method: spec.method ?? 'GET', headers: { ...(spec.headers ?? {}), ...extraHeaders }, body: spec.body, redirect: 'manual' });
20
+ if (!follow || !REDIRECTS.has(res.status))
21
+ return { res, finalUrl: url };
22
+ const loc = res.headers.get('location');
23
+ if (!loc)
24
+ return { res, finalUrl: url };
25
+ url = new URL(loc, url).toString();
26
+ }
27
+ return { refused: 'too_many_redirects' };
28
+ }
29
+ const readBody = async (res) => {
30
+ const t = (await res.text()).slice(0, 20_000);
31
+ try {
32
+ return JSON.parse(t);
33
+ }
34
+ catch {
35
+ return t;
36
+ }
37
+ };
38
+ const describe = (e) => ({ asset: e.asset, mint: e.requirement.asset, amount: e.requirement.amount, payTo: e.requirement.payTo, ok: e.ok, reasons: e.reasons });
39
+ const host = (u) => { try {
40
+ return new URL(u).host;
41
+ }
42
+ catch {
43
+ return '';
44
+ } };
45
+ const record = (e) => d.history.add({ at: now().toISOString(), ...e });
46
+ /** 402 를 받아 정책으로 평가 (서명 없음) */
47
+ async function assess(spec) {
48
+ const sent = await send(spec);
49
+ if ('refused' in sent)
50
+ return { kind: 'refused', refused: sent.refused };
51
+ const { res, finalUrl } = sent;
52
+ if (res.status !== 402)
53
+ return { kind: 'not_required', res, finalUrl };
54
+ const h = res.headers.get('payment-required');
55
+ let pr;
56
+ try {
57
+ pr = decodePaymentRequiredHeader(h ?? '');
58
+ }
59
+ catch {
60
+ return { kind: 'refused', refused: 'invalid_payment_required_header' };
61
+ }
62
+ // 402 가 다른 주소의 리소스를 가리키면 그 주소도 허용 목록에 있어야 함
63
+ if (pr.resource?.url) {
64
+ const rc = domainCheck(d.policy, pr.resource.url);
65
+ if (!rc.ok)
66
+ return { kind: 'refused', refused: `resource_on_disallowed_domain: ${rc.reason}` };
67
+ }
68
+ const evs = pr.accepts.map((r) => evaluate(d.policy, r, d.history.today(now())));
69
+ return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl };
70
+ }
71
+ async function quote(spec) {
72
+ const a = await assess(spec);
73
+ if (a.kind === 'refused')
74
+ return { result: 'refused', reasons: [a.refused] };
75
+ if (a.kind === 'not_required')
76
+ return { result: 'not_required', httpStatus: a.res.status };
77
+ const options = a.evs.map(describe);
78
+ if (!a.chosen)
79
+ return { result: 'refused', reasons: ['no_option_passes_policy'], options };
80
+ const quoteId = crypto.randomUUID();
81
+ const r = a.chosen.requirement;
82
+ quotes.set(quoteId, { url: spec.url, asset: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, at: now().getTime() });
83
+ 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'] : [] };
84
+ }
85
+ async function payAndFetch(spec) {
86
+ const base = { url: spec.url, host: host(spec.url) };
87
+ const a = await assess(spec);
88
+ if (a.kind === 'refused') {
89
+ record({ ...base, result: 'refused', reasons: [a.refused], signed: false });
90
+ return { result: 'refused', reasons: [a.refused] };
91
+ }
92
+ if (a.kind === 'not_required')
93
+ return { result: 'not_required', httpStatus: a.res.status, body: await readBody(a.res) };
94
+ const options = a.evs.map(describe);
95
+ if (!a.chosen) {
96
+ const reasons = ['no_option_passes_policy', ...a.evs.flatMap((e) => e.reasons)];
97
+ record({ ...base, result: 'refused', reasons, signed: false });
98
+ return { result: 'refused', reasons, options };
99
+ }
100
+ const r = a.chosen.requirement;
101
+ const pay = { network: r.network, asset: a.chosen.asset ?? undefined, mint: r.asset, amount: r.amount, payTo: r.payTo };
102
+ const refuse = (result, reasons) => {
103
+ record({ ...base, ...pay, result, reasons, signed: false });
104
+ return { result, reasons, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network } };
105
+ };
106
+ // 견적과 같은 조건인지 (재요청 사이에 금액·수령 주소가 바뀌면 거절)
107
+ if (spec.quoteId) {
108
+ const q = quotes.get(spec.quoteId);
109
+ if (!q || q.url !== spec.url || now().getTime() - q.at > QUOTE_TTL_MS)
110
+ return refuse('refused', ['quote_not_found_or_expired']);
111
+ const changed = ['asset', 'amount', 'payTo', 'network'].filter((k) => q[k] !== r[k]);
112
+ if (changed.length)
113
+ return refuse('refused', [`requirements_changed_since_quote: ${changed.join(',')}`]);
114
+ }
115
+ if (!d.wallet)
116
+ return refuse('refused', ['no_wallet: set X402_KEYPAIR_PATH']);
117
+ if (a.chosen.needsConfirmation) {
118
+ const human = `Pay ${a.chosen.asset === 'USDC' ? `${a.chosen.usd} USDC` : withSmallest(r.amount, a.chosen.asset ?? 'A402')} to ${r.payTo} for ${spec.url}?`;
119
+ const ans = await d.confirm(human).catch(() => 'unsupported');
120
+ if (ans === 'unsupported')
121
+ return refuse('confirmation_required', ['confirmation_required: this client cannot ask for confirmation (MCP elicitation); payment not made']);
122
+ if (ans === 'decline')
123
+ return refuse('declined_by_user', ['declined_by_user']);
124
+ }
125
+ // 서명 (이 요청에서 한 번만)
126
+ const header = await d.wallet.sign(a.pr.resource, r);
127
+ const sent = await send({ ...spec, url: a.finalUrl }, { 'payment-signature': header }, false);
128
+ if ('refused' in sent) {
129
+ record({ ...base, ...pay, result: 'failed', reasons: [sent.refused], signed: true });
130
+ return { result: 'failed', reasons: [sent.refused] };
131
+ }
132
+ const res = sent.res;
133
+ const body = await readBody(res);
134
+ if (res.ok) {
135
+ const pr = res.headers.get('payment-response');
136
+ let tx;
137
+ try {
138
+ tx = pr ? decodePaymentResponseHeader(pr).transaction : undefined;
139
+ }
140
+ catch {
141
+ tx = undefined;
142
+ }
143
+ record({ ...base, ...pay, result: 'paid', httpStatus: res.status, settlementTx: tx, signed: true });
144
+ 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 } };
145
+ }
146
+ const reason = typeof body === 'object' && body && 'reason' in body ? String(body.reason) : `http_${res.status}`;
147
+ const result = res.status === 402 ? 'rejected_by_server' : res.headers.get('x-payment-status') === 'not-settled' || res.status === 409 ? 'failed' : 'unknown';
148
+ record({ ...base, ...pay, result, reasons: [reason], httpStatus: res.status, signed: true });
149
+ return { result, httpStatus: res.status, reasons: [reason], body };
150
+ }
151
+ return { quote, payAndFetch };
152
+ }
@@ -0,0 +1,33 @@
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
+ /** 거절·실패 이유 */
13
+ reasons?: string[];
14
+ httpStatus?: number;
15
+ /** 정산 트랜잭션 id (PAYMENT-RESPONSE) */
16
+ settlementTx?: string;
17
+ /** 서명했는지 (이 요청에서 결제 트랜잭션에 서명했으면 true) */
18
+ signed: boolean;
19
+ }
20
+ export interface History {
21
+ add(e: HistoryEntry): void;
22
+ list(limit?: number): HistoryEntry[];
23
+ /** 오늘(UTC) 서명한 결제 수, USDC 합계(USD), A402 합계(원 단위) — 상한 계산용 */
24
+ today(now?: Date): {
25
+ count: number;
26
+ usd: number;
27
+ a402: bigint;
28
+ };
29
+ }
30
+ export declare function jsonlHistory(path: string, mints: () => {
31
+ USDC: string;
32
+ A402: string;
33
+ }): History;
@@ -0,0 +1,36 @@
1
+ // 결제 기록 (JSONL, 사용자 컴퓨터). 키·결제 서명 헤더·부분 서명 트랜잭션 원문은 남기지 않음.
2
+ // 남기는 것: 시각·URL·호스트·자산·금액·수령 주소·결과·이유·정산 tx id(공개 체인 기록)
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
+ // 서명한 결제는 결과(성공·거절됨·모름)와 상관없이 쓴 것으로 셈 (보수적으로)
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 a402 = xs.filter((e) => e.mint === m.A402 && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n);
33
+ return { count: xs.length, usd, a402 };
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,76 @@
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
+ export type AssetSymbol = 'USDC' | 'A402';
7
+ export interface PayPolicy {
8
+ network: string;
9
+ mints: Record<AssetSymbol, string>;
10
+ /** 결제해도 되는 호출 도메인 (host 또는 host:port, 소문자). 비어 있으면 전부 거절 */
11
+ allowedDomains: string[];
12
+ /** 결제해도 되는 수령 주소. 비어 있으면 전부 거절 */
13
+ trustedPayTo: string[];
14
+ /** 결제해도 되는 자산 (기본 USDC 만, A402 는 명시해야) */
15
+ allowedAssets: AssetSymbol[];
16
+ /** USDC 결제당 상한 (USD) */
17
+ maxUsdPerPayment: number;
18
+ /** A402 결제당 상한 (원 단위). null = 설정 안 됨 → A402 결제 거절 */
19
+ maxA402PerPayment: bigint | null;
20
+ /** A402 하루 합계 상한 (원 단위). null = 설정 안 됨 → A402 결제 거절 */
21
+ maxA402PerDay: bigint | null;
22
+ maxPaymentsPerDay: number;
23
+ /** 하루 USDC 합계 상한 (USD) */
24
+ maxUsdPerDay: number;
25
+ /** 이 금액(USD) 이상 USDC 결제는 사람 확인. null = 확인 안 함 */
26
+ confirmAboveUsd: number | null;
27
+ /** 이 금액(원 단위) 이상 A402 결제는 사람 확인. null = 확인 안 함 */
28
+ confirmAboveA402: bigint | null;
29
+ prefer: AssetSymbol;
30
+ }
31
+ export interface PolicyEnv {
32
+ X402_NETWORK?: string;
33
+ X402_ALLOWED_DOMAINS?: string;
34
+ X402_TRUSTED_PAY_TO?: string;
35
+ X402_ALLOWED_ASSETS?: string;
36
+ X402_MAX_USD?: string;
37
+ X402_MAX_A402_ATOMIC?: string;
38
+ X402_MAX_A402_PER_DAY_ATOMIC?: string;
39
+ X402_MAX_PAYMENTS_PER_DAY?: string;
40
+ X402_MAX_USD_PER_DAY?: string;
41
+ X402_CONFIRM_ABOVE_USD?: string;
42
+ X402_CONFIRM_ABOVE_A402_ATOMIC?: string;
43
+ X402_PAY_WITH?: string;
44
+ /** 리허설 등에서 민트를 바꿀 때만 */
45
+ X402_USDC_MINT?: string;
46
+ X402_A402_MINT?: string;
47
+ }
48
+ export declare function policyFromEnv(env: PolicyEnv): PayPolicy;
49
+ /** 이 URL 로 결제해도 되는지 (도메인 허용 목록 + https, 로컬만 http 허용) */
50
+ export declare function domainCheck(p: PayPolicy, url: string): {
51
+ ok: true;
52
+ host: string;
53
+ } | {
54
+ ok: false;
55
+ reason: string;
56
+ };
57
+ export interface DayUsage {
58
+ count: number;
59
+ usd: number; /** 오늘 서명한 A402 합계 (원 단위) */
60
+ a402: bigint;
61
+ }
62
+ export interface Evaluated {
63
+ requirement: PaymentRequirements;
64
+ asset: AssetSymbol | null;
65
+ ok: boolean;
66
+ reasons: string[];
67
+ /** 사람 확인이 필요한지 (ok 일 때만 의미) */
68
+ needsConfirmation: boolean;
69
+ /** USDC 면 USD 금액 */
70
+ usd: number | null;
71
+ }
72
+ export declare function symbolOf(p: PayPolicy, mint: string): AssetSymbol | null;
73
+ /** 결제 조건 하나를 정책으로 평가 (서명 전) */
74
+ export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage): Evaluated;
75
+ /** 평가 후 고를 조건 (선호 자산 우선) */
76
+ export declare function choose(p: PayPolicy, evs: Evaluated[]): Evaluated | null;
package/dist/policy.js ADDED
@@ -0,0 +1,108 @@
1
+ export const NETWORKS = {
2
+ mainnet: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
3
+ devnet: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
4
+ };
5
+ const DEFAULT_MINTS = {
6
+ [NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
7
+ [NETWORKS.devnet]: { USDC: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', A402: '5R2rKmzsNk1S5mFPR99bU1anromo73brwNApghvXeb46' },
8
+ };
9
+ const list = (s) => (s ?? '').split(',').map((x) => x.trim()).filter(Boolean);
10
+ const num = (s, d) => (s && Number.isFinite(Number(s)) ? Number(s) : d);
11
+ /** 원 단위 정수 (양수만). 없거나 잘못되면 null */
12
+ const atomic = (s) => (s && /^\d+$/.test(s.trim()) && BigInt(s.trim()) > 0n ? BigInt(s.trim()) : null);
13
+ export function policyFromEnv(env) {
14
+ const network = env.X402_NETWORK === 'devnet' ? NETWORKS.devnet : NETWORKS.mainnet;
15
+ const m = DEFAULT_MINTS[network];
16
+ return {
17
+ network,
18
+ mints: { USDC: env.X402_USDC_MINT ?? m.USDC, A402: env.X402_A402_MINT ?? m.A402 },
19
+ allowedDomains: list(env.X402_ALLOWED_DOMAINS).map((d) => d.toLowerCase()),
20
+ trustedPayTo: list(env.X402_TRUSTED_PAY_TO),
21
+ allowedAssets: (list(env.X402_ALLOWED_ASSETS).length ? list(env.X402_ALLOWED_ASSETS) : ['USDC']).filter((a) => a === 'USDC' || a === 'A402'),
22
+ maxUsdPerPayment: num(env.X402_MAX_USD, 0.05),
23
+ // A402 는 기본값 없음 — 둘 다 설정해야 A402 결제 가능 (USD 기준 한도가 A402 에는 적용되지 않으므로)
24
+ maxA402PerPayment: atomic(env.X402_MAX_A402_ATOMIC),
25
+ maxA402PerDay: atomic(env.X402_MAX_A402_PER_DAY_ATOMIC),
26
+ maxPaymentsPerDay: num(env.X402_MAX_PAYMENTS_PER_DAY, 20),
27
+ maxUsdPerDay: num(env.X402_MAX_USD_PER_DAY, 1),
28
+ confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
29
+ confirmAboveA402: env.X402_CONFIRM_ABOVE_A402_ATOMIC ? BigInt(env.X402_CONFIRM_ABOVE_A402_ATOMIC) : null,
30
+ prefer: env.X402_PAY_WITH === 'A402' ? 'A402' : 'USDC',
31
+ };
32
+ }
33
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
34
+ /** 이 URL 로 결제해도 되는지 (도메인 허용 목록 + https, 로컬만 http 허용) */
35
+ export function domainCheck(p, url) {
36
+ let u;
37
+ try {
38
+ u = new URL(url);
39
+ }
40
+ catch {
41
+ return { ok: false, reason: 'invalid_url' };
42
+ }
43
+ const host = u.host.toLowerCase();
44
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && LOOPBACK.has(u.hostname)))
45
+ return { ok: false, reason: `insecure_url: only https (http only for localhost)` };
46
+ if (!p.allowedDomains.length)
47
+ return { ok: false, reason: 'domain_not_allowed: allowed domain list is empty (X402_ALLOWED_DOMAINS)' };
48
+ if (!p.allowedDomains.includes(host))
49
+ return { ok: false, reason: `domain_not_allowed: ${host}` };
50
+ return { ok: true, host };
51
+ }
52
+ export function symbolOf(p, mint) {
53
+ return mint === p.mints.USDC ? 'USDC' : mint === p.mints.A402 ? 'A402' : null;
54
+ }
55
+ /** 결제 조건 하나를 정책으로 평가 (서명 전) */
56
+ export function evaluate(p, r, usage) {
57
+ const reasons = [];
58
+ const asset = symbolOf(p, r.asset);
59
+ if (r.scheme !== 'exact')
60
+ reasons.push(`unsupported_scheme: ${r.scheme}`);
61
+ if (r.network !== p.network)
62
+ reasons.push(`wrong_network: ${r.network}`);
63
+ if (!asset)
64
+ reasons.push(`asset_not_allowed: unknown mint ${r.asset}`);
65
+ else if (!p.allowedAssets.includes(asset))
66
+ reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)`);
67
+ if (!p.trustedPayTo.length)
68
+ reasons.push('pay_to_not_trusted: trusted recipient list is empty (X402_TRUSTED_PAY_TO)');
69
+ else if (!p.trustedPayTo.includes(r.payTo))
70
+ reasons.push(`pay_to_not_trusted: ${r.payTo}`);
71
+ let amount;
72
+ try {
73
+ amount = BigInt(r.amount);
74
+ }
75
+ catch {
76
+ amount = -1n;
77
+ }
78
+ if (amount <= 0n)
79
+ reasons.push('invalid_amount');
80
+ let usd = null;
81
+ if (asset === 'USDC' && amount > 0n) {
82
+ usd = Number(amount) / 1e6;
83
+ if (usd > p.maxUsdPerPayment)
84
+ reasons.push(`over_per_payment_limit: ${usd} USD > ${p.maxUsdPerPayment} USD`);
85
+ if (usage.usd + usd > p.maxUsdPerDay)
86
+ reasons.push(`over_daily_usd_limit: ${usage.usd} + ${usd} > ${p.maxUsdPerDay} USD`);
87
+ }
88
+ if (asset === 'A402' && p.allowedAssets.includes('A402') && amount > 0n) {
89
+ if (p.maxA402PerPayment === null)
90
+ reasons.push('a402_limit_not_configured: set X402_MAX_A402_ATOMIC (max A402 per payment, in A402 smallest units: 1 A402 = 1,000,000)');
91
+ else if (amount > p.maxA402PerPayment)
92
+ reasons.push(`over_per_payment_limit: ${amount} > ${p.maxA402PerPayment} (A402 smallest units)`);
93
+ if (p.maxA402PerDay === null)
94
+ reasons.push('a402_limit_not_configured: set X402_MAX_A402_PER_DAY_ATOMIC (max A402 per UTC day, in A402 smallest units: 1 A402 = 1,000,000)');
95
+ else if (usage.a402 + amount > p.maxA402PerDay)
96
+ reasons.push(`over_daily_a402_limit: ${usage.a402} + ${amount} > ${p.maxA402PerDay} (A402 smallest units)`);
97
+ }
98
+ if (usage.count >= p.maxPaymentsPerDay)
99
+ reasons.push(`over_daily_count_limit: ${p.maxPaymentsPerDay}`);
100
+ const needsConfirmation = (asset === 'USDC' && p.confirmAboveUsd !== null && usd !== null && usd >= p.confirmAboveUsd) ||
101
+ (asset === 'A402' && p.confirmAboveA402 !== null && amount >= p.confirmAboveA402);
102
+ return { requirement: r, asset, ok: reasons.length === 0, reasons, needsConfirmation, usd };
103
+ }
104
+ /** 평가 후 고를 조건 (선호 자산 우선) */
105
+ export function choose(p, evs) {
106
+ const ok = evs.filter((e) => e.ok);
107
+ return ok.find((e) => e.asset === p.prefer) ?? ok[0] ?? null;
108
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/server.js ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ // @agent402-dev/pay-mcp (stdio). 설정은 환경변수 — policy.ts PolicyEnv 와 아래:
3
+ // X402_KEYPAIR_PATH 결제 지갑 키 파일 (Solana CLI JSON). 없으면 결제하지 않음 (x402_quote 만)
4
+ // X402_RPC_URL 결제 트랜잭션을 만들 때 쓸 RPC (없으면 공개 RPC)
5
+ // X402_HISTORY_PATH 결제 기록 JSONL (기본 ~/.agent402/payments.jsonl)
6
+ // 허용 목록(X402_ALLOWED_DOMAINS, X402_TRUSTED_PAY_TO) 기본값은 비어 있음 = 전부 거절
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
+ const policy = policyFromEnv(process.env);
15
+ const wallet = process.env.X402_KEYPAIR_PATH
16
+ ? await loadWallet(process.env.X402_KEYPAIR_PATH, policy, process.env.X402_RPC_URL).catch((e) => {
17
+ console.error(`[a402-pay] could not load wallet, starting without payments: ${e.message}`);
18
+ return null;
19
+ })
20
+ : null;
21
+ const history = jsonlHistory(process.env.X402_HISTORY_PATH ?? join(homedir(), '.agent402', 'payments.jsonl'), () => policy.mints);
22
+ await createPayServer({ policy, wallet, history, fetch }).connect(new StdioServerTransport());
@@ -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,64 @@
1
+ // @agent402-dev/pay-mcp 도구 4개: 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 { formatUnits } from './units.js';
6
+ const out = (obj, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }], ...(isError ? { isError } : {}) });
7
+ const bigintSafe = (o) => JSON.parse(JSON.stringify(o, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
8
+ /** 결과 안의 { asset: 'USDC'|'A402', amount: '<최소 단위>' } 마다 단위 설명과 표시값을 붙임 (A402 금액은 반드시 단위와 함께) */
9
+ function withUnits(o) {
10
+ if (Array.isArray(o))
11
+ return o.map(withUnits);
12
+ if (!o || typeof o !== 'object')
13
+ return o;
14
+ const r = {};
15
+ for (const [k, v] of Object.entries(o))
16
+ r[k] = withUnits(v);
17
+ if ((r.asset === 'USDC' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
18
+ r.amountUnit = `${r.asset} smallest unit (1 ${r.asset} = 1,000,000)`;
19
+ r.amountDisplay = formatUnits(r.amount, r.asset);
20
+ }
21
+ return r;
22
+ }
23
+ const atomicLimit = (v, envName) => v === null ? `not set (${envName}) — A402 payments refused` : v;
24
+ export function createPayServer(d) {
25
+ const server = new McpServer({ name: 'a402-pay', version: '0.1.0' });
26
+ const confirm = async (message) => {
27
+ if (!server.server.getClientCapabilities()?.elicitation)
28
+ return 'unsupported';
29
+ const r = await server.server.elicitInput({
30
+ message,
31
+ requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean', title: 'Pay', description: 'Approve this payment' } }, required: ['confirm'] },
32
+ });
33
+ return r.action === 'accept' && r.content?.confirm === true ? 'accept' : 'decline';
34
+ };
35
+ const agent = createAgent({ ...d, confirm });
36
+ 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() };
37
+ 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; A402 only if listed), 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)); });
38
+ 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'); });
39
+ server.tool('wallet_status', 'Payment wallet address, network, USDC and A402 balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
40
+ const today = d.history.today(d.now?.());
41
+ const balances = d.wallet ? await d.wallet.balances() : null;
42
+ return out(bigintSafe({
43
+ address: d.wallet?.address ?? null,
44
+ network: d.policy.network,
45
+ // 잔액은 토큰 단위 (예: "10 A402")
46
+ balances: balances ? Object.fromEntries(Object.entries(balances).map(([k, v]) => [k, /^[\d.]+$/.test(v) ? `${v} ${k}` : v])) : null,
47
+ today: { ...today, usdUnit: 'USD (USDC)', a402Unit: 'A402 smallest unit (1 A402 = 1,000,000)', a402Display: formatUnits(today.a402, 'A402') },
48
+ signedThisSession: d.wallet?.signedCount ?? 0,
49
+ limits: {
50
+ maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
51
+ maxA402PerPaymentAtomic: atomicLimit(d.policy.maxA402PerPayment, 'X402_MAX_A402_ATOMIC'),
52
+ maxA402PerDayAtomic: atomicLimit(d.policy.maxA402PerDay, 'X402_MAX_A402_PER_DAY_ATOMIC'),
53
+ ...(d.policy.maxA402PerPayment !== null ? { maxA402PerPaymentDisplay: formatUnits(d.policy.maxA402PerPayment, 'A402') } : {}),
54
+ ...(d.policy.maxA402PerDay !== null ? { maxA402PerDayDisplay: formatUnits(d.policy.maxA402PerDay, 'A402') } : {}),
55
+ confirmAboveUsd: d.policy.confirmAboveUsd, confirmAboveA402Atomic: d.policy.confirmAboveA402,
56
+ units: '…Usd = US dollars (USDC); …Atomic = A402 smallest unit (1 A402 = 1,000,000)',
57
+ },
58
+ allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
59
+ ...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
60
+ }));
61
+ });
62
+ 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))));
63
+ return server;
64
+ }
@@ -0,0 +1,5 @@
1
+ export declare const DECIMALS = 6;
2
+ /** 최소 단위 정수 → "140,000 A402" */
3
+ export declare function formatUnits(atomic: string | bigint, symbol: string): string;
4
+ /** "140,000 A402 (140000000000 smallest units)" */
5
+ export declare const withSmallest: (atomic: string | bigint, symbol: string) => string;
package/dist/units.js ADDED
@@ -0,0 +1,11 @@
1
+ // 금액 표시: USDC·A402 모두 소수 6자리. A402 금액은 항상 단위와 함께 보여 줌
2
+ export const DECIMALS = 6;
3
+ /** 최소 단위 정수 → "140,000 A402" */
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 A402 (140000000000 smallest units)" */
11
+ export const withSmallest = (atomic, symbol) => `${formatUnits(atomic, symbol)} (${atomic} smallest units)`;
@@ -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
+ /** 정책 검사를 통과한 조건 하나에 서명 → PAYMENT-SIGNATURE 헤더 값 */
7
+ sign(resource: PaymentRequired['resource'], requirement: PaymentRequirements): Promise<string>;
8
+ /** 이 프로세스에서 서명한 횟수 */
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,50 @@
1
+ // 결제 지갑: 사용자 컴퓨터의 키 파일로 x402 exact 결제 트랜잭션에 서명 (공식 @x402 클라이언트).
2
+ // 키는 서버로 보내지 않음 — 부분 서명한 트랜잭션만 PAYMENT-SIGNATURE 헤더로. 이 모듈은 정책 검사를 통과한 조건 하나에만 서명
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
+ export async function loadWallet(keyPath, policy, rpcUrl) {
10
+ const bytes = Uint8Array.from(JSON.parse(readFileSync(keyPath, 'utf8')));
11
+ const signer = await createKeyPairSignerFromBytes(bytes);
12
+ bytes.fill(0);
13
+ let signed = 0;
14
+ // 공식 클라이언트의 지출 한도도 같은 값으로 (두 번째 안전망)
15
+ const client = x402Client.fromConfig({
16
+ schemes: [{ network: policy.network, client: new ExactSvmScheme(toClientSvmSigner(signer), rpcUrl ? { rpcUrl } : undefined) }],
17
+ spendControls: {
18
+ maxAmountPerPayment: `$${policy.maxUsdPerPayment}`,
19
+ // A402 는 허용 + 결제당 상한이 설정됐을 때만 공식 클라이언트에도 허용 (상한 없으면 공식 클라이언트도 거절)
20
+ ...(policy.allowedAssets.includes('A402') && policy.maxA402PerPayment !== null
21
+ ? { allowedAssets: [{ network: policy.network, asset: policy.mints.A402, maxAmountPerPayment: policy.maxA402PerPayment.toString() }] }
22
+ : {}),
23
+ },
24
+ });
25
+ const rpc = rpcUrl ?? (policy.network.includes('EtWTRAB') ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');
26
+ return {
27
+ address: signer.address,
28
+ network: policy.network,
29
+ get signedCount() { return signed; },
30
+ async sign(resource, requirement) {
31
+ const payload = await client.createPaymentPayload({ x402Version: 2, resource, accepts: [requirement] });
32
+ signed++;
33
+ return encodePaymentSignatureHeader(payload);
34
+ },
35
+ async balances() {
36
+ const out = {};
37
+ for (const [sym, mint] of Object.entries(policy.mints)) {
38
+ try {
39
+ 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' }] }) });
40
+ const j = (await r.json());
41
+ out[sym] = j.result?.value[0]?.account.data.parsed.info.tokenAmount.uiAmountString ?? '0';
42
+ }
43
+ catch {
44
+ out[sym] = 'unavailable';
45
+ }
46
+ }
47
+ return out;
48
+ },
49
+ };
50
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@agent402-dev/pay-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "MCP server that lets an AI agent pay x402 APIs (USDC, A402) 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.1.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
+ }