JS实现入门
本指南将帮助您从零开始搭建基于JavaScript的MCP服务器,并实现基本的自定义函数。
环境准备
在开始之前,请确保您的系统满足以下要求:
- Node.js(v14.0或更高版本)
- npm或yarn包管理器
- 基本的JavaScript/TypeScript知识
创建项目
首先,创建一个新的项目目录并初始化npm:
mkdir mcp-js-server
cd mcp-js-server
npm init -y
安装MCP服务器依赖:
npm install @modelcontextprotocol/server express cors
npm install typescript @types/node @types/express --save-dev
创建TypeScript配置
创建tsconfig.json文件:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
目录结构
为项目创建以下目录结构:
mcp-js-server/
├── src/
│ ├── index.ts # 主入口文件
│ ├── tools/ # 自定义工具定义
│ │ └── echo.ts # 示例工具
│ ├── resources/ # 资源定义
│ │ └── sample.ts # 示例资源
│ └── prompts/ # 提示模板定义
│ └── help.ts # 示例提示模板
├── tsconfig.json
└── package.json