跳到主要内容

开发环境搭建

本文将指导你完成 MCP 开发环境的搭建,确保你能够顺利开始开发自己的 MCP 服务器。

前置要求

在开始之前,请确保你的系统满足以下要求:

  • Node.js >= 20.0
  • npm 或 yarn
  • Git
  • 支持的操作系统:Windows 10+、macOS 10.15+、Linux

安装步骤

1. 创建新项目

# 创建项目目录
mkdir my-mcp-server
cd my-mcp-server

# 初始化 npm 项目
npm init -y

# 创建基本目录结构
mkdir -p src/{tools,resources}
mkdir -p tests

2. 安装 MCP SDK

# 安装 MCP 核心包
npm install @modelcontextprotocol/sdk

# 安装开发依赖
npm install -D typescript @types/node tsx nodemon

3. 配置 TypeScript

创建 tsconfig.json

{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

4. 创建项目配置

创建 mcp.config.json

{
"name": "my-mcp-server",
"version": "1.0.0",
"description": "我的 MCP 服务器",
"main": "dist/index.js",
"bin": {
"my-mcp-server": "dist/index.js"
},
"scripts": {
"build": "tsc",
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js"
}
}

5. 设置开发脚本

package.json 中更新脚本:

{
"scripts": {
"build": "tsc",
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js",
"test": "jest",
"lint": "eslint src --ext .ts",
"format": "prettier --write src/**/*.ts"
}
}

开发工具配置

VS Code 扩展

推荐安装以下扩展:

  • TypeScript and JavaScript Language Features
  • ESLint
  • Prettier
  • MCP Extension (如果可用)

调试配置

创建 .vscode/launch.json

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug MCP Server",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"runtimeArgs": ["-r", "tsx/cjs"],
"env": {
"NODE_ENV": "development"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

验证环境

1. 创建测试文件

创建 src/index.ts

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server(
{
name: 'my-mcp-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);

async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('MCP Server running on stdio');
}

main().catch((error) => {
console.error('Server error:', error);
process.exit(1);
});

2. 构建和运行

# 构建项目
npm run build

# 开发模式运行
npm run dev

3. 测试 MCP 连接

使用 Claude Code 测试你的 MCP 服务器:

  1. 在 Claude Code 中配置你的服务器
  2. 运行测试命令验证连接
  3. 查看服务器日志确认正常运行

常见问题

Q: TypeScript 编译报错

A: 检查 tsconfig.json 配置,确保所有依赖都已正确安装。

Q: MCP 服务器无法启动

A: 检查端口是否被占用,确认服务器配置正确。

Q: 工具无法注册

A: 确保 capabilities 中正确配置了工具列表。

下一步

环境搭建完成后,你可以:

  1. 阅读第一个 MCP 服务器创建你的第一个服务
  2. 查看高级主题了解更多进阶功能
  3. 了解MCP 生态系统探索可用的服务器

参考资源