web3-tools-mcp 1.3.1 → 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) => {
@@ -9,6 +9,7 @@ import ensTools from './ens.js'
9
9
  import gasTools from './gas.js'
10
10
  import logTools from './logs.js'
11
11
  import signatureTools from './signatures.js'
12
+ import transactionTools from './transactions.js'
12
13
 
13
14
  const allToolDefinitions = {
14
15
  ...signatureTools,
@@ -18,7 +19,8 @@ const allToolDefinitions = {
18
19
  ...logTools,
19
20
  ...advancedTools,
20
21
  ...ensTools,
21
- ...gasTools
22
+ ...gasTools,
23
+ ...transactionTools
22
24
  } as const
23
25
 
24
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
+
@@ -0,0 +1,236 @@
1
+ import express from 'express'
2
+ import cors from 'cors'
3
+ import { WebSocketServer, WebSocket } from 'ws'
4
+ import { createServer } from 'http'
5
+ import { fileURLToPath } from 'url'
6
+ import { dirname, join } from 'path'
7
+ import { exec } from 'child_process'
8
+
9
+ const __filename = fileURLToPath(import.meta.url)
10
+ const __dirname = dirname(__filename)
11
+
12
+ export interface TransactionRequest {
13
+ id: string
14
+ type: 'send_transaction' | 'sign_message' | 'sign_typed_data'
15
+ chain: string
16
+ data: unknown
17
+ }
18
+
19
+ export interface TransactionResponse {
20
+ id: string
21
+ success: boolean
22
+ result?: unknown
23
+ error?: string
24
+ }
25
+
26
+ class WalletServer {
27
+ private app: express.Application
28
+ private httpServer: ReturnType<typeof createServer>
29
+ private wss: WebSocketServer
30
+ private clients: Set<WebSocket> = new Set()
31
+ private pendingRequests: Map<string, {
32
+ resolve: (value: unknown) => void
33
+ reject: (error: Error) => void
34
+ }> = new Map()
35
+ private port: number
36
+ private isStarted = false
37
+
38
+ constructor(port = 3456) {
39
+ this.port = port
40
+ this.app = express()
41
+ this.httpServer = createServer(this.app)
42
+ this.wss = new WebSocketServer({ server: this.httpServer })
43
+
44
+ this.setupExpress()
45
+ this.setupWebSocket()
46
+ }
47
+
48
+ private setupExpress() {
49
+ this.app.use(cors())
50
+ this.app.use(express.json())
51
+ this.app.use(express.static(join(__dirname, '..', 'public')))
52
+
53
+ this.app.get('/', (_req, res) => {
54
+ res.sendFile(join(__dirname, '..', 'public', 'wallet.html'))
55
+ })
56
+
57
+ this.app.get('/health', (_req, res) => {
58
+ res.json({
59
+ status: 'ok',
60
+ clients: this.clients.size,
61
+ pendingRequests: this.pendingRequests.size
62
+ })
63
+ })
64
+ }
65
+
66
+ private setupWebSocket() {
67
+ this.wss.on('connection', (ws: WebSocket) => {
68
+ console.error('[Wallet Server] Client connected')
69
+ this.clients.add(ws)
70
+
71
+ ws.on('message', (data: Buffer) => {
72
+ try {
73
+ const response: TransactionResponse = JSON.parse(data.toString())
74
+ console.error('[Wallet Server] Received response:', response.id)
75
+ console.error('[Wallet Server] Response data:', JSON.stringify(response))
76
+
77
+ const pending = this.pendingRequests.get(response.id)
78
+ if (pending) {
79
+ if (response.success) {
80
+ pending.resolve(response.result)
81
+ } else {
82
+ pending.reject(new Error(response.error || 'Transaction failed'))
83
+ }
84
+ this.pendingRequests.delete(response.id)
85
+ }
86
+ } catch (error) {
87
+ console.error('[Wallet Server] Error parsing message:', error)
88
+ }
89
+ })
90
+
91
+ ws.on('close', () => {
92
+ console.error('[Wallet Server] Client disconnected')
93
+ this.clients.delete(ws)
94
+ })
95
+
96
+ ws.on('error', (error) => {
97
+ console.error('[Wallet Server] WebSocket error:', error)
98
+ this.clients.delete(ws)
99
+ })
100
+ })
101
+ }
102
+
103
+ async start() {
104
+ if (this.isStarted) {
105
+ return
106
+ }
107
+
108
+ return new Promise<void>((resolve, reject) => {
109
+ this.httpServer.listen(this.port, () => {
110
+ this.isStarted = true
111
+ console.error(`[Wallet Server] Running on http://localhost:${this.port}`)
112
+ resolve()
113
+ }).on('error', (error: NodeJS.ErrnoException) => {
114
+ if (error.code === 'EADDRINUSE') {
115
+ console.error(`[Wallet Server] Port ${this.port} already in use, assuming server is already running`)
116
+ this.isStarted = true
117
+ resolve()
118
+ } else {
119
+ reject(error)
120
+ }
121
+ })
122
+ })
123
+ }
124
+
125
+ async stop() {
126
+ return new Promise<void>((resolve) => {
127
+ this.clients.forEach(client => client.close())
128
+ this.wss.close(() => {
129
+ this.httpServer.close(() => {
130
+ this.isStarted = false
131
+ console.error('[Wallet Server] Stopped')
132
+ resolve()
133
+ })
134
+ })
135
+ })
136
+ }
137
+
138
+ openBrowser() {
139
+ const url = `http://localhost:${this.port}`
140
+ const platform = process.platform
141
+
142
+ let command: string
143
+ if (platform === 'darwin') {
144
+ command = `open "${url}"`
145
+ } else if (platform === 'win32') {
146
+ command = `start "${url}"`
147
+ } else {
148
+ command = `xdg-open "${url}"`
149
+ }
150
+
151
+ exec(command, (error) => {
152
+ if (error) {
153
+ console.error('[Wallet Server] Failed to open browser:', error)
154
+ console.error(`[Wallet Server] Please open manually: ${url}`)
155
+ } else {
156
+ console.error(`[Wallet Server] Opened browser at ${url}`)
157
+ }
158
+ })
159
+ }
160
+
161
+ async sendTransaction(request: TransactionRequest): Promise<unknown> {
162
+ if (!this.isStarted) {
163
+ await this.start()
164
+ }
165
+
166
+ // Always open/focus browser for transaction requests
167
+ this.openBrowser()
168
+
169
+ // Open browser if no clients connected
170
+ if (this.clients.size === 0) {
171
+ // Wait for client to connect (max 30 seconds)
172
+ const timeout = 30000
173
+ const startTime = Date.now()
174
+ while (this.clients.size === 0 && Date.now() - startTime < timeout) {
175
+ await new Promise(resolve => setTimeout(resolve, 500))
176
+ }
177
+
178
+ if (this.clients.size === 0) {
179
+ throw new Error('No wallet connected. Please open the browser and connect your wallet.')
180
+ }
181
+ }
182
+
183
+ return new Promise((resolve, reject) => {
184
+ this.pendingRequests.set(request.id, { resolve, reject })
185
+
186
+ // Send to first available connected client only
187
+ const message = JSON.stringify(request)
188
+ let sent = false
189
+ for (const client of this.clients) {
190
+ if (client.readyState === WebSocket.OPEN) {
191
+ client.send(message)
192
+ sent = true
193
+ break
194
+ }
195
+ }
196
+
197
+ if (!sent) {
198
+ this.pendingRequests.delete(request.id)
199
+ reject(new Error('No active wallet connection'))
200
+ return
201
+ }
202
+
203
+ // Timeout after 5 minutes
204
+ setTimeout(() => {
205
+ if (this.pendingRequests.has(request.id)) {
206
+ this.pendingRequests.delete(request.id)
207
+ reject(new Error('Transaction request timed out'))
208
+ }
209
+ }, 300000)
210
+ })
211
+ }
212
+
213
+ isConnected(): boolean {
214
+ return this.clients.size > 0
215
+ }
216
+
217
+ getPort(): number {
218
+ return this.port
219
+ }
220
+ }
221
+
222
+ // Singleton instance
223
+ let walletServer: WalletServer | null = null
224
+
225
+ export function getWalletServer(): WalletServer {
226
+ if (!walletServer) {
227
+ walletServer = new WalletServer()
228
+ }
229
+ return walletServer
230
+ }
231
+
232
+ export async function startWalletServer(): Promise<WalletServer> {
233
+ const server = getWalletServer()
234
+ await server.start()
235
+ return server
236
+ }