-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathtools.ts
More file actions
1339 lines (1272 loc) · 48.2 KB
/
Copy pathtools.ts
File metadata and controls
1339 lines (1272 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { getSupportedNetworks, getRpcUrl } from "./chains.js";
import * as services from "./services/index.js";
import { type Address, type Hex, type Hash } from 'viem';
import { normalize } from 'viem/ens';
/**
* Validates an Ethereum address format (0x + 40 hex chars).
* Throws if invalid. Allows ENS names (containing '.') to pass through.
*/
function validateAddressOrEns(value: string, label = 'Address'): void {
if (value.includes('.')) return;
if (!/^0x[a-fA-F0-9]{40}$/.test(value)) {
throw new Error(`${label} must be a valid Ethereum address (0x + 40 hex chars) or ENS name`);
}
}
/**
* Register all EVM-related tools with the MCP server
*
* SECURITY: Either EVM_PRIVATE_KEY or EVM_MNEMONIC environment variable must be set for write operations.
* Private keys and mnemonics are never passed as tool arguments for security reasons.
* Tools will use the configured wallet for all transactions.
*
* Configuration options:
* - EVM_PRIVATE_KEY: Hex private key (with or without 0x prefix)
* - EVM_MNEMONIC: BIP-39 mnemonic phrase (12 or 24 words)
* - EVM_ACCOUNT_INDEX: Optional account index for HD wallet derivation (default: 0)
*
* All tools that accept addresses also support ENS names (e.g., 'vitalik.eth').
* ENS names are automatically resolved to addresses using the Ethereum Name Service.
*
* @param server The MCP server instance
*/
export function registerEVMTools(server: McpServer) {
// Helpers are now imported from services/wallet.ts
const { getConfiguredPrivateKey, getWalletAddressFromKey, getConfiguredWallet } = services;
// ============================================================================
// WALLET INFORMATION TOOLS (Read-only)
// ============================================================================
server.registerTool(
"get_wallet_address",
{
description: "Get the address of the configured wallet. Use this to verify which wallet is active.",
inputSchema: {},
annotations: {
title: "Get Wallet Address",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false
}
},
async () => {
try {
const address = getWalletAddressFromKey();
return {
content: [{
type: "text",
text: JSON.stringify({
address,
message: "This is the wallet that will be used for all transactions"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// NETWORK INFORMATION TOOLS (Read-only)
// ============================================================================
server.registerTool(
"get_chain_info",
{
description: "Get information about an EVM network: chain ID, current block number, and RPC endpoint",
inputSchema: {
network: z.string().optional().describe("Network name (e.g., 'ethereum', 'optimism', 'arbitrum', 'base') or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Chain Info",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ network = "ethereum" }) => {
try {
const chainId = await services.getChainId(network);
const blockNumber = await services.getBlockNumber(network);
const rpcUrl = getRpcUrl(network);
return {
content: [{
type: "text",
text: JSON.stringify({ network, chainId, blockNumber: blockNumber.toString(), rpcUrl }, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching chain info: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_supported_networks",
{
description: "Get a list of all supported EVM networks",
inputSchema: {},
annotations: {
title: "Get Supported Networks",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false
}
},
async () => {
try {
const networks = getSupportedNetworks();
return {
content: [{ type: "text", text: JSON.stringify({ supportedNetworks: networks }, null, 2) }]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_gas_price",
{
description: "Get current gas prices (base fee, standard, and fast) for a network",
inputSchema: {
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Gas Prices",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true
}
},
async ({ network = "ethereum" }) => {
try {
const client = await services.getPublicClient(network);
const [baseFee, priorityFee] = await Promise.all([
client.getGasPrice(),
client.estimateMaxPriorityFeePerGas()
]);
return {
content: [{
type: "text",
text: JSON.stringify({
network,
baseFeePerGas: baseFee.toString(),
priorityFeePerGas: priorityFee?.toString() || "N/A",
currency: "wei"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching gas prices: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// ENS TOOLS (Read-only)
// ============================================================================
server.registerTool(
"resolve_ens_name",
{
description: "Resolve an ENS name to an Ethereum address",
inputSchema: {
ensName: z.string().describe("ENS name to resolve (e.g., 'vitalik.eth')"),
network: z.string().optional().describe("Network name or chain ID. ENS resolution works best on Ethereum mainnet. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Resolve ENS Name",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ ensName, network = "ethereum" }) => {
try {
if (!ensName.includes('.')) {
return {
content: [{ type: "text", text: `Error: "${ensName}" is not a valid ENS name. ENS names must contain a dot (e.g., 'name.eth').` }],
isError: true
};
}
const normalizedEns = normalize(ensName);
const address = await services.resolveAddress(ensName, network);
return {
content: [{
type: "text",
text: JSON.stringify({
ensName,
normalizedName: normalizedEns,
resolvedAddress: address,
network
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error resolving ENS name: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"lookup_ens_address",
{
description: "Lookup the ENS name for an Ethereum address (reverse resolution)",
inputSchema: {
address: z.string().describe("Ethereum address to lookup"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Lookup ENS Address",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ address, network = "ethereum" }) => {
try {
const client = await services.getPublicClient(network);
const ensName = await client.getEnsName({
address: address as Address
});
return {
content: [{
type: "text",
text: JSON.stringify({
address,
ensName: ensName || "No ENS name found",
network
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error looking up ENS name: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// BLOCK TOOLS (Read-only)
// ============================================================================
server.registerTool(
"get_block",
{
description: "Get block details by block number or hash",
inputSchema: {
blockIdentifier: z.string().describe("Block number (as string) or block hash"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Block",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ blockIdentifier, network = "ethereum" }) => {
try {
let block;
if (blockIdentifier.startsWith("0x") && blockIdentifier.length === 66) {
// It's a hash
block = await services.getBlockByHash(blockIdentifier as Hash, network);
} else {
// It's a number
block = await services.getBlockByNumber(parseInt(blockIdentifier), network);
}
return { content: [{ type: "text", text: services.helpers.formatJson(block) }] };
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching block: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_latest_block",
{
description: "Get the latest block from the network",
inputSchema: {
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Latest Block",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true
}
},
async ({ network = "ethereum" }) => {
try {
const block = await services.getLatestBlock(network);
return { content: [{ type: "text", text: services.helpers.formatJson(block) }] };
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching latest block: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// BALANCE TOOLS (Read-only)
// ============================================================================
server.registerTool(
"get_balance",
{
description: "Get the native token balance (ETH, MATIC, etc.) for an address",
inputSchema: {
address: z.string().describe("The wallet address or ENS name"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Native Token Balance",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ address, network = "ethereum" }) => {
try {
const balance = await services.getETHBalance(address as Address, network);
return {
content: [{
type: "text",
text: JSON.stringify({
network,
address,
balance: { wei: balance.wei.toString(), ether: balance.ether }
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching balance: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_token_balance",
{
description: "Get the ERC20 token balance for an address",
inputSchema: {
address: z.string().describe("The wallet address or ENS name"),
tokenAddress: z.string().describe("The ERC20 token contract address"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get ERC20 Token Balance",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ address, tokenAddress, network = "ethereum" }) => {
try {
const balance = await services.getERC20Balance(tokenAddress as Address, address as Address, network);
return {
content: [{
type: "text",
text: JSON.stringify({
network,
tokenAddress,
address,
balance: {
raw: balance.raw.toString(),
formatted: balance.formatted,
symbol: balance.token.symbol,
decimals: balance.token.decimals
}
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching token balance: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_allowance",
{
description: "Check the allowance granted to a spender for a token. This tells you how much of a token an address can spend on your behalf.",
inputSchema: {
tokenAddress: z.string().describe("The ERC20 token contract address"),
spenderAddress: z.string().describe("The address allowed to spend the token (usually a contract address)"),
ownerAddress: z.string().optional().describe("The owner address (defaults to the configured wallet)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Token Allowance",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ tokenAddress, spenderAddress, ownerAddress, network = "ethereum" }) => {
try {
const owner = ownerAddress ? (ownerAddress as Address) : getConfiguredWallet().address;
const client = await services.getPublicClient(network);
const allowance = await client.readContract({
address: tokenAddress as Address,
abi: [
{
name: 'allowance',
type: 'function',
inputs: [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' }
],
outputs: [{ name: '', type: 'uint256' }],
stateMutability: 'view'
}
],
functionName: 'allowance',
args: [owner, spenderAddress as Address]
});
return {
content: [{
type: "text",
text: JSON.stringify({
network,
tokenAddress,
owner,
spenderAddress,
allowance: allowance.toString(),
message: allowance === 0n ? "No allowance set" : "Allowance is set"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching allowance: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// TRANSACTION TOOLS (Read-only)
// ============================================================================
server.registerTool(
"get_transaction",
{
description: "Get transaction details by transaction hash",
inputSchema: {
txHash: z.string().describe("Transaction hash (0x...)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Transaction",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ txHash, network = "ethereum" }) => {
try {
const tx = await services.getTransaction(txHash as Hash, network);
return { content: [{ type: "text", text: services.helpers.formatJson(tx) }] };
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching transaction: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"get_transaction_receipt",
{
description: "Get transaction receipt (confirmation status, gas used, logs). Use this to check if a transaction has been confirmed.",
inputSchema: {
txHash: z.string().describe("Transaction hash (0x...)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Get Transaction Receipt",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ txHash, network = "ethereum" }) => {
try {
const client = await services.getPublicClient(network);
const receipt = await client.getTransactionReceipt({
hash: txHash as Hash
});
return { content: [{ type: "text", text: services.helpers.formatJson(receipt) }] };
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching transaction receipt: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"wait_for_transaction",
{
description: "Wait for a transaction to be confirmed (mined). Polls the network until confirmation.",
inputSchema: {
txHash: z.string().describe("Transaction hash (0x...)"),
confirmations: z.number().optional().describe("Number of block confirmations required. Defaults to 1."),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Wait For Transaction",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true
}
},
async ({ txHash, confirmations = 1, network = "ethereum" }) => {
try {
const client = await services.getPublicClient(network);
const receipt = await client.waitForTransactionReceipt({
hash: txHash as Hash,
confirmations
});
return {
content: [{
type: "text",
text: JSON.stringify({
network,
txHash,
status: receipt.status === 'success' ? 'confirmed' : 'failed',
blockNumber: receipt.blockNumber.toString(),
gasUsed: receipt.gasUsed.toString(),
confirmations
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error waiting for transaction: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
// ============================================================================
// SMART CONTRACT TOOLS
// ============================================================================
server.registerTool(
"get_contract_abi",
{
description: "Fetch a contract's full ABI from Etherscan/block explorers. Use this to understand verified contracts before interacting. Requires ETHERSCAN_API_KEY. Supports 30+ EVM networks. Works best with verified contracts on block explorers.",
inputSchema: {
contractAddress: z.string().describe("The contract address (0x...)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to ethereum. Supported: ethereum, polygon, arbitrum, optimism, base, avalanche, gnosis, fantom, bsc, celo, scroll, linea, zksync, manta, blast, and testnets (sepolia, mumbai, arbitrum-sepolia, optimism-sepolia, base-sepolia, avalanche-fuji)")
},
annotations: {
title: "Get Contract ABI",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ contractAddress, network = "ethereum" }) => {
try {
const abi = await services.fetchContractABI(contractAddress as Address, network);
const parsed = services.parseABI(abi);
const readableFunctions = services.getReadableFunctions(parsed);
return {
content: [{
type: "text",
text: JSON.stringify({
contractAddress,
network,
abiFormat: "json",
readableFunctions,
totalFunctions: parsed.filter(i => i.type === 'function').length,
abi: parsed
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error fetching ABI: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"read_contract",
{
description: "Call read-only functions on a smart contract. Automatically fetches ABI from block explorer if not provided (requires ETHERSCAN_API_KEY). Falls back to common functions if contract is not verified. Use this to query contract state and data.",
inputSchema: {
contractAddress: z.string().describe("The contract address"),
functionName: z.string().describe("Function name (e.g., 'name', 'symbol', 'balanceOf', 'totalSupply', 'owner')"),
args: z.array(z.string()).optional().describe("Function arguments as strings (e.g., ['0xAddress'] for balanceOf)"),
abiJson: z.string().optional().describe("Full contract ABI as JSON string (optional - will auto-fetch verified contract ABI if not provided)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Read Smart Contract",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ contractAddress, functionName, args = [], abiJson, network = "ethereum" }) => {
try {
validateAddressOrEns(contractAddress, 'Contract address');
const client = await services.getPublicClient(network);
let abi: any[] | undefined;
let functionAbi: any;
// If ABI is provided, use it
if (abiJson) {
try {
abi = services.parseABI(abiJson);
functionAbi = services.getFunctionFromABI(abi, functionName);
} catch (error) {
return {
content: [{
type: "text",
text: `Error parsing provided ABI: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
} else {
// Try to auto-fetch ABI from block explorer
try {
const fetchedAbi = await services.fetchContractABI(contractAddress as Address, network);
abi = services.parseABI(fetchedAbi);
functionAbi = services.getFunctionFromABI(abi, functionName);
} catch (fetchError) {
// Fall back to common function signatures
const commonFunctions: { [key: string]: any } = {
'name': { inputs: [], outputs: [{ type: 'string' }] },
'symbol': { inputs: [], outputs: [{ type: 'string' }] },
'decimals': { inputs: [], outputs: [{ type: 'uint8' }] },
'totalSupply': { inputs: [], outputs: [{ type: 'uint256' }] },
'balanceOf': { inputs: [{ type: 'address' }], outputs: [{ type: 'uint256' }] },
'allowance': { inputs: [{ type: 'address' }, { type: 'address' }], outputs: [{ type: 'uint256' }] },
};
if (!commonFunctions[functionName]) {
return {
content: [{
type: "text",
text: `Error: Could not auto-fetch ABI (${fetchError instanceof Error ? fetchError.message : String(fetchError)}). Function '${functionName}' not in common signatures. Use get_contract_abi to fetch and provide the full ABI, or provide abiJson parameter.`
}],
isError: true
};
}
functionAbi = {
name: functionName,
type: 'function',
inputs: commonFunctions[functionName].inputs,
outputs: commonFunctions[functionName].outputs,
stateMutability: 'view'
};
}
}
const result = await client.readContract({
address: contractAddress as Address,
abi: [functionAbi],
functionName: functionName,
args: args as any
});
return {
content: [{
type: "text",
text: JSON.stringify({
contractAddress,
function: functionName,
args: args.length > 0 ? args : undefined,
result: result?.toString(),
abiSource: abiJson ? 'provided' : 'auto-fetched or built-in'
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error reading contract: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"write_contract",
{
description: "Execute state-changing functions on a smart contract. Automatically fetches ABI from block explorer if not provided (requires ETHERSCAN_API_KEY). Use this to call any write function on verified contracts. Requires wallet to be configured (via private key or mnemonic).",
inputSchema: {
contractAddress: z.string().describe("The contract address"),
functionName: z.string().describe("Function name to call (e.g., 'mint', 'swap', 'stake', 'approve')"),
args: z.array(z.string()).optional().describe("Function arguments as strings (e.g., ['0xAddress', '1000000'])"),
value: z.string().optional().describe("ETH value to send with transaction in ether (e.g., '0.1' for payable functions)"),
abiJson: z.string().optional().describe("Full contract ABI as JSON string (optional - will auto-fetch verified contract ABI if not provided)"),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Write to Smart Contract",
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true
}
},
async ({ contractAddress, functionName, args = [], value, abiJson, network = "ethereum" }) => {
try {
validateAddressOrEns(contractAddress, 'Contract address');
const privateKey = getConfiguredPrivateKey();
const senderAddress = getWalletAddressFromKey();
const client = await services.getPublicClient(network);
let abi: any[] | undefined;
let functionAbi: any;
// If ABI is provided, use it
if (abiJson) {
try {
abi = services.parseABI(abiJson);
functionAbi = services.getFunctionFromABI(abi, functionName);
} catch (error) {
return {
content: [{
type: "text",
text: `Error parsing provided ABI: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
} else {
// Try to auto-fetch ABI from block explorer
try {
const fetchedAbi = await services.fetchContractABI(contractAddress as Address, network);
abi = services.parseABI(fetchedAbi);
functionAbi = services.getFunctionFromABI(abi, functionName);
} catch (fetchError) {
return {
content: [{
type: "text",
text: `Error: Could not auto-fetch ABI (${fetchError instanceof Error ? fetchError.message : String(fetchError)}). Please provide the contract ABI using the abiJson parameter, or use get_contract_abi to fetch it first.`
}],
isError: true
};
}
}
// Validate that this is not a view/pure function
if (functionAbi.stateMutability === 'view' || functionAbi.stateMutability === 'pure') {
return {
content: [{
type: "text",
text: `Error: Function '${functionName}' is a ${functionAbi.stateMutability} function and cannot modify state. Use read_contract instead.`
}],
isError: true
};
}
// Prepare write parameters
const writeParams: any = {
address: contractAddress as Address,
abi: [functionAbi],
functionName: functionName,
args: args as any
};
// Add value if provided (for payable functions)
if (value) {
const { parseEther } = await import('viem');
writeParams.value = parseEther(value);
}
// Execute the write operation
const txHash = await services.writeContract(privateKey, writeParams, network);
return {
content: [{
type: "text",
text: JSON.stringify({
network,
contractAddress,
function: functionName,
args: args.length > 0 ? args : undefined,
value: value || undefined,
from: senderAddress,
txHash,
abiSource: abiJson ? 'provided' : 'auto-fetched',
message: "Transaction sent. Use get_transaction_receipt or wait_for_transaction to check confirmation."
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error writing to contract: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}
);
server.registerTool(
"multicall",
{
description: "Batch multiple contract read calls into a single RPC request. Significantly reduces latency and RPC usage when querying multiple functions. Uses the Multicall3 contract deployed on all major networks. Perfect for portfolio analysis, price aggregation, and querying multiple contract states efficiently.",
inputSchema: {
calls: z.array(z.object({
contractAddress: z.string().describe("The contract address"),
functionName: z.string().describe("Function name to call"),
args: z.array(z.string()).optional().describe("Function arguments as strings"),
abiJson: z.string().optional().describe("Contract ABI as JSON string (optional - will auto-fetch if not provided)")
})).describe("Array of contract calls to batch together"),
allowFailure: z.boolean().optional().describe("If true, returns partial results even if some calls fail. Defaults to true."),
network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
},
annotations: {
title: "Multicall (Batch Read)",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ calls, allowFailure = true, network = "ethereum" }) => {
try {
// Build contracts array with ABIs
const contractsWithAbis = await Promise.all(
calls.map(async (call) => {
let abi: any[];
let functionAbi: any;
// If ABI is provided, use it
if (call.abiJson) {
try {
abi = services.parseABI(call.abiJson);
functionAbi = services.getFunctionFromABI(abi, call.functionName);
} catch (error) {
throw new Error(`Error parsing ABI for ${call.contractAddress}: ${error instanceof Error ? error.message : String(error)}`);
}
} else {
// Try to auto-fetch ABI
try {
const fetchedAbi = await services.fetchContractABI(call.contractAddress as Address, network);
abi = services.parseABI(fetchedAbi);
functionAbi = services.getFunctionFromABI(abi, call.functionName);
} catch (fetchError) {
// Fall back to common function signatures
const commonFunctions: { [key: string]: any } = {
'name': { inputs: [], outputs: [{ type: 'string' }], stateMutability: 'view' },
'symbol': { inputs: [], outputs: [{ type: 'string' }], stateMutability: 'view' },
'decimals': { inputs: [], outputs: [{ type: 'uint8' }], stateMutability: 'view' },
'totalSupply': { inputs: [], outputs: [{ type: 'uint256' }], stateMutability: 'view' },
'balanceOf': { inputs: [{ type: 'address' }], outputs: [{ type: 'uint256' }], stateMutability: 'view' },
'allowance': { inputs: [{ type: 'address' }, { type: 'address' }], outputs: [{ type: 'uint256' }], stateMutability: 'view' },
};
if (!commonFunctions[call.functionName]) {
throw new Error(`Could not auto-fetch ABI for ${call.contractAddress}. Function '${call.functionName}' not in common signatures. Please provide abiJson parameter.`);
}
functionAbi = {
name: call.functionName,
type: 'function',
inputs: commonFunctions[call.functionName].inputs,
outputs: commonFunctions[call.functionName].outputs,
stateMutability: 'view'
};
}
}
return {
address: call.contractAddress as Address,
abi: [functionAbi],
functionName: call.functionName,
args: call.args || []
};
})
);
// Execute multicall
const results = await services.multicall(contractsWithAbis, allowFailure, network);
// Format results
const formattedResults = results.map((result: any, index: number) => {
const call = calls[index];
if (result.status === 'success') {
return {
contractAddress: call.contractAddress,
functionName: call.functionName,
args: call.args,
result: result.result?.toString(),
status: 'success'
};
} else {
return {
contractAddress: call.contractAddress,
functionName: call.functionName,
args: call.args,
error: result.error?.message || 'Unknown error',
status: 'failure'
};
}
});
return {
content: [{
type: "text",
text: JSON.stringify({
network,
totalCalls: calls.length,
successfulCalls: formattedResults.filter((r: any) => r.status === 'success').length,
failedCalls: formattedResults.filter((r: any) => r.status === 'failure').length,
results: formattedResults
}, null, 2)
}]
};
} catch (error) {
return {
content: [{ type: "text", text: `Error executing multicall: ${error instanceof Error ? error.message : String(error)}` }],
isError: true
};
}
}