@gvnrdao/dh-mcp 0.0.1

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.
Files changed (43) hide show
  1. package/.env.example +22 -0
  2. package/README.md +39 -0
  3. package/dist/index.js +1575 -0
  4. package/package.json +26 -0
  5. package/src/actions/index.ts +13 -0
  6. package/src/actions/loan-create.action.ts +28 -0
  7. package/src/actions/loan-extend.action.ts +17 -0
  8. package/src/actions/loan-mint.action.ts +17 -0
  9. package/src/actions/loan-pay.action.ts +17 -0
  10. package/src/actions/loan-withdraw.action.ts +17 -0
  11. package/src/actions/types.ts +33 -0
  12. package/src/config.ts +43 -0
  13. package/src/context.ts +87 -0
  14. package/src/index.ts +23 -0
  15. package/src/resources/position.ts +39 -0
  16. package/src/resources/protocol.ts +57 -0
  17. package/src/server.ts +58 -0
  18. package/src/signer/eoa-dh.ts +35 -0
  19. package/src/signer/index.ts +12 -0
  20. package/src/signer/safe-module-signer-adapter.ts +61 -0
  21. package/src/signer/safe-module.ts +110 -0
  22. package/src/signer/types.ts +12 -0
  23. package/src/tools/_helpers.ts +47 -0
  24. package/src/tools/btc.ts +38 -0
  25. package/src/tools/loan.ts +197 -0
  26. package/src/tools/position.ts +93 -0
  27. package/src/tools/protocol.ts +35 -0
  28. package/src/util/btc-address.ts +58 -0
  29. package/src/util/eip712-login.ts +65 -0
  30. package/src/util/errors.ts +24 -0
  31. package/src/util/extend-fee-bound.ts +51 -0
  32. package/src/util/format.ts +9 -0
  33. package/src/util/network.ts +34 -0
  34. package/src/util/server-fetch.ts +27 -0
  35. package/src/util/server-mint.ts +108 -0
  36. package/src/util/server-renew.ts +107 -0
  37. package/src/util/server-repay.ts +118 -0
  38. package/src/util/server-session.ts +108 -0
  39. package/src/util/server-withdraw.ts +34 -0
  40. package/src/util/tx-validator.ts +231 -0
  41. package/src/util/validate.ts +41 -0
  42. package/tsconfig.json +20 -0
  43. package/tsup.config.ts +11 -0
@@ -0,0 +1,110 @@
1
+ import { ethers } from "ethers";
2
+ import type { DHSigner } from "./types.js";
3
+
4
+ const AGENT_MODULE_ABI = [
5
+ "function execute(address target, bytes calldata data) external",
6
+ "function agent() view returns (address)",
7
+ "function safe() view returns (address)",
8
+ ] as const;
9
+
10
+ const AGENT_MODULE_IFACE = new ethers.Interface(
11
+ AGENT_MODULE_ABI as unknown as string[],
12
+ );
13
+
14
+ export class SafeModuleDHSigner implements DHSigner {
15
+ readonly kind = "safe-module" as const;
16
+ private readonly agentEoa: ethers.Signer;
17
+ private readonly safeAddress: string;
18
+ private readonly agentModuleAddress: string;
19
+
20
+ constructor(agentEoa: ethers.Signer, safeAddress: string, agentModuleAddress: string) {
21
+ if (!ethers.isAddress(safeAddress)) {
22
+ throw new Error(`SafeModuleDHSigner: invalid safeAddress ${safeAddress}`);
23
+ }
24
+ if (!ethers.isAddress(agentModuleAddress)) {
25
+ throw new Error(`SafeModuleDHSigner: invalid agentModuleAddress ${agentModuleAddress}`);
26
+ }
27
+ this.agentEoa = agentEoa;
28
+ this.safeAddress = ethers.getAddress(safeAddress);
29
+ this.agentModuleAddress = ethers.getAddress(agentModuleAddress);
30
+ }
31
+
32
+ async getBorrowerAddress(): Promise<string> {
33
+ return this.safeAddress;
34
+ }
35
+
36
+ async getAuthSignerAddress(): Promise<string> {
37
+ return this.agentEoa.getAddress();
38
+ }
39
+
40
+ async signAuthMessage(messageHash: string): Promise<string> {
41
+ return this.agentEoa.signMessage(ethers.getBytes(messageHash));
42
+ }
43
+
44
+ async wrapInnerTx(innerTx: ethers.TransactionRequest): Promise<ethers.TransactionRequest> {
45
+ const innerTo = innerTx.to;
46
+ const innerData = innerTx.data;
47
+ if (typeof innerTo !== "string" || !ethers.isAddress(innerTo)) {
48
+ throw new Error(`wrapInnerTx: innerTx.to is missing or not an address`);
49
+ }
50
+ if (typeof innerData !== "string" || !innerData.startsWith("0x")) {
51
+ throw new Error(`wrapInnerTx: innerTx.data is missing or malformed`);
52
+ }
53
+ if (innerTx.value != null) {
54
+ const v = typeof innerTx.value === "bigint" ? innerTx.value : BigInt(String(innerTx.value));
55
+ if (v !== 0n) {
56
+ throw new Error(`wrapInnerTx: inner value ${v.toString()} is non-zero — refusing to wrap`);
57
+ }
58
+ }
59
+ const outerData = AGENT_MODULE_IFACE.encodeFunctionData("execute", [innerTo, innerData]);
60
+ return {
61
+ to: this.agentModuleAddress,
62
+ data: outerData,
63
+ value: 0,
64
+ chainId: innerTx.chainId,
65
+ };
66
+ }
67
+
68
+ async signTransaction(outerTx: ethers.TransactionRequest): Promise<string> {
69
+ if (!outerTx.to || ethers.getAddress(outerTx.to as string) !== this.agentModuleAddress) {
70
+ throw new Error(
71
+ `signTransaction: outer tx target is ${outerTx.to}, expected agent module ${this.agentModuleAddress} — refusing to sign`,
72
+ );
73
+ }
74
+ const provider = this.agentEoa.provider;
75
+ if (!provider) {
76
+ throw new Error(`SafeModuleDHSigner.signTransaction: agent signer has no provider attached`);
77
+ }
78
+ const populated: ethers.TransactionRequest = { ...outerTx };
79
+ const fromAddr = await this.agentEoa.getAddress();
80
+ if (populated.nonce == null) {
81
+ populated.nonce = await provider.getTransactionCount(fromAddr, "pending");
82
+ }
83
+ if (populated.gasLimit == null) {
84
+ try {
85
+ const est = await provider.estimateGas({ ...populated, from: fromAddr });
86
+ populated.gasLimit = (est * 125n) / 100n;
87
+ } catch {
88
+ populated.gasLimit = 600_000n;
89
+ }
90
+ }
91
+ if (populated.maxFeePerGas == null && populated.maxPriorityFeePerGas == null && populated.gasPrice == null) {
92
+ const fee = await provider.getFeeData();
93
+ const MIN_PRIORITY_FEE = 1_500_000_000n;
94
+ if (fee.maxFeePerGas != null && fee.maxPriorityFeePerGas != null) {
95
+ populated.type = 2;
96
+ const priority = fee.maxPriorityFeePerGas > MIN_PRIORITY_FEE ? fee.maxPriorityFeePerGas : MIN_PRIORITY_FEE;
97
+ const networkMax = fee.maxFeePerGas > priority ? fee.maxFeePerGas : priority;
98
+ populated.maxFeePerGas = networkMax > priority * 2n ? networkMax : priority * 2n;
99
+ populated.maxPriorityFeePerGas = priority;
100
+ } else if (fee.gasPrice != null) {
101
+ populated.gasPrice = fee.gasPrice > MIN_PRIORITY_FEE ? fee.gasPrice : MIN_PRIORITY_FEE;
102
+ }
103
+ }
104
+ return this.agentEoa.signTransaction(populated);
105
+ }
106
+
107
+ getEthersSigner(): ethers.Signer {
108
+ return this.agentEoa;
109
+ }
110
+ }
@@ -0,0 +1,12 @@
1
+ import { ethers } from "ethers";
2
+
3
+ export interface DHSigner {
4
+ readonly kind: "eoa-env" | "safe-module";
5
+
6
+ getBorrowerAddress(): Promise<string>;
7
+ getAuthSignerAddress(): Promise<string>;
8
+ signAuthMessage(messageHash: string): Promise<string>;
9
+ wrapInnerTx(innerTx: ethers.TransactionRequest): Promise<ethers.TransactionRequest>;
10
+ signTransaction(outerTx: ethers.TransactionRequest): Promise<string>;
11
+ getEthersSigner(): ethers.Signer;
12
+ }
@@ -0,0 +1,47 @@
1
+ import { isSuccess, type SDKError } from "@gvnrdao/dh-sdk";
2
+ import { serialize } from "../util/format.js";
3
+ import { formatSDKError } from "../util/errors.js";
4
+
5
+ export interface ToolResult {
6
+ content: Array<{ type: "text"; text: string }>;
7
+ isError?: boolean;
8
+ [key: string]: unknown;
9
+ }
10
+
11
+ export function ok(data: unknown): ToolResult {
12
+ return { content: [{ type: "text", text: serialize(data) }] };
13
+ }
14
+
15
+ export function err(message: string): ToolResult {
16
+ return { content: [{ type: "text", text: message }], isError: true };
17
+ }
18
+
19
+ /**
20
+ * Audit H-5: human-confirmation gate for irreversible, fund-moving write tools.
21
+ * Returns an error ToolResult when `confirmed !== true`, else null. The `confirmed` flag is meant
22
+ * to be set by a HUMAN (via the MCP host's approval UI), never auto-filled by the model. Paired
23
+ * with the tool's `destructiveHint` annotation so compliant hosts surface an explicit prompt.
24
+ */
25
+ export function requireConfirmation(confirmed: unknown, actionLabel: string): ToolResult | null {
26
+ if (confirmed === true) return null;
27
+ return err(
28
+ `CONFIRMATION REQUIRED — refusing to run "${actionLabel}".\n` +
29
+ `This is an irreversible, fund-moving action. A human must explicitly authorize it.\n` +
30
+ `Re-invoke with confirmed: true ONLY after a human has approved this exact operation. ` +
31
+ `Do not set confirmed on your own.`,
32
+ );
33
+ }
34
+
35
+ export function fromSdkResult<T>(result: { success: true; value: T } | { success: false; error: SDKError }): ToolResult {
36
+ if (isSuccess(result)) return ok(result.value);
37
+ return err(formatSDKError(result.error));
38
+ }
39
+
40
+ /** Wraps a tool body so any thrown error becomes an `isError: true` response. */
41
+ export async function safe(fn: () => Promise<ToolResult>): Promise<ToolResult> {
42
+ try {
43
+ return await fn();
44
+ } catch (e) {
45
+ return err((e as Error).message);
46
+ }
47
+ }
@@ -0,0 +1,38 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { Ctx } from "../context.js";
4
+ import { ok, fromSdkResult, safe } from "./_helpers.js";
5
+
6
+ export function registerBtcTools(server: McpServer, getCtx: () => Promise<Ctx>): void {
7
+ server.registerTool(
8
+ "btc_balance",
9
+ {
10
+ title: "Get BTC balance for an address",
11
+ description: "Query the current BTC balance and UTXOs for any BTC address (uses configured providers).",
12
+ inputSchema: {
13
+ address: z.string().min(1).describe("BTC address to query"),
14
+ },
15
+ },
16
+ async ({ address }) =>
17
+ safe(async () => {
18
+ const ctx = await getCtx();
19
+ const result = await ctx.sdk.getBitcoinBalance(address);
20
+ return fromSdkResult(result);
21
+ }),
22
+ );
23
+
24
+ server.registerTool(
25
+ "btc_price",
26
+ {
27
+ title: "Get the current BTC price",
28
+ description: "Return the current BTC price (USD, 8 decimals) signed by the price oracle PKP.",
29
+ inputSchema: {},
30
+ },
31
+ async () =>
32
+ safe(async () => {
33
+ const ctx = await getCtx();
34
+ const result = await ctx.sdk.getBitcoinPrice();
35
+ return ok(result);
36
+ }),
37
+ );
38
+ }
@@ -0,0 +1,197 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { Ctx } from "../context.js";
4
+ import {
5
+ createPositionAction,
6
+ mintAction,
7
+ payAction,
8
+ extendAction,
9
+ withdrawAction,
10
+ } from "../actions/index.js";
11
+ import { requireNotMainnetForWrites } from "../util/network.js";
12
+ import { ok, err, safe, requireConfirmation } from "./_helpers.js";
13
+
14
+ const LATENCY_NOTE = "Takes 60–90 seconds — invokes a LIT Action on the Lit network.";
15
+
16
+ const positionIdSchema = z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
17
+
18
+ // Audit H-5: human-approval gate for irreversible write tools. The model must NOT set this itself;
19
+ // a human authorizes via the MCP host. Compliant hosts also see `annotations.destructiveHint`.
20
+ const confirmedSchema = z
21
+ .boolean()
22
+ .optional()
23
+ .describe(
24
+ "Human authorization gate — must be set to true by a HUMAN (not the model) to execute this irreversible action.",
25
+ );
26
+
27
+ const DESTRUCTIVE_WRITE_ANNOTATIONS = {
28
+ readOnlyHint: false,
29
+ destructiveHint: true,
30
+ idempotentHint: false,
31
+ openWorldHint: true,
32
+ } as const;
33
+
34
+ export function registerLoanTools(server: McpServer, getCtx: () => Promise<Ctx>): void {
35
+ server.registerTool(
36
+ "loan_create",
37
+ {
38
+ title: "Create a new lending position",
39
+ description:
40
+ `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
41
+ inputSchema: {
42
+ selectedTerm: z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
43
+ confirmed: confirmedSchema,
44
+ },
45
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS,
46
+ },
47
+ async ({ selectedTerm, confirmed }) =>
48
+ safe(async () => {
49
+ const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
50
+ if (gate) return gate;
51
+ const ctx = await getCtx();
52
+ requireNotMainnetForWrites(ctx.config.network);
53
+ const result = await createPositionAction(ctx, { selectedTerm });
54
+ return result.success ? ok(result) : err(result.error ?? "Loan creation failed.");
55
+ }),
56
+ );
57
+
58
+ server.registerTool(
59
+ "loan_mint",
60
+ {
61
+ title: "Mint UCD against a position",
62
+ description: `Mint UCD against an existing lending position's BTC collateral. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
63
+ inputSchema: {
64
+ positionId: positionIdSchema,
65
+ amountUcd: z.number().positive().describe("Amount of UCD to mint"),
66
+ confirmed: confirmedSchema,
67
+ },
68
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS,
69
+ },
70
+ async ({ positionId, amountUcd, confirmed }) =>
71
+ safe(async () => {
72
+ const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
73
+ if (gate) return gate;
74
+ const ctx = await getCtx();
75
+ requireNotMainnetForWrites(ctx.config.network);
76
+ const result = await mintAction(ctx, { positionId, amountUcd });
77
+ return result.success ? ok(result) : err(result.error ?? "Mint failed.");
78
+ }),
79
+ );
80
+
81
+ server.registerTool(
82
+ "loan_pay",
83
+ {
84
+ title: "Make a UCD payment toward a position's debt",
85
+ description: `Repay (full or partial) a position's UCD debt. Moves UCD out of your wallet (irreversible). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
86
+ inputSchema: {
87
+ positionId: positionIdSchema,
88
+ amountUcd: z.number().positive().describe("Amount of UCD to repay"),
89
+ confirmed: confirmedSchema,
90
+ },
91
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS,
92
+ },
93
+ async ({ positionId, amountUcd, confirmed }) =>
94
+ safe(async () => {
95
+ const gate = requireConfirmation(confirmed, `repay ${amountUcd} UCD toward position ${positionId}`);
96
+ if (gate) return gate;
97
+ const ctx = await getCtx();
98
+ requireNotMainnetForWrites(ctx.config.network);
99
+ const result = await payAction(ctx, { positionId, amountUcd });
100
+ return result.success ? ok(result) : err(result.error ?? "Payment failed.");
101
+ }),
102
+ );
103
+
104
+ server.registerTool(
105
+ "loan_extend",
106
+ {
107
+ title: "Extend / renew a position's term",
108
+ description: `Renew an active position with a new term. Pays a pro-rata renewal fee in UCD (irreversible on-chain write). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
109
+ inputSchema: {
110
+ positionId: positionIdSchema,
111
+ selectedTerm: z.number().int().positive().describe("New term in months"),
112
+ confirmed: confirmedSchema,
113
+ },
114
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS,
115
+ },
116
+ async ({ positionId, selectedTerm, confirmed }) =>
117
+ safe(async () => {
118
+ const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
119
+ if (gate) return gate;
120
+ const ctx = await getCtx();
121
+ requireNotMainnetForWrites(ctx.config.network);
122
+ const result = await extendAction(ctx, { positionId, selectedTerm });
123
+ return result.success ? ok(result) : err(result.error ?? "Renewal failed.");
124
+ }),
125
+ );
126
+
127
+ server.registerTool(
128
+ "loan_withdraw",
129
+ {
130
+ title: "Withdraw BTC from a position vault",
131
+ description:
132
+ `Withdraw BTC from a position's custody vault to an external BTC address. ` +
133
+ `BTC sends are UNRECOVERABLE — verify the destination address carefully. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
134
+ inputSchema: {
135
+ positionId: positionIdSchema,
136
+ btcAddress: z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
137
+ amountSats: z.number().int().positive().describe("Amount in satoshis (1 BTC = 100,000,000 sats)"),
138
+ networkFeeSats: z.number().int().positive().optional().describe("Optional BTC network fee in sats (default 1000)"),
139
+ confirmed: confirmedSchema,
140
+ },
141
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS,
142
+ },
143
+ async ({ positionId, btcAddress, amountSats, networkFeeSats, confirmed }) =>
144
+ safe(async () => {
145
+ const gate = requireConfirmation(
146
+ confirmed,
147
+ `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress} (UNRECOVERABLE)`,
148
+ );
149
+ if (gate) return gate;
150
+ const ctx = await getCtx();
151
+ requireNotMainnetForWrites(ctx.config.network);
152
+ const result = await withdrawAction(ctx, { positionId, btcAddress, amountSats, networkFeeSats });
153
+ return result.success ? ok(result) : err(result.error ?? "Withdrawal failed.");
154
+ }),
155
+ );
156
+
157
+ server.registerTool(
158
+ "loan_recover_stale_spend",
159
+ {
160
+ title: "Recover a stale BTC reservation via LIT-attested proof",
161
+ description:
162
+ "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery " +
163
+ "attestation. The original UTXO must already be consumed on Bitcoin with ≥6 confirmations. " +
164
+ "`invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a " +
165
+ "PKP self-spend that invalidated the reservation. Permissionless on-chain.",
166
+ inputSchema: {
167
+ positionId: positionIdSchema,
168
+ utxoTxid: z.string().describe("The original authorized UTXO's txid"),
169
+ utxoVout: z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
170
+ invalidatorTxid: z.string().describe("Txid of the BTC transaction that consumed the original UTXO (≥6 confirmations)"),
171
+ minConfirmations: z.number().int().positive().optional().describe("Override minimum confirmations (default 6)"),
172
+ },
173
+ // On-chain write, but permissionless and user-beneficial (clears a stale reservation;
174
+ // does not move funds), so no confirmed gate — but it is NOT read-only.
175
+ annotations: {
176
+ readOnlyHint: false,
177
+ destructiveHint: false,
178
+ idempotentHint: true,
179
+ openWorldHint: true,
180
+ },
181
+ },
182
+ async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) =>
183
+ safe(async () => {
184
+ const ctx = await getCtx();
185
+ requireNotMainnetForWrites(ctx.config.network);
186
+ const result = await ctx.sdk.recoverStaleSpend({
187
+ positionId,
188
+ utxoTxid,
189
+ utxoVout,
190
+ invalidatorTxid,
191
+ ...(minConfirmations !== undefined && { minConfirmations }),
192
+ ...(ctx.config.rpcUrl && { rpcUrl: ctx.config.rpcUrl }),
193
+ });
194
+ return result.success ? ok(result) : err(result.error ?? "Stale spend recovery failed.");
195
+ }),
196
+ );
197
+ }
@@ -0,0 +1,93 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { Ctx } from "../context.js";
4
+ import { ok, err, fromSdkResult, safe } from "./_helpers.js";
5
+
6
+ const positionIdSchema = z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
7
+
8
+ export function registerPositionTools(server: McpServer, getCtx: () => Promise<Ctx>): void {
9
+ server.registerTool(
10
+ "position_status",
11
+ {
12
+ title: "Get a position's full status",
13
+ description: "Return detailed status (debt, term, expiry, vault, borrower) for a single position.",
14
+ inputSchema: {
15
+ id: positionIdSchema,
16
+ },
17
+ },
18
+ async ({ id }) =>
19
+ safe(async () => {
20
+ const ctx = await getCtx();
21
+ const result = await ctx.sdk.getLoanById(id, true);
22
+ if (!result.success) return err(result.error.message);
23
+ if (!result.value) return err(`Position ${id} not found.`);
24
+ return ok(result.value);
25
+ }),
26
+ );
27
+
28
+ server.registerTool(
29
+ "position_list",
30
+ {
31
+ title: "List lending positions",
32
+ description:
33
+ "List positions with optional filters. With no filter, returns currently active positions.",
34
+ inputSchema: {
35
+ borrower: z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
36
+ state: z.string().optional().describe("Filter by state (e.g. ACTIVE, EXPIRED, REPAID, LIQUIDATED)"),
37
+ page: z.number().int().positive().optional().describe("Page number (default 1)"),
38
+ pageSize: z.number().int().positive().max(100).optional().describe("Page size (default 20)"),
39
+ },
40
+ },
41
+ async ({ borrower, state, page, pageSize }) =>
42
+ safe(async () => {
43
+ const ctx = await getCtx();
44
+ const p = page ?? 1;
45
+ const size = pageSize ?? 20;
46
+ let result;
47
+ if (borrower) {
48
+ result = await ctx.sdk.getLoansByBorrower(borrower, { page: p, pageSize: size });
49
+ } else if (state) {
50
+ result = await ctx.sdk.getLoansByState(state, { page: p, pageSize: size });
51
+ } else {
52
+ result = await ctx.sdk.getActiveLoans({ page: p, pageSize: size });
53
+ }
54
+ return fromSdkResult(result);
55
+ }),
56
+ );
57
+
58
+ server.registerTool(
59
+ "position_events",
60
+ {
61
+ title: "Get a position's event history",
62
+ description: "Return mint, payment, withdrawal, renewal, status-update, and liquidation events for a position.",
63
+ inputSchema: {
64
+ id: positionIdSchema,
65
+ },
66
+ },
67
+ async ({ id }) =>
68
+ safe(async () => {
69
+ const ctx = await getCtx();
70
+ const result = await ctx.sdk.getLoanEvents(id);
71
+ return fromSdkResult(result);
72
+ }),
73
+ );
74
+
75
+ server.registerTool(
76
+ "position_pending_withdrawals",
77
+ {
78
+ title: "List a position's pending BTC withdrawal reservations",
79
+ description:
80
+ "Query BTCSpendAuthorizer for authorized-but-unspent BTC withdrawal reservations on a position. " +
81
+ "Each entry has txid/vout (the original UTXO), satoshis, target address, and `utxoKey` (for recovery).",
82
+ inputSchema: {
83
+ id: positionIdSchema,
84
+ },
85
+ },
86
+ async ({ id }) =>
87
+ safe(async () => {
88
+ const ctx = await getCtx();
89
+ const list = await ctx.sdk.getPendingWithdrawals(id);
90
+ return ok(list);
91
+ }),
92
+ );
93
+ }
@@ -0,0 +1,35 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Ctx } from "../context.js";
3
+ import { fromSdkResult, safe } from "./_helpers.js";
4
+
5
+ export function registerProtocolTools(server: McpServer, getCtx: () => Promise<Ctx>): void {
6
+ server.registerTool(
7
+ "protocol_status",
8
+ {
9
+ title: "Get protocol configuration and status",
10
+ description: "Return protocol contract addresses, pause status, and circuit breaker state.",
11
+ inputSchema: {},
12
+ },
13
+ async () =>
14
+ safe(async () => {
15
+ const ctx = await getCtx();
16
+ const result = await ctx.sdk.getProtocolConfig();
17
+ return fromSdkResult(result);
18
+ }),
19
+ );
20
+
21
+ server.registerTool(
22
+ "protocol_terms",
23
+ {
24
+ title: "List available loan terms with fees",
25
+ description: "Return all configured loan terms (in months) with their origination fees and extension fees.",
26
+ inputSchema: {},
27
+ },
28
+ async () =>
29
+ safe(async () => {
30
+ const ctx = await getCtx();
31
+ const result = await ctx.sdk.getTermsWithFees();
32
+ return fromSdkResult(result);
33
+ }),
34
+ );
35
+ }
@@ -0,0 +1,58 @@
1
+ import { address as btcAddress, networks } from "bitcoinjs-lib";
2
+
3
+ export type BtcNetworkName = "mainnet" | "testnet" | "regtest";
4
+
5
+ export function btcNetworkFor(evmNetwork: string, chainId: number): BtcNetworkName {
6
+ if (chainId === 1) return "mainnet";
7
+ const lower = evmNetwork.toLowerCase();
8
+ if (lower === "mainnet" || lower === "ethereum") return "mainnet";
9
+ return "regtest";
10
+ }
11
+
12
+ function networkObj(net: BtcNetworkName) {
13
+ if (net === "mainnet") return networks.bitcoin;
14
+ if (net === "testnet") return networks.testnet;
15
+ return networks.regtest;
16
+ }
17
+
18
+ export interface BtcAddressInfo {
19
+ normalized: string;
20
+ network: BtcNetworkName;
21
+ kind: "p2pkh" | "p2sh" | "p2wpkh" | "p2wsh" | "p2tr" | "unknown";
22
+ }
23
+
24
+ export function validateBtcAddress(addr: string, expected: BtcNetworkName): BtcAddressInfo {
25
+ if (typeof addr !== "string" || addr.length === 0) {
26
+ throw new Error("BTC address is empty");
27
+ }
28
+ const trimmed = addr.trim();
29
+ if (trimmed !== addr) {
30
+ throw new Error("BTC address has leading/trailing whitespace");
31
+ }
32
+ const net = networkObj(expected);
33
+ let kind: BtcAddressInfo["kind"] = "unknown";
34
+ try {
35
+ const decoded = btcAddress.toOutputScript(addr, net);
36
+ const hex = decoded.toString("hex");
37
+ if (/^76a914[0-9a-f]{40}88ac$/.test(hex)) kind = "p2pkh";
38
+ else if (/^a914[0-9a-f]{40}87$/.test(hex)) kind = "p2sh";
39
+ else if (/^0014[0-9a-f]{40}$/.test(hex)) kind = "p2wpkh";
40
+ else if (/^0020[0-9a-f]{64}$/.test(hex)) kind = "p2wsh";
41
+ else if (/^5120[0-9a-f]{64}$/.test(hex)) kind = "p2tr";
42
+ } catch (e) {
43
+ const msg = (e as Error).message;
44
+ const others: BtcNetworkName[] = (["mainnet", "testnet", "regtest"] as const).filter((n) => n !== expected);
45
+ for (const n of others) {
46
+ try {
47
+ btcAddress.toOutputScript(addr, networkObj(n));
48
+ throw new Error(
49
+ `BTC address '${addr}' is valid on ${n} but you are operating on ${expected}. Sending across networks would lose the funds.`,
50
+ );
51
+ } catch (innerErr) {
52
+ if ((innerErr as Error).message.startsWith("BTC address")) throw innerErr;
53
+ }
54
+ }
55
+ throw new Error(`Invalid BTC address '${addr}': ${msg}`);
56
+ }
57
+ return { normalized: addr, network: expected, kind };
58
+ }
@@ -0,0 +1,65 @@
1
+ import { ethers, TypedDataField } from "ethers";
2
+ import type { DHSigner } from "../signer/types.js";
3
+
4
+ export interface DhServerLoginMessage {
5
+ address: string;
6
+ issuedAt: number;
7
+ nonce: string;
8
+ /** Audit M-8: service endpoint URL this login targets (replay-binds to one service). */
9
+ audience?: string;
10
+ }
11
+
12
+ export interface DhServerLoginPayload {
13
+ chainId: number;
14
+ message: DhServerLoginMessage;
15
+ signature: string;
16
+ }
17
+
18
+ // EIP-712 primary type the wallet displays. Renamed DhServerLogin -> DiamondHands;
19
+ // the lit-ops-server dual-accepts the legacy name during the migration window.
20
+ const LOGIN_TYPES: Record<string, TypedDataField[]> = {
21
+ DiamondHands: [
22
+ { name: "address", type: "address" },
23
+ { name: "issuedAt", type: "uint256" },
24
+ { name: "nonce", type: "bytes32" },
25
+ ],
26
+ };
27
+
28
+ /** Audit M-8: login types with the audience binding. */
29
+ const LOGIN_TYPES_WITH_AUDIENCE: Record<string, TypedDataField[]> = {
30
+ DiamondHands: [
31
+ { name: "address", type: "address" },
32
+ { name: "issuedAt", type: "uint256" },
33
+ { name: "nonce", type: "bytes32" },
34
+ { name: "audience", type: "string" },
35
+ ],
36
+ };
37
+
38
+ function loginDomain(chainId: number) {
39
+ return { name: "Diamond Hands lit-ops-server", version: "1", chainId };
40
+ }
41
+
42
+ function randomNonceHex(): string {
43
+ return "0x" + Buffer.from(ethers.randomBytes(32)).toString("hex");
44
+ }
45
+
46
+ export async function buildSignedDhServerLoginPayload(
47
+ dhSigner: DHSigner,
48
+ chainId: number,
49
+ audience?: string,
50
+ ): Promise<DhServerLoginPayload> {
51
+ const signer = dhSigner.getEthersSigner();
52
+ const address = await signer.getAddress();
53
+ const message: DhServerLoginMessage = {
54
+ address,
55
+ issuedAt: Math.floor(Date.now() / 1000),
56
+ nonce: randomNonceHex(),
57
+ ...(audience ? { audience } : {}),
58
+ };
59
+ const signature = await signer.signTypedData(
60
+ loginDomain(chainId),
61
+ audience ? LOGIN_TYPES_WITH_AUDIENCE : LOGIN_TYPES,
62
+ message,
63
+ );
64
+ return { chainId, message, signature };
65
+ }
@@ -0,0 +1,24 @@
1
+ import type { SDKError } from "@gvnrdao/dh-sdk";
2
+
3
+ export class ServiceUnavailableError extends Error {
4
+ constructor() {
5
+ super("Service unavailable");
6
+ this.name = "ServiceUnavailableError";
7
+ }
8
+ }
9
+
10
+ export function formatSDKError(err: SDKError): string {
11
+ const parts = [`[${err.category ?? "ERROR"}] ${err.message}`];
12
+ if (err.context?.["revertReason"]) {
13
+ parts.push(` Revert: ${err.context["revertReason"]}`);
14
+ }
15
+ if (err.originalError?.message && err.originalError.message !== err.message) {
16
+ parts.push(` Cause: ${err.originalError.message}`);
17
+ }
18
+ return parts.join("\n");
19
+ }
20
+
21
+ /** Throw an Error instead of exiting the process (no TTY in MCP). */
22
+ export function fatal(message: string): never {
23
+ throw new Error(message);
24
+ }