@ic402/mcp 2.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +326 -0
- package/dist/guards.d.ts +79 -0
- package/dist/guards.js +233 -0
- package/dist/guards.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1216 -0
- package/dist/index.js.map +1 -0
- package/dist/security.d.ts +71 -0
- package/dist/security.js +190 -0
- package/dist/security.js.map +1 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 ic402 contributors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
# @ic402/mcp
|
|
2
|
+
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) (Model Context Protocol) server that exposes an
|
|
4
|
+
ic402-enabled ICP canister to an AI agent over **stdio**. It lets a model probe x402-gated
|
|
5
|
+
endpoints, open and settle streaming micropayment sessions, fetch encrypted content, drive the
|
|
6
|
+
ERC-8004 / marketplace flows, and — when an operator explicitly opts in — perform
|
|
7
|
+
controller-gated admin and signing actions.
|
|
8
|
+
|
|
9
|
+
The server identifies itself to MCP clients as:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
name: ic402
|
|
13
|
+
version: 2.5.2
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
(see `src/index.ts`, the `new McpServer({ name: 'ic402', version: '2.5.2' })` registration).
|
|
17
|
+
|
|
18
|
+
> **Security note up front.** This server is driven by an LLM whose inputs may be influenced by
|
|
19
|
+
> untrusted web content (prompt injection) while it holds a controller identity capable of
|
|
20
|
+
> signing value transfers from the canister's own EVM address. The security posture is therefore
|
|
21
|
+
> **operator-set, out-of-band** — see [Security model](#security-model). The LLM cannot loosen it.
|
|
22
|
+
|
|
23
|
+
## Build & run
|
|
24
|
+
|
|
25
|
+
The package builds with plain `tsc` (output goes to `dist/`, with `dist/index.js` as the
|
|
26
|
+
`ic402-mcp` bin):
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# From the repo root — builds the client SDK, this MCP server, and the demo client:
|
|
30
|
+
pnpm build:demo
|
|
31
|
+
|
|
32
|
+
# Or build just this package (after the @ic402/client workspace dep is built):
|
|
33
|
+
pnpm --filter @ic402/mcp build
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Run it directly over stdio:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
node integrations/mcp/dist/index.js
|
|
40
|
+
# or, after build, the bin:
|
|
41
|
+
ic402-mcp
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
It speaks MCP JSON-RPC on **stdout** and prints diagnostics (including the security banner) to
|
|
45
|
+
**stderr**, so stdout is never polluted.
|
|
46
|
+
|
|
47
|
+
### Register with an MCP client
|
|
48
|
+
|
|
49
|
+
Point your MCP client at the built entrypoint, passing operator config via env vars and/or a
|
|
50
|
+
config file (see below). For example:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"ic402": {
|
|
56
|
+
"command": "node",
|
|
57
|
+
"args": ["/abs/path/to/ic402/integrations/mcp/dist/index.js"],
|
|
58
|
+
"env": {
|
|
59
|
+
"IC402_MCP_PER_CALL_MAX_ATOMIC": "1000000",
|
|
60
|
+
"IC402_MCP_SESSION_MAX_ATOMIC": "5000000"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
You can also pass `--config <path>` (or `IC402_MCP_CONFIG=<path>`) to load a JSON config file.
|
|
68
|
+
|
|
69
|
+
## Configuration
|
|
70
|
+
|
|
71
|
+
### The `configure` tool
|
|
72
|
+
|
|
73
|
+
`configure` must be called before any other tool — every other tool throws
|
|
74
|
+
`Not configured. Call the "configure" tool first.` until an agent and client exist. It connects
|
|
75
|
+
to a canister and (optionally) loads a signing identity:
|
|
76
|
+
|
|
77
|
+
| Param | Type | Default | Purpose |
|
|
78
|
+
|---|---|---|---|
|
|
79
|
+
| `canisterId` | string | — | Principal of the canister to interact with. |
|
|
80
|
+
| `host` | string | `http://localhost:4944` | ICP replica URL. Root key is fetched automatically when the host contains `localhost`. |
|
|
81
|
+
| `network` | string | `icp:1` | CAIP-2 network identifier. |
|
|
82
|
+
| `identityPem` | string? | — | Path to a secp256k1 PEM (SEC1 `EC PRIVATE KEY` or PKCS#8 `PRIVATE KEY`). Falls back to the `ICP_IDENTITY_PEM` env var; anonymous if neither is set. |
|
|
83
|
+
| `ledger` | string? | — | ICRC-2 ledger canister ID for auto-payment (e.g. ckUSDC). |
|
|
84
|
+
| `autoPayment` | boolean | `false` | Allow paid endpoints to auto-approve/pay (opt-in). |
|
|
85
|
+
| `localDev` | boolean | `false` | Allow `http://localhost` / private / loopback fetch targets (local development only). |
|
|
86
|
+
| `perCallMaxAtomic` | string? | — | Per-call max spend in atomic token units. |
|
|
87
|
+
| `sessionMaxAtomic` | string? | — | Cumulative session max spend in atomic token units. |
|
|
88
|
+
|
|
89
|
+
The identity loader surfaces failures loudly: if `identityPem` is supplied but cannot be parsed
|
|
90
|
+
(unsupported PEM, missing secp256k1 OID, wrong key length), `configure` throws rather than
|
|
91
|
+
silently falling back to anonymous.
|
|
92
|
+
|
|
93
|
+
**The four security knobs (`autoPayment`, `localDev`, `perCallMaxAtomic`, `sessionMaxAtomic`)
|
|
94
|
+
are only honored when the operator enabled `allowSecurityChanges` at startup.** Otherwise they
|
|
95
|
+
are *ignored* — the operator/default config stands — and the `configure` result reports which
|
|
96
|
+
fields were dropped, e.g.:
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
IGNORED security params ["autoPayment","perCallMaxAtomic"] — operator did not enable
|
|
100
|
+
LLM security changes (set IC402_MCP_ALLOW_SECURITY_CHANGES=1 to allow).
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
This stops a prompt-injected model from raising its own caps or enabling `localDev` / auto-pay
|
|
104
|
+
through the `configure` tool (`resolveSecurityConfig` in `guards.ts`).
|
|
105
|
+
|
|
106
|
+
### Operator config (out-of-band) — startup only
|
|
107
|
+
|
|
108
|
+
The real security boundary is resolved once, in `main()`, from an **optional JSON config file +
|
|
109
|
+
environment variables — both inputs the LLM cannot influence**. Precedence is:
|
|
110
|
+
|
|
111
|
+
> built-in defaults < config file < env vars (env wins)
|
|
112
|
+
|
|
113
|
+
A config file is loaded from `--config <path>` or `IC402_MCP_CONFIG`. Unparseable amount values
|
|
114
|
+
fall back to the lower-precedence source rather than crashing the server (`resolveOperatorConfig`
|
|
115
|
+
in `guards.ts`).
|
|
116
|
+
|
|
117
|
+
#### Environment flags
|
|
118
|
+
|
|
119
|
+
| Env var | Config file key | Gates |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `IC402_MCP_CONFIG` | — | Path to the JSON config file (alt: `--config <path>`). |
|
|
122
|
+
| `IC402_MCP_PER_CALL_MAX_ATOMIC` | `perCallMaxAtomic` | Per-call spend cap in atomic units. Default `1_000_000` (1.00 USDC at 6 decimals). |
|
|
123
|
+
| `IC402_MCP_SESSION_MAX_ATOMIC` | `sessionMaxAtomic` | Cumulative session spend cap. Default `5_000_000` (5.00 USDC). |
|
|
124
|
+
| `IC402_MCP_LOCAL_DEV` | `localDev` | Allow `http://localhost` / private / loopback fetch targets. Default `false`. |
|
|
125
|
+
| `IC402_MCP_AUTO_PAYMENT` | `autoPayment` | Allow paid endpoints to auto-approve/pay. Default `false`. |
|
|
126
|
+
| `IC402_MCP_ALLOW_SECURITY_CHANGES` | `allowSecurityChanges` | If set, the LLM may retune caps / `localDev` / `autoPayment` via the `configure` tool. Default `false`. |
|
|
127
|
+
| `IC402_MCP_ALLOW_DANGEROUS_TOOLS` | `allowDangerousTools` | If set, enables the default-denied dangerous tools `sign_typed_data` and `delete_content`. Default `false`. |
|
|
128
|
+
| `IC402_MCP_ALLOW_ADMIN_TOOLS` | `allowAdminTools` | If set, enables the default-denied state-changing admin tools (`register_service`, `enable_service`, `claim_job`, `submit_job_result`, `upload_content`). Default `false` (SEC-3). |
|
|
129
|
+
|
|
130
|
+
Booleans are true when the value is exactly `"1"` or `"true"`. Amounts are parsed as
|
|
131
|
+
non-negative integer **strings** (a JS number that has already lost precision is rejected — see
|
|
132
|
+
`parseAtomicAmount`).
|
|
133
|
+
|
|
134
|
+
The signing identity PEM path can also come from the `ICP_IDENTITY_PEM` env var (consumed by the
|
|
135
|
+
`configure` tool).
|
|
136
|
+
|
|
137
|
+
## Tool inventory
|
|
138
|
+
|
|
139
|
+
All tools are registered in `src/index.ts` via `server.tool(...)` (and `adminTool(...)` for the
|
|
140
|
+
controller-gated set).
|
|
141
|
+
|
|
142
|
+
### Read-only / query tools
|
|
143
|
+
|
|
144
|
+
- **`call`** — a generic read-only escape hatch. It may only invoke **allowlisted** query/read
|
|
145
|
+
methods on the canister. Anything state-changing, signing, payment, or admin is blocked here;
|
|
146
|
+
use the dedicated tool instead. The allowlist and blocklist are detailed under
|
|
147
|
+
[The `call` allowlist & blocklist](#the-call-allowlist--blocklist).
|
|
148
|
+
- **`list_services`** — list available paid services from the canister.
|
|
149
|
+
- **`request_session`** — request a session intent (pricing: `suggestedDeposit`, `costPerCall`)
|
|
150
|
+
*without* opening a session.
|
|
151
|
+
- **`get_session`** — state of an active session (consumed, remaining, voucher count).
|
|
152
|
+
- **`list_sessions`** — list all active sessions managed by this server.
|
|
153
|
+
- **`get_job_result`** — poll for a job result until it completes or times out.
|
|
154
|
+
- **`session_query`** — send a query through an open session (auto-signs a voucher). Each call
|
|
155
|
+
consumes `costPerCall` from the already-escrowed deposit, so it is not separately confirm-gated.
|
|
156
|
+
- **`search`** — call the canister's `search` endpoint (x402 charge flow); returns results or a
|
|
157
|
+
payment requirement.
|
|
158
|
+
- **`dispute_job`** — dispute a job result (for `BuyerConfirm` verification services).
|
|
159
|
+
|
|
160
|
+
### Payment / session tools (capped + confirmation-gated)
|
|
161
|
+
|
|
162
|
+
These move or settle value, so they enforce the spend caps and require an explicit `confirm:true`
|
|
163
|
+
(when `confirm` is `false` they return a structured `confirmation_required` proposal describing
|
|
164
|
+
amount / recipient / asset / chain):
|
|
165
|
+
|
|
166
|
+
- **`fetch_x402`** — full x402 flow: probe a gated URL → canister signs the payment → retry with
|
|
167
|
+
the payment header. Probe-only when `confirm:false`; signing the proposed payment requires
|
|
168
|
+
`confirm:true`. SSRF-guarded on the URL and every redirect hop.
|
|
169
|
+
- **`fetch_content`** — fetch content from a `ContentDelivery` response. Supports `inline`,
|
|
170
|
+
`httpUrl` (SSRF-guarded `safeFetch`), `assetCanister` (validated canister id + URL-API origin),
|
|
171
|
+
and `canisterQuery` (restricted to the `getChunk` / `getContent` query methods).
|
|
172
|
+
- **`open_session`** — open a streaming micropayment session. ICP uses ICRC-2 escrow; EVM takes
|
|
173
|
+
an `evmTxHash` (and EIP-3009 `authorization`) proving the USDC deposit. The escrow deposit is
|
|
174
|
+
capped + confirmed, and the deposited amount is counted against the cumulative cap.
|
|
175
|
+
- **`close_session`** — settle the consumed amount on-chain and refund the remainder; returns a
|
|
176
|
+
payment receipt. Requires `confirm:true` (the consumed amount was already counted at deposit
|
|
177
|
+
time, so it is not re-charged against the cap).
|
|
178
|
+
- **`submit_request`** — submit a paid service request. If the service demands payment, the
|
|
179
|
+
operator must have opted into `autoPayment` *and* the caller must pass `confirm:true` after
|
|
180
|
+
reviewing the amount. The price is discovered via a **read-only** `quoteServiceRequest` query
|
|
181
|
+
(no nonce minted), and the cap is checked against the **total** (price + ledger fee), not the
|
|
182
|
+
bare price. Free / session-billed services (total `0`) submit directly.
|
|
183
|
+
- **`register_agent`** — register the canister as an ERC-8004 agent on Base: get nonce + gas →
|
|
184
|
+
canister signs → broadcast → poll receipt. Broadcasting spends native gas, so it is
|
|
185
|
+
confirm-gated (no USDC amount, hence no spend cap); a custom `rpcUrl` is SSRF-validated.
|
|
186
|
+
|
|
187
|
+
### State-changing / signing tools (the 7 operator tools)
|
|
188
|
+
|
|
189
|
+
Registered via `adminTool(...)`, each binds a **fixed** controller-gated canister method (the LLM
|
|
190
|
+
cannot choose the method) and requires `confirm:true`:
|
|
191
|
+
|
|
192
|
+
| Tool | Canister method | Notes |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `upload_content` | `uploadContent` | Upload + encrypt content into the ContentStore (controller-gated). |
|
|
195
|
+
| `delete_content` | `deleteContent` | Destructive delete. **DEFAULT-DENIED** — see below. |
|
|
196
|
+
| `register_service` | `registerService` | Register a paid marketplace service (controller-gated). |
|
|
197
|
+
| `enable_service` | `enableService` | Enable a registered service so it can accept paid requests. |
|
|
198
|
+
| `claim_job` | `claimJob` | Operator claims a pending marketplace job. |
|
|
199
|
+
| `submit_job_result` | `submitJobResult` | Operator submits a job result (+ optional proof) for verification + settlement. |
|
|
200
|
+
| `sign_typed_data` | `signTypedData` | Sign arbitrary EIP-712 typed data with the canister tECDSA key. **DEFAULT-DENIED** — generic signing primitive. |
|
|
201
|
+
|
|
202
|
+
**Default-denied tools (operator opt-in required).** Two categories throw unless the operator
|
|
203
|
+
enables them at startup — a prompt-injected LLM must not reach them via an in-band `confirm` alone:
|
|
204
|
+
|
|
205
|
+
- **Dangerous primitives** — `sign_typed_data` (a raw EIP-712 signing oracle that can authorize an
|
|
206
|
+
arbitrary-value transfer and *bypasses the spend caps*) and `delete_content` (irreversible delete).
|
|
207
|
+
Enable with `IC402_MCP_ALLOW_DANGEROUS_TOOLS=1`.
|
|
208
|
+
- **State-changing admin tools (SEC-3)** — `register_service`, `enable_service`, `claim_job`,
|
|
209
|
+
`submit_job_result`, `upload_content` mutate the canister and drive the value-moving job lifecycle.
|
|
210
|
+
Enable with `IC402_MCP_ALLOW_ADMIN_TOOLS=1`.
|
|
211
|
+
|
|
212
|
+
(`isToolAllowed` / `DANGEROUS_TOOLS` / `ADMIN_TOOLS` in `guards.ts`.)
|
|
213
|
+
|
|
214
|
+
## Security model
|
|
215
|
+
|
|
216
|
+
The server assumes the LLM driving it may be steered by untrusted web content while it holds a
|
|
217
|
+
controller identity that can sign value transfers from the canister's own EVM address. Every
|
|
218
|
+
money-moving or signing path is therefore capped, SSRF-guarded, and gated behind explicit
|
|
219
|
+
confirmation.
|
|
220
|
+
|
|
221
|
+
### Spend caps — per-call and cumulative
|
|
222
|
+
|
|
223
|
+
Two caps, in atomic token units (USDC has 6 decimals, so `1_000_000` atomic = 1.00 USDC):
|
|
224
|
+
|
|
225
|
+
- **`perCallMaxAtomic`** — caps a single signed transfer (default `1_000_000` = 1.00 USDC).
|
|
226
|
+
- **`sessionMaxAtomic`** — caps the cumulative total spent/approved across this server session
|
|
227
|
+
(default `5_000_000` = 5.00 USDC).
|
|
228
|
+
|
|
229
|
+
`checkSpend` (in `guards.ts`) rejects negative amounts, any single amount over the per-call cap,
|
|
230
|
+
and any amount that would push the running session total over the cumulative cap. The running
|
|
231
|
+
total (`sessionSpentAtomic`) is only incremented by `commitSpend` **after** a spend actually
|
|
232
|
+
succeeds. The conservative defaults force the LLM to stay within a trivial budget unless a human
|
|
233
|
+
raises the caps out-of-band (and only when `allowSecurityChanges` is set).
|
|
234
|
+
|
|
235
|
+
### Explicit confirmation gating
|
|
236
|
+
|
|
237
|
+
Money-moving / signing tools route through `requireConfirmation`, which **enforces the caps
|
|
238
|
+
first** (so an over-cap action is refused even before any confirmation) and then, when
|
|
239
|
+
`confirm:false`, returns a structured `confirmation_required` result echoing the proposed
|
|
240
|
+
`amount` / `recipient` / `asset` / `chain` plus the current caps and instructs the caller to
|
|
241
|
+
re-invoke with `confirm:true`. The instruction explicitly says *"Do NOT confirm automatically."*
|
|
242
|
+
|
|
243
|
+
### Operator-only escalation
|
|
244
|
+
|
|
245
|
+
The security boundary is resolved at startup from a config file + env vars the LLM cannot touch
|
|
246
|
+
(see [Operator config](#operator-config-out-of-band--startup-only)). The `configure` tool can
|
|
247
|
+
loosen caps / `localDev` / `autoPayment` **only** when `allowSecurityChanges` is enabled;
|
|
248
|
+
otherwise those request fields are ignored and reported. The two dangerous tools stay off unless
|
|
249
|
+
`allowDangerousTools` is enabled.
|
|
250
|
+
|
|
251
|
+
### SSRF guard (and a known limitation)
|
|
252
|
+
|
|
253
|
+
Every outbound fetch path (`fetch_x402`, the `httpUrl` / `assetCanister` deliveries in
|
|
254
|
+
`fetch_content`, and any custom `rpcUrl`) is validated by `validateFetchUrl` and uses the
|
|
255
|
+
redirect-safe `safeFetch` (both in `security.ts`):
|
|
256
|
+
|
|
257
|
+
- Requires `https:` (or `http://localhost` / `127.0.0.1` / `::1` only when `localDev` is set).
|
|
258
|
+
- Rejects literal private / loopback / link-local / CGNAT IPv4 ranges (10/8, 172.16/12,
|
|
259
|
+
192.168/16, 127/8, 169.254/16, 100.64/10, 0/8), the `169.254.169.254` cloud-metadata endpoint,
|
|
260
|
+
private/loopback/link-local IPv6 (including IPv4-mapped `::ffff:` forms in both dotted and
|
|
261
|
+
hex-compressed notation), and `.local` / `.internal` TLDs.
|
|
262
|
+
- `safeFetch` follows redirects **manually** (default max 5) and **re-validates every hop's
|
|
263
|
+
`Location` before following it**, closing the TOCTOU redirect-bypass where an allowlisted
|
|
264
|
+
origin 30x's to an internal/metadata target. The x402 probe uses the same per-hop
|
|
265
|
+
`validateRedirect` check.
|
|
266
|
+
|
|
267
|
+
> **Known limitation — DNS rebinding.** `validateFetchUrl` validates the *literal* host only. A
|
|
268
|
+
> public hostname that resolves to a private IP is **not** covered. Closing it requires resolving
|
|
269
|
+
> the host and re-checking the resolved addresses before connecting (a resolver seam, noted in
|
|
270
|
+
> `security.ts`).
|
|
271
|
+
|
|
272
|
+
### The `call` allowlist & blocklist
|
|
273
|
+
|
|
274
|
+
The generic `call` tool is restricted to read-only methods by `isCallMethodAllowed` in
|
|
275
|
+
`index.ts`:
|
|
276
|
+
|
|
277
|
+
1. **Curated read-only allowlist (authoritative):** `listContent`, `getChunk`, `getAgentCard`,
|
|
278
|
+
`getAgentId`, `verifyGrant`, `listServices`, `getJobStatus`, `getJob`, `getJobResult`,
|
|
279
|
+
`keccak256`, `getPolicyConfig`. These are accepted even if their name contains a blocked
|
|
280
|
+
substring (`getPolicyConfig` contains `policy`).
|
|
281
|
+
2. **Hard blocklist of substrings** that denote signing/admin/value-moving methods (each has a
|
|
282
|
+
dedicated tool): `sign`, `set`, `submit`, `open`, `close`, `transfer`, `register`, `pay`,
|
|
283
|
+
`approve`, `policy`, `upload`, `delete`, `claim`, `confirm`, `dispute`, `enable`, `disable`,
|
|
284
|
+
`end`. Any method whose name contains one of these is rejected.
|
|
285
|
+
3. **Forward-compat fallback:** after the blocklist clears a name, read-only getter prefixes
|
|
286
|
+
(`get…`, `list…`, `fetch…`, `is…`) are allowed. Anything else is rejected with a message
|
|
287
|
+
pointing the LLM at the dedicated, capped, confirmation-gated tool.
|
|
288
|
+
|
|
289
|
+
### Startup security banner
|
|
290
|
+
|
|
291
|
+
On startup the server prints the **effective** security posture to **stderr** (stdout is the MCP
|
|
292
|
+
JSON-RPC channel) so the operator can verify what's active before the agent connects. The banner
|
|
293
|
+
shows the config source (config file path or `env vars / defaults`), `perCallMaxAtomic`,
|
|
294
|
+
`sessionMaxAtomic`, `localDev`, `autoPayment`, `allowSecurityChanges`, and `allowDangerousTools`,
|
|
295
|
+
and warns when any loosened knob is enabled:
|
|
296
|
+
|
|
297
|
+
```
|
|
298
|
+
───────────────────────────────────────────────────────────────
|
|
299
|
+
ic402 MCP — effective security config (operator-set, out-of-band)
|
|
300
|
+
source : env vars / defaults
|
|
301
|
+
perCallMaxAtomic : 1000000
|
|
302
|
+
sessionMaxAtomic : 5000000
|
|
303
|
+
localDev : false
|
|
304
|
+
autoPayment : false
|
|
305
|
+
allowSecurityChanges : false (LLM may retune caps via "configure")
|
|
306
|
+
allowDangerousTools : false (sign_typed_data / delete_content)
|
|
307
|
+
───────────────────────────────────────────────────────────────
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
When `allowSecurityChanges` or `allowDangerousTools` is enabled, the banner adds:
|
|
311
|
+
|
|
312
|
+
```
|
|
313
|
+
⚠ a loosened knob is enabled — only do this in a TRUSTED context (no prompt-injection risk).
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
## Source layout
|
|
317
|
+
|
|
318
|
+
- `src/index.ts` — `McpServer` registration, all tool definitions, the `configure` flow, the
|
|
319
|
+
confirmation gate, the `call` allowlist/blocklist, the `adminTool` helper, and `main()`
|
|
320
|
+
(operator-config resolution + security banner + stdio transport).
|
|
321
|
+
- `src/guards.ts` — pure, unit-tested guards: `parseAtomicAmount`, `checkSpend`,
|
|
322
|
+
`resolveSecurityConfig`, `isToolAllowed` / `DANGEROUS_TOOLS`, `resolveOperatorConfig`.
|
|
323
|
+
- `src/security.ts` — pure SSRF validation (`validateFetchUrl` and the IPv4/IPv6 helpers) and the
|
|
324
|
+
redirect-safe `safeFetch`.
|
|
325
|
+
- `package.json` — `@ic402/mcp` v2.1.1; `build` runs `tsc`, `start` runs `node dist/index.js`,
|
|
326
|
+
and the `ic402-mcp` bin maps to `dist/index.js`.
|
package/dist/guards.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spend caps, config-escalation guard, dangerous-tool gate, and safe amount parsing
|
|
3
|
+
* for the ic402 MCP server.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from index.ts so the security-critical decisions are pure and unit-testable
|
|
6
|
+
* (see test/mcp-guards.test.ts). The MCP is driven by a possibly prompt-injected LLM
|
|
7
|
+
* while holding a controller identity, so these guards are the last line between the
|
|
8
|
+
* model and value movement.
|
|
9
|
+
*/
|
|
10
|
+
export interface SpendCaps {
|
|
11
|
+
perCallMaxAtomic: bigint;
|
|
12
|
+
sessionMaxAtomic: bigint;
|
|
13
|
+
}
|
|
14
|
+
export interface SecurityConfig extends SpendCaps {
|
|
15
|
+
localDev: boolean;
|
|
16
|
+
autoPayment: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface ConfigureRequest {
|
|
19
|
+
localDev?: boolean;
|
|
20
|
+
autoPayment?: boolean;
|
|
21
|
+
perCallMaxAtomic?: string;
|
|
22
|
+
sessionMaxAtomic?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Parse a token amount (atomic units) from untrusted input into a bigint, REJECTING
|
|
26
|
+
* floats and JS numbers that have already lost precision. C5: `value: z.number()`
|
|
27
|
+
* silently truncated uint256 amounts above 2^53; callers must pass amounts as decimal
|
|
28
|
+
* strings, and an unsafe number is rejected (not silently used).
|
|
29
|
+
*/
|
|
30
|
+
export declare function parseAtomicAmount(input: unknown, field?: string): bigint;
|
|
31
|
+
/**
|
|
32
|
+
* Enforce the per-call and cumulative session spend caps. Throws on violation; never
|
|
33
|
+
* mutates state. (S1/S9 — the cap logic that every value-moving tool must pass.)
|
|
34
|
+
*/
|
|
35
|
+
export declare function checkSpend(amountAtomic: bigint, caps: SpendCaps, sessionSpentAtomic: bigint): void;
|
|
36
|
+
/**
|
|
37
|
+
* S8: Resolve the effective security config from an LLM-supplied `configure` request.
|
|
38
|
+
* The caps / localDev / autoPayment knobs loosen the server's security posture, so the
|
|
39
|
+
* LLM may only change them when the OPERATOR opted in at startup (allowSecurityChanges).
|
|
40
|
+
* Otherwise the request's security fields are IGNORED and the operator/default config
|
|
41
|
+
* stands — a prompt-injected model cannot raise its own caps or enable localDev.
|
|
42
|
+
* Returns the resolved config and the list of fields that were ignored (for reporting).
|
|
43
|
+
*/
|
|
44
|
+
export declare function resolveSecurityConfig(base: SecurityConfig, req: ConfigureRequest, allowSecurityChanges: boolean): {
|
|
45
|
+
config: SecurityConfig;
|
|
46
|
+
ignored: string[];
|
|
47
|
+
};
|
|
48
|
+
export declare function isToolAllowed(toolName: string, allowDangerousTools: boolean, allowAdminTools: boolean): boolean;
|
|
49
|
+
export interface OperatorConfig {
|
|
50
|
+
security: SecurityConfig;
|
|
51
|
+
allowSecurityChanges: boolean;
|
|
52
|
+
allowDangerousTools: boolean;
|
|
53
|
+
allowAdminTools: boolean;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the operator's startup security config from an optional JSON config file and the
|
|
57
|
+
* environment. BOTH are out-of-band inputs the LLM cannot influence, so the security boundary
|
|
58
|
+
* stays with the operator (audit S8). Precedence: built-in defaults < config file < env vars
|
|
59
|
+
* (env wins, so an operator can override a file value at launch). Unparseable values fall back
|
|
60
|
+
* to the lower-precedence source rather than throwing, so a typo can't crash the server.
|
|
61
|
+
*/
|
|
62
|
+
export declare function resolveOperatorConfig(file: Record<string, unknown> | null, env: Record<string, string | undefined>, defaults: {
|
|
63
|
+
perCallMaxAtomic: bigint;
|
|
64
|
+
sessionMaxAtomic: bigint;
|
|
65
|
+
}): OperatorConfig;
|
|
66
|
+
/** Curated read-only allowlist — every entry is a `query` (or otherwise non-state-changing read)
|
|
67
|
+
* in the IDL. Authoritative: wins over the substring blocklist, so a genuine read-only getter
|
|
68
|
+
* whose name contains a blocked substring (e.g. getPolicyConfig contains 'policy') is still
|
|
69
|
+
* admitted. ONLY add verified non-state-changing query methods. */
|
|
70
|
+
export declare const READONLY_CALL_ALLOWLIST: Set<string>;
|
|
71
|
+
/** Substrings that must NEVER be reachable through the generic `call` path — signing/admin/
|
|
72
|
+
* value-moving method names that have dedicated tools. */
|
|
73
|
+
export declare const CALL_BLOCK_SUBSTRINGS: string[];
|
|
74
|
+
/** Decide whether a method name may be called through the generic (uncapped, unconfirmed) `call`
|
|
75
|
+
* tool. Order: allowlist (authoritative) → substring blocklist → read-only name-prefix fallback. */
|
|
76
|
+
export declare function isCallMethodAllowed(method: string): {
|
|
77
|
+
ok: boolean;
|
|
78
|
+
reason?: string;
|
|
79
|
+
};
|