@mortiseagentvault/mcp 0.1.0 → 0.2.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 +18 -6
- package/dist/THIRD_PARTY_NOTICES.txt +342 -0
- package/dist/main.js +59002 -17
- package/package.json +21 -8
- package/dist/actions.js +0 -172
- package/dist/config.js +0 -80
- package/dist/server.js +0 -231
package/package.json
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mortiseagentvault/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "MCP server that lets an AI agent act inside a Mortise vault, within the limits the vault's owner set on-chain.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"mortise",
|
|
8
|
+
"mcp",
|
|
9
|
+
"model-context-protocol",
|
|
10
|
+
"robinhood-chain",
|
|
11
|
+
"vault",
|
|
12
|
+
"ai-agents"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/mortiseagentvault/mortise#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/mortiseagentvault/mortise/issues"
|
|
17
|
+
},
|
|
6
18
|
"type": "module",
|
|
7
19
|
"bin": {
|
|
8
20
|
"mortise-mcp": "dist/main.js"
|
|
@@ -14,21 +26,22 @@
|
|
|
14
26
|
"node": ">=20"
|
|
15
27
|
},
|
|
16
28
|
"scripts": {
|
|
17
|
-
"build": "
|
|
29
|
+
"build": "node scripts/build.mjs",
|
|
18
30
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
19
31
|
"test": "node --experimental-strip-types --no-warnings --test --test-concurrency=1 test/*.test.ts",
|
|
20
32
|
"prepublishOnly": "npm run build"
|
|
21
33
|
},
|
|
22
|
-
"
|
|
34
|
+
"devDependencies": {
|
|
23
35
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
24
|
-
"@mortiseagentvault/sdk": "0.
|
|
36
|
+
"@mortiseagentvault/sdk": "0.2.0",
|
|
37
|
+
"@types/node": "22.20.7",
|
|
38
|
+
"@x402/core": "2.33.0",
|
|
39
|
+
"@x402/evm": "2.33.0",
|
|
40
|
+
"esbuild": "0.28.2",
|
|
41
|
+
"typescript": "5.9.3",
|
|
25
42
|
"viem": "2.58.8",
|
|
26
43
|
"zod": "4.6.7"
|
|
27
44
|
},
|
|
28
|
-
"devDependencies": {
|
|
29
|
-
"@types/node": "22.20.7",
|
|
30
|
-
"typescript": "5.9.3"
|
|
31
|
-
},
|
|
32
45
|
"repository": {
|
|
33
46
|
"type": "git",
|
|
34
47
|
"url": "git+https://github.com/mortiseagentvault/mortise.git",
|
package/dist/actions.js
DELETED
|
@@ -1,172 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { actions } from "@mortiseagentvault/sdk";
|
|
3
|
-
// Amounts are integer strings in the token's smallest unit (wei for ETH, 1e-6 for USDG), so no precision is lost.
|
|
4
|
-
const amount = z.string().regex(/^\d+$/, "an integer string in the token's smallest unit");
|
|
5
|
-
const address = z.string().regex(/^0x[0-9a-fA-F]{40}$/, "a 0x-prefixed 20-byte address");
|
|
6
|
-
const bytes32 = z.string().regex(/^0x[0-9a-fA-F]{64}$/, "a 0x-prefixed 32-byte value");
|
|
7
|
-
const ethNote = "0x0000000000000000000000000000000000000000 is native ETH";
|
|
8
|
-
const poolKey = z.object({
|
|
9
|
-
currency0: address,
|
|
10
|
-
currency1: address,
|
|
11
|
-
fee: z.number().int().min(0).max(16_777_215),
|
|
12
|
-
tickSpacing: z.number().int(),
|
|
13
|
-
hooks: address,
|
|
14
|
-
});
|
|
15
|
-
const marketParams = z.object({ loanToken: address, collateralToken: address, oracle: address, irm: address, lltv: amount });
|
|
16
|
-
export const actionSchema = z.discriminatedUnion("kind", [
|
|
17
|
-
z.object({ kind: z.literal("weth"), wrap: z.boolean().describe("true wraps ETH into WETH, false unwraps"), amount }),
|
|
18
|
-
z
|
|
19
|
-
.object({ kind: z.literal("uniswapV3Swap"), tokenIn: address, tokenOut: address, fee: z.number().int().describe("pool fee in hundredths of a bip, e.g. 100, 500, 3000"), amountIn: amount, amountOutMinimum: amount })
|
|
20
|
-
.describe(`Exact-input swap on one Uniswap v3 pool; ${ethNote}`),
|
|
21
|
-
z.object({ kind: z.literal("uniswapV4Swap"), key: poolKey, zeroForOne: z.boolean(), amountIn: amount, amountOutMinimum: amount }).describe(`Exact-input swap on one Uniswap v4 pool; ${ethNote}`),
|
|
22
|
-
z
|
|
23
|
-
.object({ kind: z.literal("morpho"), op: z.enum(["supply", "withdraw"]), market: marketParams, assets: amount, shares: amount })
|
|
24
|
-
.describe("Supply or withdraw the loan token of a Morpho Blue market; give assets or shares, the other 0"),
|
|
25
|
-
z.object({ kind: z.literal("pons"), side: z.enum(["buy", "sell"]), token: address, amountIn: amount, minOut: amount }).describe("Buy or sell a Pons token on its bonding curve"),
|
|
26
|
-
z.object({ kind: z.literal("flap"), tokenIn: address, tokenOut: address, amountIn: amount, minOut: amount }).describe(`Buy or sell through the Flap Portal; ${ethNote}`),
|
|
27
|
-
z.object({ kind: z.literal("erc4626"), op: z.enum(["deposit", "withdraw", "redeem"]), target: address, amount }).describe("Deposit into, withdraw from or redeem shares of an ERC-4626 vault"),
|
|
28
|
-
z.object({ kind: z.literal("transfer"), token: address, to: address, amount }).describe("Send an ERC-20 to a recipient the owner listed for it"),
|
|
29
|
-
z.object({ kind: z.literal("familyTransfer"), token: address, to: address, amount }).describe(`Move a token to another vault of the same family; ${ethNote}`),
|
|
30
|
-
z
|
|
31
|
-
.object({
|
|
32
|
-
kind: z.literal("across"),
|
|
33
|
-
destinationChainId: amount,
|
|
34
|
-
recipient: bytes32,
|
|
35
|
-
inputToken: address,
|
|
36
|
-
outputToken: bytes32,
|
|
37
|
-
minRate: amount,
|
|
38
|
-
inputAmount: amount,
|
|
39
|
-
outputAmount: amount,
|
|
40
|
-
quoteTimestamp: z.number().int().nonnegative(),
|
|
41
|
-
fillDeadline: z.number().int().nonnegative(),
|
|
42
|
-
})
|
|
43
|
-
.describe("Bridge an ERC-20 through Across on a route the owner listed"),
|
|
44
|
-
z
|
|
45
|
-
.object({
|
|
46
|
-
kind: z.literal("uniswapV3Liquidity"),
|
|
47
|
-
op: z.enum(["mint", "increase", "decrease", "collect", "burn"]),
|
|
48
|
-
token0: address.optional(),
|
|
49
|
-
token1: address.optional(),
|
|
50
|
-
fee: z.number().int().optional(),
|
|
51
|
-
tickLower: z.number().int().optional(),
|
|
52
|
-
tickUpper: z.number().int().optional(),
|
|
53
|
-
tokenId: amount.optional(),
|
|
54
|
-
liquidity: amount.optional(),
|
|
55
|
-
amount0: amount.optional(),
|
|
56
|
-
amount1: amount.optional(),
|
|
57
|
-
amount0Min: amount.optional(),
|
|
58
|
-
amount1Min: amount.optional(),
|
|
59
|
-
})
|
|
60
|
-
.describe("Uniswap v3 position: mint needs token0, token1, fee, ticks, amount0/1 and amount0/1Min; increase needs tokenId, amount0/1 and amount0/1Min; decrease needs tokenId, liquidity and amount0/1Min; collect and burn need tokenId"),
|
|
61
|
-
z
|
|
62
|
-
.object({
|
|
63
|
-
kind: z.literal("uniswapV4Liquidity"),
|
|
64
|
-
op: z.enum(["mint", "increase", "decrease", "burn"]),
|
|
65
|
-
key: poolKey.optional(),
|
|
66
|
-
tickLower: z.number().int().optional(),
|
|
67
|
-
tickUpper: z.number().int().optional(),
|
|
68
|
-
tokenId: amount.optional(),
|
|
69
|
-
liquidity: amount.optional(),
|
|
70
|
-
amount0: amount.optional(),
|
|
71
|
-
amount1: amount.optional(),
|
|
72
|
-
amount0Min: amount.optional(),
|
|
73
|
-
amount1Min: amount.optional(),
|
|
74
|
-
})
|
|
75
|
-
.describe("Uniswap v4 position: amounts are maximums for mint and increase, minimums for decrease and burn"),
|
|
76
|
-
]);
|
|
77
|
-
const A = (s) => s;
|
|
78
|
-
const B = (s) => BigInt(s);
|
|
79
|
-
function need(v, name, op) {
|
|
80
|
-
if (v === undefined)
|
|
81
|
-
throw new Error(`${op} needs ${name}`);
|
|
82
|
-
return v;
|
|
83
|
-
}
|
|
84
|
-
/** Turns a validated tool input into the action data the adapter decodes. */
|
|
85
|
-
export function toAction(a) {
|
|
86
|
-
switch (a.kind) {
|
|
87
|
-
case "weth":
|
|
88
|
-
return actions.weth({ wrap: a.wrap, amount: B(a.amount) });
|
|
89
|
-
case "uniswapV3Swap":
|
|
90
|
-
return actions.uniswapV3Swap({ tokenIn: A(a.tokenIn), tokenOut: A(a.tokenOut), fee: a.fee, amountIn: B(a.amountIn), amountOutMinimum: B(a.amountOutMinimum) });
|
|
91
|
-
case "uniswapV4Swap":
|
|
92
|
-
return actions.uniswapV4Swap({ key: key(a.key), zeroForOne: a.zeroForOne, amountIn: B(a.amountIn), amountOutMinimum: B(a.amountOutMinimum) });
|
|
93
|
-
case "morpho":
|
|
94
|
-
return actions.morpho({
|
|
95
|
-
op: a.op,
|
|
96
|
-
market: { loanToken: A(a.market.loanToken), collateralToken: A(a.market.collateralToken), oracle: A(a.market.oracle), irm: A(a.market.irm), lltv: B(a.market.lltv) },
|
|
97
|
-
assets: B(a.assets),
|
|
98
|
-
shares: B(a.shares),
|
|
99
|
-
});
|
|
100
|
-
case "pons":
|
|
101
|
-
return actions.pons({ side: a.side, token: A(a.token), amountIn: B(a.amountIn), minOut: B(a.minOut) });
|
|
102
|
-
case "flap":
|
|
103
|
-
return actions.flap({ tokenIn: A(a.tokenIn), tokenOut: A(a.tokenOut), amountIn: B(a.amountIn), minOut: B(a.minOut) });
|
|
104
|
-
case "erc4626":
|
|
105
|
-
return actions.erc4626({ op: a.op, target: A(a.target), amount: B(a.amount) });
|
|
106
|
-
case "transfer":
|
|
107
|
-
return actions.transfer({ token: A(a.token), to: A(a.to), amount: B(a.amount) });
|
|
108
|
-
case "familyTransfer":
|
|
109
|
-
return actions.familyTransfer({ token: A(a.token), to: A(a.to), amount: B(a.amount) });
|
|
110
|
-
case "across":
|
|
111
|
-
return actions.across({
|
|
112
|
-
destinationChainId: B(a.destinationChainId),
|
|
113
|
-
recipient: a.recipient,
|
|
114
|
-
inputToken: A(a.inputToken),
|
|
115
|
-
outputToken: a.outputToken,
|
|
116
|
-
minRate: B(a.minRate),
|
|
117
|
-
inputAmount: B(a.inputAmount),
|
|
118
|
-
outputAmount: B(a.outputAmount),
|
|
119
|
-
quoteTimestamp: a.quoteTimestamp,
|
|
120
|
-
fillDeadline: a.fillDeadline,
|
|
121
|
-
});
|
|
122
|
-
case "uniswapV3Liquidity": {
|
|
123
|
-
const op = a.op;
|
|
124
|
-
const n = (name) => need(a[name], name, `uniswapV3Liquidity ${op}`);
|
|
125
|
-
const i = (name) => need(a[name], name, `uniswapV3Liquidity ${op}`);
|
|
126
|
-
if (op === "mint") {
|
|
127
|
-
return actions.uniswapV3Liquidity({
|
|
128
|
-
op,
|
|
129
|
-
token0: A(n("token0")),
|
|
130
|
-
token1: A(n("token1")),
|
|
131
|
-
fee: i("fee"),
|
|
132
|
-
tickLower: i("tickLower"),
|
|
133
|
-
tickUpper: i("tickUpper"),
|
|
134
|
-
amount0: B(n("amount0")),
|
|
135
|
-
amount1: B(n("amount1")),
|
|
136
|
-
amount0Min: B(n("amount0Min")),
|
|
137
|
-
amount1Min: B(n("amount1Min")),
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
// The adapter reads only the amounts on increase and only the liquidity on decrease; the field it
|
|
141
|
-
// ignores is not asked for.
|
|
142
|
-
if (op === "increase") {
|
|
143
|
-
return actions.uniswapV3Liquidity({ op, tokenId: B(n("tokenId")), liquidity: 0n, amount0: B(n("amount0")), amount1: B(n("amount1")), amount0Min: B(n("amount0Min")), amount1Min: B(n("amount1Min")) });
|
|
144
|
-
}
|
|
145
|
-
if (op === "decrease") {
|
|
146
|
-
return actions.uniswapV3Liquidity({ op, tokenId: B(n("tokenId")), liquidity: B(n("liquidity")), amount0: 0n, amount1: 0n, amount0Min: B(n("amount0Min")), amount1Min: B(n("amount1Min")) });
|
|
147
|
-
}
|
|
148
|
-
return actions.uniswapV3Liquidity({ op, tokenId: B(n("tokenId")) });
|
|
149
|
-
}
|
|
150
|
-
case "uniswapV4Liquidity": {
|
|
151
|
-
const op = a.op;
|
|
152
|
-
const n = (name) => need(a[name], name, `uniswapV4Liquidity ${op}`);
|
|
153
|
-
if (op === "mint") {
|
|
154
|
-
return actions.uniswapV4Liquidity({
|
|
155
|
-
op,
|
|
156
|
-
key: key(need(a.key, "key", "uniswapV4Liquidity mint")),
|
|
157
|
-
tickLower: need(a.tickLower, "tickLower", "uniswapV4Liquidity mint"),
|
|
158
|
-
tickUpper: need(a.tickUpper, "tickUpper", "uniswapV4Liquidity mint"),
|
|
159
|
-
liquidity: B(n("liquidity")),
|
|
160
|
-
amount0: B(n("amount0")),
|
|
161
|
-
amount1: B(n("amount1")),
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
if (op === "burn")
|
|
165
|
-
return actions.uniswapV4Liquidity({ op, tokenId: B(n("tokenId")), amount0Min: B(n("amount0Min")), amount1Min: B(n("amount1Min")) });
|
|
166
|
-
return actions.uniswapV4Liquidity({ op, tokenId: B(n("tokenId")), liquidity: B(n("liquidity")), amount0: B(n("amount0")), amount1: B(n("amount1")) });
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
function key(k) {
|
|
171
|
-
return { currency0: A(k.currency0), currency1: A(k.currency1), fee: k.fee, tickSpacing: k.tickSpacing, hooks: A(k.hooks) };
|
|
172
|
-
}
|
package/dist/config.js
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import { readFileSync, statSync } from "node:fs";
|
|
2
|
-
import { createPublicClient, createWalletClient, http, isAddress, isHex } from "viem";
|
|
3
|
-
import { privateKeyToAccount } from "viem/accounts";
|
|
4
|
-
import { robinhood, vaultStatus } from "@mortiseagentvault/sdk";
|
|
5
|
-
const PUBLIC_RPC = "https://rpc.mainnet.chain.robinhood.com";
|
|
6
|
-
/**
|
|
7
|
-
* Reads the configuration from the environment:
|
|
8
|
-
* MORTISE_VAULT the vault the agent works in (required)
|
|
9
|
-
* MORTISE_AGENT_KEY_FILE a file holding the agent's private key, readable by its owner only (required)
|
|
10
|
-
* MORTISE_RPC_URL_FILE a file holding the RPC URL, for URLs that carry an API key (optional)
|
|
11
|
-
* MORTISE_RPC_URL the RPC URL (optional; defaults to the public Robinhood Chain RPC)
|
|
12
|
-
*/
|
|
13
|
-
export function configFromEnv(env = process.env) {
|
|
14
|
-
const vault = env.MORTISE_VAULT;
|
|
15
|
-
if (!vault || !isAddress(vault))
|
|
16
|
-
throw new Error("MORTISE_VAULT must be the vault's address");
|
|
17
|
-
const keyFile = env.MORTISE_AGENT_KEY_FILE;
|
|
18
|
-
if (!keyFile)
|
|
19
|
-
throw new Error("MORTISE_AGENT_KEY_FILE must point to a file holding the agent's private key");
|
|
20
|
-
// An empty value would make viem fall back to another RPC without a word, so it is refused instead.
|
|
21
|
-
let rpcUrl = env.MORTISE_RPC_URL === undefined ? PUBLIC_RPC : env.MORTISE_RPC_URL.trim();
|
|
22
|
-
if (env.MORTISE_RPC_URL_FILE)
|
|
23
|
-
rpcUrl = readPrivateFile(env.MORTISE_RPC_URL_FILE, "MORTISE_RPC_URL_FILE");
|
|
24
|
-
if (!/^https?:\/\/\S+$/.test(rpcUrl))
|
|
25
|
-
throw new Error("the RPC URL must be an http(s) URL");
|
|
26
|
-
return { vault, keyFile, rpcUrl };
|
|
27
|
-
}
|
|
28
|
-
/** Reads a secret file, refusing one that other users can read or write. */
|
|
29
|
-
function readPrivateFile(path, name) {
|
|
30
|
-
const st = statSync(path);
|
|
31
|
-
if (!st.isFile())
|
|
32
|
-
throw new Error(`${name} is not a regular file`);
|
|
33
|
-
if ((st.mode & 0o077) !== 0)
|
|
34
|
-
throw new Error(`${name} is readable or writable by other users; run chmod 600 on it`);
|
|
35
|
-
if (typeof process.getuid === "function" && st.uid !== process.getuid())
|
|
36
|
-
throw new Error(`${name} belongs to another user`);
|
|
37
|
-
return readFileSync(path, "utf8").trim();
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Builds the clients and checks the key before any tool runs: the vault must exist, and the key must be neither
|
|
41
|
-
* a root key nor a guardian of the vault. An agent key belongs in the Gate, where the owner's limits apply.
|
|
42
|
-
*/
|
|
43
|
-
export async function connect(cfg) {
|
|
44
|
-
const key = readPrivateFile(cfg.keyFile, "MORTISE_AGENT_KEY_FILE");
|
|
45
|
-
const hex = (key.startsWith("0x") ? key : `0x${key}`);
|
|
46
|
-
if (!isHex(hex) || hex.length !== 66)
|
|
47
|
-
throw new Error("MORTISE_AGENT_KEY_FILE must hold a 32-byte hex private key");
|
|
48
|
-
const account = privateKeyToAccount(hex);
|
|
49
|
-
const transport = http(cfg.rpcUrl, { retryCount: 2, retryDelay: 500, timeout: 10_000 });
|
|
50
|
-
const client = createPublicClient({ chain: robinhood, transport });
|
|
51
|
-
const wallet = createWalletClient({ account, chain: robinhood, transport });
|
|
52
|
-
const chainId = await client.getChainId();
|
|
53
|
-
if (chainId !== robinhood.id)
|
|
54
|
-
throw new Error(`the RPC serves chain ${chainId}, not Robinhood Chain (${robinhood.id})`);
|
|
55
|
-
const status = await vaultStatus(client, cfg.vault);
|
|
56
|
-
if (!status.exists)
|
|
57
|
-
throw new Error(`no vault is deployed at ${cfg.vault}`);
|
|
58
|
-
// The vault's own root and guardians, then those of every vault above it: the sub-vault parent whose root
|
|
59
|
-
// runs it through MortiseSubVaults, and the Gate's family parent.
|
|
60
|
-
const me = account.address.toLowerCase();
|
|
61
|
-
const seen = new Set();
|
|
62
|
-
const queue = [{ status, depth: 0 }];
|
|
63
|
-
while (queue.length > 0) {
|
|
64
|
-
const { status: s, depth } = queue.shift();
|
|
65
|
-
if (!s.exists || seen.has(s.vault.toLowerCase()) || depth > 8)
|
|
66
|
-
continue;
|
|
67
|
-
seen.add(s.vault.toLowerCase());
|
|
68
|
-
const whose = depth === 0 ? "the vault" : `the parent vault ${s.vault}`;
|
|
69
|
-
if (s.root.members.some((m) => m.type === "ecdsa" && m.signer.toLowerCase() === me)) {
|
|
70
|
-
throw new Error(`this key is a root key of ${whose}; give the agent its own key and add it with gate.setAgent`);
|
|
71
|
-
}
|
|
72
|
-
if (s.recovery.guardians.some((g) => g.toLowerCase() === me))
|
|
73
|
-
throw new Error(`this key is a guardian of ${whose}; give the agent its own key`);
|
|
74
|
-
for (const up of [s.family.controller, s.family.parent]) {
|
|
75
|
-
if (up && !seen.has(up.toLowerCase()))
|
|
76
|
-
queue.push({ status: await vaultStatus(client, up), depth: depth + 1 });
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return { client, wallet, agent: account.address, vault: cfg.vault };
|
|
80
|
-
}
|
package/dist/server.js
DELETED
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
import { ETH, decodeMortiseError, erc20Abi, actionReceipt, minRate, mortise, permissions, planAction, revertData, sendActions, sendTrigger, simulateActions, vaultStatus, } from "@mortiseagentvault/sdk";
|
|
4
|
-
import { actionSchema, toAction } from "./actions.js";
|
|
5
|
-
const adapters = {
|
|
6
|
-
uniswapV3: mortise.uniswapV3,
|
|
7
|
-
uniswapV3Liquidity: mortise.uniswapV3Liquidity,
|
|
8
|
-
uniswapV4: mortise.uniswapV4,
|
|
9
|
-
uniswapV4Liquidity: mortise.uniswapV4Liquidity,
|
|
10
|
-
pons: mortise.pons,
|
|
11
|
-
flap: mortise.flap,
|
|
12
|
-
morphoBlue: mortise.morphoBlue,
|
|
13
|
-
erc4626: mortise.erc4626,
|
|
14
|
-
transfer: mortise.transfer,
|
|
15
|
-
weth: mortise.weth,
|
|
16
|
-
across: mortise.across,
|
|
17
|
-
familyTransfer: mortise.familyTransfer,
|
|
18
|
-
};
|
|
19
|
-
const adapterName = new Map(Object.entries(adapters).map(([name, a]) => [a.toLowerCase(), name]));
|
|
20
|
-
const modules = { dca: mortise.dca, automation: mortise.automation, rebalance: mortise.rebalance };
|
|
21
|
-
// MCP hosts give up on a request after about 60 s.
|
|
22
|
-
const TOOL_DEADLINE_MS = 45_000;
|
|
23
|
-
const WRITE_BUDGET_MS = 45_000;
|
|
24
|
-
const SEND_DEADLINE_MS = 30_000;
|
|
25
|
-
// A queued write starts only with at least this much of its send time left.
|
|
26
|
-
const MIN_SEND_MS = 10_000;
|
|
27
|
-
const address = z.string().regex(/^0x[0-9a-fA-F]{40}$/);
|
|
28
|
-
const actionList = z.array(actionSchema).min(1).max(16);
|
|
29
|
-
/** The MCP server for one agent key in one vault. Every limit is enforced on-chain by the Gate, not here. */
|
|
30
|
-
export function createServer(c, hide) {
|
|
31
|
-
const server = new McpServer({ name: "mortise", version: "0.1.0" });
|
|
32
|
-
// Every output passes through hide, successful ones included: a reason inside a result is still an error text.
|
|
33
|
-
const ok = (value) => ({ content: [{ type: "text", text: hide(json(value)) }] });
|
|
34
|
-
const fail = (err) => ({ content: [{ type: "text", text: hide(explain(err)) }], isError: true });
|
|
35
|
-
// Reads have no side effects, so a deadline that leaves them running in the background is harmless.
|
|
36
|
-
const run = (fn) => withDeadline(fn(), TOOL_DEADLINE_MS, "the RPC did not answer in time").then(ok, fail);
|
|
37
|
-
// A write runs within one budget, sending and confirming together, so the host never gives up first. Before
|
|
38
|
-
// the transaction is signed and broadcast, a timeout stops the send itself, so "nothing was sent" is true.
|
|
39
|
-
// Once it is out, the answer is its hash (confirmed, pending or unknown), never an invitation to resend.
|
|
40
|
-
// Writes run one at a time, so two of them never pick the same nonce.
|
|
41
|
-
let writes = Promise.resolve();
|
|
42
|
-
const act = (fn, signal) => {
|
|
43
|
-
// Time counts from arrival, queue included: the host's clock started then.
|
|
44
|
-
const arrived = Date.now();
|
|
45
|
-
const run = writes.then(() => actNow(fn, arrived, signal));
|
|
46
|
-
writes = run.catch(() => undefined);
|
|
47
|
-
return run;
|
|
48
|
-
};
|
|
49
|
-
const actNow = async (fn, arrived, signal) => {
|
|
50
|
-
const sendLeft = arrived + SEND_DEADLINE_MS - Date.now();
|
|
51
|
-
if (sendLeft < MIN_SEND_MS || signal?.aborted) {
|
|
52
|
-
return fail(new Error("too many writes were waiting, so this one was not started; nothing was sent"));
|
|
53
|
-
}
|
|
54
|
-
let signed;
|
|
55
|
-
let stopped = false;
|
|
56
|
-
let timer;
|
|
57
|
-
let onAbort;
|
|
58
|
-
const late = new Promise((_, reject) => {
|
|
59
|
-
// Set here, in the timer or the host's cancel: the send checks it right before signing and broadcasting.
|
|
60
|
-
const stop = (why) => {
|
|
61
|
-
if (!signed)
|
|
62
|
-
stopped = true;
|
|
63
|
-
reject(new Error(signed ? why : `${why}; nothing was sent`));
|
|
64
|
-
};
|
|
65
|
-
timer = setTimeout(() => stop("the RPC did not answer in time"), sendLeft);
|
|
66
|
-
onAbort = () => stop("the request was cancelled");
|
|
67
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
68
|
-
});
|
|
69
|
-
let hash;
|
|
70
|
-
try {
|
|
71
|
-
hash = await Promise.race([fn({ shouldSend: () => !stopped, onSigned: (h) => (signed = h) }), late]);
|
|
72
|
-
}
|
|
73
|
-
catch (err) {
|
|
74
|
-
if (!signed)
|
|
75
|
-
return fail(err);
|
|
76
|
-
return ok({ status: "unknown", transactionHash: signed, note: `sent but the RPC did not confirm it (${explain(err)}); check this hash before sending again` });
|
|
77
|
-
}
|
|
78
|
-
finally {
|
|
79
|
-
clearTimeout(timer);
|
|
80
|
-
if (onAbort)
|
|
81
|
-
signal?.removeEventListener("abort", onAbort);
|
|
82
|
-
}
|
|
83
|
-
try {
|
|
84
|
-
const r = await actionReceipt(c.client, hash, Math.max(arrived + WRITE_BUDGET_MS - Date.now(), 2_000));
|
|
85
|
-
return ok({ status: "confirmed", ...r, executed: r.executed.map((e) => ({ ...e, adapter: adapterName.get(e.adapter.toLowerCase()) ?? e.adapter })) });
|
|
86
|
-
}
|
|
87
|
-
catch (err) {
|
|
88
|
-
if (err?.name === "TransactionRevertedError")
|
|
89
|
-
return fail(err);
|
|
90
|
-
return ok({ status: "pending", transactionHash: hash, note: "sent but not confirmed yet; do not send it again, check this hash later" });
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
server.registerTool("mortise_permissions", {
|
|
94
|
-
title: "Agent permissions",
|
|
95
|
-
description: "What this agent may do in the vault right now: whether it is live and until when, whether the vault is paused, which adapters it may use, and how much of each token is left under its caps in the current window.",
|
|
96
|
-
inputSchema: { tokens: z.array(address).max(20).optional().describe("Tokens to report caps for; native ETH (address zero) is always included") },
|
|
97
|
-
annotations: { readOnlyHint: true },
|
|
98
|
-
}, ({ tokens }) => run(async () => {
|
|
99
|
-
const list = [ETH, ...(tokens ?? []).filter((t) => t.toLowerCase() !== ETH)];
|
|
100
|
-
const p = await permissions(c.client, c.vault, c.agent, { adapters: Object.values(adapters), tokens: list });
|
|
101
|
-
return {
|
|
102
|
-
vault: c.vault,
|
|
103
|
-
agent: c.agent,
|
|
104
|
-
live: p.live,
|
|
105
|
-
until: p.until,
|
|
106
|
-
paused: p.paused,
|
|
107
|
-
gateInstalled: p.installed,
|
|
108
|
-
openFloor: p.openFloor,
|
|
109
|
-
adapters: p.adapters.filter((a) => a.canUse).map((a) => ({ name: adapterName.get(a.adapter.toLowerCase()), adapter: a.adapter, anyMarket: a.openMarkets })),
|
|
110
|
-
caps: p.caps,
|
|
111
|
-
};
|
|
112
|
-
}));
|
|
113
|
-
server.registerTool("mortise_vault", {
|
|
114
|
-
title: "Vault status",
|
|
115
|
-
description: "The vault's state: whether the Gate is installed or paused, the timelock delay, the family (parent and number of sub-vaults) and its ETH balance.",
|
|
116
|
-
inputSchema: {},
|
|
117
|
-
annotations: { readOnlyHint: true },
|
|
118
|
-
}, () => run(async () => {
|
|
119
|
-
const s = await vaultStatus(c.client, c.vault);
|
|
120
|
-
if (!s.exists)
|
|
121
|
-
throw new Error(`no vault at ${c.vault}`);
|
|
122
|
-
return { vault: s.vault, gate: s.gate, timelock: s.timelock, family: s.family, paymasterOnly: s.paymasterOnly, ethBalance: s.ethBalance };
|
|
123
|
-
}));
|
|
124
|
-
server.registerTool("mortise_balances", {
|
|
125
|
-
title: "Vault balances",
|
|
126
|
-
description: "The vault's balance of native ETH and of each token given, in the token's smallest unit, with its decimals and symbol.",
|
|
127
|
-
inputSchema: { tokens: z.array(address).max(20).default([]) },
|
|
128
|
-
annotations: { readOnlyHint: true },
|
|
129
|
-
}, ({ tokens }) => run(async () => {
|
|
130
|
-
const eth = { token: ETH, symbol: "ETH", decimals: 18, balance: await c.client.getBalance({ address: c.vault }) };
|
|
131
|
-
const rest = await Promise.all(tokens.map(async (t) => {
|
|
132
|
-
const token = t;
|
|
133
|
-
const [balance, decimals, symbol] = await Promise.all([
|
|
134
|
-
c.client.readContract({ address: token, abi: erc20Abi, functionName: "balanceOf", args: [c.vault] }),
|
|
135
|
-
c.client.readContract({ address: token, abi: [{ type: "function", name: "decimals", inputs: [], outputs: [{ type: "uint8" }], stateMutability: "view" }], functionName: "decimals" }).catch(() => undefined),
|
|
136
|
-
c.client.readContract({ address: token, abi: [{ type: "function", name: "symbol", inputs: [], outputs: [{ type: "string" }], stateMutability: "view" }], functionName: "symbol" }).catch(() => undefined),
|
|
137
|
-
]);
|
|
138
|
-
return { token, symbol, decimals, balance };
|
|
139
|
-
}));
|
|
140
|
-
return [eth, ...rest];
|
|
141
|
-
}));
|
|
142
|
-
server.registerTool("mortise_min_rate", {
|
|
143
|
-
title: "Price floor",
|
|
144
|
-
description: "The lowest price the owner accepts when the vault sells tokenIn for tokenOut, as raw tokenOut per 1e36 raw tokenIn (0 means no floor). Swaps below it are refused.",
|
|
145
|
-
inputSchema: { tokenIn: address, tokenOut: address },
|
|
146
|
-
annotations: { readOnlyHint: true },
|
|
147
|
-
}, ({ tokenIn, tokenOut }) => run(async () => ({ tokenIn, tokenOut, rate: await minRate(c.client, c.vault, tokenIn, tokenOut) })));
|
|
148
|
-
server.registerTool("mortise_simulate", {
|
|
149
|
-
title: "Simulate actions",
|
|
150
|
-
description: "Runs actions exactly as mortise_execute would, without sending anything. Returns the market each action needs, or the reason the Gate or an adapter refuses (for example CapExceeded, MarketNotAllowed, NotAgent). Amounts are integer strings in the token's smallest unit.",
|
|
151
|
-
inputSchema: { actions: actionList },
|
|
152
|
-
annotations: { readOnlyHint: true },
|
|
153
|
-
}, ({ actions }) => run(async () => {
|
|
154
|
-
const built = actions.map(toAction);
|
|
155
|
-
const plans = await Promise.all(built.map(async (a, i) => {
|
|
156
|
-
try {
|
|
157
|
-
const p = await planAction(c.client, c.vault, a);
|
|
158
|
-
return { index: i, kind: actions[i].kind, adapter: adapterName.get(a.adapter.toLowerCase()), market: p.market };
|
|
159
|
-
}
|
|
160
|
-
catch (err) {
|
|
161
|
-
if (!isRevert(err))
|
|
162
|
-
throw err;
|
|
163
|
-
return { index: i, kind: actions[i].kind, error: explain(err) };
|
|
164
|
-
}
|
|
165
|
-
}));
|
|
166
|
-
try {
|
|
167
|
-
await simulateActions(c.client, c.agent, c.vault, built);
|
|
168
|
-
return { ok: true, actions: plans };
|
|
169
|
-
}
|
|
170
|
-
catch (err) {
|
|
171
|
-
// Only a refusal by the contracts is an answer; an RPC failure is an error of the tool.
|
|
172
|
-
if (!isRevert(err))
|
|
173
|
-
throw err;
|
|
174
|
-
return { ok: false, reason: explain(err), actions: plans };
|
|
175
|
-
}
|
|
176
|
-
}));
|
|
177
|
-
server.registerTool("mortise_execute", {
|
|
178
|
-
title: "Execute actions",
|
|
179
|
-
description: "Sends the actions to the Gate from the agent's key, in one transaction: all of them run or none. They are simulated first, and the Gate refuses anything outside the owner's limits. The agent's key pays the gas in ETH. Amounts are integer strings in the token's smallest unit.",
|
|
180
|
-
inputSchema: { actions: actionList },
|
|
181
|
-
annotations: { destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
182
|
-
}, ({ actions }, extra) => act((o) => sendActions(c.client, c.wallet, c.vault, actions.map(toAction), o), extra.signal));
|
|
183
|
-
server.registerTool("mortise_trigger", {
|
|
184
|
-
title: "Trigger a module",
|
|
185
|
-
description: "As the module's keeper, runs what an enabled automation module (dca, automation or rebalance) proposes now. The module refuses when nothing is due.",
|
|
186
|
-
inputSchema: { module: z.enum(["dca", "automation", "rebalance"]) },
|
|
187
|
-
annotations: { destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
188
|
-
}, ({ module }, extra) => act((o) => sendTrigger(c.client, c.wallet, c.vault, modules[module], o), extra.signal));
|
|
189
|
-
return server;
|
|
190
|
-
}
|
|
191
|
-
/** A short reason: the contract error by name when it is one, otherwise the error's own short message. */
|
|
192
|
-
export function explain(err) {
|
|
193
|
-
const data = revertData(err);
|
|
194
|
-
const d = data ? decodeMortiseError(data) : undefined;
|
|
195
|
-
if (d)
|
|
196
|
-
return d.args.length ? `${d.name}(${d.args.map(String).join(", ")})` : d.name;
|
|
197
|
-
// viem errors carry a one-line shortMessage; checked by shape, as the error may come from another viem copy.
|
|
198
|
-
const short = err?.shortMessage;
|
|
199
|
-
if (typeof short === "string")
|
|
200
|
-
return short;
|
|
201
|
-
return err instanceof Error ? err.message : String(err);
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* True when a contract reverted, as opposed to the RPC failing: revert data, error code 3, or the node's
|
|
205
|
-
* "execution reverted". viem also labels a bare internal RPC error as a revert, so its class alone is not enough.
|
|
206
|
-
*/
|
|
207
|
-
function isRevert(err) {
|
|
208
|
-
if (revertData(err))
|
|
209
|
-
return true;
|
|
210
|
-
for (let e = err, depth = 0; e && typeof e === "object" && depth < 20; depth++) {
|
|
211
|
-
if (e.code === 3)
|
|
212
|
-
return true;
|
|
213
|
-
for (const k of ["details", "shortMessage", "message"]) {
|
|
214
|
-
const m = e[k];
|
|
215
|
-
if (typeof m === "string" && /execution reverted/i.test(m))
|
|
216
|
-
return true;
|
|
217
|
-
}
|
|
218
|
-
e = e.cause;
|
|
219
|
-
}
|
|
220
|
-
return false;
|
|
221
|
-
}
|
|
222
|
-
function json(value) {
|
|
223
|
-
return JSON.stringify(value, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2);
|
|
224
|
-
}
|
|
225
|
-
function withDeadline(p, ms, message) {
|
|
226
|
-
let timer;
|
|
227
|
-
const late = new Promise((_, reject) => {
|
|
228
|
-
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
229
|
-
});
|
|
230
|
-
return Promise.race([p, late]).finally(() => clearTimeout(timer));
|
|
231
|
-
}
|