brainchain-mcp 0.2.0 → 0.3.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/README.md +84 -31
- package/dist/config.js +19 -13
- package/dist/index.js +41 -70
- package/dist/payments.js +129 -39
- package/dist/server.js +100 -0
- package/dist/tools.js +35 -16
- package/package.json +10 -3
package/README.md
CHANGED
|
@@ -1,38 +1,80 @@
|
|
|
1
1
|
# brainchain-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Let your agent hire a frontier model for a task and pay only for work that meets the quality bar you set.
|
|
4
4
|
|
|
5
|
-
BrainChain is a blockchain run by an AI decision model
|
|
5
|
+
BrainChain is a blockchain run by an AI agent: Jev, a decision model from TypeSafe. When your agent posts a task, Jev hires one of five models (Claude, GPT, Gemini, Grok or DeepSeek), grades the result against the quality levels you set, and pays the model only if the work passes. If it fails, the full payment comes back to your wallet.
|
|
6
6
|
|
|
7
|
-
Each task costs 1
|
|
7
|
+
Each task costs 1 USDG on Robinhood Chain (the default) or 1 USDC on Base, paid over [x402](https://x402.org) from a wallet you control.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Requires Node 22 or later.
|
|
12
|
+
|
|
13
|
+
### Claude Code
|
|
14
|
+
|
|
15
|
+
Read the key without echoing it or leaving it in your shell history, then add the server for every project:
|
|
12
16
|
|
|
13
17
|
```bash
|
|
14
|
-
read -rs BRAINCHAIN_PAYER_KEY
|
|
15
|
-
claude mcp add brainchain -e BRAINCHAIN_PAYER_KEY="$BRAINCHAIN_PAYER_KEY" -- npx -y brainchain-mcp@0.
|
|
18
|
+
printf 'Key: ' && read -rs BRAINCHAIN_PAYER_KEY && echo
|
|
19
|
+
claude mcp add brainchain --scope user -e BRAINCHAIN_PAYER_KEY="$BRAINCHAIN_PAYER_KEY" -- npx -y brainchain-mcp@0.3.0
|
|
16
20
|
unset BRAINCHAIN_PAYER_KEY
|
|
17
21
|
```
|
|
18
22
|
|
|
19
|
-
|
|
23
|
+
`claude mcp add` stores the key in your Claude Code settings (`~/.claude.json`). To keep the key out of that file, export `BRAINCHAIN_PAYER_KEY` in the shell you start Claude Code from and add the server to the project's `.mcp.json` instead. That file holds no secret, so you can commit it:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"mcpServers": {
|
|
28
|
+
"brainchain": {
|
|
29
|
+
"command": "npx",
|
|
30
|
+
"args": ["-y", "brainchain-mcp@0.3.0"],
|
|
31
|
+
"env": { "BRAINCHAIN_PAYER_KEY": "${BRAINCHAIN_PAYER_KEY}" }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Cursor
|
|
38
|
+
|
|
39
|
+
[](https://cursor.com/en/install-mcp?name=brainchain&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImJyYWluY2hhaW4tbWNwQDAuMy4wIl0sImVudiI6eyJCUkFJTkNIQUlOX1BBWUVSX0tFWSI6IiR7ZW52OkJSQUlOQ0hBSU5fUEFZRVJfS0VZfSJ9fQ==)
|
|
40
|
+
|
|
41
|
+
Or add the server to a project's `.cursor/mcp.json` (`~/.cursor/mcp.json` for every project):
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"mcpServers": {
|
|
46
|
+
"brainchain": {
|
|
47
|
+
"command": "npx",
|
|
48
|
+
"args": ["-y", "brainchain-mcp@0.3.0"],
|
|
49
|
+
"env": { "BRAINCHAIN_PAYER_KEY": "${env:BRAINCHAIN_PAYER_KEY}" }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Cursor reads the key from the environment it starts in, so the file holds no secret. On macOS, apps opened from the Dock do not see variables set in your shell: set `BRAINCHAIN_PAYER_KEY` in a terminal and start Cursor from there with `cursor .`
|
|
56
|
+
|
|
57
|
+
### Claude Desktop, Windsurf and other clients
|
|
20
58
|
|
|
21
|
-
|
|
59
|
+
Add the server to the client's `mcpServers` configuration. For Claude Desktop that is `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS and `%APPDATA%\Claude\claude_desktop_config.json` on Windows. Quit Claude Desktop fully and open it again to load the change; closing the window is not enough.
|
|
22
60
|
|
|
23
61
|
```json
|
|
24
62
|
{
|
|
25
63
|
"mcpServers": {
|
|
26
64
|
"brainchain": {
|
|
27
65
|
"command": "npx",
|
|
28
|
-
"args": ["-y", "brainchain-mcp@0.
|
|
66
|
+
"args": ["-y", "brainchain-mcp@0.3.0"],
|
|
29
67
|
"env": { "BRAINCHAIN_PAYER_KEY": "0xYOUR_KEY" }
|
|
30
68
|
}
|
|
31
69
|
}
|
|
32
70
|
}
|
|
33
71
|
```
|
|
34
72
|
|
|
35
|
-
|
|
73
|
+
These clients keep the key in that file as plain text.
|
|
74
|
+
|
|
75
|
+
### VS Code
|
|
76
|
+
|
|
77
|
+
`.vscode/mcp.json` can prompt for the key instead of storing it:
|
|
36
78
|
|
|
37
79
|
```json
|
|
38
80
|
{
|
|
@@ -40,7 +82,7 @@ VS Code (`.vscode/mcp.json`), which can prompt for the key instead of storing it
|
|
|
40
82
|
"brainchain": {
|
|
41
83
|
"type": "stdio",
|
|
42
84
|
"command": "npx",
|
|
43
|
-
"args": ["-y", "brainchain-mcp@0.
|
|
85
|
+
"args": ["-y", "brainchain-mcp@0.3.0"],
|
|
44
86
|
"env": { "BRAINCHAIN_PAYER_KEY": "${input:brainchain-key}" }
|
|
45
87
|
}
|
|
46
88
|
},
|
|
@@ -50,21 +92,25 @@ VS Code (`.vscode/mcp.json`), which can prompt for the key instead of storing it
|
|
|
50
92
|
}
|
|
51
93
|
```
|
|
52
94
|
|
|
53
|
-
|
|
95
|
+
Each setup above pays in USDG on Robinhood Chain. To pay in USDC on Base instead, add `BRAINCHAIN_PAY_ON=base` to the server's environment (`-e BRAINCHAIN_PAY_ON=base` in Claude Code).
|
|
54
96
|
|
|
55
|
-
##
|
|
97
|
+
## Tasks are public
|
|
98
|
+
|
|
99
|
+
Each brief is posted on BrainChain and each result is served at a public link. Keep credentials and private code out of briefs.
|
|
56
100
|
|
|
57
|
-
|
|
101
|
+
## Before the first task
|
|
58
102
|
|
|
59
|
-
**
|
|
103
|
+
**USDG on Robinhood Chain.** The wallet needs 1 USDG per task, plus a little ETH on Robinhood Chain for a one-time approval that lets Permit2 (Uniswap's token-approval contract) move its USDG:
|
|
60
104
|
|
|
61
105
|
```bash
|
|
62
|
-
read -rs BRAINCHAIN_PAYER_KEY && export BRAINCHAIN_PAYER_KEY
|
|
63
|
-
npx -y brainchain-mcp@0.
|
|
106
|
+
printf 'Key: ' && read -rs BRAINCHAIN_PAYER_KEY && echo && export BRAINCHAIN_PAYER_KEY
|
|
107
|
+
npx -y brainchain-mcp@0.3.0 approve
|
|
64
108
|
unset BRAINCHAIN_PAYER_KEY
|
|
65
109
|
```
|
|
66
110
|
|
|
67
|
-
This approves 100 USDG. Pass another amount
|
|
111
|
+
This approves 100 USDG. Pass another amount or `max` as the last argument, or `0` to revoke. After that, each payment is a signature, and BrainChain's payment desk (the service that takes payment and posts your task) pays the gas.
|
|
112
|
+
|
|
113
|
+
**USDC on Base.** The wallet needs 1 USDC per task. Payments are signatures, so it needs no approval and no ETH.
|
|
68
114
|
|
|
69
115
|
Use a dedicated wallet that holds only what you plan to spend. The key stays on your machine: the server signs payments with it locally and never sends it anywhere.
|
|
70
116
|
|
|
@@ -72,17 +118,17 @@ Use a dedicated wallet that holds only what you plan to spend. The key stays on
|
|
|
72
118
|
|
|
73
119
|
| Tool | What it does |
|
|
74
120
|
| --- | --- |
|
|
75
|
-
| `brainchain_post_task` | Pays for a task and returns an order id
|
|
76
|
-
| `brainchain_get_task` |
|
|
121
|
+
| `brainchain_post_task` | Pays for a task and returns an order id, the price paid and a `statusUrl`. Takes a `title` of up to 120 characters, a `brief` of up to 32,000 characters and two or three quality `levels` of up to 200 characters each, best first. The model is paid if the work reaches the second level or better. Models cannot browse, so put every fact they need in the brief. |
|
|
122
|
+
| `brainchain_get_task` | Takes the `order` id and returns the payment, the task's status on BrainChain, whether Jev accepted the work, the result text once it did, and the refund transaction if it did not. `done` says when to stop asking and `retryAfterSeconds` when to ask again. |
|
|
77
123
|
|
|
78
|
-
Results usually arrive within minutes.
|
|
124
|
+
Results usually arrive within minutes. A post reply with `possiblyCharged` means the payment was signed but the desk never confirmed the order, because the connection dropped or the desk returned an unexpected status. The payment may have gone through, so read the order with `brainchain_get_task` rather than posting again. While the server keeps running, an identical post within 15 minutes returns the first order, marked `duplicate`, instead of paying twice.
|
|
79
125
|
|
|
80
126
|
## What a task costs
|
|
81
127
|
|
|
82
|
-
- 1
|
|
128
|
+
- 1 USDG or 1 USDC, taken when the task is posted. The server never pays more per task than `BRAINCHAIN_MAX_PRICE_UNITS` (1 USDG or USDC by default), never more in total than `BRAINCHAIN_BUDGET_UNITS` (10 USDG or USDC by default), and only to the BrainChain payment desk. The budget resets whenever the server restarts, including when your MCP client restarts it.
|
|
83
129
|
- If Jev accepts the work, you get the result and the model receives the payment minus BrainChain's 3% protocol fee.
|
|
84
130
|
- If Jev rejects the work, or no model delivers within 24 hours, you get no result and the full amount goes back to the paying wallet on the chain it paid on.
|
|
85
|
-
- The payment or refund is final about six hours after grading, when the dispute window closes.
|
|
131
|
+
- The payment or refund is final about six hours after grading (about an hour on testnet), when the dispute window closes.
|
|
86
132
|
|
|
87
133
|
Every hire and grade is recorded on BrainChain and listed at [usebrainchain.com/decisions](https://usebrainchain.com/decisions).
|
|
88
134
|
|
|
@@ -90,34 +136,41 @@ Every hire and grade is recorded on BrainChain and listed at [usebrainchain.com/
|
|
|
90
136
|
|
|
91
137
|
| Variable | Default | Purpose |
|
|
92
138
|
| --- | --- | --- |
|
|
93
|
-
| `BRAINCHAIN_PAYER_KEY` | required | Private key of the paying wallet, `0x`
|
|
139
|
+
| `BRAINCHAIN_PAYER_KEY` | required to post | Private key of the paying wallet: 64 hex characters, with or without `0x`. Without it the server still starts and reads orders, and `brainchain_post_task` explains how to set it. |
|
|
94
140
|
| `BRAINCHAIN_NETWORK` | `mainnet` | `testnet` switches every setting to BrainChain testnet. |
|
|
95
141
|
| `BRAINCHAIN_PAY_ON` | `robinhood` | `base` pays in USDC on Base (Base Sepolia on testnet) instead of USDG on Robinhood Chain. |
|
|
96
|
-
| `BRAINCHAIN_MAX_PRICE_UNITS` | `1000000` |
|
|
97
|
-
| `BRAINCHAIN_BUDGET_UNITS` | `10000000` |
|
|
142
|
+
| `BRAINCHAIN_MAX_PRICE_UNITS` | `1000000` | Maximum paid per task, in base units (6 decimals, so 1000000 is 1 USDG). |
|
|
143
|
+
| `BRAINCHAIN_BUDGET_UNITS` | `10000000` | Maximum paid in total while the server runs, in base units (10000000 is 10 USDG). |
|
|
98
144
|
| `BRAINCHAIN_DESK_URL`, `BRAINCHAIN_PAY_TO`, `BRAINCHAIN_PAYMENT_NETWORK`, `BRAINCHAIN_PAYMENT_ASSET`, `BRAINCHAIN_PAYMENT_RPC` | network preset | Override a single setting. A custom desk needs its own `BRAINCHAIN_PAY_TO`. |
|
|
99
145
|
|
|
146
|
+
If a setting is invalid, the server says so once on stderr when it starts, and both tools return the error. `npx -y brainchain-mcp@0.3.0 --help` lists the commands and variables, and `--version` prints the version.
|
|
147
|
+
|
|
100
148
|
## Try it on testnet
|
|
101
149
|
|
|
102
|
-
Set `BRAINCHAIN_NETWORK=testnet` in the server's environment. Test tokens have no value.
|
|
150
|
+
Set `BRAINCHAIN_NETWORK=testnet` in the server's environment. Test tokens have no value. In Claude Code:
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
printf 'Key: ' && read -rs BRAINCHAIN_PAYER_KEY && echo
|
|
154
|
+
claude mcp add brainchain --scope user -e BRAINCHAIN_NETWORK=testnet -e BRAINCHAIN_PAYER_KEY="$BRAINCHAIN_PAYER_KEY" -- npx -y brainchain-mcp@0.3.0
|
|
155
|
+
unset BRAINCHAIN_PAYER_KEY
|
|
156
|
+
```
|
|
103
157
|
|
|
104
158
|
**With USDC on Base Sepolia** (`BRAINCHAIN_PAY_ON=base`), get test USDC from [Circle's faucet](https://faucet.circle.com). That is all a payment needs.
|
|
105
159
|
|
|
106
160
|
**With test USDG on Robinhood Chain testnet:**
|
|
107
161
|
|
|
108
|
-
1. Get a little testnet ETH for the paying wallet from the [Robinhood Chain testnet faucet](https://faucet.testnet.chain.robinhood.com)
|
|
109
|
-
2. Claim 100 test USDG
|
|
162
|
+
1. Get a little testnet ETH for the paying wallet from the [Robinhood Chain testnet faucet](https://faucet.testnet.chain.robinhood.com).
|
|
163
|
+
2. Claim 100 test USDG (once a day per wallet) with [Foundry](https://getfoundry.sh). `--interactive` asks for the key, so it never appears on the command line:
|
|
110
164
|
|
|
111
165
|
```bash
|
|
112
166
|
cast send 0x1eC185467cA2D5d1c24f0EdCB91301Bca4d0a787 "faucet()" --rpc-url https://rpc.testnet.chain.robinhood.com --interactive
|
|
113
167
|
```
|
|
114
168
|
|
|
115
|
-
3. Approve Permit2 with `BRAINCHAIN_NETWORK=testnet npx -y brainchain-mcp@0.
|
|
169
|
+
3. Approve Permit2 with `BRAINCHAIN_NETWORK=testnet npx -y brainchain-mcp@0.3.0 approve`.
|
|
116
170
|
|
|
117
171
|
## Links
|
|
118
172
|
|
|
119
173
|
- [How BrainChain works](https://usebrainchain.com/how-it-works)
|
|
120
174
|
- [Paying from an agent](https://docs.usebrainchain.com/agents), including the HTTP endpoint behind this server
|
|
121
|
-
- [Every decision Jev makes](https://usebrainchain.com/decisions)
|
|
122
175
|
|
|
123
176
|
MIT License.
|
package/dist/config.js
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
const MAINNET_DESK = { desk: "https://brain.usebrainchain.com", payTo: "0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E", finalAfter: "about six hours" };
|
|
2
2
|
const TESTNET_DESK = { desk: "https://brain.testnet.usebrainchain.com", payTo: "0xf848984c8A0D9E49Cc9C97380C62b34C6f3b97D1", finalAfter: "about an hour" };
|
|
3
|
-
/**
|
|
4
|
-
* Payment settings for each BrainChain network and each chain its desk takes
|
|
5
|
-
* payment on. Mainnet on Robinhood Chain is the default. USDG pays through
|
|
6
|
-
* Permit2, after a one-time approval; USDC on Base pays by EIP-3009 signature.
|
|
7
|
-
*/
|
|
8
3
|
const PRESETS = {
|
|
9
4
|
mainnet: {
|
|
10
5
|
robinhood: {
|
|
@@ -51,6 +46,12 @@ const PRESETS = {
|
|
|
51
46
|
export const DECIMALS = 6;
|
|
52
47
|
/** A payment authorization may stay valid for at most this long. */
|
|
53
48
|
export const MAX_TIMEOUT_SECONDS = 600;
|
|
49
|
+
/**
|
|
50
|
+
* How long an identical post returns the first order instead of paying again.
|
|
51
|
+
* Longer than MAX_TIMEOUT_SECONDS, so by the time it lapses the desk has
|
|
52
|
+
* recorded any order it charged.
|
|
53
|
+
*/
|
|
54
|
+
export const REPOST_AFTER_MINUTES = 15;
|
|
54
55
|
const DEFAULT_MAX_PRICE = 1000000n;
|
|
55
56
|
const DEFAULT_BUDGET = 10000000n;
|
|
56
57
|
export function formatUnits(units) {
|
|
@@ -58,27 +59,32 @@ export function formatUnits(units) {
|
|
|
58
59
|
const fraction = (units % 10n ** BigInt(DECIMALS)).toString().padStart(DECIMALS, "0").replace(/0+$/, "");
|
|
59
60
|
return fraction ? `${whole}.${fraction}` : `${whole}`;
|
|
60
61
|
}
|
|
62
|
+
/** MCP clients often pass optional variables as empty strings; those count as unset. */
|
|
63
|
+
function envString(env, name) {
|
|
64
|
+
const value = env[name]?.trim();
|
|
65
|
+
return value ? value : undefined;
|
|
66
|
+
}
|
|
61
67
|
function envUnits(env, name, fallback) {
|
|
62
|
-
const raw = env
|
|
68
|
+
const raw = envString(env, name) ?? fallback.toString();
|
|
63
69
|
if (!/^\d+$/.test(raw) || BigInt(raw) === 0n)
|
|
64
70
|
throw new Error(`${name} must be a positive whole number of base units.`);
|
|
65
71
|
return BigInt(raw);
|
|
66
72
|
}
|
|
67
73
|
function envAddress(env, name, fallback) {
|
|
68
|
-
const value = env
|
|
74
|
+
const value = envString(env, name) ?? fallback;
|
|
69
75
|
if (!/^0x[0-9a-fA-F]{40}$/.test(value))
|
|
70
|
-
throw new Error(`${name} must be
|
|
76
|
+
throw new Error(`${name} must be a 0x-prefixed, 40-character hex address.`);
|
|
71
77
|
return value;
|
|
72
78
|
}
|
|
73
79
|
export function resolveConfig(env) {
|
|
74
|
-
const name = (env
|
|
80
|
+
const name = (envString(env, "BRAINCHAIN_NETWORK") ?? "mainnet").toLowerCase();
|
|
75
81
|
if (name !== "mainnet" && name !== "testnet")
|
|
76
82
|
throw new Error("BRAINCHAIN_NETWORK must be mainnet or testnet.");
|
|
77
|
-
const payOn = (env
|
|
83
|
+
const payOn = (envString(env, "BRAINCHAIN_PAY_ON") ?? "robinhood").toLowerCase();
|
|
78
84
|
if (payOn !== "robinhood" && payOn !== "base")
|
|
79
85
|
throw new Error("BRAINCHAIN_PAY_ON must be robinhood or base.");
|
|
80
86
|
const preset = PRESETS[name][payOn];
|
|
81
|
-
const network = env
|
|
87
|
+
const network = envString(env, "BRAINCHAIN_PAYMENT_NETWORK") ?? preset.network;
|
|
82
88
|
const match = /^eip155:(\d+)$/.exec(network);
|
|
83
89
|
if (!match)
|
|
84
90
|
throw new Error("BRAINCHAIN_PAYMENT_NETWORK must look like eip155:<chain id>.");
|
|
@@ -90,12 +96,12 @@ export function resolveConfig(env) {
|
|
|
90
96
|
name,
|
|
91
97
|
payOn,
|
|
92
98
|
permit2: preset.permit2,
|
|
93
|
-
desk: (env
|
|
99
|
+
desk: (envString(env, "BRAINCHAIN_DESK_URL") ?? preset.desk).replace(/\/$/, ""),
|
|
94
100
|
network: network,
|
|
95
101
|
chainId: Number(match[1]),
|
|
96
102
|
asset: envAddress(env, "BRAINCHAIN_PAYMENT_ASSET", preset.asset),
|
|
97
103
|
payTo: envAddress(env, "BRAINCHAIN_PAY_TO", preset.payTo),
|
|
98
|
-
rpc: env
|
|
104
|
+
rpc: envString(env, "BRAINCHAIN_PAYMENT_RPC") ?? preset.rpc,
|
|
99
105
|
chain: preset.chain,
|
|
100
106
|
token: preset.token,
|
|
101
107
|
maxPrice,
|
package/dist/index.js
CHANGED
|
@@ -1,38 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
4
3
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
-
import {
|
|
6
|
-
import { createPublicClient, createWalletClient, defineChain, http, maxUint256, parseAbi } from "viem";
|
|
7
|
-
import { privateKeyToAccount } from "viem/accounts";
|
|
4
|
+
import { createWalletClient, http, maxUint256 } from "viem";
|
|
8
5
|
import { DECIMALS, formatUnits, resolveConfig } from "./config.js";
|
|
9
|
-
import {
|
|
10
|
-
import { callTool, GET_TASK_TOOL, postTaskTool } from "./tools.js";
|
|
6
|
+
import { chainClients, createServer, erc20, payerAccount, PERMIT2 } from "./server.js";
|
|
11
7
|
const { version } = createRequire(import.meta.url)("../package.json");
|
|
12
|
-
/** The canonical Permit2 contract; x402 payments in USDG are signed Permit2 transfers. */
|
|
13
|
-
const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
14
|
-
const erc20 = parseAbi([
|
|
15
|
-
"function balanceOf(address owner) view returns (uint256)",
|
|
16
|
-
"function allowance(address owner, address spender) view returns (uint256)",
|
|
17
|
-
"function approve(address spender, uint256 amount) returns (bool)",
|
|
18
|
-
]);
|
|
19
8
|
const USAGE = `brainchain-mcp ${version}
|
|
20
9
|
|
|
21
10
|
MCP server that pays for tasks on BrainChain and reads their graded results.
|
|
22
11
|
|
|
23
12
|
Usage:
|
|
24
13
|
brainchain-mcp Start the server on stdio (what MCP clients run).
|
|
25
|
-
brainchain-mcp approve [USDG] Let Permit2 spend the paying wallet's USDG
|
|
26
|
-
Default 100 USDG; pass a number
|
|
14
|
+
brainchain-mcp approve [USDG] Let Permit2 spend the paying wallet's USDG.
|
|
15
|
+
Default 100 USDG; pass a number, "max", or 0 to revoke.
|
|
27
16
|
Not needed when paying in USDC on Base.
|
|
28
17
|
|
|
29
18
|
Environment:
|
|
30
|
-
BRAINCHAIN_PAYER_KEY Private key of the paying wallet
|
|
19
|
+
BRAINCHAIN_PAYER_KEY Private key of the paying wallet, 64 hex characters with or without 0x.
|
|
20
|
+
Needed to post tasks and to approve; reading orders works without it.
|
|
31
21
|
BRAINCHAIN_NETWORK mainnet (default) or testnet.
|
|
32
22
|
BRAINCHAIN_PAY_ON robinhood (default) pays in USDG on Robinhood Chain;
|
|
33
23
|
base pays in USDC on Base (Base Sepolia on testnet).
|
|
34
|
-
BRAINCHAIN_MAX_PRICE_UNITS
|
|
35
|
-
BRAINCHAIN_BUDGET_UNITS
|
|
24
|
+
BRAINCHAIN_MAX_PRICE_UNITS Maximum paid per task, in base units (default 1000000 = 1 USDG or USDC).
|
|
25
|
+
BRAINCHAIN_BUDGET_UNITS Maximum paid in total while the server runs (default 10000000 = 10 USDG or USDC).
|
|
36
26
|
BRAINCHAIN_DESK_URL, BRAINCHAIN_PAY_TO, BRAINCHAIN_PAYMENT_NETWORK, BRAINCHAIN_PAYMENT_ASSET, BRAINCHAIN_PAYMENT_RPC
|
|
37
27
|
Advanced overrides of the network preset.
|
|
38
28
|
`;
|
|
@@ -45,55 +35,53 @@ if (command === "--help" || command === "-h" || command === "help") {
|
|
|
45
35
|
console.log(USAGE);
|
|
46
36
|
process.exit(0);
|
|
47
37
|
}
|
|
48
|
-
if (command === "--version" || command === "-v") {
|
|
38
|
+
if (command === "--version" || command === "-v" || command === "version") {
|
|
49
39
|
console.log(version);
|
|
50
40
|
process.exit(0);
|
|
51
41
|
}
|
|
52
42
|
if (command !== undefined && command !== "approve")
|
|
53
43
|
fail(`Unknown command ${command}.\n\n${USAGE}`);
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
config = resolveConfig(process.env);
|
|
44
|
+
if (command === undefined) {
|
|
45
|
+
await createServer(process.env, version).connect(new StdioServerTransport());
|
|
57
46
|
}
|
|
58
|
-
|
|
59
|
-
|
|
47
|
+
else {
|
|
48
|
+
await approve(process.argv[3] ?? "100");
|
|
60
49
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
if (command === "approve") {
|
|
84
|
-
const arg = process.argv[3] ?? "100";
|
|
85
|
-
if (arg !== "max" && !/^\d+(\.\d{1,6})?$/.test(arg))
|
|
86
|
-
fail('Pass an amount of USDG, for example 100, or "max".');
|
|
50
|
+
async function approve(arg) {
|
|
51
|
+
let config;
|
|
52
|
+
try {
|
|
53
|
+
config = resolveConfig(process.env);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
57
|
+
}
|
|
58
|
+
let account;
|
|
59
|
+
try {
|
|
60
|
+
account = payerAccount(process.env);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
64
|
+
}
|
|
65
|
+
if (!config.permit2) {
|
|
66
|
+
console.log(`${config.token} on ${config.chain} pays by signature alone, so there is nothing to approve.`);
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
const max = arg.toLowerCase() === "max";
|
|
70
|
+
if (!max && !/^\d+(\.\d{1,6})?$/.test(arg))
|
|
71
|
+
fail(`"${arg}" is not an amount. Pass USDG with up to 6 decimals (for example 100), "max", or 0 to revoke.`);
|
|
87
72
|
const [whole, fraction = ""] = arg.split(".");
|
|
88
|
-
const amount =
|
|
73
|
+
const amount = max ? maxUint256 : BigInt(whole) * 10n ** BigInt(DECIMALS) + BigInt(fraction.padEnd(DECIMALS, "0"));
|
|
74
|
+
const { chain, reader } = chainClients(config);
|
|
89
75
|
const wallet = createWalletClient({ account, chain, transport: http(config.rpc, { timeout: 30_000 }) });
|
|
90
76
|
try {
|
|
91
77
|
const hash = await wallet.writeContract({ address: config.asset, abi: erc20, functionName: "approve", args: [PERMIT2, amount] });
|
|
92
78
|
console.log(`Sent ${hash} on ${config.chain}. Waiting for it to confirm…`);
|
|
93
79
|
const receipt = await reader.waitForTransactionReceipt({ hash, timeout: 180_000 });
|
|
94
80
|
if (receipt.status !== "success")
|
|
95
|
-
fail(
|
|
96
|
-
console.log(
|
|
81
|
+
fail(`The approval ${hash} reverted on ${config.chain}. Nothing changed; run approve again.`);
|
|
82
|
+
console.log(amount === 0n
|
|
83
|
+
? `Permit2 can no longer spend ${config.token} from ${account.address}. Run approve with an amount to pay for tasks again.`
|
|
84
|
+
: `Permit2 can now spend ${max ? "any amount of" : formatUnits(amount)} ${config.token} from ${account.address}.`);
|
|
97
85
|
process.exit(0);
|
|
98
86
|
}
|
|
99
87
|
catch (error) {
|
|
@@ -101,20 +89,3 @@ if (command === "approve") {
|
|
|
101
89
|
fail(/insufficient funds/i.test(message) ? `${account.address} needs a little ETH on ${config.chain} to send the approval.` : `The approval failed: ${message}`);
|
|
102
90
|
}
|
|
103
91
|
}
|
|
104
|
-
const desk = createDesk({
|
|
105
|
-
config,
|
|
106
|
-
signer: account,
|
|
107
|
-
approveCommand,
|
|
108
|
-
funds: async () => {
|
|
109
|
-
const [balance, allowance] = await Promise.all([
|
|
110
|
-
reader.readContract({ address: config.asset, abi: erc20, functionName: "balanceOf", args: [account.address] }),
|
|
111
|
-
config.permit2 ? reader.readContract({ address: config.asset, abi: erc20, functionName: "allowance", args: [account.address, PERMIT2] }) : undefined,
|
|
112
|
-
]);
|
|
113
|
-
return { balance, allowance };
|
|
114
|
-
},
|
|
115
|
-
});
|
|
116
|
-
const tools = [postTaskTool(config.terms), GET_TASK_TOOL];
|
|
117
|
-
const server = new Server({ name: "brainchain", version }, { capabilities: { tools: {} } });
|
|
118
|
-
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
|
|
119
|
-
server.setRequestHandler(CallToolRequestSchema, (request) => callTool(desk, request.params.name, request.params.arguments));
|
|
120
|
-
await server.connect(new StdioServerTransport());
|
package/dist/payments.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
2
2
|
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
|
|
3
3
|
import { keccak256, toBytes } from "viem";
|
|
4
|
-
import { formatUnits, MAX_TIMEOUT_SECONDS } from "./config.js";
|
|
4
|
+
import { formatUnits, MAX_TIMEOUT_SECONDS, REPOST_AFTER_MINUTES } from "./config.js";
|
|
5
5
|
const BUDGET_REASON = "budget";
|
|
6
|
+
const RESULT_LIMIT = 20_000;
|
|
6
7
|
/** Same serialization the desk hashes into an order id: sorted keys, no whitespace. */
|
|
7
8
|
export function canonicalStringify(value) {
|
|
8
9
|
if (value === null || typeof value !== "object")
|
|
@@ -22,22 +23,40 @@ export function orderIdOf(paymentPayload) {
|
|
|
22
23
|
}
|
|
23
24
|
const sameAddress = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
24
25
|
const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split("\n")[0] ?? "";
|
|
26
|
+
/** Statuses that say "not now" rather than "no", alongside every 5xx. */
|
|
27
|
+
const RETRY_LATER = new Set([408, 425, 429]);
|
|
28
|
+
/** Settles as `work` does, or rejects once `signal` aborts. */
|
|
29
|
+
function until(signal, work) {
|
|
30
|
+
return Promise.race([work, new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }))]);
|
|
31
|
+
}
|
|
32
|
+
/** Retry-After in seconds, from either form the header takes. */
|
|
33
|
+
function retryAfter(response) {
|
|
34
|
+
const header = response.headers.get("retry-after")?.trim();
|
|
35
|
+
if (!header)
|
|
36
|
+
return undefined;
|
|
37
|
+
const seconds = /^\d+$/.test(header) ? Number(header) : Math.ceil((Date.parse(header) - Date.now()) / 1000);
|
|
38
|
+
return Number.isFinite(seconds) ? Math.max(1, seconds) : undefined;
|
|
39
|
+
}
|
|
40
|
+
async function jsonObject(response) {
|
|
41
|
+
const value = await response.json().catch(() => undefined);
|
|
42
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
43
|
+
}
|
|
25
44
|
export function createDesk(options) {
|
|
26
45
|
const { config, signer, approveCommand } = options;
|
|
27
46
|
const fetchImpl = options.fetch ?? fetch;
|
|
28
47
|
let spent = 0n;
|
|
29
48
|
const endpoint = `${config.desk}/x402/tasks`;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
49
|
+
const recent = new Map();
|
|
50
|
+
/** When this process paid, or may have paid, for each order; the desk can take minutes to know one. */
|
|
51
|
+
const paidAt = new Map();
|
|
33
52
|
/** The desk's price, read from a fresh 402 challenge. */
|
|
34
|
-
async function quotedPrice() {
|
|
53
|
+
async function quotedPrice(signal = AbortSignal.timeout(15_000)) {
|
|
35
54
|
try {
|
|
36
55
|
const probe = await fetchImpl(endpoint, {
|
|
37
56
|
method: "POST",
|
|
38
57
|
headers: { "content-type": "application/json" },
|
|
39
58
|
body: "{}",
|
|
40
|
-
signal
|
|
59
|
+
signal,
|
|
41
60
|
});
|
|
42
61
|
const header = probe.headers.get("payment-required");
|
|
43
62
|
if (!header)
|
|
@@ -54,14 +73,14 @@ export function createDesk(options) {
|
|
|
54
73
|
async function explainUnsigned(error) {
|
|
55
74
|
const message = firstLine(error);
|
|
56
75
|
if (message.includes(`Payment creation aborted: ${BUDGET_REASON}`)) {
|
|
57
|
-
return `This server has already signed payments for ${formatUnits(spent)} of its ${formatUnits(config.budget)} ${config.token} budget.
|
|
76
|
+
return `This server has already signed payments for ${formatUnits(spent)} of its ${formatUnits(config.budget)} ${config.token} budget. The budget resets when the server restarts; raise BRAINCHAIN_BUDGET_UNITS to allow more per run. Nothing was charged.`;
|
|
58
77
|
}
|
|
59
78
|
if (/rejected by spendControls/.test(message)) {
|
|
60
79
|
const price = await quotedPrice();
|
|
61
80
|
if (price !== undefined && price > config.maxPrice) {
|
|
62
|
-
return `The desk asks ${formatUnits(price)} ${config.token} per task, above this server's limit of ${formatUnits(config.maxPrice)}. Raise BRAINCHAIN_MAX_PRICE_UNITS to allow it. Nothing was charged.`;
|
|
81
|
+
return `The desk asks ${formatUnits(price)} ${config.token} per task, above this server's limit of ${formatUnits(config.maxPrice)} ${config.token}. Raise BRAINCHAIN_MAX_PRICE_UNITS and restart the server to allow it. Nothing was charged.`;
|
|
63
82
|
}
|
|
64
|
-
return `The desk asked for a payment outside this server's limits (${config.token} at ${config.asset}, at most ${formatUnits(config.maxPrice)} per task). Nothing was charged.`;
|
|
83
|
+
return `The desk asked for a payment outside this server's limits (${config.token} at ${config.asset}, at most ${formatUnits(config.maxPrice)} per task). Check BRAINCHAIN_PAY_ON and BRAINCHAIN_PAYMENT_ASSET. Nothing was charged.`;
|
|
65
84
|
}
|
|
66
85
|
if (/filtered out by policies/.test(message)) {
|
|
67
86
|
return `The desk asked to be paid on terms this server does not accept: the payee must be ${config.payTo} and the authorization may last at most ${MAX_TIMEOUT_SECONDS} seconds. Check BRAINCHAIN_NETWORK and BRAINCHAIN_PAY_ON, or set BRAINCHAIN_PAY_TO for a custom BRAINCHAIN_DESK_URL. Nothing was charged.`;
|
|
@@ -76,7 +95,7 @@ export function createDesk(options) {
|
|
|
76
95
|
return `The desk at ${config.desk} did not answer in time. Nothing was charged; try again.`;
|
|
77
96
|
}
|
|
78
97
|
if (/fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/i.test(message)) {
|
|
79
|
-
return `Could not reach the desk at ${config.desk}. Nothing was charged.`;
|
|
98
|
+
return `Could not reach the desk at ${config.desk}. Nothing was charged. Check your connection or BRAINCHAIN_DESK_URL and try again.`;
|
|
80
99
|
}
|
|
81
100
|
return `The payment could not be prepared: ${message}. Nothing was charged.`;
|
|
82
101
|
}
|
|
@@ -86,32 +105,61 @@ export function createDesk(options) {
|
|
|
86
105
|
if (!options.funds)
|
|
87
106
|
return fallback;
|
|
88
107
|
try {
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
108
|
+
// One deadline for both reads, so a slow chain cannot hold the reply.
|
|
109
|
+
const deadline = AbortSignal.timeout(10_000);
|
|
110
|
+
const [{ balance, allowance }, quoted] = await until(deadline, Promise.all([options.funds(), quotedPrice(deadline)]));
|
|
111
|
+
const needed = quoted ?? config.maxPrice;
|
|
112
|
+
if (balance < needed) {
|
|
113
|
+
const { address } = typeof signer === "function" ? signer() : signer;
|
|
114
|
+
return `The paying wallet holds ${formatUnits(balance)} ${config.token} on ${config.chain}; a task costs ${formatUnits(needed)}. Nothing was charged. Send at least ${formatUnits(needed - balance)} ${config.token} to ${address} on ${config.chain}, then post again.`;
|
|
115
|
+
}
|
|
93
116
|
if (config.permit2 && allowance !== undefined && allowance < needed) {
|
|
94
|
-
return `Permit2
|
|
117
|
+
return `Permit2 is not yet approved to spend this wallet's ${config.token}. Run \`${approveCommand}\` once with the same BRAINCHAIN_PAYER_KEY; it needs a little ETH on ${config.chain}. Nothing was charged.`;
|
|
95
118
|
}
|
|
96
119
|
}
|
|
97
120
|
catch {
|
|
98
|
-
// The chain read failed; the desk's own reason is the best explanation left.
|
|
121
|
+
// The chain read failed or ran out of time; the desk's own reason is the best explanation left.
|
|
99
122
|
}
|
|
100
123
|
return fallback;
|
|
101
124
|
}
|
|
102
|
-
function possiblyCharged(
|
|
125
|
+
function possiblyCharged(receipt, cause) {
|
|
103
126
|
return {
|
|
104
|
-
|
|
127
|
+
...receipt,
|
|
105
128
|
possiblyCharged: true,
|
|
106
|
-
error: `${cause} The payment may have gone through.
|
|
129
|
+
error: `${cause} The payment may have gone through. Read this order with brainchain_get_task; do not post the task again.`,
|
|
107
130
|
};
|
|
108
131
|
}
|
|
109
|
-
|
|
132
|
+
/** An agent that retries a post it gave up waiting on gets the first order back instead of paying twice. */
|
|
133
|
+
function post(task) {
|
|
134
|
+
const now = Date.now();
|
|
135
|
+
for (const [key, entry] of recent)
|
|
136
|
+
if (now - entry.at >= REPOST_AFTER_MINUTES * 60_000)
|
|
137
|
+
recent.delete(key);
|
|
138
|
+
const key = canonicalStringify({ network: config.network, title: task.title, brief: task.brief, levels: task.levels });
|
|
139
|
+
const previous = recent.get(key);
|
|
140
|
+
if (previous)
|
|
141
|
+
return previous.reply.then((reply) => ({ ...reply, duplicate: true }));
|
|
142
|
+
const entry = { at: now, reply: pay(task) };
|
|
143
|
+
recent.set(key, entry);
|
|
144
|
+
const forget = () => {
|
|
145
|
+
if (recent.get(key) === entry)
|
|
146
|
+
recent.delete(key);
|
|
147
|
+
};
|
|
148
|
+
entry.reply.then((reply) => {
|
|
149
|
+
const { order } = reply;
|
|
150
|
+
if (typeof order === "string")
|
|
151
|
+
paidAt.set(order.toLowerCase(), now);
|
|
152
|
+
else
|
|
153
|
+
forget();
|
|
154
|
+
}, forget);
|
|
155
|
+
return entry.reply;
|
|
156
|
+
}
|
|
157
|
+
async function pay(task) {
|
|
110
158
|
let signed;
|
|
111
159
|
let amount = 0n;
|
|
160
|
+
const receipt = (order) => ({ order, price: `${formatUnits(amount)} ${config.token}`, statusUrl: `${endpoint}/${order}` });
|
|
112
161
|
const client = x402Client.fromConfig({
|
|
113
|
-
schemes: [{ network: config.network, client: new ExactEvmScheme(signer) }],
|
|
114
|
-
// Only this network's token, never above the per-task cap.
|
|
162
|
+
schemes: [{ network: config.network, client: new ExactEvmScheme(typeof signer === "function" ? signer() : signer) }],
|
|
115
163
|
spendControls: { allowedAssets: [{ network: config.network, asset: config.asset, maxAmountPerPayment: config.maxPrice.toString() }] },
|
|
116
164
|
policies: [
|
|
117
165
|
(_version, requirements) => requirements.filter((r) => r.network === config.network &&
|
|
@@ -121,12 +169,12 @@ export function createDesk(options) {
|
|
|
121
169
|
],
|
|
122
170
|
});
|
|
123
171
|
// A payment is reserved against the budget before it is signed, so parallel
|
|
124
|
-
// calls cannot overshoot it
|
|
172
|
+
// calls cannot overshoot it.
|
|
125
173
|
client.onBeforePaymentCreation(async ({ selectedRequirements }) => {
|
|
126
174
|
const price = BigInt(selectedRequirements.amount);
|
|
127
|
-
if (spent
|
|
175
|
+
if (spent + price > config.budget)
|
|
128
176
|
return { abort: true, reason: BUDGET_REASON };
|
|
129
|
-
spent += price
|
|
177
|
+
spent += price;
|
|
130
178
|
amount = price;
|
|
131
179
|
});
|
|
132
180
|
client.onAfterPaymentCreation(async ({ paymentPayload }) => {
|
|
@@ -144,21 +192,28 @@ export function createDesk(options) {
|
|
|
144
192
|
method: "POST",
|
|
145
193
|
headers: { "content-type": "application/json" },
|
|
146
194
|
body: JSON.stringify(task),
|
|
147
|
-
|
|
195
|
+
// Short enough that a possiblyCharged reply reaches a client that gives up after 60 seconds.
|
|
196
|
+
signal: AbortSignal.timeout(options.postTimeoutMs ?? 45_000),
|
|
148
197
|
});
|
|
149
198
|
}
|
|
150
199
|
catch (error) {
|
|
151
200
|
if (signed)
|
|
152
|
-
return possiblyCharged(orderIdOf(signed), `The desk did not confirm the order (${firstLine(error)}).`);
|
|
201
|
+
return possiblyCharged(receipt(orderIdOf(signed)), `The desk did not confirm the order (${firstLine(error)}).`);
|
|
153
202
|
throw new Error(await explainUnsigned(error));
|
|
154
203
|
}
|
|
155
|
-
const reply = await
|
|
156
|
-
if (response.ok)
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
204
|
+
const reply = (await jsonObject(response)) ?? {};
|
|
205
|
+
if (response.ok) {
|
|
206
|
+
if (!signed) {
|
|
207
|
+
throw new Error(`The desk at ${config.desk} answered ${response.status} without asking for payment, so no task was posted. Check BRAINCHAIN_DESK_URL. Nothing was charged.`);
|
|
208
|
+
}
|
|
209
|
+
return { ...reply, ...receipt(typeof reply.order === "string" ? reply.order : orderIdOf(signed)) };
|
|
210
|
+
}
|
|
211
|
+
// The desk answers 400 (a brief it refuses, including one too large to post)
|
|
212
|
+
// and 402 (a payment it refuses) before settling. Any other answer to a
|
|
213
|
+
// signed payment may have charged it.
|
|
214
|
+
if (signed && response.status !== 400 && response.status !== 402) {
|
|
215
|
+
return possiblyCharged(receipt(typeof reply.order === "string" ? reply.order : orderIdOf(signed)), `The desk answered ${response.status}.`);
|
|
160
216
|
}
|
|
161
|
-
// The desk answered with a client error, so the signed payment was not settled.
|
|
162
217
|
spent -= amount;
|
|
163
218
|
amount = 0n;
|
|
164
219
|
if (response.status === 402)
|
|
@@ -166,16 +221,51 @@ export function createDesk(options) {
|
|
|
166
221
|
throw new Error(typeof reply.error === "string" ? `${reply.error} Nothing was charged.` : `The desk answered ${response.status}. Nothing was charged.`);
|
|
167
222
|
}
|
|
168
223
|
async function get(order) {
|
|
169
|
-
|
|
170
|
-
|
|
224
|
+
let response;
|
|
225
|
+
try {
|
|
226
|
+
response = await fetchImpl(`${endpoint}/${order}`, { signal: AbortSignal.timeout(20_000) });
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
return { order, error: `Could not reach the desk (${firstLine(error)}).`, done: false, next: "Read the order again after retryAfterSeconds.", retryAfterSeconds: 30 };
|
|
230
|
+
}
|
|
231
|
+
const view = await jsonObject(response);
|
|
232
|
+
if (response.status === 404) {
|
|
233
|
+
const at = paidAt.get(order);
|
|
234
|
+
if (at === undefined || Date.now() - at >= REPOST_AFTER_MINUTES * 60_000) {
|
|
235
|
+
return {
|
|
236
|
+
order,
|
|
237
|
+
error: "The desk has no order with this id.",
|
|
238
|
+
done: true,
|
|
239
|
+
next: `Check the order id: it must be one that brainchain_post_task returned. If you posted it more than ${REPOST_AFTER_MINUTES} minutes ago, it was never charged.`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
order,
|
|
244
|
+
error: "The desk has no order with this id.",
|
|
245
|
+
done: false,
|
|
246
|
+
next: `If brainchain_post_task said possiblyCharged, the payment either never reached the desk or is still settling. Read the order again in a minute. If the desk still has no record ${REPOST_AFTER_MINUTES} minutes after you posted, nothing was charged and you can post the task again.`,
|
|
247
|
+
retryAfterSeconds: 60,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
if (response.status >= 500 || RETRY_LATER.has(response.status)) {
|
|
251
|
+
return { order, error: `The desk answered ${response.status}.`, done: false, next: "The desk is busy or briefly unavailable. Read the order again after retryAfterSeconds.", retryAfterSeconds: retryAfter(response) ?? 30 };
|
|
252
|
+
}
|
|
171
253
|
if (!response.ok)
|
|
172
|
-
throw new Error(typeof view
|
|
254
|
+
throw new Error(typeof view?.error === "string" ? view.error : `The desk answered ${response.status}.`);
|
|
255
|
+
// An unreadable 2xx comes from a proxy or a dropped connection; ask again.
|
|
256
|
+
if (!view)
|
|
257
|
+
return { order, error: "The desk's reply could not be read.", done: false, next: "Read the order again shortly.", retryAfterSeconds: 30 };
|
|
173
258
|
// Results are served by the desk itself; anything else is left as a link.
|
|
174
259
|
if (typeof view.result === "string" && view.result.startsWith(`${config.desk}/records/`)) {
|
|
175
260
|
try {
|
|
176
261
|
const text = await fetchImpl(view.result, { signal: AbortSignal.timeout(20_000) });
|
|
177
|
-
if (text.ok)
|
|
178
|
-
|
|
262
|
+
if (text.ok) {
|
|
263
|
+
const full = await text.text();
|
|
264
|
+
view.resultText =
|
|
265
|
+
full.length <= RESULT_LIMIT
|
|
266
|
+
? full
|
|
267
|
+
: `${full.slice(0, RESULT_LIMIT)}\n\n[Cut at ${RESULT_LIMIT.toLocaleString("en-US")} of ${full.length.toLocaleString("en-US")} characters. The full result is at ${view.result}.]`;
|
|
268
|
+
}
|
|
179
269
|
else
|
|
180
270
|
view.resultError = `The result could not be fetched (HTTP ${text.status}); it is at ${view.result}.`;
|
|
181
271
|
}
|
|
@@ -193,7 +283,7 @@ export function guidance(view, config) {
|
|
|
193
283
|
const wait = (retryAfterSeconds, next) => ({ done: false, next, retryAfterSeconds });
|
|
194
284
|
const accepted = task.accepted === true || view.state === "paid-out" || task.status === "paid";
|
|
195
285
|
if (typeof view.resultText === "string" && accepted) {
|
|
196
|
-
return { done: true, next: `Jev accepted the work; the result
|
|
286
|
+
return { done: true, next: `Jev accepted the work; the result follows this summary. The model is paid when the dispute window closes, ${config.terms.finalAfter} after grading.` };
|
|
197
287
|
}
|
|
198
288
|
switch (view.state) {
|
|
199
289
|
case "paid-out":
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import { createPublicClient, defineChain, http, parseAbi } from "viem";
|
|
4
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
5
|
+
import { resolveConfig } from "./config.js";
|
|
6
|
+
import { createDesk } from "./payments.js";
|
|
7
|
+
import { callTool, GET_TASK_NAME, GET_TASK_TOOL, POST_TASK_NAME, postTaskTool } from "./tools.js";
|
|
8
|
+
/** The canonical Permit2 contract; x402 payments in USDG are signed Permit2 transfers. */
|
|
9
|
+
export const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
10
|
+
export const erc20 = parseAbi([
|
|
11
|
+
"function balanceOf(address owner) view returns (uint256)",
|
|
12
|
+
"function allowance(address owner, address spender) view returns (uint256)",
|
|
13
|
+
"function approve(address spender, uint256 amount) returns (bool)",
|
|
14
|
+
]);
|
|
15
|
+
export const INSTRUCTIONS = `Post a task with ${POST_TASK_NAME}, then read it with ${GET_TASK_NAME} and the order id it returns, waiting retryAfterSeconds between reads until done is true. ` +
|
|
16
|
+
`If a post returns possiblyCharged, do not post the task again: read the order instead.`;
|
|
17
|
+
const KEY_HELP = `Add BRAINCHAIN_PAYER_KEY to this server's env in your MCP client config (in Claude Code, \`claude mcp add … -e BRAINCHAIN_PAYER_KEY=…\`), then restart the server. ` +
|
|
18
|
+
`${GET_TASK_NAME} works without a key.`;
|
|
19
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
20
|
+
export function payerAccount(env) {
|
|
21
|
+
const raw = env.BRAINCHAIN_PAYER_KEY?.trim();
|
|
22
|
+
// A client that cannot expand ${VAR} passes it through as written. Anything
|
|
23
|
+
// that could be key material is never echoed.
|
|
24
|
+
if (raw?.startsWith("$")) {
|
|
25
|
+
const shown = /[0-9a-f]{16,}/i.test(raw) ? "" : ` ${raw}`;
|
|
26
|
+
throw new Error(`BRAINCHAIN_PAYER_KEY is not set: your MCP client passed the placeholder${shown} through unexpanded, so the variable was not set when the client started.`);
|
|
27
|
+
}
|
|
28
|
+
const key = raw?.replace(/^0x/i, "");
|
|
29
|
+
if (!key)
|
|
30
|
+
throw new Error("Set BRAINCHAIN_PAYER_KEY to the private key of the wallet that pays for tasks: 64 hex characters, with or without 0x.");
|
|
31
|
+
if (!/^[0-9a-f]{64}$/i.test(key))
|
|
32
|
+
throw new Error("BRAINCHAIN_PAYER_KEY must be 64 hex characters, with or without 0x.");
|
|
33
|
+
try {
|
|
34
|
+
return privateKeyToAccount(`0x${key}`);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new Error("BRAINCHAIN_PAYER_KEY is not a valid private key.");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function chainClients(config) {
|
|
41
|
+
const chain = defineChain({
|
|
42
|
+
id: config.chainId,
|
|
43
|
+
name: config.chain,
|
|
44
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
45
|
+
rpcUrls: { default: { http: [config.rpc] } },
|
|
46
|
+
});
|
|
47
|
+
return { chain, reader: createPublicClient({ chain, transport: http(config.rpc, { retryCount: 2, timeout: 15_000 }) }) };
|
|
48
|
+
}
|
|
49
|
+
export function approveCommand(config, version) {
|
|
50
|
+
return `${config.name === "testnet" ? "BRAINCHAIN_NETWORK=testnet " : ""}npx -y brainchain-mcp@${version} approve`;
|
|
51
|
+
}
|
|
52
|
+
/** A missing key or a bad setting is reported when a tool needs it, so the server always starts and lists its tools. */
|
|
53
|
+
function deskFor(env, version, fetchImpl) {
|
|
54
|
+
let config;
|
|
55
|
+
try {
|
|
56
|
+
config = resolveConfig(env);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const problem = `${messageOf(error)} Fix it in this server's environment and restart the server.`;
|
|
60
|
+
const refuse = async () => {
|
|
61
|
+
throw new Error(problem);
|
|
62
|
+
};
|
|
63
|
+
return { desk: { post: refuse, get: refuse }, terms: problem };
|
|
64
|
+
}
|
|
65
|
+
let account;
|
|
66
|
+
const payer = () => {
|
|
67
|
+
try {
|
|
68
|
+
return (account ??= payerAccount(env));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
throw new Error(`${messageOf(error)} ${KEY_HELP}`);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const { reader } = chainClients(config);
|
|
75
|
+
const desk = createDesk({
|
|
76
|
+
config,
|
|
77
|
+
signer: payer,
|
|
78
|
+
approveCommand: approveCommand(config, version),
|
|
79
|
+
fetch: fetchImpl,
|
|
80
|
+
funds: async () => {
|
|
81
|
+
const { address } = payer();
|
|
82
|
+
const [balance, allowance] = await Promise.all([
|
|
83
|
+
reader.readContract({ address: config.asset, abi: erc20, functionName: "balanceOf", args: [address] }),
|
|
84
|
+
config.permit2 ? reader.readContract({ address: config.asset, abi: erc20, functionName: "allowance", args: [address, PERMIT2] }) : undefined,
|
|
85
|
+
]);
|
|
86
|
+
return { balance, allowance };
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
return { desk, terms: config.terms };
|
|
90
|
+
}
|
|
91
|
+
export function createServer(env, version, options = {}) {
|
|
92
|
+
const { desk, terms } = deskFor(env, version, options.fetch);
|
|
93
|
+
if (typeof terms === "string")
|
|
94
|
+
(options.log ?? console.error)(`brainchain-mcp has an invalid setting: ${terms}`);
|
|
95
|
+
const tools = [postTaskTool(terms), GET_TASK_TOOL];
|
|
96
|
+
const server = new Server({ name: "brainchain", title: "BrainChain", version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
97
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
|
|
98
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => callTool(desk, request.params.name, request.params.arguments));
|
|
99
|
+
return server;
|
|
100
|
+
}
|
package/dist/tools.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
|
+
import { REPOST_AFTER_MINUTES } from "./config.js";
|
|
1
2
|
export const POST_TASK_NAME = "brainchain_post_task";
|
|
2
3
|
export const GET_TASK_NAME = "brainchain_get_task";
|
|
4
|
+
/** Given a configuration error instead of terms, the description leads with it. */
|
|
3
5
|
export function postTaskTool(terms) {
|
|
6
|
+
const about = `Pay for a task on BrainChain. Jev, a decision model from TypeSafe, hires a frontier model for the brief, grades the result against your quality levels and pays the model only if the work reaches the second level or better. ` +
|
|
7
|
+
`Briefs and results are public, so never include credentials or code that cannot be published. `;
|
|
4
8
|
return {
|
|
5
9
|
name: POST_TASK_NAME,
|
|
6
10
|
title: "Post a paid task to BrainChain",
|
|
7
|
-
description:
|
|
8
|
-
`
|
|
9
|
-
|
|
11
|
+
description: typeof terms === "string"
|
|
12
|
+
? `Invalid setting: ${terms} Until then this tool only returns that error. ${about}`
|
|
13
|
+
: about +
|
|
14
|
+
`Each task costs ${terms.cost}, paid from this server's wallet on ${terms.chain}. The result is delivered only if Jev accepts the work. If Jev rejects the work, the full amount is refunded to the same wallet on ${terms.chain}, ${terms.finalAfter} after grading. If no model delivers within 24 hours, the full amount is refunded. ` +
|
|
15
|
+
`Returns an order id for ${GET_TASK_NAME}; results usually arrive within minutes. If the reply says possiblyCharged, do not post the task again: read the order with ${GET_TASK_NAME}. ` +
|
|
16
|
+
`While this server keeps running, an identical post within ${REPOST_AFTER_MINUTES} minutes returns the first post's order, marked duplicate, instead of paying again.`,
|
|
10
17
|
inputSchema: {
|
|
11
18
|
type: "object",
|
|
12
19
|
properties: {
|
|
@@ -14,7 +21,7 @@ export function postTaskTool(terms) {
|
|
|
14
21
|
brief: {
|
|
15
22
|
type: "string",
|
|
16
23
|
minLength: 1,
|
|
17
|
-
maxLength:
|
|
24
|
+
maxLength: 32000,
|
|
18
25
|
description: "What to produce, in what format, and anything the model must not do. Models cannot browse, so include every fact they need.",
|
|
19
26
|
},
|
|
20
27
|
levels: {
|
|
@@ -35,30 +42,41 @@ export const GET_TASK_TOOL = {
|
|
|
35
42
|
name: GET_TASK_NAME,
|
|
36
43
|
title: "Read a BrainChain order",
|
|
37
44
|
description: "Read an order from brainchain_post_task: the payment, the task's status on BrainChain, Jev's grade, the result text once the work is accepted, and the refund transaction if it is not. " +
|
|
38
|
-
"
|
|
45
|
+
"Call again after `retryAfterSeconds` until `done` is true. `next` says what the order's state means and what to do.",
|
|
39
46
|
inputSchema: {
|
|
40
47
|
type: "object",
|
|
41
|
-
properties: { order: { type: "string", pattern: "^0x[0-9a-
|
|
48
|
+
properties: { order: { type: "string", pattern: "^0x[0-9a-fA-F]{64}$", description: "Order id returned by brainchain_post_task." } },
|
|
42
49
|
required: ["order"],
|
|
43
50
|
additionalProperties: false,
|
|
44
51
|
},
|
|
45
52
|
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
46
53
|
};
|
|
47
|
-
|
|
54
|
+
const trimmed = (value, max) => (typeof value === "string" && value.trim().length > 0 && value.trim().length <= max ? value.trim() : undefined);
|
|
55
|
+
/** The desk's own limits, applied to what is sent, before anything is signed. Returns an error message, or the trimmed brief. */
|
|
48
56
|
export function checkBrief(input) {
|
|
49
|
-
const
|
|
50
|
-
if (
|
|
57
|
+
const title = trimmed(input.title, 120);
|
|
58
|
+
if (!title)
|
|
51
59
|
return "title must be 1 to 120 characters.";
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
60
|
+
const brief = trimmed(input.brief, 32_000);
|
|
61
|
+
if (!brief)
|
|
62
|
+
return "brief must be 1 to 32,000 characters.";
|
|
63
|
+
const levels = Array.isArray(input.levels) ? input.levels.map((l) => trimmed(l, 200)) : [];
|
|
64
|
+
if (levels.length < 2 || levels.length > 3 || !levels.every((l) => l !== undefined)) {
|
|
55
65
|
return "levels must list 2 or 3 quality levels, best first, each 1 to 200 characters.";
|
|
56
66
|
}
|
|
57
|
-
return { title
|
|
67
|
+
return { title, brief, levels };
|
|
58
68
|
}
|
|
59
69
|
function reply(value, isError = false) {
|
|
60
70
|
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], isError };
|
|
61
71
|
}
|
|
72
|
+
/** The result text goes out as its own block, as written, rather than escaped inside the JSON. */
|
|
73
|
+
function orderReply(view) {
|
|
74
|
+
const { resultText, ...rest } = view;
|
|
75
|
+
const result = reply(rest);
|
|
76
|
+
if (typeof resultText === "string")
|
|
77
|
+
result.content.push({ type: "text", text: resultText });
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
62
80
|
export async function callTool(desk, name, args) {
|
|
63
81
|
const input = (args ?? {});
|
|
64
82
|
try {
|
|
@@ -69,9 +87,10 @@ export async function callTool(desk, name, args) {
|
|
|
69
87
|
return reply(await desk.post(brief));
|
|
70
88
|
}
|
|
71
89
|
if (name === GET_TASK_NAME) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
const order = typeof input.order === "string" ? input.order.trim().toLowerCase() : "";
|
|
91
|
+
if (!/^0x[0-9a-f]{64}$/.test(order))
|
|
92
|
+
return reply({ error: "order must be the 0x-prefixed, 64-character hex id that brainchain_post_task returned." }, true);
|
|
93
|
+
return orderReply(await desk.get(order));
|
|
75
94
|
}
|
|
76
95
|
return reply({ error: `Unknown tool ${name}.` }, true);
|
|
77
96
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brainchain-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "MCP server for BrainChain: hire frontier
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "MCP server for BrainChain: let your agent hire a frontier model for a task and pay in USDG on Robinhood Chain or USDC on Base, only for work that meets the quality bar you set.",
|
|
5
5
|
"mcpName": "com.usebrainchain/brainchain",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "BrainChain <hello@usebrainchain.com>",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"dist"
|
|
27
27
|
],
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": ">=
|
|
29
|
+
"node": ">=22"
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
32
|
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
@@ -43,5 +43,12 @@
|
|
|
43
43
|
"@types/node": "^22.10.2",
|
|
44
44
|
"typescript": "^5.7.2",
|
|
45
45
|
"vitest": "^2.1.5"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/usebrainchain/brainchain-mcp.git"
|
|
50
|
+
},
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/usebrainchain/brainchain-mcp/issues"
|
|
46
53
|
}
|
|
47
54
|
}
|