web3-tools-mcp 1.3.0 → 1.3.2

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/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
6
6
  import { initializeClientManager } from "./client.js";
7
7
  import { registerAllTools } from "./tools/index.js";
8
8
  import { parseCommandLineArgs } from "./utils.js";
9
+ import { startWalletServer } from "./wallet-server.js";
9
10
 
10
11
  // Parse configuration
11
12
  const config = parseCommandLineArgs();
@@ -83,11 +84,18 @@ const server = new McpServer({
83
84
  // Register all tools
84
85
  registerAllTools(server);
85
86
 
87
+ // Start wallet server in background
88
+ startWalletServer().catch((error) => {
89
+ console.error("[MCP] Wallet server failed to start:", error.message);
90
+ console.error("[MCP] Transaction signing features will not be available");
91
+ });
92
+
86
93
  // Start server
87
94
  async function main() {
88
95
  const transport = new StdioServerTransport();
89
96
  await server.connect(transport);
90
97
  console.error("Web3 Tools MCP Server running on stdio");
98
+ console.error("Wallet interface available at http://localhost:3456");
91
99
  }
92
100
 
93
101
  main().catch((error) => {
@@ -0,0 +1,267 @@
1
+ import { type AbiFunction, type Address, isAddress, parseAbiItem, encodeFunctionData, decodeFunctionResult } from "viem";
2
+ import { z } from "zod";
3
+ import type { ChainName } from "../types.js";
4
+ import { getClientManager, SUPPORTED_CHAINS } from "../client.js";
5
+ import { convertArgumentsToTypes, createTool, formatResponse } from "../utils.js";
6
+
7
+ export default {
8
+ simulate_contract: createTool(
9
+ "Simulate Contract Call",
10
+ "Simulate a contract call (including state-changing functions) without broadcasting. Returns simulation result and estimated gas.",
11
+ z.object({
12
+ chain: z
13
+ .enum(SUPPORTED_CHAINS)
14
+ .describe("Blockchain network to simulate on"),
15
+ contractAddress: z
16
+ .string()
17
+ .describe("Contract address to call"),
18
+ functionAbi: z
19
+ .string()
20
+ .describe(
21
+ 'Function ABI signature (e.g., "function transfer(address to, uint256 amount)"). Can be any function type.'
22
+ ),
23
+ args: z
24
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
25
+ .optional()
26
+ .describe("Function arguments in order matching the ABI signature"),
27
+ from: z
28
+ .string()
29
+ .optional()
30
+ .describe("Sender address (defaults to zero address)"),
31
+ value: z
32
+ .string()
33
+ .optional()
34
+ .describe("ETH value to send with the transaction (in wei as string)"),
35
+ blockNumber: z
36
+ .string()
37
+ .optional()
38
+ .describe("Block number for simulation (defaults to latest)"),
39
+ }),
40
+ async (args) => {
41
+ if (!isAddress(args.contractAddress)) {
42
+ throw new Error(`Invalid contract address: ${args.contractAddress}`);
43
+ }
44
+
45
+ if (args.from && !isAddress(args.from)) {
46
+ throw new Error(`Invalid from address: ${args.from}`);
47
+ }
48
+
49
+ const clientManager = getClientManager();
50
+ const client = clientManager.getClient(args.chain as ChainName);
51
+
52
+ try {
53
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction;
54
+ const convertedArgs = convertArgumentsToTypes(args.args || [], abiItem.inputs);
55
+
56
+ const blockTag = args.blockNumber ? BigInt(args.blockNumber) : undefined;
57
+
58
+ // Simulate the call
59
+ const result = await client.call({
60
+ to: args.contractAddress as Address,
61
+ data: encodeFunctionData({
62
+ abi: [abiItem],
63
+ functionName: abiItem.name,
64
+ args: convertedArgs,
65
+ }),
66
+ account: args.from ? (args.from as Address) : undefined,
67
+ value: args.value ? BigInt(args.value) : undefined,
68
+ blockNumber: blockTag,
69
+ });
70
+
71
+ // Also estimate gas
72
+ const gasEstimate = await client.estimateGas({
73
+ to: args.contractAddress as Address,
74
+ data: encodeFunctionData({
75
+ abi: [abiItem],
76
+ functionName: abiItem.name,
77
+ args: convertedArgs,
78
+ }),
79
+ account: args.from ? (args.from as Address) : undefined,
80
+ value: args.value ? BigInt(args.value) : undefined,
81
+ blockNumber: blockTag,
82
+ });
83
+
84
+ // Decode the result if the function has outputs
85
+ let decodedResult: unknown = result.data;
86
+ if (abiItem.outputs && abiItem.outputs.length > 0 && result.data) {
87
+ decodedResult = decodeFunctionResult({
88
+ abi: [abiItem],
89
+ functionName: abiItem.name,
90
+ data: result.data,
91
+ });
92
+ }
93
+
94
+ return formatResponse({
95
+ success: true,
96
+ chain: args.chain,
97
+ contractAddress: args.contractAddress,
98
+ functionName: abiItem.name,
99
+ result: decodedResult,
100
+ rawData: result.data,
101
+ gasEstimate: gasEstimate.toString(),
102
+ blockNumber: args.blockNumber || "latest",
103
+ });
104
+ } catch (error) {
105
+ // Check if it's a revert error
106
+ const errorMessage = error instanceof Error ? error.message : String(error);
107
+
108
+ return formatResponse({
109
+ success: false,
110
+ chain: args.chain,
111
+ contractAddress: args.contractAddress,
112
+ error: errorMessage,
113
+ reverted: errorMessage.includes("revert") || errorMessage.includes("execution reverted"),
114
+ });
115
+ }
116
+ }
117
+ ),
118
+
119
+ estimate_gas: createTool(
120
+ "Estimate Gas",
121
+ "Estimate gas required for a transaction. Supports contract calls, transfers, and deployments.",
122
+ z.object({
123
+ chain: z
124
+ .enum(SUPPORTED_CHAINS)
125
+ .describe("Blockchain network"),
126
+ to: z
127
+ .string()
128
+ .optional()
129
+ .describe("Recipient address (omit for contract deployment)"),
130
+ from: z
131
+ .string()
132
+ .optional()
133
+ .describe("Sender address (optional)"),
134
+ value: z
135
+ .string()
136
+ .optional()
137
+ .describe("ETH value to send (in wei as string)"),
138
+ data: z
139
+ .string()
140
+ .optional()
141
+ .describe("Transaction data (hex string for contract calls or deployment bytecode)"),
142
+ functionAbi: z
143
+ .string()
144
+ .optional()
145
+ .describe("Optional: Function ABI signature to encode call data automatically"),
146
+ args: z
147
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
148
+ .optional()
149
+ .describe("Optional: Function arguments (only used with functionAbi)"),
150
+ }),
151
+ async (args) => {
152
+ if (args.to && !isAddress(args.to)) {
153
+ throw new Error(`Invalid to address: ${args.to}`);
154
+ }
155
+
156
+ if (args.from && !isAddress(args.from)) {
157
+ throw new Error(`Invalid from address: ${args.from}`);
158
+ }
159
+
160
+ const clientManager = getClientManager();
161
+ const client = clientManager.getClient(args.chain as ChainName);
162
+
163
+ try {
164
+ let callData = args.data;
165
+
166
+ // If functionAbi is provided, encode the call data
167
+ if (args.functionAbi) {
168
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction;
169
+ const convertedArgs = convertArgumentsToTypes(args.args || [], abiItem.inputs);
170
+ callData = encodeFunctionData({
171
+ abi: [abiItem],
172
+ functionName: abiItem.name,
173
+ args: convertedArgs,
174
+ });
175
+ }
176
+
177
+ const gasEstimate = await client.estimateGas({
178
+ to: args.to ? (args.to as Address) : undefined,
179
+ account: args.from ? (args.from as Address) : undefined,
180
+ value: args.value ? BigInt(args.value) : undefined,
181
+ data: callData as `0x${string}` | undefined,
182
+ });
183
+
184
+ return formatResponse({
185
+ success: true,
186
+ chain: args.chain,
187
+ gasEstimate: gasEstimate.toString(),
188
+ to: args.to,
189
+ from: args.from,
190
+ value: args.value,
191
+ });
192
+ } catch (error) {
193
+ throw new Error(`Gas estimation failed: ${error}`);
194
+ }
195
+ }
196
+ ),
197
+
198
+ get_gas_price: createTool(
199
+ "Get Gas Price",
200
+ "Get current gas prices for a chain. Returns both legacy gasPrice and EIP-1559 fees (maxFeePerGas, maxPriorityFeePerGas).",
201
+ z.object({
202
+ chain: z
203
+ .enum(SUPPORTED_CHAINS)
204
+ .describe("Blockchain network"),
205
+ formatted: z
206
+ .boolean()
207
+ .optional()
208
+ .default(true)
209
+ .describe("Return prices in Gwei (default: true). If false, returns wei."),
210
+ }),
211
+ async (args) => {
212
+ const clientManager = getClientManager();
213
+ const client = clientManager.getClient(args.chain as ChainName);
214
+
215
+ try {
216
+ // Get both legacy and EIP-1559 gas prices
217
+ const [gasPrice, feeData] = await Promise.all([
218
+ client.getGasPrice(),
219
+ client.estimateFeesPerGas().catch(() => null), // Some chains don't support EIP-1559
220
+ ]);
221
+
222
+ const formatPrice = (wei: bigint): string => {
223
+ if (args.formatted) {
224
+ // Convert to Gwei (1 Gwei = 1e9 wei)
225
+ const gwei = Number(wei) / 1e9;
226
+ return `${gwei.toFixed(2)} Gwei`;
227
+ }
228
+ return wei.toString();
229
+ };
230
+
231
+ const response: any = {
232
+ chain: args.chain,
233
+ timestamp: new Date().toISOString(),
234
+ legacy: {
235
+ gasPrice: args.formatted ? formatPrice(gasPrice) : gasPrice.toString(),
236
+ gasPriceWei: gasPrice.toString(),
237
+ },
238
+ };
239
+
240
+ // Add EIP-1559 data if available
241
+ if (feeData) {
242
+ response.eip1559 = {
243
+ maxFeePerGas: args.formatted
244
+ ? formatPrice(feeData.maxFeePerGas)
245
+ : feeData.maxFeePerGas.toString(),
246
+ maxPriorityFeePerGas: args.formatted
247
+ ? formatPrice(feeData.maxPriorityFeePerGas)
248
+ : feeData.maxPriorityFeePerGas.toString(),
249
+ maxFeePerGasWei: feeData.maxFeePerGas.toString(),
250
+ maxPriorityFeePerGasWei: feeData.maxPriorityFeePerGas.toString(),
251
+ };
252
+
253
+ // Calculate estimated total cost for a standard 21000 gas transaction
254
+ const standardGasLimit = 21000n;
255
+ const estimatedCost = feeData.maxFeePerGas * standardGasLimit;
256
+ response.eip1559.estimatedCostFor21kGas = args.formatted
257
+ ? `${(Number(estimatedCost) / 1e18).toFixed(6)} ETH`
258
+ : estimatedCost.toString();
259
+ }
260
+
261
+ return formatResponse(response);
262
+ } catch (error) {
263
+ throw new Error(`Failed to get gas price: ${error}`);
264
+ }
265
+ }
266
+ ),
267
+ };
@@ -6,8 +6,10 @@ import balanceTools from './balance.js'
6
6
  import contractTools from './contract.js'
7
7
  import contractInfoTools from './contract-info.js'
8
8
  import ensTools from './ens.js'
9
+ import gasTools from './gas.js'
9
10
  import logTools from './logs.js'
10
11
  import signatureTools from './signatures.js'
12
+ import transactionTools from './transactions.js'
11
13
 
12
14
  const allToolDefinitions = {
13
15
  ...signatureTools,
@@ -16,7 +18,9 @@ const allToolDefinitions = {
16
18
  ...balanceTools,
17
19
  ...logTools,
18
20
  ...advancedTools,
19
- ...ensTools
21
+ ...ensTools,
22
+ ...gasTools,
23
+ ...transactionTools
20
24
  } as const
21
25
 
22
26
  // Register all tools with the MCP server
@@ -6,7 +6,8 @@ import {
6
6
  parseAbiItem,
7
7
  toBytes,
8
8
  toEventSignature,
9
- toFunctionSignature
9
+ toFunctionSignature,
10
+ encodeFunctionData
10
11
  } from 'viem'
11
12
  import { z } from 'zod'
12
13
  import type { AbiError } from '../types.js'
@@ -122,5 +123,37 @@ export default {
122
123
  throw new Error(`Failed to parse error ABI: ${error}`)
123
124
  }
124
125
  }
126
+ ),
127
+
128
+ encode_function_data: createTool(
129
+ 'Encode Function Call Data',
130
+ 'Encode a function call with parameters into transaction data. Use this before calling call_contract_write.',
131
+ z.object({
132
+ functionAbi: z.string().describe('Function ABI definition (e.g., "function transfer(address to, uint256 amount)")'),
133
+ args: z.array(z.union([z.string(), z.number(), z.boolean()])).describe('Function arguments in order matching the ABI signature. Automatically type-converted.')
134
+ }),
135
+ async (args) => {
136
+ try {
137
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction
138
+
139
+ // Encode the function data
140
+ const data = encodeFunctionData({
141
+ abi: [abiItem],
142
+ functionName: abiItem.name,
143
+ args: args.args as readonly unknown[]
144
+ })
145
+
146
+ return formatResponse({
147
+ data,
148
+ functionName: abiItem.name,
149
+ functionSignature: toFunctionSignature(abiItem),
150
+ selector: data.slice(0, 10),
151
+ encodedArgs: data.slice(10),
152
+ message: 'Function data encoded successfully. Use this data with call_contract_write tool.'
153
+ })
154
+ } catch (error) {
155
+ throw new Error(`Failed to encode function data: ${error}`)
156
+ }
157
+ }
125
158
  )
126
159
  }
@@ -0,0 +1,246 @@
1
+ import { z } from 'zod'
2
+ import { getWalletServer } from '../wallet-server.js'
3
+ import { SUPPORTED_CHAINS } from '../client.js'
4
+ import { parseUnits, encodeFunctionData, parseAbiItem, type AbiFunction } from 'viem'
5
+ import { randomBytes } from 'crypto'
6
+ import { createTool, formatResponse } from '../utils.js'
7
+
8
+ function generateRequestId(): string {
9
+ return randomBytes(16).toString('hex')
10
+ }
11
+
12
+ export default {
13
+ send_native_token: createTool(
14
+ 'Send Native Token',
15
+ 'Send native tokens (ETH, MATIC, BNB, etc.) to an address. Opens browser wallet for approval.',
16
+ z.object({
17
+ chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
18
+ to: z.string().describe('Recipient address'),
19
+ amount: z.string().describe('Amount in native token (e.g., "0.1" for 0.1 ETH)'),
20
+ data: z.string().optional().describe('Optional hex-encoded data to include with transaction')
21
+ }),
22
+ async (args) => {
23
+ const walletServer = getWalletServer()
24
+
25
+ try {
26
+ // Parse amount to wei
27
+ const value = '0x' + parseUnits(args.amount, 18).toString(16)
28
+
29
+ const txRequest = {
30
+ id: generateRequestId(),
31
+ type: 'send_transaction' as const,
32
+ chain: args.chain,
33
+ data: {
34
+ to: args.to,
35
+ value,
36
+ ...(args.data && { data: args.data })
37
+ }
38
+ }
39
+
40
+ console.error(`[Transaction] Sending ${args.amount} native token to ${args.to} on ${args.chain}`)
41
+ const txHash = await walletServer.sendTransaction(txRequest)
42
+
43
+ return formatResponse({
44
+ success: true,
45
+ chain: args.chain,
46
+ transactionHash: txHash,
47
+ to: args.to,
48
+ amount: args.amount,
49
+ message: `Successfully sent ${args.amount} native token`,
50
+ explorerUrl: `https://etherscan.io/tx/${txHash}`
51
+ })
52
+ } catch (error) {
53
+ const errorMessage = error instanceof Error ? error.message : String(error)
54
+ return formatResponse({
55
+ success: false,
56
+ error: errorMessage,
57
+ message: 'Transaction failed or was rejected'
58
+ })
59
+ }
60
+ }
61
+ ),
62
+
63
+ send_erc20_token: createTool(
64
+ 'Send ERC20 Token',
65
+ 'Send ERC20 tokens to an address. Opens browser wallet for approval.',
66
+ z.object({
67
+ chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
68
+ tokenAddress: z.string().describe('ERC20 token contract address'),
69
+ to: z.string().describe('Recipient address'),
70
+ amount: z.string().describe('Amount in token units (e.g., "100" for 100 USDC)'),
71
+ decimals: z.number().optional().default(18).describe('Token decimals (default: 18)')
72
+ }),
73
+ async (args) => {
74
+ const walletServer = getWalletServer()
75
+
76
+ try {
77
+ const decimals = args.decimals || 18
78
+ const amountWei = parseUnits(args.amount, decimals)
79
+
80
+ // ERC20 transfer(address to, uint256 amount)
81
+ const data = `0xa9059cbb${args.to.slice(2).padStart(64, '0')}${amountWei.toString(16).padStart(64, '0')}`
82
+
83
+ const txRequest = {
84
+ id: generateRequestId(),
85
+ type: 'send_transaction' as const,
86
+ chain: args.chain,
87
+ data: {
88
+ to: args.tokenAddress,
89
+ data,
90
+ value: '0x0'
91
+ }
92
+ }
93
+
94
+ console.error(`[Transaction] Sending ${args.amount} tokens to ${args.to} on ${args.chain}`)
95
+ const txHash = await walletServer.sendTransaction(txRequest)
96
+
97
+ return formatResponse({
98
+ success: true,
99
+ chain: args.chain,
100
+ transactionHash: txHash,
101
+ tokenAddress: args.tokenAddress,
102
+ to: args.to,
103
+ amount: args.amount,
104
+ message: `Successfully sent ${args.amount} tokens`,
105
+ explorerUrl: `https://etherscan.io/tx/${txHash}`
106
+ })
107
+ } catch (error) {
108
+ const errorMessage = error instanceof Error ? error.message : String(error)
109
+ return formatResponse({
110
+ success: false,
111
+ error: errorMessage,
112
+ message: 'Token transfer failed or was rejected'
113
+ })
114
+ }
115
+ }
116
+ ),
117
+
118
+ call_contract_write: createTool(
119
+ 'Call Contract (Write)',
120
+ 'Call a state-changing contract function (write operation). Opens browser wallet for approval.',
121
+ z.object({
122
+ chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
123
+ contractAddress: z.string().describe('Contract address'),
124
+ functionAbi: z.string().describe('Function ABI definition (e.g., "function transfer(address to, uint256 amount)")'),
125
+ args: z.array(z.union([z.string(), z.number(), z.boolean()])).optional().describe('Function arguments in order matching the ABI signature'),
126
+ value: z.string().optional().describe('Optional ETH value to send with transaction (in ETH units, e.g., "0.1")')
127
+ }),
128
+ async (args) => {
129
+ const walletServer = getWalletServer()
130
+
131
+ try {
132
+ // Parse the function ABI and encode the call data
133
+ console.error(`[Transaction] Parsing ABI: ${args.functionAbi}`)
134
+ console.error(`[Transaction] Args: ${JSON.stringify(args.args)}`)
135
+
136
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction
137
+ console.error(`[Transaction] Parsed function: ${abiItem.name}`)
138
+
139
+ const data = encodeFunctionData({
140
+ abi: [abiItem],
141
+ functionName: abiItem.name,
142
+ args: (args.args || []) as readonly unknown[]
143
+ })
144
+ console.error(`[Transaction] Encoded data: ${data}`)
145
+
146
+ const valueHex = args.value ? '0x' + parseUnits(args.value, 18).toString(16) : '0x0'
147
+
148
+ const txRequest = {
149
+ id: generateRequestId(),
150
+ type: 'send_transaction' as const,
151
+ chain: args.chain,
152
+ data: {
153
+ to: args.contractAddress,
154
+ data,
155
+ value: valueHex
156
+ }
157
+ }
158
+
159
+ console.error(`[Transaction] Calling ${abiItem.name}() on ${args.contractAddress} (${args.chain})`)
160
+ const txHash = await walletServer.sendTransaction(txRequest)
161
+
162
+ return formatResponse({
163
+ success: true,
164
+ chain: args.chain,
165
+ transactionHash: txHash,
166
+ contractAddress: args.contractAddress,
167
+ functionName: abiItem.name,
168
+ message: `Contract call to ${abiItem.name}() successful`,
169
+ explorerUrl: `https://etherscan.io/tx/${txHash}`
170
+ })
171
+ } catch (error) {
172
+ console.error(`[Transaction] Error:`, error)
173
+ const errorMessage = error instanceof Error ? error.message : String(error)
174
+ return formatResponse({
175
+ success: false,
176
+ error: errorMessage,
177
+ message: 'Contract call failed or was rejected'
178
+ })
179
+ }
180
+ }
181
+ ),
182
+
183
+ sign_message: createTool(
184
+ 'Sign Message',
185
+ 'Sign a message with the connected wallet. Opens browser wallet for approval.',
186
+ z.object({
187
+ message: z.string().describe('Message to sign')
188
+ }),
189
+ async (args) => {
190
+ const walletServer = getWalletServer()
191
+
192
+ try {
193
+ const request = {
194
+ id: generateRequestId(),
195
+ type: 'sign_message' as const,
196
+ chain: 'any',
197
+ data: {
198
+ message: args.message
199
+ }
200
+ }
201
+
202
+ console.error(`[Transaction] Signing message`)
203
+ const signature = await walletServer.sendTransaction(request)
204
+
205
+ return formatResponse({
206
+ success: true,
207
+ message: args.message,
208
+ signature,
209
+ signatureType: 'personal_sign'
210
+ })
211
+ } catch (error) {
212
+ const errorMessage = error instanceof Error ? error.message : String(error)
213
+ return formatResponse({
214
+ success: false,
215
+ error: errorMessage,
216
+ message: 'Message signing failed or was rejected'
217
+ })
218
+ }
219
+ }
220
+ ),
221
+
222
+ wallet_status: createTool(
223
+ 'Wallet Status',
224
+ 'Check if a wallet is connected to the browser interface',
225
+ z.object({}),
226
+ async () => {
227
+ const walletServer = getWalletServer()
228
+ const isConnected = walletServer.isConnected()
229
+ const port = walletServer.getPort()
230
+
231
+ // Auto-open browser if no wallet connected
232
+ if (!isConnected) {
233
+ walletServer.openBrowser()
234
+ }
235
+
236
+ return formatResponse({
237
+ connected: isConnected,
238
+ walletUrl: `http://localhost:${port}`,
239
+ message: isConnected
240
+ ? 'Wallet is connected and ready to sign transactions'
241
+ : `No wallet connected. Opening browser to connect... Visit http://localhost:${port} if it didn't open automatically.`
242
+ })
243
+ }
244
+ )
245
+ }
246
+