@priors/mcp 0.2.11 → 0.5.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 +50 -11
- package/bin/priors-mcp.mjs +1 -1
- package/deployments/4663.v2.json +4 -1
- package/package.json +2 -2
- package/src/server.mjs +345 -46
package/README.md
CHANGED
|
@@ -2,15 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
An MCP server that gives an AI assistant (Claude Desktop, Claude Code, or any MCP client) a USDG wallet on Robinhood
|
|
4
4
|
Chain: pay x402-priced APIs, check balances, read any agent's [Priors](https://priors.trade) credit record, and
|
|
5
|
-
borrow from and repay the agent's own Priors line.
|
|
5
|
+
borrow from and repay the agent's own Priors line, and keep its spare USDG saved in a Morpho vault until it needs it.
|
|
6
6
|
|
|
7
7
|
## Just reading? Use the hosted server
|
|
8
8
|
|
|
9
9
|
No install and no key: `https://mcp.priors.trade/mcp` (Streamable HTTP) answers the read-only questions (an agent's
|
|
10
10
|
record and score, the pool's figures, recent loans, the facilitator's services) from the same public data as
|
|
11
|
-
priors.trade. It holds no key and cannot send a transaction.
|
|
12
|
-
`request_borrow` / `request_repay` return two links where the agent's owner confirms the borrow or repayment: one in
|
|
13
|
-
Go mode, one in the agent console on priors.trade for the wallet that owns the agent.
|
|
11
|
+
priors.trade. It holds no key and cannot send a transaction.
|
|
14
12
|
|
|
15
13
|
```bash
|
|
16
14
|
claude mcp add --transport http priors https://mcp.priors.trade/mcp
|
|
@@ -23,13 +21,18 @@ repaying.
|
|
|
23
21
|
|
|
24
22
|
| tool | what it does | needs the key |
|
|
25
23
|
|---|---|---|
|
|
26
|
-
| `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase (the same method, URL and body) that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
|
|
24
|
+
| `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?, use_savings?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); once the 402 names the price, if the wallet is short it first takes the difference out of savings (unless `use_savings: false`), and borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase (the same method, URL and body) that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
|
|
27
25
|
| `wallet_balance(address?)` | USDG and gas ETH of the wallet (or any address) | no (with `address`) |
|
|
28
26
|
| `credit_status(agent_id?)` | line, drawn, available, backer, record, score, open loans and due dates; on a stock line, the stock tokens behind it, and `available` capped by what the stock vault lets it draw | no (with `agent_id`) |
|
|
29
27
|
| `stock_assets(symbol?)` | the stock tokens the Priors stock vault accepts: live Chainlink price, whether it lends against each now (or why not: a sharp price move, a multiplier change, a paused or blocked token), loan-to-value | no |
|
|
30
28
|
| `stock_position(agent_id?)` | the stock tokens behind an agent's stock line: amount, what the vault values them at, loan-to-value, what the line can draw now, any lending hold | no (with `agent_id`) |
|
|
31
29
|
| `borrow(amount_usd, days, dry_run?)` | borrow USDG from the line into the wallet; both amounts required; `dry_run` quotes the fee. A borrow sent whose answer is lost is counted and said to be possibly open (check `credit_status`) | yes |
|
|
32
|
-
| `repay(loan_id? \| all)` | repay one of the agent's own loans, or all of them earliest due first; another agent's loan is refused | yes |
|
|
30
|
+
| `repay(loan_id? \| all, use_savings?)` | repay one of the agent's own loans, or all of them earliest due first; another agent's loan is refused. If the wallet is short of what is due, it first takes the difference out of savings (unless `use_savings: false`) | yes |
|
|
31
|
+
| `savings(address?)` | what the wallet (or any address) has saved in the savings vault, how much can come out right now, and the USDG in the wallet | no (with `address`) |
|
|
32
|
+
| `save(amount_usd)` | move spare USDG from the wallet into the savings vault, where it earns the vault's rate (at most `PRIORS_MAX_SAVE_USD` per call, `PRIORS_MAX_SAVE_TOTAL_USD` per run); needs ETH for gas | yes |
|
|
33
|
+
| `unsave(amount_usd? \| all)` | take USDG back out of savings into the wallet: a normal withdrawal, and when that is not enough, the rest from the vault's other markets in the same transaction (only where that costs no penalty); refused before any transaction when even that cannot pay it; needs ETH for gas | yes |
|
|
34
|
+
| `autopay_on(cap_usd?, use_savings?, late?, budget_usd?)` | turn on Autopay: the wallet approves AutoRepay for a budget (4 x the limit per loan, never unlimited) and enrolls, so each loan is repaid from the wallet (then its savings, if chosen) in the 6 hours before it is due, with no call per loan, while the wallet holds enough. It makes an on-time repayment more likely; it is not a promise. Default limit: the line plus a 30-day fee, at most `PRIORS_MAX_AUTOPAY_USD`; call again to approve more. Works once AutoRepay is deployed; needs ETH for gas | yes |
|
|
35
|
+
| `autopay_off(clear_budget?)` | turn Autopay off (and with `clear_budget`, set the approvals to 0) | yes |
|
|
33
36
|
| `score_of(agent_id)` | any agent's on-chain score (0 to 1000) and repayment record, plus its Priors Score v2 and trust rung when published | no |
|
|
34
37
|
| `find_services(query?)` | services registered with the Priors facilitator that accept USDG (`GET /merchants`), each marked as approved by Priors or self-registered and not reviewed | no |
|
|
35
38
|
|
|
@@ -37,6 +40,34 @@ Tools that move money state the amounts in their answer, are marked destructive
|
|
|
37
40
|
descriptions tell the assistant to confirm with you first. Merchant text (response bodies, listings, redirect targets)
|
|
38
41
|
comes back between random `<<merchant-data …>>` markers, as data. They act on Robinhood Chain mainnet.
|
|
39
42
|
|
|
43
|
+
## Savings
|
|
44
|
+
|
|
45
|
+
Spare USDG doesn't have to sit idle. `save` puts it in a Morpho vault (Steakhouse USDG by default, a Morpho Vault V2
|
|
46
|
+
curated by Steakhouse Financial), where it earns the vault's rate. When the agent has to pay (`pay_url`) or repay
|
|
47
|
+
(`repay`) and its wallet is short, the server takes the difference back out first, and only then borrows. That makes
|
|
48
|
+
an on-time repayment more likely; it does not guarantee one: savings come out only while the vault's markets have
|
|
49
|
+
liquidity.
|
|
50
|
+
|
|
51
|
+
It is the agent's own money in someone else's vault: Priors never holds it, and the saver carries the vault's risks: a
|
|
52
|
+
loss in one of its markets lowers the share value at once; its curator and allocators choose the markets and some
|
|
53
|
+
settings change with no timelock; liquidity can be lent out; USDG's issuer can freeze addresses. The rate moves with
|
|
54
|
+
Morpho's markets. How money goes in and comes out: the Savings section of
|
|
55
|
+
[@priors/x402's README](https://www.npmjs.com/package/@priors/x402).
|
|
56
|
+
|
|
57
|
+
How the server handles it: the vault must be a contract whose asset is USDG; `save` checks the vault's deposit gate
|
|
58
|
+
before approving, and approves the amount only when the current allowance is lower; every vault transaction is sent
|
|
59
|
+
with a gas margin; what can come out is found by simulating the withdrawal (Morpho Vault V2 answers 0 to `maxWithdraw`
|
|
60
|
+
by design). A failed top-up never stops a payment or repayment, and the answer says what happened.
|
|
61
|
+
|
|
62
|
+
A top-up is bounded by the call's own time. When time runs out it stops before sending anything; if a withdrawal
|
|
63
|
+
was already sent and has not confirmed, `pay_url` neither borrows nor signs, says so, and the next money call waits
|
|
64
|
+
for that withdrawal. `save` keeps the USDG that signed, unsettled payments still need.
|
|
65
|
+
|
|
66
|
+
`PRIORS_SAVINGS_VAULT=off` stops `save` and the automatic top-ups, not the way out: `savings` and `unsave` keep working
|
|
67
|
+
on the default vault. Pointing `PRIORS_SAVINGS_VAULT` at another vault means trusting that vault (the only check is a
|
|
68
|
+
contract whose asset is USDG); money saved in the default one stays there, and money saved in a custom one is reached
|
|
69
|
+
by setting that vault again.
|
|
70
|
+
|
|
40
71
|
## Configure
|
|
41
72
|
|
|
42
73
|
The only secret is the wallet key, and it is read from the environment variable `PRIORS_KEY`, never from the command
|
|
@@ -56,6 +87,13 @@ dedicated agent wallet holding only what the agent may spend.
|
|
|
56
87
|
| `PRIORS_ALLOW_LOCAL` | off | `1` lets `pay_url` reach `http://localhost` and private addresses (local testing only) |
|
|
57
88
|
| `PRIORS_SCORE_V2` | `https://priors.trade/api/score-v2` | where `score_of` reads Priors Score v2; `off` shows the on-chain score only |
|
|
58
89
|
| `PRIORS_STOCK_VAULT` | the bundled deployments file's `stockVault` | the stock vault the stock tools and `credit_status` read |
|
|
90
|
+
| `PRIORS_SAVINGS_VAULT` | Steakhouse USDG on Morpho (`0xBeEff033F34C046626B8D0A041844C5d1A5409dd`) | the USDG vault savings go to; `off` (or `false`, `0`, `no`) stops `save` and the automatic top-ups, while `savings` and `unsave` keep working on the default vault. Its value is never echoed |
|
|
91
|
+
| `PRIORS_MAX_SAVE_USD` | `50` | most one `save` call may move into the vault |
|
|
92
|
+
| `PRIORS_MAX_SAVE_TOTAL_USD` | `200` | most `save` may move in total while the server runs |
|
|
93
|
+
| `PRIORS_AUTOREPAY` | the bundled deployments file's `autoRepay` (none until AutoRepay v2 is deployed) | AutoRepay v2's address, for `autopay_on`, `autopay_off` and the Autopay lines of `credit_status`; AutoRepay v1 (retired before use) is refused |
|
|
94
|
+
| `PRIORS_V5`, `PRIORS_V5_ROOT` | the bundled deployments file's `seatVaultV5` and `seatVaultV5AgentId` (none until V5 is deployed) | SeatVaultV5 and its root's agent id: a borrow on a V5 line (the `borrow` tool, `pay_url`) refreshes it first. The agent's key may do so 24 hours after V5 recorded it (`noteDelegate`, sent for it when needed); until then a borrow goes ahead only within the line's room, and the tool says when the key can borrow more |
|
|
95
|
+
| `PRIORS_MAX_AUTOPAY_USD` | `25` | the most `autopay_on` enrolls per loan (stage 0) |
|
|
96
|
+
| `PRIORS_AUTOPAY_RESERVE` | on | with Autopay on, `pay_url` keeps back what loans whose window opens in the next 24 h will pull, and says so when a payment would cut into it; `off` turns that off |
|
|
59
97
|
| `PRIORS_STATE_DIR` | `~/.local/state/priors-mcp` | where the payments signed and not yet settled are kept (one owner-only file per wallet, never the key, with a short-lived `.lock` beside it while it is written), so a restart, a new session or another session of the same wallet resends them instead of signing again. An absolute path, or one starting with `~/` (a relative one is refused at start). A payment that cannot be written there is not sent. `off` keeps them in memory only |
|
|
60
98
|
|
|
61
99
|
Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
|
|
@@ -71,7 +109,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
|
|
|
71
109
|
"mcpServers": {
|
|
72
110
|
"priors": {
|
|
73
111
|
"command": "npx",
|
|
74
|
-
"args": ["-y", "@priors/mcp@0.
|
|
112
|
+
"args": ["-y", "@priors/mcp@0.5.0"],
|
|
75
113
|
"env": {
|
|
76
114
|
"PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
|
|
77
115
|
"PRIORS_AGENT_ID": "1234"
|
|
@@ -93,7 +131,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
93
131
|
"mcpServers": {
|
|
94
132
|
"priors": {
|
|
95
133
|
"command": "npx",
|
|
96
|
-
"args": ["-y", "@priors/mcp@0.
|
|
134
|
+
"args": ["-y", "@priors/mcp@0.5.0"],
|
|
97
135
|
"env": {
|
|
98
136
|
"PRIORS_KEY": "${PRIORS_KEY}",
|
|
99
137
|
"PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
|
|
@@ -103,7 +141,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
103
141
|
}
|
|
104
142
|
```
|
|
105
143
|
|
|
106
|
-
or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.
|
|
144
|
+
or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.5.0`
|
|
107
145
|
(the key is expanded by your shell from the environment; do not paste it on the command line).
|
|
108
146
|
|
|
109
147
|
## Try it
|
|
@@ -111,6 +149,7 @@ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIO
|
|
|
111
149
|
"What's the Priors score of agent 6228?" · "How much USDG does my wallet hold?" · "Find services that sell token
|
|
112
150
|
prices" · "Pay https://api.example.com/report, up to 5 cents" · "Borrow $5 for 7 days, show me the fee first".
|
|
113
151
|
|
|
114
|
-
##
|
|
152
|
+
## Tests
|
|
115
153
|
|
|
116
|
-
|
|
154
|
+
`npm run test:packages` in the Priors repository lists and calls every tool through the MCP SDK's in-memory client and
|
|
155
|
+
over stdio, and checks that the key never appears in any output or error.
|
package/bin/priors-mcp.mjs
CHANGED
|
@@ -9,7 +9,7 @@ if (argv.some((a) => /(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}($|[^0-9a-fA-F])/.test
|
|
|
9
9
|
process.exit(2);
|
|
10
10
|
}
|
|
11
11
|
if (argv.includes("--help") || argv.includes("-h")) {
|
|
12
|
-
process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
|
|
12
|
+
process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_SAVINGS_VAULT, PRIORS_MAX_SAVE_USD, PRIORS_MAX_SAVE_TOTAL_USD, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
|
|
13
13
|
process.exit(0);
|
|
14
14
|
}
|
|
15
15
|
if (argv.length > 0) {
|
package/deployments/4663.v2.json
CHANGED
|
@@ -29,5 +29,8 @@
|
|
|
29
29
|
"seatVaultV4AgentId": 6466,
|
|
30
30
|
"seatVaultV4Block": 75614831,
|
|
31
31
|
"seatSizerV4": "0x97C4e594D458f8BBE961d5384Bbd8a9Cc2D18777",
|
|
32
|
-
"seatSizerV4Block": 75614955
|
|
32
|
+
"seatSizerV4Block": 75614955,
|
|
33
|
+
"autoRepayV1": "0x765f51Bd38404154762f2822d3ac5d16CE9AF822",
|
|
34
|
+
"autoRepayV1Block": 79616581,
|
|
35
|
+
"autoRepayV1Note": "AutoRepay v1: retired before use, never enrolled, no allowance. Replaced by AutoRepay v2, recorded here as autoRepay and autoRepayBlock once deployed. Kept so the score mapping recognises both; nothing else uses it."
|
|
33
36
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@priors/mcp",
|
|
3
3
|
"mcpName": "io.github.priors-agents/priors",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.5.0",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay. Key from PRIORS_KEY only.",
|
|
7
7
|
"type": "module",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
46
|
-
"@priors/x402": "0.
|
|
46
|
+
"@priors/x402": "0.5.0",
|
|
47
47
|
"ethers": "^6.13.4",
|
|
48
48
|
"undici": "6.29.0",
|
|
49
49
|
"zod": "^4.6.5"
|
package/src/server.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @priors/mcp: an MCP server that lets an AI assistant pay x402 URLs in USDG on Robinhood Chain and run a Priors
|
|
2
|
-
// credit line. Tools: pay_url, wallet_balance, credit_status,
|
|
3
|
-
// find_services.
|
|
2
|
+
// credit line, with the agent's spare USDG saved in a Morpho vault. Tools: pay_url, wallet_balance, credit_status,
|
|
3
|
+
// stock_assets, stock_position, borrow, repay, score_of, find_services, savings, save, unsave, autopay_on, autopay_off.
|
|
4
4
|
//
|
|
5
5
|
// The private key comes from the environment (PRIORS_KEY) only. It is never read from argv, never logged, and never
|
|
6
6
|
// part of any tool result or error: every text this server returns passes through `redact()`, which removes the key
|
|
@@ -18,6 +18,18 @@
|
|
|
18
18
|
// PRIORS_ALLOW_LOCAL "1": pay_url may reach http://localhost and private addresses (testing only)
|
|
19
19
|
// PRIORS_SCORE_V2 where score_of reads Priors Score v2 (default https://priors.trade/api/score-v2; "off": v1 only)
|
|
20
20
|
// PRIORS_STOCK_VAULT the stock vault's address (default: deployments/4663.v2.json `stockVault`)
|
|
21
|
+
// PRIORS_SAVINGS_VAULT the USDG vault savings go to (default Steakhouse USDG on Morpho). "off" stops save and the
|
|
22
|
+
// automatic top-ups; savings and unsave keep working on the default vault, so saved money can
|
|
23
|
+
// always come out
|
|
24
|
+
// PRIORS_MAX_SAVE_USD most one save call may move into the vault (default 50)
|
|
25
|
+
// PRIORS_MAX_SAVE_TOTAL_USD most save may move in total while the server runs (default 200)
|
|
26
|
+
// PRIORS_AUTOREPAY AutoRepay v2's address (default: deployments/4663.v2.json `autoRepay`; none until it is
|
|
27
|
+
// deployed: autopay_on and autopay_off then say so). AutoRepay v1 (retired) is refused
|
|
28
|
+
// PRIORS_V5, PRIORS_V5_ROOT SeatVaultV5's address and its root's agent id (default: deployments/4663.v2.json
|
|
29
|
+
// `seatVaultV5`, `seatVaultV5AgentId`; none until V5 is deployed): a borrow on a V5 line
|
|
30
|
+
// refreshes it first (owner, or this key 24 h after V5 recorded it with noteDelegate)
|
|
31
|
+
// PRIORS_MAX_AUTOPAY_USD the most autopay_on enrolls per loan (default 25, the stage 0 cap)
|
|
32
|
+
// PRIORS_AUTOPAY_RESERVE "off": pay_url no longer keeps back what Autopay loans pull in the next 24 h (default on)
|
|
21
33
|
// PRIORS_STATE_DIR where signed, unsettled payments are kept across restarts and shared by every session of the
|
|
22
34
|
// wallet (default ~/.local/state/priors-mcp; "off": memory only)
|
|
23
35
|
import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
|
|
@@ -35,13 +47,13 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
35
47
|
// @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
|
|
36
48
|
async function loadX402() {
|
|
37
49
|
try {
|
|
38
|
-
return { X: await import("@priors/x402"), C: await import("@priors/x402/credit") };
|
|
50
|
+
return { X: await import("@priors/x402"), C: await import("@priors/x402/credit"), S: await import("@priors/x402/savings"), A: await import("@priors/x402/autopay") };
|
|
39
51
|
} catch (e) {
|
|
40
52
|
if (e?.code !== "ERR_MODULE_NOT_FOUND" || !String(e.message).includes("@priors/x402")) throw e;
|
|
41
|
-
return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs") };
|
|
53
|
+
return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs"), S: await import("../../x402/src/savings.mjs"), A: await import("../../x402/src/autopay.mjs") };
|
|
42
54
|
}
|
|
43
55
|
}
|
|
44
|
-
const { X, C } = await loadX402();
|
|
56
|
+
const { X, C, S, A } = await loadX402();
|
|
45
57
|
|
|
46
58
|
export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
47
59
|
const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
|
|
@@ -179,7 +191,22 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
179
191
|
// Per-call caps alone let a model (or a page steering it) spend the wallet a dollar at a time: these bound the process.
|
|
180
192
|
const spendCap = envDollars(env, "PRIORS_MAX_SPEND_USD", 5);
|
|
181
193
|
const borrowTotalCap = envDollars(env, "PRIORS_MAX_BORROW_TOTAL_USD", 25);
|
|
182
|
-
const
|
|
194
|
+
const maxSaveCeiling = envDollars(env, "PRIORS_MAX_SAVE_USD", 50);
|
|
195
|
+
const saveTotalCap = envDollars(env, "PRIORS_MAX_SAVE_TOTAL_USD", 200);
|
|
196
|
+
// Savings (Morpho). "off" stops new saving and the automatic top-ups, never the way out: savings and unsave then read
|
|
197
|
+
// the default vault. The setting's value is never echoed (a key pasted into it must not reach the model).
|
|
198
|
+
const savingsRaw = String(env.PRIORS_SAVINGS_VAULT ?? "").trim();
|
|
199
|
+
const savingsOff = /^(off|false|0|no|none)$/i.test(savingsRaw);
|
|
200
|
+
const savingsVault = savingsOff || savingsRaw === "" ? S.DEFAULT_SAVINGS_VAULT : savingsRaw;
|
|
201
|
+
const savingsProblem = ethers.isAddress(savingsVault) ? null
|
|
202
|
+
: looksLikeKey(savingsRaw) ? "PRIORS_SAVINGS_VAULT holds what looks like a private key, not a vault address: take it out of that variable and restart the server"
|
|
203
|
+
: "PRIORS_SAVINGS_VAULT is not a 0x address: fix it and restart the server";
|
|
204
|
+
const autoSavings = !savingsOff && !savingsProblem;
|
|
205
|
+
// Autopay: the agent's wallet approves AutoRepay and enrolls; the keeper repays in the
|
|
206
|
+
// window. The cap per loan is bounded by this server (stage 0: $25); pay_url keeps back what Autopay loans pull soon.
|
|
207
|
+
const maxAutopayCap = envDollars(env, "PRIORS_MAX_AUTOPAY_USD", 25);
|
|
208
|
+
const reserveOn = !/^(off|false|0|no)$/i.test(String(env.PRIORS_AUTOPAY_RESERVE ?? "").trim());
|
|
209
|
+
const session = { spent: 0n, borrowed: 0n, saved: 0n };
|
|
183
210
|
const allowLocal = env.PRIORS_ALLOW_LOCAL === "1";
|
|
184
211
|
const lookup = deps.lookup || ((host) => dnsLookup(host, { all: true }));
|
|
185
212
|
const sleep = deps.sleep; // undefined: the library's own
|
|
@@ -194,10 +221,21 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
194
221
|
let moneyQueue = Promise.resolve();
|
|
195
222
|
// The time budget counts from the call's arrival, not from its turn: a call queued behind a slow one must still answer
|
|
196
223
|
// before the client gives up (a client timeout hides the "do not retry" answer and invites a retry).
|
|
224
|
+
// A savings withdrawal sent by a top-up that ran out of time, still in flight: every money call waits for it (at
|
|
225
|
+
// most until its own deadline), so none sends a second withdrawal or borrows for money that is on its way. The hold
|
|
226
|
+
// ends when the withdrawal settles, or after HOLD_MAX_MS whatever happens (a dropped transaction can't lock the queue).
|
|
227
|
+
let hold = null;
|
|
228
|
+
const HOLD_MAX_MS = deps.holdMaxMs ?? 120_000;
|
|
197
229
|
const serial = (fn) => (args) => {
|
|
198
230
|
const deadline = Date.now() + callBudgetMs;
|
|
199
|
-
const
|
|
200
|
-
|
|
231
|
+
const margin = Math.min(1000, callBudgetMs / 10);
|
|
232
|
+
const run = moneyQueue.then(async () => {
|
|
233
|
+
if (hold) {
|
|
234
|
+
const h = hold;
|
|
235
|
+
await Promise.race([h, new Promise((ok) => setTimeout(ok, Math.max(0, deadline - margin - Date.now())).unref?.())]);
|
|
236
|
+
if (hold === h) throw new ToolError("a savings withdrawal from an earlier call is still in flight. Nothing was done: check the savings tool and try again in a minute.");
|
|
237
|
+
}
|
|
238
|
+
if (Date.now() >= deadline - margin) throw new ToolError("another payment call was still running and this one ran out of time before it could start. Nothing was signed or paid: try again.");
|
|
201
239
|
return fn(args, deadline);
|
|
202
240
|
});
|
|
203
241
|
moneyQueue = run.catch(() => {});
|
|
@@ -228,7 +266,11 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
228
266
|
for (const n of ["PAYMENT-RESPONSE", "X-PAYMENT-RESPONSE"]) { const h = res.headers.get(n); if (h) { try { return JSON.parse(Buffer.from(h, "base64").toString("utf8")); } catch (_) { /* not ours to read */ } } }
|
|
229
267
|
return undefined;
|
|
230
268
|
};
|
|
231
|
-
const addresses = { ...ADDRESSES, ...(env.PRIORS_STOCK_VAULT ? { stockVault: env.PRIORS_STOCK_VAULT } : {}),
|
|
269
|
+
const addresses = { ...ADDRESSES, ...(env.PRIORS_STOCK_VAULT ? { stockVault: env.PRIORS_STOCK_VAULT } : {}),
|
|
270
|
+
...(env.PRIORS_V5 ? { seatVaultV5: env.PRIORS_V5 } : {}), ...(env.PRIORS_V5_ROOT ? { seatVaultV5AgentId: env.PRIORS_V5_ROOT } : {}), ...(deps.addresses || {}) };
|
|
271
|
+
// SeatVaultV5, when known: both its address and its root's agent id, or neither (L-05: a borrow on its line refreshes it)
|
|
272
|
+
const v5 = addresses.seatVaultV5 && ethers.isAddress(String(addresses.seatVaultV5)) && /^[1-9][0-9]*$/.test(String(addresses.seatVaultV5AgentId ?? ""))
|
|
273
|
+
? { v5: ethers.getAddress(String(addresses.seatVaultV5)), v5Root: BigInt(addresses.seatVaultV5AgentId) } : { v5: null, v5Root: null };
|
|
232
274
|
|
|
233
275
|
// Everything returned passes through here. The key is cut with or without 0x, in any case, and with separators between
|
|
234
276
|
// its digits (spaced, split over lines, dashed, JSON-quoted chunks). A private RPC URL is cut whole and by its parts
|
|
@@ -268,17 +310,20 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
268
310
|
if (stateHome && !/^(off|none|false|0)$/i.test(stateHome) && !isAbsolute(stateHome)) throw new Error(`PRIORS_STATE_DIR must be an absolute path (or start with ~/), not "${stateRaw}"`);
|
|
269
311
|
const stateDir = /^(off|none|false|0)$/i.test(stateRaw) ? null : stateHome || join(homedir(), ".local", "state", "priors-mcp");
|
|
270
312
|
const stateFile = wallet && stateDir ? join(stateDir, `outstanding-${wallet.address.toLowerCase()}.json`) : null;
|
|
271
|
-
// An entry is { paymentHeaders, validBefore, price
|
|
272
|
-
//
|
|
273
|
-
// is checked on its own, so one bad entry never costs the others. No reviver.
|
|
313
|
+
// An entry is { paymentHeaders, validBefore, price, payTo, borrowed, loanId }: only what this server wrote, never the
|
|
314
|
+
// merchant's requirement object (its fields are the merchant's to choose). On disk the amounts are decimal strings;
|
|
315
|
+
// each entry is checked on its own, so one bad entry never costs the others. No reviver.
|
|
274
316
|
const live = (e, nowS) => e.validBefore + X.SKEW_SECONDS > nowS;
|
|
317
|
+
const DEC = /^\d{1,30}$/;
|
|
275
318
|
function entryFrom(v) {
|
|
276
319
|
if (!v || typeof v !== "object" || !v.paymentHeaders || typeof v.paymentHeaders !== "object") return null;
|
|
277
320
|
const headers = {};
|
|
278
321
|
for (const [k, x] of Object.entries(v.paymentHeaders)) { if (!/^(payment-signature|x-payment)$/i.test(k) || typeof x !== "string") return null; headers[k] = x; }
|
|
279
322
|
const validBefore = Number(v.validBefore);
|
|
280
|
-
if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) ||
|
|
281
|
-
|
|
323
|
+
if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !DEC.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
|
|
324
|
+
const borrowed = DEC.test(String(v.borrowed ?? "0")) ? BigInt(v.borrowed ?? "0") : 0n;
|
|
325
|
+
const loanId = v.loanId !== null && v.loanId !== undefined && DEC.test(String(v.loanId)) ? BigInt(v.loanId) : null;
|
|
326
|
+
return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo), borrowed, loanId };
|
|
282
327
|
}
|
|
283
328
|
function readState() {
|
|
284
329
|
const m = new Map();
|
|
@@ -292,14 +337,15 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
292
337
|
function writeState(m) {
|
|
293
338
|
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
294
339
|
const tmp = `${stateFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
295
|
-
|
|
340
|
+
const out = Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo, borrowed: String(e.borrowed || 0n), loanId: e.loanId === null || e.loanId === undefined ? null : String(e.loanId) }]));
|
|
341
|
+
writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 });
|
|
296
342
|
renameSync(tmp, stateFile);
|
|
297
343
|
}
|
|
298
|
-
// Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a
|
|
299
|
-
// of the file under an exclusive lock file, so no server rewrites
|
|
300
|
-
// Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it.
|
|
301
|
-
// this call only (an async wait, never a blocking one): the server keeps answering meanwhile.
|
|
302
|
-
// lock is held only across synchronous code, so two calls of this server never contend.
|
|
344
|
+
// Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a
|
|
345
|
+
// read-modify-write of the file under an exclusive lock file, so no server rewrites it from its own map and erases
|
|
346
|
+
// another's entries. Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it.
|
|
347
|
+
// Waiting for it delays this call only (an async wait, never a blocking one): the server keeps answering meanwhile.
|
|
348
|
+
// Inside one process the lock is held only across synchronous code, so two calls of this server never contend.
|
|
303
349
|
async function locked(fn) {
|
|
304
350
|
const lock = `${stateFile}.lock`;
|
|
305
351
|
const giveUp = Date.now() + 2000;
|
|
@@ -309,13 +355,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
309
355
|
if (e?.code === "ENOENT") { try { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); continue; } catch (_) { break; } }
|
|
310
356
|
if (e?.code !== "EEXIST") break;
|
|
311
357
|
try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { rmSync(lock, { force: true }); continue; } } catch (_) { continue; }
|
|
312
|
-
if (Date.now() > giveUp) break;
|
|
358
|
+
if (Date.now() > giveUp) break;
|
|
313
359
|
await new Promise((res) => setTimeout(res, 10));
|
|
314
360
|
}
|
|
315
361
|
}
|
|
316
362
|
try { return fn(); } finally { if (held) rmSync(lock, { force: true }); }
|
|
317
363
|
}
|
|
318
|
-
/** Entries another server wrote since: merged in before any decision to sign. */
|
|
364
|
+
/** Entries another server of this wallet wrote since: merged in before any decision to sign. */
|
|
319
365
|
function refresh() { if (stateFile) for (const [k, e] of readState()) if (!outstanding.has(k)) outstanding.set(k, e); }
|
|
320
366
|
/** Kept on file before the payment leaves; a failure throws, and the payer then does not send it (own audit: a
|
|
321
367
|
* record silently lost made a restart or another session sign again). */
|
|
@@ -342,7 +388,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
342
388
|
if (stateFile) { try { await locked(() => { const m = readState(); if (same(m.get(key)) && m.delete(key)) writeState(m); }); } catch (_) { /* best effort */ } }
|
|
343
389
|
}
|
|
344
390
|
refresh();
|
|
345
|
-
const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null } });
|
|
391
|
+
const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null, seatVaultV5: v5.v5, seatVaultV5AgentId: v5.v5Root } });
|
|
346
392
|
|
|
347
393
|
// The chain, behind one facade (tests replace it).
|
|
348
394
|
const credit = deps.credit || {
|
|
@@ -356,7 +402,69 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
356
402
|
loanAgent: async (loanId) => (await contracts.pool.getLoan(loanId)).agentId,
|
|
357
403
|
isController: (id, addr) => contracts.pool.isController(id, addr),
|
|
358
404
|
agentsOf: (addr) => discoverAgents(addr),
|
|
405
|
+
loanDue: async (loanId) => { const l = await contracts.pool.getLoan(loanId); return Number(l.status) === 1 ? l.principal + l.fee : null; },
|
|
406
|
+
// savings: the vault is checked (a contract, asset = USDG) once, on first use
|
|
407
|
+
savingsOf: async (addr) => S.savingsOf(await savingsC(), addr),
|
|
408
|
+
savedOf: async (addr) => { const c = await savingsC(); const sh = await c.vault.balanceOf(addr); return sh === 0n ? 0n : c.vault.previewRedeem(sh); },
|
|
409
|
+
save: async (amount) => S.save(await savingsC(), wallet, amount),
|
|
410
|
+
unsave: async (o) => S.unsave(await savingsC(), wallet, o),
|
|
411
|
+
topUp: async (need, o) => S.topUpFromSavings(await savingsC(), wallet, need, o),
|
|
359
412
|
};
|
|
413
|
+
let savingsCache = null;
|
|
414
|
+
function needSavings() { if (savingsProblem) throw new ToolError(savingsProblem); }
|
|
415
|
+
function savingsC() {
|
|
416
|
+
needSavings();
|
|
417
|
+
if (!savingsCache) savingsCache = S.savingsContracts({ runner: provider, vault: savingsVault, usdg: addresses.usdg }).catch((e) => { savingsCache = null; throw e; });
|
|
418
|
+
return savingsCache;
|
|
419
|
+
}
|
|
420
|
+
/** A read that may be slow (savedNote): at most `ms`. */
|
|
421
|
+
const withinTime = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new ToolError("timed out")), ms).unref?.())]);
|
|
422
|
+
const SAVINGS_WAIT_MS = 30_000;
|
|
423
|
+
/**
|
|
424
|
+
* A top-up bounded by the call's own deadline (at most 30 s). When time runs out it is stopped before it sends
|
|
425
|
+
* anything; if a withdrawal was already sent, the answer says so (`pending`: the payer then neither borrows nor
|
|
426
|
+
* signs) and the next money call waits for that withdrawal to settle.
|
|
427
|
+
*/
|
|
428
|
+
function topUpWithin(need, deadline) {
|
|
429
|
+
const ac = new AbortController();
|
|
430
|
+
const o = { signal: ac.signal };
|
|
431
|
+
const ms = Math.max(1_000, Math.min(SAVINGS_WAIT_MS, (deadline ?? Infinity) - Date.now() - 2_000));
|
|
432
|
+
const p = credit.topUp(need, o);
|
|
433
|
+
return new Promise((resolve, reject) => {
|
|
434
|
+
const t = setTimeout(() => {
|
|
435
|
+
ac.abort();
|
|
436
|
+
if (o.sent || o.sending) {
|
|
437
|
+
const h = Promise.race([p.then(() => {}, () => {}), new Promise((ok) => setTimeout(ok, HOLD_MAX_MS).unref?.())]).then(() => { if (hold === h) hold = null; });
|
|
438
|
+
hold = h;
|
|
439
|
+
reject(Object.assign(new ToolError(`a savings withdrawal${o.sent ? ` (tx ${o.sent})` : ""} was sent and has not confirmed within ${Math.round(ms / 1000)} s; it may still land (the savings tool shows it)`), { pending: true }));
|
|
440
|
+
} else reject(new ToolError(`the savings step took longer than ${Math.round(ms / 1000)} s and was stopped before it sent anything`));
|
|
441
|
+
}, ms);
|
|
442
|
+
t.unref?.();
|
|
443
|
+
p.then((r) => { clearTimeout(t); resolve(r); }, (e) => { clearTimeout(t); reject(e); });
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
function savingsFailure(e) {
|
|
447
|
+
const m = explain(e);
|
|
448
|
+
if (e?.pending || e?.code === "UNCONFIRMED") return `${m}.`;
|
|
449
|
+
return `Could not check or use savings (${/insufficient funds|gas required exceeds|intrinsic gas|NO_GAS/i.test(m) ? "the wallet has no ETH to pay the withdrawal's gas" : m}); went on with the wallet's balance.`;
|
|
450
|
+
}
|
|
451
|
+
/** What a top-up did, as lines for the answer: taken out, still saved but stuck, or why it failed. */
|
|
452
|
+
function savingsLines(r, lines) {
|
|
453
|
+
if (!r) return;
|
|
454
|
+
if (r.error) { lines.push(savingsFailure(r.error)); return; }
|
|
455
|
+
if (r.withdrawn > 0n) lines.push(`Took ${usd(r.withdrawn)} out of savings first${r.inKind ? " (from the vault's other markets, in one transaction)" : ""}${r.hash ? ` (tx ${r.hash})` : ""}.`);
|
|
456
|
+
if (r.short > 0n && r.saved > r.withdrawn) lines.push(`${usd(r.saved - r.withdrawn)} is still saved but the vault could not pay it out right now (its liquidity is lent out); went on with the wallet's balance.`);
|
|
457
|
+
}
|
|
458
|
+
/** Before a repayment: take what the wallet is short of `need` (a value or a function) out of savings. Never fails the call. */
|
|
459
|
+
async function fromSavings(needOf, lines, deadline) {
|
|
460
|
+
if (!autoSavings || typeof credit.topUp !== "function") return;
|
|
461
|
+
try {
|
|
462
|
+
const need = typeof needOf === "function" ? await needOf() : needOf;
|
|
463
|
+
if (need === null || need === undefined) return;
|
|
464
|
+
if (wallet && typeof credit.balances === "function" && (await credit.balances(wallet.address)).usdg >= need) return; // covered: the vault is not touched
|
|
465
|
+
savingsLines(await topUpWithin(need, deadline), lines);
|
|
466
|
+
} catch (e) { lines.push(savingsFailure(e)); }
|
|
467
|
+
}
|
|
360
468
|
|
|
361
469
|
// The registry is not enumerable: find identities minted to `addr` since the v2 deploy, keep what it owns. Only a mint
|
|
362
470
|
// counts: anyone can transfer an identity with an open loan to this wallet, and `repay` would then pay it (own audit).
|
|
@@ -391,7 +499,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
391
499
|
|
|
392
500
|
function needWallet(action) {
|
|
393
501
|
if (keyProblem) throw new ToolError(`${action} needs a wallet, but ${keyProblem}. Fix PRIORS_KEY in the MCP server's environment.`);
|
|
394
|
-
if (!wallet) throw new ToolError(`${action} moves money and needs a wallet: set PRIORS_KEY in the MCP server's environment (never pass a key as a tool argument or on the command line). Read-only tools (wallet_balance with an address, credit_status, stock_assets, stock_position, score_of, find_services) work without it.`);
|
|
502
|
+
if (!wallet) throw new ToolError(`${action} moves money and needs a wallet: set PRIORS_KEY in the MCP server's environment (never pass a key as a tool argument or on the command line). Read-only tools (wallet_balance and savings with an address, credit_status, stock_assets, stock_position, score_of, find_services) work without it.`);
|
|
395
503
|
return wallet;
|
|
396
504
|
}
|
|
397
505
|
async function needController(id) {
|
|
@@ -402,6 +510,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
402
510
|
const failure = (t) => ({ content: [{ type: "text", text: redact(t) }], isError: true });
|
|
403
511
|
const explain = (e) => {
|
|
404
512
|
if (e instanceof ToolError) return e.message;
|
|
513
|
+
if (e?.name === "SavingsError") return `${e.message} [${e.code}]`;
|
|
405
514
|
if (e?.name === "PayError") return `${e.message} [${e.code}]`;
|
|
406
515
|
if (e?.name === "ZodError") return `invalid arguments: ${e.message}`;
|
|
407
516
|
const m = e?.shortMessage || e?.message || String(e);
|
|
@@ -409,8 +518,47 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
409
518
|
return m;
|
|
410
519
|
};
|
|
411
520
|
|
|
521
|
+
// ---- Autopay: the chain, behind one facade (tests replace it) ----
|
|
522
|
+
const autoRepayRaw = String(env.PRIORS_AUTOREPAY ?? addresses.autoRepay ?? "").trim();
|
|
523
|
+
const autoRepayProblem = autoRepayRaw && !ethers.isAddress(autoRepayRaw) ? (looksLikeKey(autoRepayRaw) ? "PRIORS_AUTOREPAY holds what looks like a private key, not an address: take it out of that variable and restart the server" : "PRIORS_AUTOREPAY is not a 0x address: fix it and restart the server") : null;
|
|
524
|
+
let autopayCache = null;
|
|
525
|
+
const autopayC = () => (autopayCache ||= A.autopayContracts({ runner: provider, address: autoRepayRaw, registry: addresses.registry, usdg: addresses.usdg, savingsVault: savingsProblem ? null : savingsVault, pool: addresses.pool }));
|
|
526
|
+
const autopay = deps.autopay !== undefined ? deps.autopay : autoRepayRaw && !autoRepayProblem ? {
|
|
527
|
+
status: (walletAddr, id) => A.autopayStatus(autopayC(), walletAddr, id),
|
|
528
|
+
on: (id, o) => A.autopayOn(autopayC(), wallet, id, o),
|
|
529
|
+
off: (id, o) => A.autopayOff(autopayC(), wallet, id, o),
|
|
530
|
+
} : null;
|
|
531
|
+
function needAutopay() {
|
|
532
|
+
if (autoRepayProblem) throw new ToolError(autoRepayProblem);
|
|
533
|
+
if (!autopay) throw new ToolError("Autopay isn't deployed yet: no AutoRepay address is known to this server (PRIORS_AUTOREPAY, or deployments/4663.v2.json `autoRepay` in a later version). Repay loans with the repay tool before their due date.");
|
|
534
|
+
return autopay;
|
|
535
|
+
}
|
|
536
|
+
/** What pay_url keeps back: what the wallet's Autopay plan pulls for loans whose window opens in the next 24 h. A
|
|
537
|
+
* failed read keeps nothing back (the payment goes on as before) and is never an error. */
|
|
538
|
+
async function autopayReserve() {
|
|
539
|
+
if (!reserveOn || !autopay || !wallet) return 0n;
|
|
540
|
+
try {
|
|
541
|
+
const id = await resolveAgent();
|
|
542
|
+
return A.autopayReserve(await withinTime(autopay.status(wallet.address, id), 10_000));
|
|
543
|
+
} catch (_) { return 0n; }
|
|
544
|
+
}
|
|
545
|
+
/** Autopay lines for credit_status: the wallet's plan, its budget, the next loan it pays, a shortfall. */
|
|
546
|
+
async function autopayLines(id) {
|
|
547
|
+
if (!autopay || !wallet) return [];
|
|
548
|
+
let st;
|
|
549
|
+
try { st = await withinTime(autopay.status(wallet.address, id), 10_000); } catch (e) { return [`Autopay: couldn't read it (${explain(e)}).`]; }
|
|
550
|
+
if (!st.declared) return ["Autopay: off. This wallet is not the agent's declared wallet, so it can't repay the agent's loans through AutoRepay."];
|
|
551
|
+
if (!st.plan.on) return ["Autopay: off. autopay_on turns it on: this wallet then repays each loan a few hours before it is due, if it holds enough."];
|
|
552
|
+
if (!st.plan.current) return [st.plan.stale ? "Autopay: the plan was set before the agent's key or owner changed, so it pays nothing now. Call autopay_on again." : "Autopay: the plan was set under an earlier owner of the agent, so it pays nothing now. Call autopay_on again."];
|
|
553
|
+
const out = [`Autopay: on, from this wallet${st.plan.useSavings ? " (then its savings)" : ""}; limit ${usd(st.plan.cap)} per loan, budget left ${usd(st.budget)}${st.plan.late ? "; also in the grace period" : ""}.${st.held ? " On hold: it pays nothing until resumed." : ""}${st.paused ? ` Paused by the Safe until ${when(st.paused.until)}: repay by hand before the due date.` : ""}`];
|
|
554
|
+
if (st.next) out.push(`Next autopay: loan #${st.next.loanId}, ${usd(st.next.due)}, from ${when(st.next.opens)} (due ${when(st.next.dueAt)}).`);
|
|
555
|
+
if (st.short) out.push(st.short.overCap ? `Loan #${st.short.loanId} is above the Autopay limit. Raise the limit with autopay_on, or repay it by hand.` : `This wallet won't cover its autopay of loan #${st.short.loanId}: ${usd(st.short.need)} is needed by then and ${usd(st.short.have)} can be pulled. Add USDG to this wallet, approve more with autopay_on, or repay by hand.`);
|
|
556
|
+
if (st.budget < st.plan.cap) out.push("The budget left is under one loan's limit: call autopay_on again to approve more.");
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
559
|
+
|
|
412
560
|
const server = new McpServer({ name: "priors", version: VERSION }, {
|
|
413
|
-
instructions: "Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Amounts are in US dollars of USDG.",
|
|
561
|
+
instructions: "Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay, save, unsave, autopay_on, autopay_off) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Spare USDG can be saved in a Morpho vault (save); pay_url and repay take it back out when the wallet is short, before any borrowing. Amounts are in US dollars of USDG.",
|
|
414
562
|
});
|
|
415
563
|
const tool = (name, config, handler) => server.registerTool(name, config, async (args) => {
|
|
416
564
|
try { return text(await handler(args || {})); } catch (e) { return failure(explain(e)); }
|
|
@@ -426,9 +574,10 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
426
574
|
body: z.string().max(100_000).optional().describe("Request body (not for GET). Sent as application/json when it parses as JSON, else text/plain."),
|
|
427
575
|
max_price_usd: z.number().positive().optional().describe("Most to pay for this one call, in US dollars. Default 0.10."),
|
|
428
576
|
max_borrow_usd: z.number().nonnegative().optional().describe("Most to borrow from the Priors line if the wallet is short, in US dollars. Default 0: never borrow."),
|
|
577
|
+
use_savings: z.boolean().optional().describe("Default true: once the price is known, if the wallet holds less, first take the difference out of the agent's savings, before any borrowing."),
|
|
429
578
|
},
|
|
430
579
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
431
|
-
}, serial(async ({ url, method = "GET", body, max_price_usd, max_borrow_usd }, deadline) => {
|
|
580
|
+
}, serial(async ({ url, method = "GET", body, max_price_usd, max_borrow_usd, use_savings = true }, deadline) => {
|
|
432
581
|
const signer = needWallet("pay_url");
|
|
433
582
|
const u = await checkTarget(url);
|
|
434
583
|
if (method === "GET" && body !== undefined) throw new ToolError("A GET request cannot carry a body: use POST (or another method) with body.");
|
|
@@ -466,43 +615,51 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
466
615
|
throw new ToolError(`A payment of ${usd(unmatched.price)} to ${unmatched.payTo} for ${urlOnly} was signed earlier and kept without its request body (by an earlier version of this server, or for a call without a body), and the merchant may still settle it until ${until}. It cannot be told apart from this purchase, so nothing was signed: do NOT call pay_url again for this URL before ${until}; check wallet_balance.`);
|
|
467
616
|
}
|
|
468
617
|
let r;
|
|
469
|
-
let signedPrice = null; // what the payer checked and signed
|
|
618
|
+
let signedPrice = null; // what the payer checked and signed; never a merchant field read again here
|
|
470
619
|
if (prior) {
|
|
471
620
|
// A payment for this purchase is already out and still cashable: send that same one, never a second.
|
|
472
621
|
r = await X.createPayer({ signer, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}) }).resend(url, prior.paymentHeaders, init);
|
|
473
622
|
r = { ...r, requirement: { payTo: prior.payTo }, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
|
|
474
623
|
signedPrice = prior.price;
|
|
475
624
|
lines.push("No new payment was signed: the same signed payment was sent again.");
|
|
625
|
+
if (prior.borrowed > 0n) lines.push(`The first attempt at this purchase borrowed ${usd(prior.borrowed)}${prior.loanId !== null && prior.loanId !== undefined ? ` as loan #${prior.loanId}` : ""}: repay it with the repay tool.`);
|
|
476
626
|
} else {
|
|
477
627
|
if (session.spent + maxPrice > spendCap) throw new ToolError(`this would bring what pay_url may sign in this session to ${usd(session.spent + maxPrice)}, above ${usd(spendCap)} (PRIORS_MAX_SPEND_USD). ${usd(session.spent)} was signed so far; the user can raise the limit and restart the server.`);
|
|
478
628
|
if (maxBorrow > 0n && session.borrowed + maxBorrow > borrowTotalCap) throw new ToolError(`this could bring what is borrowed in this session to ${usd(session.borrowed + maxBorrow)}, above ${usd(borrowTotalCap)} (PRIORS_MAX_BORROW_TOTAL_USD).`);
|
|
479
629
|
let agentId;
|
|
480
630
|
if (maxBorrow > 0n) { agentId = await resolveAgent(); await needController(agentId); }
|
|
481
|
-
|
|
631
|
+
// The agent's own savings before a loan: once the 402 names the price, only what the wallet is short of.
|
|
632
|
+
const topUp = use_savings && autoSavings && typeof credit.topUp === "function" ? (need) => topUpWithin(need, deadline) : undefined;
|
|
633
|
+
const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId, ...v5 } : {}), ...(topUp ? { topUp } : {}), ...(reserveOn && autopay ? { reserve: autopayReserve } : {}),
|
|
482
634
|
// Recorded, then counted, when signed, at the price the payer checked and signed (a v1 requirement's `amount` is the
|
|
483
635
|
// merchant's text). A record that cannot be kept throws, and the payer does not send the payment.
|
|
484
|
-
onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo }); signedPrice = s.price; session.spent += s.price; } });
|
|
636
|
+
onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo, borrowed: s.borrowed || 0n, loanId: s.loanId ?? null }); signedPrice = s.price; session.spent += s.price; } });
|
|
485
637
|
try { r = await payer.pay(url, init); } catch (e) {
|
|
638
|
+
// What savings did before the failure is part of the answer, whatever failed after.
|
|
639
|
+
const sv = []; savingsLines(e?.savings, sv);
|
|
640
|
+
const note = sv.length ? ` ${sv.join(" ")}` : "";
|
|
486
641
|
// What the error carries was done: a loan taken and a payment signed are counted, whatever failed after.
|
|
487
642
|
if (e?.borrowed > 0n) session.borrowed += e.borrowed;
|
|
488
643
|
// A borrow sent whose answer was lost may have mined (GHSA-v9xj): counted above, and said, never "nothing done".
|
|
489
|
-
if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was signed or paid
|
|
644
|
+
if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was signed or paid.${note}`);
|
|
490
645
|
if (e?.signed) {
|
|
491
|
-
|
|
646
|
+
// onSigned ran before the payment left; should it not have, count the most this call could sign
|
|
647
|
+
if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await recordSent(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo, borrowed: e.borrowed || 0n, loanId: e.loanId ?? null }); }
|
|
492
648
|
const price = signedPrice;
|
|
493
649
|
const until = when(e.signed.validBefore + X.SKEW_SECONDS);
|
|
494
|
-
throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}`);
|
|
650
|
+
throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}${note}`);
|
|
495
651
|
}
|
|
496
652
|
const loan = e?.borrowed > 0n ? ` ${usd(e.borrowed)} was borrowed${e.loanId !== null ? ` as loan #${e.loanId}` : ""} before it failed: repay it with the repay tool.` : "";
|
|
497
653
|
if (e?.code === "NOT_RECORDED" && e.cause?.code === "OTHER_SESSION") { outstanding.set(purchase, e.cause.prior); throw new ToolError(`Another session of this wallet signed a payment of ${usd(e.cause.prior.price)} for this purchase a moment ago, and it may still settle until ${when(e.cause.prior.validBefore + X.SKEW_SECONDS)}. Nothing was sent from this call and no payment of its own is out: calling pay_url again resends that same payment, never a new one.${loan}`); }
|
|
498
|
-
if (e?.code === "NOT_RECORDED") throw new ToolError(`A payment was signed but could not be written to PRIORS_STATE_DIR (${explain(e.cause ?? e)}), so it was not sent and nothing can be settled. Fix that directory, or set PRIORS_STATE_DIR=off to keep payments in this process's memory only, then call again.${loan}`);
|
|
499
|
-
if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}`);
|
|
500
|
-
if (loan) throw new ToolError(`${explain(e)}.${loan}`);
|
|
654
|
+
if (e?.code === "NOT_RECORDED") throw new ToolError(`A payment was signed but could not be written to PRIORS_STATE_DIR (${explain(e.cause ?? e)}), so it was not sent and nothing can be settled. Fix that directory, or set PRIORS_STATE_DIR=off to keep payments in this process's memory only, then call again.${loan}${note}`);
|
|
655
|
+
if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}${note}`);
|
|
656
|
+
if (loan || note) throw new ToolError(`${explain(e)}.${loan}${note}`);
|
|
501
657
|
throw e;
|
|
502
658
|
}
|
|
503
|
-
|
|
659
|
+
savingsLines(r.savings, lines);
|
|
660
|
+
if (r.signed && signedPrice === null) { // onSigned counted and recorded it; should it not have, the most this call could sign
|
|
504
661
|
signedPrice = maxPrice; session.spent += maxPrice;
|
|
505
|
-
if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo });
|
|
662
|
+
if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo, borrowed: r.borrowed || 0n, loanId: r.loanId ?? null });
|
|
506
663
|
}
|
|
507
664
|
if (r.borrowed > 0n) { session.borrowed += r.borrowed; lines.push(`Borrowed ${usd(r.borrowed)} from the Priors line for agent #${agentId}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}${r.dueAt ? `, due ${when(r.dueAt)}` : ""}. Repay it with the repay tool before then.`); }
|
|
508
665
|
else if (r.requirement) lines.push("Nothing was borrowed.");
|
|
@@ -536,13 +693,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
536
693
|
if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
|
|
537
694
|
if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
|
|
538
695
|
const b = await credit.balances(ethers.getAddress(addr));
|
|
539
|
-
return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain
|
|
696
|
+
return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain.${await savedNote(b.address)}`;
|
|
540
697
|
});
|
|
541
698
|
|
|
542
699
|
// ---- credit_status -------------------------------------------------------------------------------------------
|
|
543
700
|
tool("credit_status", {
|
|
544
701
|
title: "Priors credit line of an agent",
|
|
545
|
-
description: "Show a Priors agent's credit line on Robinhood Chain: who backs it, the line, what is drawn and available, its repayment record, score and open loans with due dates. agent_id defaults to the configured wallet's agent. Read-only.",
|
|
702
|
+
description: "Show a Priors agent's credit line on Robinhood Chain: who backs it, the line, what is drawn and available, its repayment record, score and open loans with due dates, and (for the configured wallet) its Autopay: on or off, the limit per loan, the budget left, the next loan it repays and any shortfall. agent_id defaults to the configured wallet's agent. Read-only.",
|
|
546
703
|
inputSchema: { agent_id: z.number().int().nonnegative().optional().describe("Priors (ERC-8004) agent id; default: the configured wallet's agent.") },
|
|
547
704
|
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
548
705
|
}, async ({ agent_id }) => {
|
|
@@ -558,6 +715,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
558
715
|
];
|
|
559
716
|
if (s.openLoans.length === 0) lines.push("Open loans: none.");
|
|
560
717
|
for (const l of s.openLoans) lines.push(`Open loan #${l.loanId}: ${usd(l.principal)} + fee ${usd(l.fee)} = ${usd(l.due)}, due ${when(l.dueAt)}${Date.now() / 1000 > l.dueAt ? " (PAST DUE: repay now)" : ""}.`);
|
|
718
|
+
lines.push(...(await autopayLines(id)));
|
|
561
719
|
return lines.join("\n");
|
|
562
720
|
});
|
|
563
721
|
|
|
@@ -652,7 +810,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
652
810
|
const id = await resolveAgent();
|
|
653
811
|
await needController(id);
|
|
654
812
|
const q = await credit.quote(id, amount, term);
|
|
655
|
-
if (dry_run) return `Quote for agent #${id}: borrow ${usd(amount)} for ${days} days, fee ${usd(q.fee)}, ${usd(q.due)} due at the end. Nothing was borrowed
|
|
813
|
+
if (dry_run) return `Quote for agent #${id}: borrow ${usd(amount)} for ${days} days, fee ${usd(q.fee)}, ${usd(q.due)} due at the end. Nothing was borrowed.${await savedNote(wallet.address)}`;
|
|
656
814
|
let r;
|
|
657
815
|
try { r = await credit.borrow(id, amount, term); } catch (e) {
|
|
658
816
|
// sent, and its answer lost: it may have mined, so it is counted and said (GHSA-v9xj)
|
|
@@ -663,20 +821,23 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
663
821
|
throw e;
|
|
664
822
|
}
|
|
665
823
|
session.borrowed += r.principal;
|
|
666
|
-
|
|
824
|
+
const v5Note = r.v5Refreshed ? " Its SeatVaultV5 line was refreshed first." : r.v5Noted ? ` SeatVaultV5 recorded this key now (tx ${r.v5Noted}): it can raise the line itself 24 hours from now.` : "";
|
|
825
|
+
return `Borrowed ${usd(r.principal)} for agent #${id}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}: fee ${usd(r.fee)}, so ${usd(r.principal + r.fee)} is due${r.dueAt ? ` by ${when(r.dueAt)}` : ""}. The USDG is in ${wallet.address}. Tx ${r.hash}.${v5Note}`;
|
|
667
826
|
}));
|
|
668
827
|
|
|
669
828
|
// ---- repay ---------------------------------------------------------------------------------------------------
|
|
670
829
|
tool("repay", {
|
|
671
830
|
title: "Repay Priors loans",
|
|
672
|
-
description: "Repay the agent's own Priors loans in full (principal + fee) from the configured wallet's USDG; a loan of another agent is refused. Give either loan_id for one loan, or all: true to repay every open loan, earliest due first, as far as the balance covers. Moves real money: state the amounts (credit_status lists them) to the user first.",
|
|
831
|
+
description: "Repay the agent's own Priors loans in full (principal + fee) from the configured wallet's USDG; a loan of another agent is refused. Give either loan_id for one loan, or all: true to repay every open loan, earliest due first, as far as the balance covers. Moves real money: state the amounts (credit_status lists them) to the user and get their go-ahead first.",
|
|
673
832
|
inputSchema: {
|
|
674
833
|
loan_id: z.number().int().nonnegative().optional().describe("The loan to repay."),
|
|
675
834
|
all: z.boolean().optional().describe("true: repay every open loan of the agent, earliest due first."),
|
|
835
|
+
use_savings: z.boolean().optional().describe("Default true: if the wallet holds less than what is due, first take the difference out of the agent's savings."),
|
|
676
836
|
},
|
|
677
837
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
678
|
-
}, serial(async ({ loan_id, all }) => {
|
|
838
|
+
}, serial(async ({ loan_id, all, use_savings = true }, deadline) => {
|
|
679
839
|
needWallet("repay");
|
|
840
|
+
const pre = [];
|
|
680
841
|
if ((loan_id === undefined) === (all !== true)) throw new ToolError("Give exactly one of loan_id or all: true.");
|
|
681
842
|
// Only the loans of an agent this wallet controls: the pool lets anyone repay any loan, and this wallet's USDG is
|
|
682
843
|
// not for others. PRIORS_AGENT_ID alone is not proof: a stale or mistyped id would point at someone else's agent.
|
|
@@ -685,22 +846,160 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
685
846
|
if (loan_id !== undefined) {
|
|
686
847
|
const owner = BigInt(await credit.loanAgent(BigInt(loan_id)));
|
|
687
848
|
if (owner !== id) throw new ToolError(`loan #${loan_id} belongs to agent #${owner}, not to agent #${id}. This tool only repays the configured agent's own loans.`);
|
|
688
|
-
|
|
689
|
-
|
|
849
|
+
// the due is read inside the savings step: a failed read there never stops the repayment
|
|
850
|
+
if (use_savings) await fromSavings(() => credit.loanDue(BigInt(loan_id)), pre, deadline);
|
|
851
|
+
let r;
|
|
852
|
+
try { r = await credit.repay(BigInt(loan_id)); } catch (e) {
|
|
853
|
+
if (pre.length) throw new ToolError(`${pre.join(" ")} Then the repayment failed: ${explain(e)}`);
|
|
854
|
+
throw e;
|
|
855
|
+
}
|
|
856
|
+
return [...pre, `Repaid loan #${r.loanId} of agent #${r.agentId}: ${usd(r.paid)} (principal + fee). Tx ${r.hash}.`].join("\n");
|
|
690
857
|
}
|
|
691
858
|
const s = await credit.status(id);
|
|
692
859
|
if (s.openLoans.length === 0) return `Agent #${id} has no open loan. Nothing was repaid.`;
|
|
860
|
+
if (use_savings) await fromSavings(s.openLoans.reduce((a, l) => a + l.due, 0n), pre, deadline);
|
|
693
861
|
const done = [], left = [];
|
|
694
862
|
let stop = null;
|
|
695
863
|
for (const l of s.openLoans) {
|
|
696
864
|
if (stop) { left.push(l); continue; }
|
|
697
865
|
try { const r = await credit.repay(l.loanId); done.push(`loan #${r.loanId}: ${usd(r.paid)}, tx ${r.hash}`); } catch (e) { stop = explain(e); left.push(l); }
|
|
698
866
|
}
|
|
699
|
-
const out = [done.length ? `Repaid for agent #${id}:\n- ${done.join("\n- ")}` : `Nothing was repaid for agent #${id}.`];
|
|
867
|
+
const out = [...pre, done.length ? `Repaid for agent #${id}:\n- ${done.join("\n- ")}` : `Nothing was repaid for agent #${id}.`];
|
|
700
868
|
if (left.length) out.push(`Still open: ${left.map((l) => `#${l.loanId} (${usd(l.due)} due ${when(l.dueAt)})`).join(", ")}.${stop ? ` Stopped because: ${stop}` : ""}`);
|
|
701
869
|
return out.join("\n");
|
|
702
870
|
}));
|
|
703
871
|
|
|
872
|
+
// ---- autopay_on / autopay_off ---------------------------------------------------------------------------------
|
|
873
|
+
// Autopay: the agent's own wallet approves AutoRepay for a budget (4 x the limit, never unlimited)
|
|
874
|
+
// and enrolls; Priors' keeper (or anyone) then repays each loan in the 6 hours before it is due, from this wallet,
|
|
875
|
+
// while it holds enough. Two plain transactions from the wallet (its own ETH pays the gas).
|
|
876
|
+
tool("autopay_on", {
|
|
877
|
+
title: "Turn on Autopay (repay loans on time from this wallet)",
|
|
878
|
+
description: "Turn on Autopay for the configured agent: this wallet approves AutoRepay for a USDG budget (4 x the limit per loan) and enrolls, so each Priors loan is repaid from this wallet (then its savings, if chosen) in the 6 hours before it is due, by Priors' keeper or anyone, with no call per loan, while the wallet holds enough. It makes an on-time repayment more likely; it is not a promise. Call it again to change the limit or approve more budget when it runs low. Moves real allowances: state the limit and the budget to the user and get their go-ahead once. Needs ETH for gas.",
|
|
879
|
+
inputSchema: {
|
|
880
|
+
cap_usd: z.number().positive().optional().describe("Most it repays per loan, in US dollars. Default: the line plus a 30-day fee, at most this server's ceiling (PRIORS_MAX_AUTOPAY_USD, default 25)."),
|
|
881
|
+
use_savings: z.boolean().optional().describe("Also take from the wallet's savings when its USDG is short. Default: on when the wallet has savings."),
|
|
882
|
+
late: z.boolean().optional().describe("Default true: also repay in the 3-day grace period after the due date (late, but no default)."),
|
|
883
|
+
budget_usd: z.number().positive().optional().describe("The allowance to approve, in US dollars. Default 4 x the limit."),
|
|
884
|
+
},
|
|
885
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
886
|
+
}, serial(async ({ cap_usd, use_savings, late = true, budget_usd }) => {
|
|
887
|
+
needWallet("autopay_on");
|
|
888
|
+
const ap = needAutopay();
|
|
889
|
+
const id = await resolveAgent();
|
|
890
|
+
await needController(id);
|
|
891
|
+
let cap = cap_usd !== undefined ? dollars(cap_usd, "cap_usd") : null;
|
|
892
|
+
if (cap === null) { const st = await credit.status(id); cap = A.defaultCap(st.line, maxAutopayCap); }
|
|
893
|
+
if (cap === 0n) throw new ToolError("cap_usd must be above zero");
|
|
894
|
+
if (cap > maxAutopayCap) throw new ToolError(`cap_usd ${X.formatUsdg(cap)} is above this server's Autopay ceiling of ${usd(maxAutopayCap)} (PRIORS_MAX_AUTOPAY_USD).`);
|
|
895
|
+
const budget = budget_usd !== undefined ? dollars(budget_usd, "budget_usd") : cap * A.BUDGET_LOANS;
|
|
896
|
+
if (budget < cap) throw new ToolError("budget_usd must cover at least one loan's limit.");
|
|
897
|
+
let useSavings = use_savings;
|
|
898
|
+
if (useSavings === undefined) { try { useSavings = autoSavings && (await credit.savedOf(wallet.address)) > 0n; } catch (_) { useSavings = false; } }
|
|
899
|
+
if (useSavings && savingsProblem) throw new ToolError(savingsProblem);
|
|
900
|
+
const r = await ap.on(id, { cap, useSavings, late, budget, ceiling: maxAutopayCap });
|
|
901
|
+
return `Autopay is on for agent #${id}: each loan up to ${usd(r.cap)} is repaid from ${wallet.address}${useSavings ? ", then its savings," : ""} in the 6 hours before it is due${late ? ", and in the grace period if it is late" : ""}, while the wallet holds enough. Budget approved: ${usd(r.budget)}; call autopay_on again to approve more when it runs low. credit_status shows the next loan it pays.${r.hashes.length ? ` Tx ${r.hashes.join(", ")}.` : ""}`;
|
|
902
|
+
}));
|
|
903
|
+
|
|
904
|
+
tool("autopay_off", {
|
|
905
|
+
title: "Turn off Autopay",
|
|
906
|
+
description: "Turn off Autopay for the configured agent: AutoRepay stops repaying its loans from this wallet at once. With clear_budget: true, also set this wallet's allowances to AutoRepay to 0. Loans must then be repaid with the repay tool before their due date.",
|
|
907
|
+
inputSchema: { clear_budget: z.boolean().optional().describe("true: also set the allowances to AutoRepay to 0.") },
|
|
908
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
909
|
+
}, serial(async ({ clear_budget = false }) => {
|
|
910
|
+
needWallet("autopay_off");
|
|
911
|
+
const ap = needAutopay();
|
|
912
|
+
const id = await resolveAgent();
|
|
913
|
+
const r = await ap.off(id, { clearBudget: clear_budget });
|
|
914
|
+
return `Autopay is off for agent #${id}: AutoRepay no longer repays its loans from ${wallet.address}${clear_budget ? ", and its allowances to AutoRepay are 0" : ""}. Repay open loans with the repay tool before their due date.${r.hashes.length ? ` Tx ${r.hashes.join(", ")}.` : ""}`;
|
|
915
|
+
}));
|
|
916
|
+
|
|
917
|
+
// ---- savings / save / unsave ----------------------------------------------------------------------------------
|
|
918
|
+
// Spare USDG kept in a Morpho vault (Steakhouse USDG by default) and taken back out when the agent pays or repays
|
|
919
|
+
// (pay_url and repay take from savings before borrowing). The agent's own money: Priors never holds it, and the
|
|
920
|
+
// vault's risk is the agent's. savings and unsave work even with PRIORS_SAVINGS_VAULT=off, so saved money can come out.
|
|
921
|
+
/** " It also has X saved ..." for an address, or "" (never fails the calling tool). */
|
|
922
|
+
async function savedNote(addr) {
|
|
923
|
+
if (savingsProblem || typeof credit.savedOf !== "function") return "";
|
|
924
|
+
try {
|
|
925
|
+
const v = await withinTime(credit.savedOf(addr), 5_000);
|
|
926
|
+
if (!(v > 0n)) return "";
|
|
927
|
+
if (!wallet || ethers.getAddress(addr) !== wallet.address) return ` It also has ${usd(v)} saved in the savings vault.`;
|
|
928
|
+
return ` It also has ${usd(v)} saved in the savings vault (the savings tool shows it; ${autoSavings ? "pay_url and repay use it before borrowing" : "savings are off on this server, so pay_url and repay don't use it; unsave takes it out"}).`;
|
|
929
|
+
} catch (_) { return ""; }
|
|
930
|
+
}
|
|
931
|
+
const RISK = "Savings earn the vault's rate, which moves with Morpho's markets; the vault's risk (its curator's markets and settings, a loss in a market) is the saver's, and Priors never holds the money.";
|
|
932
|
+
tool("savings", {
|
|
933
|
+
title: "Savings in the Morpho vault",
|
|
934
|
+
description: "Show how much USDG an address has saved in the savings vault (Steakhouse USDG on Morpho by default), what the vault can pay out to it right now, and the USDG in its wallet. Defaults to the configured wallet. Read-only.",
|
|
935
|
+
inputSchema: { address: z.string().optional().describe("0x address to check; default: the configured wallet.") },
|
|
936
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
937
|
+
}, async ({ address }) => {
|
|
938
|
+
const addr = address ?? wallet?.address;
|
|
939
|
+
if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
|
|
940
|
+
if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
|
|
941
|
+
needSavings();
|
|
942
|
+
const s = await credit.savingsOf(ethers.getAddress(addr));
|
|
943
|
+
const reach = s.reachable ?? s.withdrawable;
|
|
944
|
+
const out = [`${s.owner} has ${usd(s.saved)} saved in vault ${s.vault} and ${usd(s.wallet)} in its wallet.`];
|
|
945
|
+
if (s.saved > 0n) {
|
|
946
|
+
out.push(reach >= s.saved ? "All of it can come out right now (unsave)." : `${usd(reach)} can come out right now${reach > s.withdrawable ? ` (${usd(s.withdrawable)} by a normal withdrawal, the rest from the vault's other markets; unsave does both)` : ""}; ${usd(s.saved - reach)} can't until the vault's markets have liquidity again.`);
|
|
947
|
+
}
|
|
948
|
+
if (savingsOff) out.push("Savings are off on this server: no new saving and no automatic top-ups; unsave still works.");
|
|
949
|
+
out.push(RISK);
|
|
950
|
+
return out.join(" ");
|
|
951
|
+
});
|
|
952
|
+
|
|
953
|
+
tool("save", {
|
|
954
|
+
title: "Save spare USDG in the Morpho vault",
|
|
955
|
+
description: "Move USDG from the configured wallet into the savings vault (Steakhouse USDG on Morpho by default), where it earns the vault's rate (which moves with its markets) until the agent needs it; pay_url and repay take it back out automatically when the wallet is short. Moves real money into a third-party vault, whose risk the agent carries: state the amount to the user and get their go-ahead first. Keep enough in the wallet for loans coming due and payments expected soon. Needs ETH for gas.",
|
|
956
|
+
inputSchema: { amount_usd: z.number().positive().describe("How much to save, in US dollars of USDG.") },
|
|
957
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
958
|
+
}, serial(async ({ amount_usd }) => {
|
|
959
|
+
needSavings();
|
|
960
|
+
if (savingsOff) throw new ToolError("Savings are off on this server (PRIORS_SAVINGS_VAULT=off): save is disabled. The savings and unsave tools still work.");
|
|
961
|
+
needWallet("save");
|
|
962
|
+
const amount = dollars(amount_usd, "amount_usd");
|
|
963
|
+
if (amount === 0n) throw new ToolError("amount_usd must be above zero");
|
|
964
|
+
if (amount > maxSaveCeiling) throw new ToolError(`amount_usd ${X.formatUsdg(amount)} is above this server's ceiling of ${usd(maxSaveCeiling)} per save (PRIORS_MAX_SAVE_USD).`);
|
|
965
|
+
if (session.saved + amount > saveTotalCap) throw new ToolError(`this would bring what save moved in this session to ${usd(session.saved + amount)}, above ${usd(saveTotalCap)} (PRIORS_MAX_SAVE_TOTAL_USD).`);
|
|
966
|
+
// Payments signed and not yet settled still need their USDG in the wallet: never save it away from under them.
|
|
967
|
+
const nowS = Math.floor(Date.now() / 1000);
|
|
968
|
+
refresh(); // another session's pending payments need their USDG too
|
|
969
|
+
const reserved = [...outstanding.values()].filter((v) => live(v, nowS)).reduce((a, v) => a + v.price, 0n);
|
|
970
|
+
if (reserved > 0n) {
|
|
971
|
+
const b = await credit.balances(wallet.address);
|
|
972
|
+
if (b.usdg < amount + reserved) throw new ToolError(`${usd(reserved)} of the wallet's USDG is held for signed payments that have not settled yet; at most ${usd(b.usdg > reserved ? b.usdg - reserved : 0n)} can be saved now.`);
|
|
973
|
+
}
|
|
974
|
+
let r;
|
|
975
|
+
try { r = await credit.save(amount); } catch (e) {
|
|
976
|
+
if (e?.code === "UNCONFIRMED") session.saved += amount; // it may have landed: counted, so a retry can't pass the cap
|
|
977
|
+
throw e;
|
|
978
|
+
}
|
|
979
|
+
session.saved += r.amount;
|
|
980
|
+
let after = "";
|
|
981
|
+
try { const s = await credit.savingsOf(wallet.address); after = ` Now ${usd(s.saved)} saved, ${usd(s.wallet)} left in the wallet.`; } catch (_) { after = " (The balances could not be read just now: check the savings tool.)"; }
|
|
982
|
+
return `Saved ${usd(r.amount)} in vault ${r.vault || savingsVault}. Tx ${r.hash}.${after}`;
|
|
983
|
+
}));
|
|
984
|
+
|
|
985
|
+
tool("unsave", {
|
|
986
|
+
title: "Take USDG out of savings",
|
|
987
|
+
description: "Move USDG from the savings vault back into the configured wallet: amount_usd, or all: true for everything. When the vault's normal withdrawal cannot pay it all, it takes the rest from the vault's other markets in the same transaction (only where that costs no penalty). Refused before any transaction when even that cannot pay the amount. Moves the agent's own money back to its own wallet; state the amount to the user and get their go-ahead first. Needs ETH for gas.",
|
|
988
|
+
inputSchema: {
|
|
989
|
+
amount_usd: z.number().positive().optional().describe("How much to take out, in US dollars of USDG."),
|
|
990
|
+
all: z.boolean().optional().describe("true: take everything out."),
|
|
991
|
+
},
|
|
992
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
993
|
+
}, serial(async ({ amount_usd, all }) => {
|
|
994
|
+
needSavings();
|
|
995
|
+
needWallet("unsave");
|
|
996
|
+
if ((amount_usd === undefined) === (all !== true)) throw new ToolError("Give exactly one of amount_usd or all: true.");
|
|
997
|
+
const r = await credit.unsave(all ? { all: true } : { amount: dollars(amount_usd, "amount_usd") });
|
|
998
|
+
let after = "";
|
|
999
|
+
try { const s = await credit.savingsOf(wallet.address); after = ` Now ${usd(s.saved)} saved, ${usd(s.wallet)} in the wallet.`; } catch (_) { after = " (The balances could not be read just now: check the savings tool.)"; }
|
|
1000
|
+
return `Took ${usd(r.amount)} out of savings${r.inKind ? " (part of it from the vault's other markets, in one transaction)" : ""}. Tx ${r.hash}.${after}`;
|
|
1001
|
+
}));
|
|
1002
|
+
|
|
704
1003
|
// ---- find_services -------------------------------------------------------------------------------------------
|
|
705
1004
|
tool("find_services", {
|
|
706
1005
|
title: "Find services that accept USDG",
|