> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monad.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何构建可与 Monad 测试网交互的 MCP 服务器

在本指南中，您将学习如何构建一个 [Model Context Protocol](https://github.com/modelcontextprotocol)（MCP）服务器，让 MCP 客户端（Claude Desktop）能够查询 Monad 测试网以检查账户的 MON 余额。

## 什么是 MCP？

[Model Context Protocol](https://github.com/modelcontextprotocol)（MCP）是一个标准，允许 AI 模型与外部工具和服务进行交互。

## 前置条件

* Node.js（v16 或更高版本）
* `npm` 或 `yarn`
* Claude Desktop

## 开始使用

1. 克隆 [`monad-mcp-tutorial`](https://github.com/monad-developers/monad-mcp-tutorial) 仓库。此仓库包含一些代码可以帮助您快速上手。

```shell theme={null}
git clone https://github.com/monad-developers/monad-mcp-tutorial.git
```

2. 安装依赖：

```
npm install
```

## 构建 MCP 服务器

Monad 测试网相关的配置已经添加到 `src` 文件夹中的 `index.ts` 里。

### 定义服务器实例

```ts lines title="src/index.ts" theme={null}
// Create a new MCP server instance
const server = new McpServer({
  name: "monad-mcp-tutorial",
  version: "0.0.1",
  // Array of supported tool names that clients can call
  capabilities: ["get-mon-balance"]
});
```

### 定义 MON 余额工具

以下是 `get-mon-balance` 工具的框架：

```ts lines title="src/index.ts" theme={null}
server.tool(
    // Tool ID 
    "get-mon-balance",
    // Description of what the tool does
    "Get MON balance for an address on Monad testnet",
    // Input schema
    {
        address: z.string().describe("Monad testnet address to check balance for"),
    },
    // Tool implementation
    async ({ address }) => {
        // code to check MON balance
    }
);
```

让我们向该工具添加 MON 余额检查的实现：

```ts lines title="src/index.ts" theme={null}
server.tool(
    // Tool ID 
    "get-mon-balance",
    // Description of what the tool does
    "Get MON balance for an address on Monad testnet",
    // Input schema
    {
        address: z.string().describe("Monad testnet address to check balance for"),
    },
    // Tool implementation
    async ({ address }) => {
        try {
            // Check MON balance for the input address
            const balance = await publicClient.getBalance({
                address: address as `0x${string}`,
            });

            // Return a human friendly message indicating the balance.
            return {
                content: [
                    {
                        type: "text",
                        text: `Balance for ${address}: ${formatUnits(balance, 18)} MON`,
                    },
                ],
            };
        } catch (error) {
            // If the balance check process fails, return a graceful message back to the MCP client indicating a failure.
            return {
                content: [
                    {
                        type: "text",
                        text: `Failed to retrieve balance for address: ${address}. Error: ${
                        error instanceof Error ? error.message : String(error)
                        }`,
                    },
                ],
            };
        }
    }
);
```

### 在 `main` 函数中初始化传输层和服务器

```ts lines title="src/index.ts" theme={null}
async function main() {
    // Create a transport layer using standard input/output
    const transport = new StdioServerTransport();
    
    // Connect the server to the transport
    await server.connect(transport);
}
```

### 构建项目

```shell theme={null}
npm run build
```

服务器现在可以使用了！

### 将 MCP 服务器添加到 Claude Desktop

1. 打开"Claude Desktop"

![claude desktop](https://github.com/monad-developers/monad-mcp-tutorial/blob/main/static/1.png?raw=true)

2. 打开设置

Claude > Settings > Developer

![claude settings](https://github.com/monad-developers/monad-mcp-tutorial/blob/main/static/claude_settings.gif?raw=true)

3. 打开 `claude_desktop_config.json`

![claude config](https://github.com/monad-developers/monad-mcp-tutorial/blob/main/static/config.gif?raw=true)

4. 添加 MCP 服务器详情并保存文件。

```json lines title="claude_desktop_config.json" theme={null}
{
  "mcpServers": {
    ...
    "monad-mcp": {
      "command": "node",
      "args": [
        "/<path-to-project>/build/index.js"
      ]
    }
  }
}
```

5. 重启"Claude Desktop"

### 使用 MCP 服务器

您现在应该能够在 Claude 中看到这些工具了！

![tools](https://github.com/monad-developers/monad-mcp-tutorial/blob/main/static/tools.gif?raw=true)

以下是最终结果

![final result](https://github.com/monad-developers/monad-mcp-tutorial/blob/main/static/final_result.gif?raw=true)

## 更多资源

* [Model Context Protocol 文档](https://modelcontextprotocol.io/introduction)
* [Monad 文档](https://docs.monad.xyz/)
* [Viem 文档](https://viem.sh/)
