Web3 Beginner Series:MCP completes the transaction in one sentence!

The content in the language you are looking for is not available yet

Overview

MCP (Model-Context Protocol) is an open protocol launched by Anthropic, which provides a standardized way for large language models to securely access external tools, data sources, and services. Unlike traditional plug-in systems, MCP adopts a client-server architecture and achieves seamless integration of models and external systems through standardized protocol interfaces.

MCP's core advantages

Standardized interface: MCP defines a unified protocol specification, avoiding the problem that each application needs to develop its own integration solution.

Security: Ensure secure access to external tools through strict permission control and sandbox mechanism.

Scalability: Support a wide range of tool types, from simple API calls to complex data processing flows.

Interoperability: Any client that supports MCP can use compatible services, achieving true cross-platform compatibility.

Application scenarios of Web3 + MCP

In the Web3 field, MCP can provide rich blockchain interaction capabilities for large language models:

● Asset query: query various token balances and transaction history

● On-chain operations: send transactions, deploy contracts, call smart contracts

● DeFi integration: interact with DeFi applications such as DEX, lending agreements, and liquidity mining

● Cross-chain operations: support multi-chain asset management and cross-chain transfers

● NFT management: query, transfer, and trade NFT assets

This article will build a simple Web3 MCP service through nodejs+typescript, and take you to analyze the working principle and best practices of MCP.

一、Create a project

  1. Create a project folder and initialize the project
mkdir web3-mcp-project
cd web3-mcp-project
npm init -y
  1. Install required packages
npm install @modelcontextprotocol/sdk ethers
  1. Add typescript configuration and modify it according to personal needs
{
  "compilerOptions": {
    "target": "es2020",
    "module": "es2020",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "build",
    "rootDir": "src",
    "allowJs": true,
    "checkJs": false,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build"]
}
  1. Modify the package.json configuration
"type": "module",
"bin": {
  "web3-mcp": "./build/index.js"
},
"scripts": {
  "build": "tsc && chmod +x build/index.js"
},

二、Coding server

Use server.tool to quickly create a tool. Here we take the getBalance of the sepolia test network as an example to write a tool

  1. First we need to register a zan account, activate the node service, get the rpcUrl, and then instantiate a provider
import { JsonRpcProvider } from 'ethers';

const NETWORK = {
  name: "Sepolia",
  rpc: 'https://api.zan.top/node/v1/eth/sepolia/YOUR_API_KEY',
  chainId: 11_155_111,
  currencySymbol: "SepoliaETH",
  explorer: "https://sepolia.etherscan.io"
  },
}

const provider = new JsonRpcProvider(NETWORK.rpc)
  1. Writing tool logic
export function registerEvmTools(server: McpServer) {
  server.tool(
    "getEvmBalance",
    "Get native token balance for an EVM address on any supported network",
    {
      address: z.string().describe("EVM account address"),
    },
    async ({ address }) => {
      try {
        const balance = await provider.getBalance(address);
        const formattedBalance = formatEther(balance);
  
        return {
          content: [
            {
              type: "text",
              text: `Balance on ${NETWORK.name}:\n${formattedBalance} ${NETWORK.currencySymbol}`,
            },
          ],
        };
      } catch (err) {
        const error = err as Error;
        return {
          content: [
            {
              type: "text",
              text: `Failed to retrieve balance: ${error.message}`,
            },
          ],
        };
      }
    }
  );
}
  1. Start the service and add error handling
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { registerEvmTools } from "./utils.ts";

const server = new McpServer({
  name: "web3-rpc",
  version: "1.0.0",
});
registerEvmTools(server);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch((err: unknown) => {
  const error = err as Error;
  console.error("Fatal error in main():", error.message);
  process.exit(1);
});

So far, a minimal mcp service has been written

三、Debugging Services

At this point, we need to package the js product, and then execute modelcontextprotocol/inspector to debug it.

npm run build

npx @modelcontextprotocol/inspector node build/index.js

四、Improve the logic and reference it in Cursor

Improve more logic and methods, such as supporting multiple evm networks, querying gas, sending transactions, querying token information, and token transactions, and package them and reference them in Cursor. Cursor is a new intelligent IDE that seamlessly integrates AI technology. Cursor is built on VSCode, easy to use, and can greatly improve your work efficiency. It is also an application that supports MCP integration.

{
  "mcpServers": {
    "web3-rpc": {
      "command": "node",
      "args": [
        "/Users/wutian/Documents/demoCode/web3-mcp/build/index.js"
      ]
    }
  }
}

五、use

Then you can use it happily in chat~ (chat is Cursor's AI assistant, which is located in the sidebar and can interact with the code base through natural language.)

For example, "Query the balance of this address 0xE21E97Ad8B527acb90F0b148EfaFbA46625382cE on sepolia":

For example, "Transfer 0.1ETH to this address 0x2c1d9ef7ccede70d77e6038701cd63138dd920a0":


六、Last words

There is still a lot of room for our imagination. This article has explained the overall process. What else can we do later? For example, support multiple chains (Bitcoin, Solana, Tron), or connect to cross-chain. In the chat, we can exchange the USDT of my chain for another chain? The combination of Web3 and MCP opens up a new world full of possibilities for us. Whether it is DeFi protocol integration, NFT market operations, or complex cross-chain asset management, these can be achieved through simple conversations. Interested friends, come and try it!

About ZAN

As a technology brand of Ant Digital Technologies for Web3 products and services, ZAN provides rich and reliable services for business innovations and a development platform for Web3 endeavors.

The ZAN product family includes ZAN Node ServiceZAN PowerZebra (zk acceleration), ZAN Identity (Know your customers and clients), ZAN Smart Contract Review, with more products in the pipeline.

Contact Us

WebsiteXDiscordTelegram