charter-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 +21 -0
- package/README.md +89 -2
- package/dist/core.js +290 -0
- package/dist/main.js +28 -0
- package/dist/server.js +415 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Drew Pierson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# charter-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An MCP server that lets an agent rent a machine on [Charter](https://charter.mainnet.toonprotocol.dev/agents) and pay for it itself. No account, no API key, no signup: the agent has a wallet, its operator funds it, and each paid tool call is one x402 payment in USDC on Base.
|
|
4
|
+
|
|
5
|
+
What it rents, by the hour, at 0.007 USDC an hour on the live host:
|
|
6
|
+
|
|
7
|
+
- **A Python sandbox.** Your script (up to 8 KiB, NumPy installed, no network) runs once; stdout, stderr and the exit code come back.
|
|
8
|
+
- **A page fetcher.** Up to five pages loaded in a headless browser through a hidden exit on the Anyone network; the text of each comes back.
|
|
9
|
+
- **A Linux home.** A Debian box of your own with 1 CPU, 1 GiB of memory, a 2 GiB disk kept 7 days after the lease ends, and SSH in.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
Claude Code:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
claude mcp add charter -- npx -y charter-mcp
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Any other MCP client, in its server config:
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"mcpServers": {
|
|
24
|
+
"charter": { "command": "npx", "args": ["-y", "charter-mcp"] }
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Node 22 or newer.
|
|
30
|
+
|
|
31
|
+
## First run
|
|
32
|
+
|
|
33
|
+
1. The server makes a wallet key at `~/.charter/mcp.key` (mode 600). It never leaves the machine.
|
|
34
|
+
2. Ask the agent to call `charter_wallet`. It prints the address.
|
|
35
|
+
3. Send USDC on Base to that address. No ETH is needed: the facilitator submits each transfer. 0.05 USDC is enough for seven test runs; 1 USDC is about 6 days of a home.
|
|
36
|
+
4. Ask the agent to run something: "run `print(2 + 2)` on Charter".
|
|
37
|
+
|
|
38
|
+
Until the wallet is funded the free tools work and the paid ones answer with the reason; `charter_wallet` gives the address to fund.
|
|
39
|
+
|
|
40
|
+
## Tools
|
|
41
|
+
|
|
42
|
+
| tool | cost | what it does |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `charter_offers` | free | the machines on sale now, with price, size and images |
|
|
45
|
+
| `charter_wallet` | free | the wallet address, its USDC balance, the caps, today's spend |
|
|
46
|
+
| `charter_run_python` | one interval | runs a Python script and returns its output |
|
|
47
|
+
| `charter_fetch_pages` | one interval | loads up to five pages and returns their text |
|
|
48
|
+
| `charter_rent_home` | one interval | opens a Linux home with your SSH public keys |
|
|
49
|
+
| `charter_lease` | free | a lease's state, paid time left, SSH address, finished output |
|
|
50
|
+
| `charter_extend` | one interval each | pays the next 1 to 24 intervals of a running lease |
|
|
51
|
+
|
|
52
|
+
A job tool waits up to 40 seconds by default, under most clients' tool timeout. A job still running then hands back its `leaseId`, and `charter_lease` collects the output for free.
|
|
53
|
+
|
|
54
|
+
## What bounds the money
|
|
55
|
+
|
|
56
|
+
- The server signs only `exact` payments in USDC on Base, to the payee Charter's door names at `GET /v1/door`. Anything else a 402 offers is never signed.
|
|
57
|
+
- It reads the price first and never signs for more than that price, whatever the 402 then asks.
|
|
58
|
+
- `CHARTER_MAX_USDC_PER_HOUR` (default `0.01`): a dearer interval is never signed.
|
|
59
|
+
- `CHARTER_MAX_USDC_PER_DAY` (default `0.25`): the most one UTC day may cost. The count is kept in `~/.charter/mcp-spend.json`, under a lock, so a restart or a second client on the same machine does not reset it. A damaged file stops payments until you delete it.
|
|
60
|
+
- A call is counted against the day unless no payment was signed, or the signed payment was turned down with a 402 (an empty wallet, most often). So a call refused as `busy` after signing is counted although it never settles: the count errs toward having spent.
|
|
61
|
+
- It talks to the door's own address only, follows no redirect, and gives up on a request after 30 seconds (90 for a paid one).
|
|
62
|
+
- Every paid tool's description starts with `PAID` and names the price, so a client that asks before a tool call shows it.
|
|
63
|
+
- What the caps do not do: bind a door that lies about a refusal. Against that the bound is the wallet's balance. Keep only what the rent needs in this wallet; the key is a plain file.
|
|
64
|
+
|
|
65
|
+
Other settings: `CHARTER_MCP_KEY_FILE`, `CHARTER_MCP_SPEND_FILE`, `CHARTER_MCP_NO_NEW_KEY` (never make a key; paid tools stay off without one), `CHARTER_BASE_RPC`, `CHARTER_DOOR_URL`.
|
|
66
|
+
|
|
67
|
+
## Read this before renting a home
|
|
68
|
+
|
|
69
|
+
- SSH is reachable only at an onion address on the Anyone network. Whoever logs in needs an Anyone client: `ssh -o ProxyCommand="nc -x 127.0.0.1:<SOCKS port> %h %p" tenant@<host>`.
|
|
70
|
+
- The box has no public address and all its traffic leaves through Anyone: slow, and some services refuse shared exits.
|
|
71
|
+
- No root. 1 GiB of memory. The live host has two home slots; an open answers `busy` when both are taken.
|
|
72
|
+
- The operator of the host can read the disk. Secrets go in over `scp`, never through Charter.
|
|
73
|
+
- A home that is not paid closes; its disk and address are kept 7 days and the same keys open it again.
|
|
74
|
+
|
|
75
|
+
The full procedure is at [charter.mainnet.toonprotocol.dev/agents](https://charter.mainnet.toonprotocol.dev/agents).
|
|
76
|
+
|
|
77
|
+
## Status
|
|
78
|
+
|
|
79
|
+
One host, run by the project, live on Base mainnet since 2026-10-17. No uptime figure. Charter runs on [TOON](https://toon.ar.io/): ILP routes each packet, x402 settles it. MIT.
|
|
80
|
+
|
|
81
|
+
## Develop
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm install
|
|
85
|
+
npm test
|
|
86
|
+
npm run build
|
|
87
|
+
node scripts/smoke.mjs --free
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`node scripts/smoke.mjs` without `--free` also makes one paid call from the wallet in the key file.
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the Charter MCP server does, with the network, the clock and the disk handed in so every rule
|
|
3
|
+
* here is tested without a door or a wallet (server.ts wires the real ones).
|
|
4
|
+
*
|
|
5
|
+
* The money rules, all in this file:
|
|
6
|
+
* - only `exact` in USDC on Base, to the payee the door itself names, is ever signed (onlyDoorExact);
|
|
7
|
+
* - one hour never costs more than `maxHour` (a dearer 402 is not signed);
|
|
8
|
+
* - a payment is never signed for more than the price read before the call (the reservation);
|
|
9
|
+
* - one UTC day never costs more than `maxDay`. The amount is reserved before a payment and given
|
|
10
|
+
* back only when no payment was signed, or when the signed payment was refused with a 402. Any other
|
|
11
|
+
* answer after signing keeps the reservation, so the book errs toward having spent.
|
|
12
|
+
*
|
|
13
|
+
* What the caps do not do: bind a door that lies. A door that answers 402 and settles anyway is bounded
|
|
14
|
+
* by the wallet's balance, not by this book. Keep the wallet small.
|
|
15
|
+
*/
|
|
16
|
+
export const BASE = 'eip155:8453';
|
|
17
|
+
export const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
|
|
18
|
+
export const DEFAULT_DOOR = 'https://charter.mainnet.toonprotocol.dev';
|
|
19
|
+
export const LEASE_ID = /^[0-9a-f]{32}$/;
|
|
20
|
+
/** Longest text handed back for one page or one stream, so a tool answer stays readable. */
|
|
21
|
+
export const MAX_TEXT = 20_000;
|
|
22
|
+
/** The most output parts and bytes read for one lease, whatever the door says there are. */
|
|
23
|
+
export const MAX_PARTS = 64;
|
|
24
|
+
export const MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
25
|
+
/** Between two looks at a lease: the door caches a status for 5 s and each fresh look costs it a paid read. */
|
|
26
|
+
export const POLL_MS = 5_000;
|
|
27
|
+
/** A paid call that failed without an answer. `signed` says whether a signed payment had already left. */
|
|
28
|
+
export class PayError extends Error {
|
|
29
|
+
signed;
|
|
30
|
+
constructor(message, signed) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.signed = signed;
|
|
33
|
+
this.name = 'PayError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** A decimal USDC amount as micro-USDC. Throws on anything that is not a plain non-negative decimal. */
|
|
37
|
+
export function usdcToMicro(s) {
|
|
38
|
+
const m = /^(\d{1,9})(?:\.(\d{1,6}))?$/.exec(s.trim());
|
|
39
|
+
if (!m)
|
|
40
|
+
throw new Error(`not a USDC amount: ${JSON.stringify(s)} (use a decimal such as 0.25)`);
|
|
41
|
+
return BigInt(m[1]) * 1000000n + BigInt((m[2] ?? '').padEnd(6, '0'));
|
|
42
|
+
}
|
|
43
|
+
export function microToUsdc(micro) {
|
|
44
|
+
const n = BigInt(micro);
|
|
45
|
+
const frac = (n % 1000000n).toString().padStart(6, '0').replace(/0+$/, '');
|
|
46
|
+
return `${n / 1000000n}${frac ? `.${frac}` : ''}`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The payment policy: of what a 402 offers, only `exact` in USDC on Base, to the door's own payee, at
|
|
50
|
+
* no more than `maxHour`. Nothing left means nothing is signed.
|
|
51
|
+
*/
|
|
52
|
+
export function onlyDoorExact(payTo, maxHour) {
|
|
53
|
+
return (_version, reqs) => reqs.filter((r) => r.scheme === 'exact' &&
|
|
54
|
+
r.network === BASE &&
|
|
55
|
+
String(r.asset).toLowerCase() === BASE_USDC.toLowerCase() &&
|
|
56
|
+
String(r.payTo).toLowerCase() === payTo.toLowerCase() &&
|
|
57
|
+
/^\d+$/.test(String(r.amount)) &&
|
|
58
|
+
BigInt(String(r.amount)) <= maxHour);
|
|
59
|
+
}
|
|
60
|
+
export class CapError extends Error {
|
|
61
|
+
}
|
|
62
|
+
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
63
|
+
/** A price as the door states it: whole micro-USDC, more than nothing. Anything else is refused before a payment. */
|
|
64
|
+
export function price(raw) {
|
|
65
|
+
const t = String(raw ?? '');
|
|
66
|
+
if (!/^\d{1,12}$/.test(t) || BigInt(t) <= 0n)
|
|
67
|
+
throw new Error(`the door states no usable price (${JSON.stringify(raw)}); nothing was paid`);
|
|
68
|
+
return BigInt(t);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Reserves `micro` against today's cap, then runs `pay` with `micro` as the most it may sign. The
|
|
72
|
+
* reservation is given back only when nothing was signed, or the signed payment was refused with a 402.
|
|
73
|
+
*/
|
|
74
|
+
async function capped(d, micro, pay) {
|
|
75
|
+
const today = day(d.now());
|
|
76
|
+
if (!d.spend.reserve(today, micro)) {
|
|
77
|
+
throw new CapError(`the day's cap is reached: ${microToUsdc(d.spend.spent(today))} of ${microToUsdc(d.spend.maxDay)} USDC spent today (UTC) and this call costs ${microToUsdc(micro)}. The operator raises it with CHARTER_MAX_USDC_PER_DAY.`);
|
|
78
|
+
}
|
|
79
|
+
let r;
|
|
80
|
+
try {
|
|
81
|
+
r = await pay(micro);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (e instanceof PayError && !e.signed)
|
|
85
|
+
d.spend.release(today, micro);
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
if (r.status !== 200 && (r.signed === false || (r.status === 402 && !r.tx)))
|
|
89
|
+
d.spend.release(today, micro);
|
|
90
|
+
return r;
|
|
91
|
+
}
|
|
92
|
+
const IMAGE_OF = (job) => 'python' in job ? 'charter-job-python' : 'urls' in job ? 'charter-job-fetch' : (job.home.image ?? 'charter-home');
|
|
93
|
+
/** The cheapest live offer that runs the job, as the door itself would pick. */
|
|
94
|
+
export async function cheapestOffer(d, job) {
|
|
95
|
+
const r = await d.get('/v1/offers');
|
|
96
|
+
if (r.status !== 200 || !Array.isArray(r.body))
|
|
97
|
+
throw new Error(`GET /v1/offers answered ${r.status}: cannot read the price, nothing paid`);
|
|
98
|
+
const image = IMAGE_OF(job);
|
|
99
|
+
const fits = r.body.filter((o) => Array.isArray(o?.images) && o.images.includes(image) && /^\d{1,12}$/.test(String(o.tickPrice)) && BigInt(o.tickPrice) > 0n);
|
|
100
|
+
if (fits.length === 0)
|
|
101
|
+
throw new Error(`no machine on sale runs ${image} right now (GET /v1/offers lists ${r.body.length}). Try again later; nothing was paid.`);
|
|
102
|
+
return fits.reduce((a, b) => (BigInt(b.tickPrice) < BigInt(a.tickPrice) ? b : a));
|
|
103
|
+
}
|
|
104
|
+
function needWallet(d) {
|
|
105
|
+
if (!d.pay)
|
|
106
|
+
throw new Error('this server has no wallet key, so the paid tools are off. Call charter_wallet to see why.');
|
|
107
|
+
return d.pay;
|
|
108
|
+
}
|
|
109
|
+
function refusal(what, r) {
|
|
110
|
+
const error = typeof r.body?.error === 'string' ? r.body.error : `status ${r.status}`;
|
|
111
|
+
const why = r.status === 402
|
|
112
|
+
? `the wallet's payment was turned down${r.reason ? ` (${r.reason})` : ''}. Most often the wallet holds too little USDC on Base: call charter_wallet for the balance and the address to fund`
|
|
113
|
+
: error === 'busy'
|
|
114
|
+
? 'the machine is busy (every slot is taken). Try again in a few minutes'
|
|
115
|
+
: error === 'payer_blocked'
|
|
116
|
+
? 'this wallet is blocked by the door because an earlier payment from it failed to settle'
|
|
117
|
+
: error;
|
|
118
|
+
const unpaid = r.body?.leaseId ? ` The lease ${r.body.leaseId} exists unpaid and lapses by itself in 90 seconds.` : '';
|
|
119
|
+
return new Error(`${what} was refused: ${why}. A refused call never settles, so nothing was charged.${unpaid}`);
|
|
120
|
+
}
|
|
121
|
+
/** Opens a lease and pays its first interval: one paid call. */
|
|
122
|
+
export async function rent(d, job) {
|
|
123
|
+
const pay = needWallet(d);
|
|
124
|
+
const offer = await cheapestOffer(d, job);
|
|
125
|
+
const cost = price(offer.tickPrice);
|
|
126
|
+
if (cost > d.maxHour) {
|
|
127
|
+
throw new CapError(`one interval costs ${microToUsdc(cost)} USDC, over this server's cap of ${microToUsdc(d.maxHour)} (CHARTER_MAX_USDC_PER_HOUR). Nothing was paid.`);
|
|
128
|
+
}
|
|
129
|
+
const r = await capped(d, cost, (limit) => pay('/v1/rent', { ...job, offerId: offer.offerId }, limit));
|
|
130
|
+
if (r.status !== 200 || !LEASE_ID.test(String(r.body?.leaseId)))
|
|
131
|
+
throw refusal('the rent', r);
|
|
132
|
+
return {
|
|
133
|
+
leaseId: r.body.leaseId,
|
|
134
|
+
offerId: offer.offerId,
|
|
135
|
+
paidUsdc: microToUsdc(cost),
|
|
136
|
+
paidThrough: iso(r.body.paidThrough),
|
|
137
|
+
...(r.tx ? { tx: r.tx } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const iso = (ms) => (typeof ms === 'number' && Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 19) + 'Z' : 'unknown');
|
|
141
|
+
const cut = (s) => {
|
|
142
|
+
const t = typeof s === 'string' ? s : '';
|
|
143
|
+
return t.length > MAX_TEXT ? `${t.slice(0, MAX_TEXT)}\n[cut: ${t.length - MAX_TEXT} more characters]` : t;
|
|
144
|
+
};
|
|
145
|
+
/** A free read of a lease. */
|
|
146
|
+
export async function lease(d, leaseId) {
|
|
147
|
+
if (!LEASE_ID.test(leaseId))
|
|
148
|
+
throw new Error('a leaseId is 32 lowercase hex characters');
|
|
149
|
+
const r = await d.get(`/v1/leases/${leaseId}`);
|
|
150
|
+
if (r.status === 404)
|
|
151
|
+
throw new Error('the door does not know this lease (only a lease opened through the door can be read here)');
|
|
152
|
+
if (r.status === 429)
|
|
153
|
+
throw new Error('the door is rate limiting reads of this lease. Wait a minute and ask again.');
|
|
154
|
+
const l = r.body?.lease;
|
|
155
|
+
if (r.status !== 200 || !l)
|
|
156
|
+
throw new Error(`the status read answered ${r.status}`);
|
|
157
|
+
const through = typeof l.paidThrough === 'number' ? l.paidThrough : undefined;
|
|
158
|
+
const ssh = l.access?.ssh;
|
|
159
|
+
const view = {
|
|
160
|
+
leaseId,
|
|
161
|
+
state: String(l.state),
|
|
162
|
+
...(l.closedReason ? { closedReason: String(l.closedReason) } : {}),
|
|
163
|
+
paidIntervals: Number(l.paidIntervals ?? 0),
|
|
164
|
+
paidThrough: iso(through),
|
|
165
|
+
minutesLeft: through === undefined ? null : Math.round((through - d.now()) / 60_000),
|
|
166
|
+
...(ssh?.host
|
|
167
|
+
? {
|
|
168
|
+
ssh: {
|
|
169
|
+
host: String(ssh.host),
|
|
170
|
+
port: Number(ssh.port ?? 22),
|
|
171
|
+
user: String(ssh.user ?? 'tenant'),
|
|
172
|
+
how: 'The host is an onion address on the Anyone network. With an Anyone client running: ssh -o ProxyCommand="nc -x 127.0.0.1:<its SOCKS port> %h %p" tenant@<host>. No Anyone client, no way in.',
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
: {}),
|
|
176
|
+
outputParts: Number.isSafeInteger(l.outputParts) && l.outputParts > 0 ? l.outputParts : 0,
|
|
177
|
+
...(r.body.stopped ? { note: 'stopped by the door' } : {}),
|
|
178
|
+
};
|
|
179
|
+
return { view, raw: r.body };
|
|
180
|
+
}
|
|
181
|
+
/** A finished job's output, decoded: a python job's streams and exit code, or a fetch job's pages without the screenshots. */
|
|
182
|
+
export async function output(d, leaseId, parts) {
|
|
183
|
+
if (!Number.isSafeInteger(parts) || parts < 1 || parts > MAX_PARTS)
|
|
184
|
+
throw new Error(`the lease names ${parts} output parts; at most ${MAX_PARTS} are read`);
|
|
185
|
+
const chunks = [];
|
|
186
|
+
let bytes = 0;
|
|
187
|
+
for (let n = 0; n < parts; n++) {
|
|
188
|
+
const r = await d.get(`/v1/leases/${leaseId}/output/${n}`);
|
|
189
|
+
if (r.status !== 200 || typeof r.body?.data !== 'string')
|
|
190
|
+
throw new Error(`output part ${n} answered ${r.status}`);
|
|
191
|
+
const chunk = Buffer.from(r.body.data, 'base64');
|
|
192
|
+
bytes += chunk.length;
|
|
193
|
+
if (bytes > MAX_OUTPUT_BYTES)
|
|
194
|
+
throw new Error(`the output is over ${MAX_OUTPUT_BYTES} bytes; not read further`);
|
|
195
|
+
chunks.push(chunk);
|
|
196
|
+
}
|
|
197
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
198
|
+
let out;
|
|
199
|
+
try {
|
|
200
|
+
out = JSON.parse(text);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return { raw: cut(text) };
|
|
204
|
+
}
|
|
205
|
+
if (Array.isArray(out?.pages)) {
|
|
206
|
+
return {
|
|
207
|
+
pages: out.pages.map((p) => ({
|
|
208
|
+
url: p.url,
|
|
209
|
+
...(p.error ? { error: p.error } : {}),
|
|
210
|
+
text: cut(p.text),
|
|
211
|
+
screenshot: p.jpegBase64 ? 'taken (not returned here; it is in the raw output part)' : 'none',
|
|
212
|
+
})),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
if (out && typeof out === 'object' && ('stdout' in out || 'exitCode' in out)) {
|
|
216
|
+
const { stdout, stderr, ...rest } = out;
|
|
217
|
+
return { ...rest, stdout: cut(stdout), stderr: cut(stderr) };
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
/** Rents a python or fetch job, waits for it to finish (it has one paid hour), and hands back the output. */
|
|
222
|
+
export async function runJob(d, job, waitSeconds) {
|
|
223
|
+
const rented = await rent(d, job);
|
|
224
|
+
const until = d.now() + waitSeconds * 1000;
|
|
225
|
+
let seen;
|
|
226
|
+
let lastError = '';
|
|
227
|
+
while (d.now() < until) {
|
|
228
|
+
await d.sleep(POLL_MS);
|
|
229
|
+
try {
|
|
230
|
+
seen = (await lease(d, rented.leaseId)).view;
|
|
231
|
+
if (seen.state === 'done' || seen.state === 'closed')
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
// One failed look does not end the wait: the lease is paid and the job is running.
|
|
236
|
+
lastError = e.message;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (!seen) {
|
|
240
|
+
return {
|
|
241
|
+
rented,
|
|
242
|
+
lease: { leaseId: rented.leaseId, state: 'unknown', paidIntervals: 1, paidThrough: rented.paidThrough, minutesLeft: null, outputParts: 0 },
|
|
243
|
+
next: `The lease is paid but its state could not be read (${lastError || 'no answer'}). Call charter_lease with this leaseId; it costs nothing.`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
if (seen.state !== 'done' && seen.state !== 'closed') {
|
|
247
|
+
return { rented, lease: seen, next: 'Still running. Call charter_lease with this leaseId to collect the output; it costs nothing and the hour is already paid.' };
|
|
248
|
+
}
|
|
249
|
+
if (seen.outputParts === 0)
|
|
250
|
+
return { rented, lease: seen, next: `The lease ended with no output (${seen.closedReason ?? seen.state}).` };
|
|
251
|
+
return { rented, lease: seen, output: await output(d, rented.leaseId, seen.outputParts) };
|
|
252
|
+
}
|
|
253
|
+
/** Pays the next `hours` intervals of a running lease, one payment each, in order. Stops at the first refusal. */
|
|
254
|
+
export async function extend(d, leaseId, hours) {
|
|
255
|
+
const pay = needWallet(d);
|
|
256
|
+
const first = await lease(d, leaseId);
|
|
257
|
+
if (first.view.state === 'done' || first.view.state === 'closed') {
|
|
258
|
+
throw new Error(`the lease is over (${first.view.closedReason ?? first.view.state}); nothing to extend and nothing was paid. A home opens again with the same keys.`);
|
|
259
|
+
}
|
|
260
|
+
const cost = price(first.raw.offer?.tickPrice);
|
|
261
|
+
if (cost > d.maxHour)
|
|
262
|
+
throw new CapError(`one interval costs ${microToUsdc(cost)} USDC, over this server's cap of ${microToUsdc(d.maxHour)}. Nothing was paid.`);
|
|
263
|
+
let index = first.view.paidIntervals;
|
|
264
|
+
let paid = 0;
|
|
265
|
+
let through = first.view.paidThrough;
|
|
266
|
+
const txs = [];
|
|
267
|
+
let stopped;
|
|
268
|
+
for (; paid < hours; paid++, index++) {
|
|
269
|
+
let r;
|
|
270
|
+
try {
|
|
271
|
+
r = await capped(d, cost, (limit) => pay(`/v1/leases/${leaseId}/ticks`, { index }, limit));
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
if (paid === 0)
|
|
275
|
+
throw e;
|
|
276
|
+
stopped = e.message;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
if (r.status !== 200) {
|
|
280
|
+
if (paid === 0)
|
|
281
|
+
throw refusal('the payment', r);
|
|
282
|
+
stopped = refusal('the next payment', r).message;
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
if (r.tx)
|
|
286
|
+
txs.push(r.tx);
|
|
287
|
+
through = iso(r.body?.paidThrough);
|
|
288
|
+
}
|
|
289
|
+
return { leaseId, hoursPaid: paid, paidUsdc: microToUsdc(cost * BigInt(paid)), paidThrough: through, txs, ...(stopped ? { stopped } : {}) };
|
|
290
|
+
}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { run, VERSION } from './server.js';
|
|
3
|
+
const arg = process.argv[2];
|
|
4
|
+
if (arg === '--version' || arg === '-v') {
|
|
5
|
+
console.log(VERSION);
|
|
6
|
+
}
|
|
7
|
+
else if (arg === '--help' || arg === '-h') {
|
|
8
|
+
console.log(`charter-mcp ${VERSION}: an MCP server (stdio) that rents Charter machines and pays for them in USDC on Base.
|
|
9
|
+
|
|
10
|
+
claude mcp add charter -- npx -y charter-mcp
|
|
11
|
+
|
|
12
|
+
Environment, all optional:
|
|
13
|
+
CHARTER_MAX_USDC_PER_HOUR the most one interval may cost (default 0.01)
|
|
14
|
+
CHARTER_MAX_USDC_PER_DAY the most one UTC day may cost (default 0.25)
|
|
15
|
+
CHARTER_MCP_KEY_FILE the wallet key file (default ~/.charter/mcp.key, made on first run)
|
|
16
|
+
CHARTER_MCP_NO_NEW_KEY set to never make a key: with no key file the paid tools stay off
|
|
17
|
+
CHARTER_MCP_SPEND_FILE where the day's spend is kept (default ~/.charter/mcp-spend.json)
|
|
18
|
+
CHARTER_BASE_RPC Base RPC for the balance read
|
|
19
|
+
CHARTER_DOOR_URL the door (default https://charter.mainnet.toonprotocol.dev)
|
|
20
|
+
|
|
21
|
+
Docs: https://charter.mainnet.toonprotocol.dev/agents`);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
run(process.env).catch((e) => {
|
|
25
|
+
process.stderr.write(`charter-mcp: ${String(e?.message ?? e)}\n`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
});
|
|
28
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Charter MCP server, over stdio: the tools an agent needs to rent a machine and pay for it itself.
|
|
3
|
+
*
|
|
4
|
+
* An MCP client cannot sign an x402 payment, so this process runs beside it, holds one Base key in a
|
|
5
|
+
* file (USDC only; no ETH, the facilitator submits each transfer) and pays Charter's door once per paid
|
|
6
|
+
* tool call. The rules that bound the money are in core.ts.
|
|
7
|
+
*
|
|
8
|
+
* stdout belongs to the MCP transport; every log line here goes to stderr.
|
|
9
|
+
*/
|
|
10
|
+
import { randomBytes } from 'node:crypto';
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
15
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
16
|
+
import { ExactEvmScheme } from '@x402/evm/exact/client';
|
|
17
|
+
import { decodePaymentResponseHeader, wrapFetchWithPaymentFromConfig } from '@x402/fetch';
|
|
18
|
+
import { createPublicClient, erc20Abi, http } from 'viem';
|
|
19
|
+
import { privateKeyToAccount } from 'viem/accounts';
|
|
20
|
+
import { base } from 'viem/chains';
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
import { BASE, BASE_USDC, CapError, DEFAULT_DOOR, PayError, extend, lease, microToUsdc, onlyDoorExact, output, rent, runJob, usdcToMicro, } from './core.js';
|
|
23
|
+
export const VERSION = '0.1.0';
|
|
24
|
+
export function optionsFromEnv(env) {
|
|
25
|
+
const dir = join(homedir(), '.charter');
|
|
26
|
+
const v = (k) => env[k]?.trim() || undefined;
|
|
27
|
+
return {
|
|
28
|
+
door: (v('CHARTER_DOOR_URL') ?? DEFAULT_DOOR).replace(/\/+$/, ''),
|
|
29
|
+
keyFile: v('CHARTER_MCP_KEY_FILE') ?? join(dir, 'mcp.key'),
|
|
30
|
+
spendFile: v('CHARTER_MCP_SPEND_FILE') ?? join(dir, 'mcp-spend.json'),
|
|
31
|
+
maxHour: usdcToMicro(v('CHARTER_MAX_USDC_PER_HOUR') ?? '0.01'),
|
|
32
|
+
maxDay: usdcToMicro(v('CHARTER_MAX_USDC_PER_DAY') ?? '0.25'),
|
|
33
|
+
...(v('CHARTER_BASE_RPC') ? { baseRpc: v('CHARTER_BASE_RPC') } : {}),
|
|
34
|
+
makeKey: v('CHARTER_MCP_NO_NEW_KEY') === undefined,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const KEY = /^0x[0-9a-fA-F]{64}$/;
|
|
38
|
+
const GET_TIMEOUT_MS = 30_000;
|
|
39
|
+
/** A rent waits for the host to open the lease over an onion hop, which has taken 15 s and more. */
|
|
40
|
+
const PAY_TIMEOUT_MS = 90_000;
|
|
41
|
+
/** The key in the file; made first (mode 600, never overwriting) when the file is absent and `make` is set. */
|
|
42
|
+
export function loadKey(file, make) {
|
|
43
|
+
if (!existsSync(file)) {
|
|
44
|
+
if (!make)
|
|
45
|
+
return undefined;
|
|
46
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
47
|
+
try {
|
|
48
|
+
writeFileSync(file, `0x${randomBytes(32).toString('hex')}\n`, { mode: 0o600, flag: 'wx' });
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
// Another server started at the same moment and made it first: use that one.
|
|
52
|
+
if (e.code !== 'EEXIST')
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const key = readFileSync(file, 'utf8').trim();
|
|
57
|
+
if (!KEY.test(key))
|
|
58
|
+
throw new Error(`${file} must hold one private key: 0x and 64 hex digits`);
|
|
59
|
+
return key;
|
|
60
|
+
}
|
|
61
|
+
const LOCK_WAIT_MS = 3_000;
|
|
62
|
+
const LOCK_STALE_MS = 10_000;
|
|
63
|
+
/** Runs `fn` holding `<file>.lock` (a directory, so making it is atomic), since two MCP clients may run two servers on one book. */
|
|
64
|
+
function locked(file, fn) {
|
|
65
|
+
const lock = `${file}.lock`;
|
|
66
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
67
|
+
const until = Date.now() + LOCK_WAIT_MS;
|
|
68
|
+
for (;;) {
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(lock);
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
if (e.code !== 'EEXIST')
|
|
75
|
+
throw e;
|
|
76
|
+
try {
|
|
77
|
+
// A server killed while holding it must not block the book for good.
|
|
78
|
+
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
|
|
79
|
+
rmdirSync(lock);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// Gone already: try again.
|
|
83
|
+
}
|
|
84
|
+
if (Date.now() > until)
|
|
85
|
+
throw new CapError(`the spend book ${file} is locked by another server; nothing was paid. Try again.`);
|
|
86
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
return fn();
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
try {
|
|
94
|
+
rmdirSync(lock);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
// Removed as stale by another server: nothing to undo.
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The day's spend in one small JSON file, changed only under a lock and rewritten whole. A file that
|
|
103
|
+
* exists but cannot be read is an error, never "nothing spent": a damaged book must not reopen the cap.
|
|
104
|
+
*/
|
|
105
|
+
export function fileSpendBook(file, maxDay) {
|
|
106
|
+
const read = () => {
|
|
107
|
+
let raw;
|
|
108
|
+
try {
|
|
109
|
+
raw = readFileSync(file, 'utf8');
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
if (e.code === 'ENOENT')
|
|
113
|
+
return {};
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
let o;
|
|
117
|
+
try {
|
|
118
|
+
o = JSON.parse(raw);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
o = undefined;
|
|
122
|
+
}
|
|
123
|
+
if (!o || typeof o !== 'object' || Array.isArray(o) || Object.values(o).some((v) => typeof v !== 'string' || !/^\d{1,15}$/.test(v))) {
|
|
124
|
+
throw new CapError(`the spend book ${file} is damaged, so today's spend is unknown and nothing is paid. Delete the file to start the day's count again.`);
|
|
125
|
+
}
|
|
126
|
+
return o;
|
|
127
|
+
};
|
|
128
|
+
const of = (o, d) => (typeof o[d] === 'string' ? BigInt(o[d]) : 0n);
|
|
129
|
+
const write = (d, total) => {
|
|
130
|
+
// Only today is kept: yesterday's total bounds nothing.
|
|
131
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
132
|
+
writeFileSync(tmp, JSON.stringify({ [d]: (total < 0n ? 0n : total).toString() }), { mode: 0o600 });
|
|
133
|
+
renameSync(tmp, file);
|
|
134
|
+
};
|
|
135
|
+
return {
|
|
136
|
+
maxDay,
|
|
137
|
+
spent: (d) => of(read(), d),
|
|
138
|
+
reserve: (d, micro) => locked(file, () => {
|
|
139
|
+
const next = of(read(), d) + micro;
|
|
140
|
+
if (micro < 0n || next > maxDay)
|
|
141
|
+
return false;
|
|
142
|
+
write(d, next);
|
|
143
|
+
return true;
|
|
144
|
+
}),
|
|
145
|
+
release: (d, micro) => locked(file, () => write(d, of(read(), d) - micro)),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
async function body(res) {
|
|
149
|
+
const text = await res.text();
|
|
150
|
+
try {
|
|
151
|
+
return JSON.parse(text);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return { raw: text.slice(0, 200) };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const text = (o) => ({ content: [{ type: 'text', text: typeof o === 'string' ? o : JSON.stringify(o, null, 2) }] });
|
|
158
|
+
const fail = (e) => ({ content: [{ type: 'text', text: `Error: ${e?.message ?? String(e)}` }], isError: true });
|
|
159
|
+
const SSH_KEY = /^(ssh-ed25519|ecdsa-sha2-nistp(256|384|521)|ssh-rsa) [A-Za-z0-9+/=]+( .*)?$/;
|
|
160
|
+
/** The server with its tools, not yet connected to a transport. `fetchFn` is the network (a test hands in a fake door). */
|
|
161
|
+
export function build(o, log, fetchFn = fetch) {
|
|
162
|
+
const key = loadKey(o.keyFile, o.makeKey);
|
|
163
|
+
const account = key ? privateKeyToAccount(key) : undefined;
|
|
164
|
+
const spend = fileSpendBook(o.spendFile, o.maxDay);
|
|
165
|
+
const origin = new URL(o.door).origin;
|
|
166
|
+
const agent = { 'user-agent': `charter-mcp/${VERSION}` };
|
|
167
|
+
/**
|
|
168
|
+
* Every request this server makes: to the door's own origin only, never following a redirect (a
|
|
169
|
+
* redirect could carry a signed payment to another host), and never waiting for ever.
|
|
170
|
+
*/
|
|
171
|
+
const guarded = (ms, onSend) => (async (input, init) => {
|
|
172
|
+
const req = new Request(input, init);
|
|
173
|
+
if (new URL(req.url).origin !== origin)
|
|
174
|
+
throw new Error(`refusing a request to ${new URL(req.url).origin}: this server talks to ${origin} only`);
|
|
175
|
+
onSend?.(req.headers.has('payment-signature') || req.headers.has('x-payment'));
|
|
176
|
+
return fetchFn(new Request(req, { redirect: 'error', signal: AbortSignal.timeout(ms) }));
|
|
177
|
+
});
|
|
178
|
+
const get = async (path) => {
|
|
179
|
+
const res = await guarded(GET_TIMEOUT_MS)(`${o.door}${path}`, { headers: agent });
|
|
180
|
+
return { status: res.status, body: await body(res) };
|
|
181
|
+
};
|
|
182
|
+
// Where payments go is read from the door once, and nothing is signed until it is known.
|
|
183
|
+
let payee;
|
|
184
|
+
const payTo = () => (payee ??= (async () => {
|
|
185
|
+
const info = await get('/v1/door');
|
|
186
|
+
if (info.status !== 200 || !/^0x[0-9a-fA-F]{40}$/.test(info.body?.payTo ?? '') || info.body.network !== BASE) {
|
|
187
|
+
throw new Error(`GET /v1/door answered ${info.status}: cannot tell where payments go, nothing signed`);
|
|
188
|
+
}
|
|
189
|
+
return info.body.payTo;
|
|
190
|
+
})().catch((e) => {
|
|
191
|
+
payee = undefined;
|
|
192
|
+
throw e;
|
|
193
|
+
}));
|
|
194
|
+
const pay = async (path, json, limit) => {
|
|
195
|
+
let signed = false;
|
|
196
|
+
let res;
|
|
197
|
+
try {
|
|
198
|
+
const to = await payTo();
|
|
199
|
+
// One client a call, so each signs at most what this call reserved (and never over the hourly cap).
|
|
200
|
+
const paidFetch = wrapFetchWithPaymentFromConfig(guarded(PAY_TIMEOUT_MS, (s) => void (signed ||= s)), {
|
|
201
|
+
schemes: [{ network: BASE, client: new ExactEvmScheme(account) }],
|
|
202
|
+
policies: [onlyDoorExact(to, limit < o.maxHour ? limit : o.maxHour)],
|
|
203
|
+
});
|
|
204
|
+
res = await paidFetch(`${o.door}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', ...agent }, body: JSON.stringify(json) });
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
log(`paid call ${path} failed ${signed ? 'after' : 'before'} a payment was signed: ${String(e?.message ?? e).slice(0, 160)}`);
|
|
208
|
+
throw new PayError(`${String(e?.message ?? e).slice(0, 300)}. ${signed ? 'A signed payment had left, so it is counted against the day in case it settles.' : 'No payment was signed; nothing was charged.'}`, signed);
|
|
209
|
+
}
|
|
210
|
+
const out = { status: res.status, body: await body(res), signed };
|
|
211
|
+
const receipt = res.headers.get('payment-response');
|
|
212
|
+
if (receipt) {
|
|
213
|
+
try {
|
|
214
|
+
const d = decodePaymentResponseHeader(receipt);
|
|
215
|
+
if (d.transaction)
|
|
216
|
+
out.tx = d.transaction;
|
|
217
|
+
if (d.errorReason)
|
|
218
|
+
out.reason = d.errorReason;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
// A receipt that does not decode changes nothing about the answer.
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// An x402 v2 refusal says why in the 402's own header, not the body.
|
|
225
|
+
const refusal = res.status === 402 ? res.headers.get('payment-required') : null;
|
|
226
|
+
if (refusal && !out.reason) {
|
|
227
|
+
try {
|
|
228
|
+
const d = JSON.parse(Buffer.from(refusal, 'base64').toString('utf8'));
|
|
229
|
+
if (typeof d.error === 'string')
|
|
230
|
+
out.reason = d.error.slice(0, 120);
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// No reason to show.
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
log(`paid call ${path} -> ${out.status}${out.tx ? ` tx ${out.tx}` : ''}${out.reason ? ` (${out.reason})` : ''}`);
|
|
237
|
+
return out;
|
|
238
|
+
};
|
|
239
|
+
const deps = {
|
|
240
|
+
get,
|
|
241
|
+
...(account ? { pay } : {}),
|
|
242
|
+
now: Date.now,
|
|
243
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
244
|
+
spend,
|
|
245
|
+
maxHour: o.maxHour,
|
|
246
|
+
};
|
|
247
|
+
const balance = async () => {
|
|
248
|
+
const client = createPublicClient({ chain: base, transport: http(o.baseRpc) });
|
|
249
|
+
const raw = await client.readContract({ address: BASE_USDC, abi: erc20Abi, functionName: 'balanceOf', args: [account.address] });
|
|
250
|
+
return microToUsdc(raw);
|
|
251
|
+
};
|
|
252
|
+
const caps = () => {
|
|
253
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
254
|
+
return {
|
|
255
|
+
maxUsdcPerHour: microToUsdc(o.maxHour),
|
|
256
|
+
maxUsdcPerDay: microToUsdc(o.maxDay),
|
|
257
|
+
spentTodayUsdc: microToUsdc(spend.spent(today)),
|
|
258
|
+
};
|
|
259
|
+
};
|
|
260
|
+
const server = new McpServer({ name: 'charter', version: VERSION });
|
|
261
|
+
const cost = 'Costs one interval of the cheapest machine: 0.007 USDC on the live host (see charter_offers), paid from this server\'s own wallet in USDC on Base.';
|
|
262
|
+
server.registerTool('charter_offers', {
|
|
263
|
+
title: 'Charter machines on sale',
|
|
264
|
+
description: 'Free. The machines for rent on Charter right now: price per interval in USDC (0.007 an hour on the live host), CPU, memory, the job images each runs, and how many home slots it has. Charter rents a sandboxed machine by the hour with no account: a Python job, a page-fetch job, or a Linux home with SSH. Call this first to see the price before any paid tool.',
|
|
265
|
+
inputSchema: {},
|
|
266
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
267
|
+
}, async () => {
|
|
268
|
+
try {
|
|
269
|
+
const r = await get('/v1/offers');
|
|
270
|
+
if (r.status !== 200 || !Array.isArray(r.body))
|
|
271
|
+
throw new Error(`GET /v1/offers answered ${r.status}`);
|
|
272
|
+
return text({
|
|
273
|
+
offers: r.body.map((x) => ({
|
|
274
|
+
offerId: x.offerId,
|
|
275
|
+
usdcPerInterval: /^\d+$/.test(String(x.tickPrice)) ? microToUsdc(x.tickPrice) : x.tickPrice,
|
|
276
|
+
intervalSeconds: x.intervalSeconds,
|
|
277
|
+
cpu: x.cpu,
|
|
278
|
+
memoryMiB: x.memoryMiB,
|
|
279
|
+
images: x.images,
|
|
280
|
+
home: x.home ?? null,
|
|
281
|
+
})),
|
|
282
|
+
docs: `${o.door}/agents`,
|
|
283
|
+
...caps(),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
return fail(e);
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
server.registerTool('charter_wallet', {
|
|
291
|
+
title: 'Charter payer wallet',
|
|
292
|
+
description: 'Free. The wallet this server pays Charter from: its address, its USDC balance on Base, the spending caps, what has been spent today, and how to fund it. Call this when a paid tool is refused, or to tell your operator where to send USDC.',
|
|
293
|
+
inputSchema: {},
|
|
294
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
295
|
+
}, async () => {
|
|
296
|
+
try {
|
|
297
|
+
if (!account) {
|
|
298
|
+
return text({ address: null, paidTools: 'off', why: `no key at ${o.keyFile} and CHARTER_MCP_NO_NEW_KEY is set. Put a key there (0x and 64 hex digits, mode 600) or unset the variable to have one made.`, ...caps() });
|
|
299
|
+
}
|
|
300
|
+
const usdc = await balance().catch((e) => `unavailable (${e.message.slice(0, 80)})`);
|
|
301
|
+
return text({
|
|
302
|
+
address: account.address,
|
|
303
|
+
usdcOnBase: usdc,
|
|
304
|
+
...caps(),
|
|
305
|
+
keyFile: o.keyFile,
|
|
306
|
+
fund: `Send USDC on Base (chain id 8453, token ${BASE_USDC}) to ${account.address}. No ETH is needed. 0.007 USDC buys one hour; 1 USDC is about 6 days of a home. Keep only what the rent needs in this wallet: the key is a plain file on this machine.`,
|
|
307
|
+
pays: 'Only Charter: exact USDC on Base, to the payee the door names, within the caps above. The operator changes the caps with CHARTER_MAX_USDC_PER_HOUR and CHARTER_MAX_USDC_PER_DAY.',
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
catch (e) {
|
|
311
|
+
return fail(e);
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
server.registerTool('charter_run_python', {
|
|
315
|
+
title: 'Run a Python script on a rented machine',
|
|
316
|
+
description: `PAID. ${cost} Runs your Python 3 script once in a sandbox on a rented machine and returns its stdout, stderr and exit code. NumPy is installed; there is no network and no other package; the script is at most 8 KiB. Most scripts finish in seconds. If it is still running when the wait ends, the leaseId comes back and charter_lease collects the output for free.`,
|
|
317
|
+
inputSchema: {
|
|
318
|
+
script: z.string().min(1).max(8192).describe('the Python 3 source, at most 8192 bytes'),
|
|
319
|
+
waitSeconds: z.number().int().min(10).max(240).optional().describe('how long to wait for the job before handing back the leaseId (default 40, under most clients\' 60 s tool timeout)'),
|
|
320
|
+
},
|
|
321
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
322
|
+
}, async ({ script, waitSeconds }) => {
|
|
323
|
+
try {
|
|
324
|
+
if (Buffer.byteLength(script, 'utf8') > 8192)
|
|
325
|
+
throw new Error('the script is over 8192 bytes; nothing was paid');
|
|
326
|
+
return text(await runJob(deps, { python: { script } }, waitSeconds ?? 40));
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
return fail(e);
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
server.registerTool('charter_fetch_pages', {
|
|
333
|
+
title: 'Fetch pages in a headless browser through a hidden exit',
|
|
334
|
+
description: `PAID. ${cost} Loads up to five http or https pages in a headless browser on a rented machine, through an exit on the Anyone network so the site sees neither you nor the host, and returns each page's text. Useful when a page needs JavaScript or your own address is refused. Slow (a page can take a minute) and some sites refuse shared exits. If it is still running when the wait ends, charter_lease collects the output for free.`,
|
|
335
|
+
inputSchema: {
|
|
336
|
+
urls: z.array(z.string().url().regex(/^https?:\/\//i)).min(1).max(5).describe('one to five http or https URLs'),
|
|
337
|
+
waitSeconds: z.number().int().min(10).max(240).optional().describe('how long to wait for the job before handing back the leaseId (default 40, under most clients\' 60 s tool timeout; pages often need longer, so expect to collect with charter_lease)'),
|
|
338
|
+
},
|
|
339
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
340
|
+
}, async ({ urls, waitSeconds }) => {
|
|
341
|
+
try {
|
|
342
|
+
return text(await runJob(deps, { urls }, waitSeconds ?? 40));
|
|
343
|
+
}
|
|
344
|
+
catch (e) {
|
|
345
|
+
return fail(e);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
server.registerTool('charter_rent_home', {
|
|
349
|
+
title: 'Rent a Linux home with SSH',
|
|
350
|
+
description: `PAID. ${cost} Opens a Linux box of your own (Debian, 1 CPU, 1 GiB memory, a 2 GiB disk kept 7 days after the lease ends, user "tenant", no root) and pays its first interval. Pass 1 to 8 SSH PUBLIC keys; the key set is the home's identity, so the same keys open the same disk again. Read this before renting: SSH is reachable only at an onion address on the Anyone network, so whoever logs in needs an Anyone client; all outbound traffic leaves through Anyone and is slow; the live host has two home slots and an open answers busy when both are taken. After renting, call charter_lease about once a minute until it shows the SSH address, and charter_extend before the paid time runs out.`,
|
|
351
|
+
inputSchema: {
|
|
352
|
+
sshKeys: z.array(z.string().max(1023)).min(1).max(8).describe('SSH public key lines (ssh-ed25519, ecdsa-sha2-nistp256/384/521 or ssh-rsa). Public keys only: never a private key.'),
|
|
353
|
+
image: z.enum(['charter-home', 'charter-hermes']).optional().describe('charter-home (default) is a plain box; charter-hermes has Hermes Agent preinstalled'),
|
|
354
|
+
},
|
|
355
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
356
|
+
}, async ({ sshKeys, image }) => {
|
|
357
|
+
try {
|
|
358
|
+
const keys = sshKeys.map((k) => k.trim());
|
|
359
|
+
const bad = keys.find((k) => !SSH_KEY.test(k));
|
|
360
|
+
if (bad !== undefined) {
|
|
361
|
+
throw new Error(/PRIVATE KEY/.test(bad)
|
|
362
|
+
? 'that is a private key. Pass the PUBLIC key line only (the .pub file); nothing was sent or paid'
|
|
363
|
+
: 'each key must be one public key line starting with ssh-ed25519, ecdsa-sha2-nistp256/384/521 or ssh-rsa; nothing was paid');
|
|
364
|
+
}
|
|
365
|
+
const rented = await rent(deps, { home: { sshKeys: keys, ...(image ? { image } : {}) } });
|
|
366
|
+
return text({
|
|
367
|
+
...rented,
|
|
368
|
+
next: 'Call charter_lease with this leaseId about once a minute until it shows ssh (the onion address is published within about a minute). Pay more time with charter_extend before paidThrough; a home that lapses keeps its disk 7 days and opens again with the same keys.',
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
catch (e) {
|
|
372
|
+
return fail(e);
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
server.registerTool('charter_lease', {
|
|
376
|
+
title: 'Read a Charter lease',
|
|
377
|
+
description: 'Free. The state of a lease opened by this server: running, done or closed, the paid time left, a home\'s SSH address once published, and a finished job\'s output (a Python job\'s stdout, stderr and exit code, or a fetch job\'s page text).',
|
|
378
|
+
inputSchema: { leaseId: z.string().regex(/^[0-9a-f]{32}$/).describe('the 32 hex character leaseId a paid tool returned') },
|
|
379
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
380
|
+
}, async ({ leaseId }) => {
|
|
381
|
+
try {
|
|
382
|
+
const { view } = await lease(deps, leaseId);
|
|
383
|
+
if ((view.state === 'done' || view.state === 'closed') && view.outputParts > 0)
|
|
384
|
+
return text({ lease: view, output: await output(deps, leaseId, view.outputParts) });
|
|
385
|
+
return text({ lease: view });
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
return fail(e);
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
server.registerTool('charter_extend', {
|
|
392
|
+
title: 'Pay more time on a lease',
|
|
393
|
+
description: 'PAID. Pays the next intervals of a running lease, one payment each (0.007 USDC an hour on the live host), from this server\'s wallet. Use it to keep a home running: pay before the paid time runs out, ideally half an hour early. Stops at the first refused payment and reports what was paid. A lease that has closed cannot be extended; a home opens again with the same keys.',
|
|
394
|
+
inputSchema: {
|
|
395
|
+
leaseId: z.string().regex(/^[0-9a-f]{32}$/).describe('the leaseId to pay for'),
|
|
396
|
+
hours: z.number().int().min(1).max(24).describe('how many intervals to pay now, 1 to 24. The door refunds nothing, so pay only what you will use.'),
|
|
397
|
+
},
|
|
398
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
399
|
+
}, async ({ leaseId, hours }) => {
|
|
400
|
+
try {
|
|
401
|
+
return text(await extend(deps, leaseId, hours));
|
|
402
|
+
}
|
|
403
|
+
catch (e) {
|
|
404
|
+
return fail(e);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
return { server, address: account?.address };
|
|
408
|
+
}
|
|
409
|
+
export async function run(env) {
|
|
410
|
+
const log = (line) => void process.stderr.write(`charter-mcp: ${line}\n`);
|
|
411
|
+
const o = optionsFromEnv(env);
|
|
412
|
+
const { server, address } = build(o, log);
|
|
413
|
+
await server.connect(new StdioServerTransport());
|
|
414
|
+
log(`connected: door ${o.door}, wallet ${address ?? 'none (free tools only)'}, at most ${microToUsdc(o.maxHour)} USDC an hour and ${microToUsdc(o.maxDay)} a day`);
|
|
415
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "charter-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server that lets an agent rent a sandboxed machine by the hour on Charter and pay for it itself: run a Python script, fetch pages through a hidden exit, or rent a Linux home with SSH. USDC on Base over x402, no account.",
|
|
5
|
+
"mcpName": "io.github.drew-dot-com/charter",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "Drew Pierson (https://github.com/drew-dot-com)",
|
|
9
|
+
"homepage": "https://charter.mainnet.toonprotocol.dev/agents",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/drew-dot-com/charter.git",
|
|
13
|
+
"directory": "mcp"
|
|
14
|
+
},
|
|
15
|
+
"bugs": "https://github.com/drew-dot-com/charter/issues",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"mcp",
|
|
18
|
+
"mcp-server",
|
|
19
|
+
"model-context-protocol",
|
|
20
|
+
"x402",
|
|
21
|
+
"compute",
|
|
22
|
+
"sandbox",
|
|
23
|
+
"vps",
|
|
24
|
+
"server",
|
|
25
|
+
"hosting",
|
|
26
|
+
"agent",
|
|
27
|
+
"ai-agent",
|
|
28
|
+
"usdc",
|
|
29
|
+
"base",
|
|
30
|
+
"rent",
|
|
31
|
+
"python",
|
|
32
|
+
"ssh"
|
|
33
|
+
],
|
|
34
|
+
"bin": {
|
|
35
|
+
"charter-mcp": "dist/main.js"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"!dist/**/*.test.*",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "rm -rf dist && tsc -p tsconfig.json && chmod +x dist/main.js",
|
|
48
|
+
"test": "node --test --import tsx 'src/**/*.test.ts'",
|
|
49
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
50
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
54
|
+
"@x402/evm": "2.28.0",
|
|
55
|
+
"@x402/fetch": "2.28.0",
|
|
56
|
+
"viem": "2.57.7",
|
|
57
|
+
"zod": "^4.5.4"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/node": "^22.0.0",
|
|
61
|
+
"tsx": "^4.19.0",
|
|
62
|
+
"typescript": "^5.6.0"
|
|
63
|
+
}
|
|
64
|
+
}
|