使用说明
MCP服务器示例
一个可扩展的模型上下文协议(MCP)服务器实现,使用Node.js和Express.js构建,使用官方的MCP JavaScript SDK。
🏗️ 项目结构
mcp-server-example/
├── src/
│ ├── config/
│ │ └── server-config.js # Server configuration
│ ├── server/
│ │ ├── http-server.js # Express.js HTTP server setup
│ │ ├── http-utils.js # HTTP utilities and error handling
│ │ └── server.js # MCP server and session management
│ ├── prompts/
│ │ ├── health-assessment.js # Health assessment prompt
│ │ ├── project-analysis.js # Project analysis prompt
│ │ ├── weather-planning.js # Weather planning prompt
│ │ ├── code-review.js # Code review prompt
│ │ ├── onboarding.js # Onboarding prompt
│ │ └── index.js # Prompt exports and registration
│ ├── resources/
│ │ ├── static-resources.js # Static resources (config, info)
│ │ ├── dynamic-resources.js # Dynamic resources with templates
│ │ └── index.js # Resource exports and registration
│ ├── tools/
│ │ ├── calculate-bmi.js # BMI calculator tool
│ │ ├── fetch-weather.js # Weather fetcher tool
│ │ ├── list-files.js # File listing tool
│ │ └── index.js # Tool exports and registration
│ └── index.js # Main entry point
├── tests/ # Test suite (JavaScript, run directly)
│ ├── tools.test.js # Tool functionality tests
│ ├── resources.test.js # Resource functionality tests
│ ├── prompts.test.js # Prompt functionality tests
│ ├── server.test.js # Server architecture tests
│ └── http-integration-test.js # HTTP integration tests
├── examples/ # Testing examples and scripts
│ ├── curl/ # cURL testing scripts
│ │ ├── common.sh # Shared utilities
│ │ ├── tools.sh # Tools testing
│ │ ├── resources.sh # Resources testing
│ │ ├── prompts.sh # Prompts testing
│ │ └── all.sh # Complete test suite
│ └── README.md # Examples documentation
├── package.json
└── README.md
🚀 快速开始
先决条件
- Node.js 18+
- npm或纱线
安装
npm install
运行服务器
# Start the server
npm start
# Development mode with auto-restart
npm run dev
# Test the server
npm test
测试服务器
# Easiest way: Use MCP Inspector (web interface)
npx @modelcontextprotocol/inspector
# Then connect to: http://localhost:3000/mcp
# Alternative: Command-line testing
npm run test:manual
🔧 可用工具(示例)
1.BMI计算器(calculate-bmi)
根据健康类别分类计算体重指数。
参数:
weightKg(数量):重量(公斤)heightM(数字):高度(米)
例子:
{
"name": "calculate-bmi",
"arguments": {
"weightKg": 70,
"heightM": 1.75
}
}
2.天气费彻(fetch-weather)
检索城市的天气信息(模拟数据)。
参数:
city(string):城市名称
例子:
{
"name": "fetch-weather",
"arguments": {
"city": "London"
}
}
3.文件列表器(list-files)
列出与模式匹配的项目文件。
参数:
pattern(string):文件模式(例如,“.js“,”.md”)
例子:
{
"name": "list-files",
"arguments": {
"pattern": "*.js"
}
}
📚 可用资源(示例)
静态资源
config://app-应用程序配置info://server-服务器信息
动态资源
users://{userId}/profile-按ID列出的用户配置文件github://repos/{owner}/{repo}-GitHub存储库信息
🎯 可用提示(示例)
1.健康评估(health-assessment)
综合健康评估,包括BMI计算和活动建议。
参数:
weight(字符串):重量(公斤)height(字符串):高度(单位:米)city(string):基于天气的活动推荐城市goals(字符串,可选):健康或健身目标
例子:
{
"name": "health-assessment",
"arguments": {
"weight": "70",
"height": "1.75",
"city": "London",
"goals": "lose weight and improve fitness"
}
}
2.项目分析(project-analysis)
全面的项目分析和代码库探索指南。
参数:
focus(枚举):分析重点-“概述”、“结构”、“配置”或“全部”fileTypes(字符串,可选):要分析的特定文件类型(例如,'js、json、md')
3.天气规划(weather-planning)
基于天气的活动和旅行计划助理。
参数:
cities(string):以逗号分隔的待检查城市列表activity(枚举):活动类型-“旅行”、“户外”、“健身”或“一般”duration(字符串,可选):计划持续时间(例如,“周末”、“周”)
4.代码审查(code-review)
系统代码审查和质量评估指南。
参数:
scope(enum):审查范围-“完整”、“更改”或“特定”focus(枚举):审查重点-“质量”、“安全性”、“性能”、“可维护性”或“全部”filePattern(字符串,可选):要查看的特定文件模式(例如,'.js','.json)
5.入职培训(onboarding)
为新团队成员和用户提供全面的入职指南。
参数:
role(枚举):角色-“开发人员”、“用户”、“管理员”或“审阅者”experience(枚举):经验水平-“初级”、“中级”或“专家”focus(字符串,可选):特定的兴趣或责任领域
💡 使用提示
服务器提供5个全面的提示,为各种用例生成上下文指导。每个提示都接受参数,并返回根据您的特定需求量身定制的详细、可操作的说明。
可用提示:
- 健康评估:基于天气活动建议的BMI计算
- 项目分析:代码库探索和分析指南
- 天气计划:活动的多城市天气规划
- 代码审查:系统代码审查和质量评估
- 入职:团队成员基于角色的入职培训
使用示例:
# Get health assessment prompt
curl -X POST http://localhost:3000/mcp \
-H "mcp-session-id: YOUR_SESSION_ID" \
-d '{
"method": "prompts/get",
"params": {
"name": "health-assessment",
"arguments": {
"weight": "70",
"height": "1.75",
"city": "London"
}
}
}'
🧪 测试
该项目包括使用Node.js内置测试运行器进行全面测试:
测试结构
tests/
├── tools.test.js # Tool functionality tests (7 tests)
├── resources.test.js # Resource functionality tests (3 tests)
├── prompts.test.js # Prompt functionality tests (10 tests)
├── server.test.js # Server architecture tests (6 tests)
└── http-integration-test.js # HTTP endpoint integration tests
运行测试
# Run all tests
npm test
# Run tests in watch mode (auto-rerun on file changes)
npm run test:watch
# Run HTTP integration tests specifically
npm run test:integration
# Manual testing with cURL
npm run test:manual
测试覆盖率
综合测试套件包括:
- ✅ 工具功能:BMI计算、天气获取、文件列表
- ✅ 资源管理:静态资源(配置、信息)和动态资源(用户配置文件、存储库)
- ✅ 提示系统:健康评估、项目分析、天气规划、代码审查、入职培训
- ✅ 会话管理:创建、限制、清理和错误处理
- ✅ 服务器架构:MCP服务器创建、HTTP服务器设置、配置
- ✅ 集成组件:工具、资源和快速注册系统
- ✅ 错误处理:边缘情况、无效输入、格式错误的请求
测试结果:4个测试套件中的26个测试,通过率为100%
手动测试
基于浏览器的测试(推荐)
# Start the MCP server
npm start
# In another terminal, launch MCP Inspector
npx @modelcontextprotocol/inspector
# Then open your browser to the URL shown (usually http://localhost:5173)
# Connect to: http://localhost:3000/mcp
MCP检查器界面显示具有交互式测试功能的工具、资源和提示
MCP检查器提供了一个用户友好的web界面,用于:
- ✅ 交互式测试:基于点击的工具执行和资源访问
- ✅ 实时结果:查看格式化并突出显示的回复
- ✅ 架构验证:内置参数验证和帮助
- ✅ 会话管理:自动会话处理
- ✅ 协议调试:查看原始MCP协议消息
命令行测试
# Health check
curl http://localhost:3000/health
# Individual functionality testing
./examples/curl/tools.sh # Test tools only
./examples/curl/resources.sh # Test resources only
./examples/curl/prompts.sh # Test prompts only
# Complete test suite
./examples/curl/all.sh # Test everything
📡 API终点
POST /mcp-主MCP协议端点(工具、资源、提示)GET /mcp-服务器到客户端通知(SSE)DELETE /mcp-会话终止GET /health-健康检查和服务器状态
🌐 浏览器测试
为了获得最简单的测试体验,请使用官方的MCP Inspector:
npx @modelcontextprotocol/inspector
然后连接到 http://localhost:3000/mcp 在web界面中。
MCP协议方法
tools/list-列出可用工具tools/call-执行工具resources/list-列出可用资源resources/read-阅读资源prompts/list-列出可用提示prompts/get-获取带有参数的提示
⚙️ 配置
编辑 src/config/server-config.js 自定义:
- 服务器端口和主机
- 会话管理设置
- 日志记录配置
- MCP协议设置
环境变量
PORT-服务器端口(默认值:3000)HOST-服务器主机(默认:localhost)LOG_LEVEL-日志记录级别(默认值:info)NODE_ENV-环境(开发/生产)
🔧 添加新工具
- 在中创建新文件
src/tools/:
// src/tools/my-new-tool.js
import { z } from "zod";
export const myNewTool = {
name: "my-new-tool",
config: {
title: "My New Tool",
description: "Description of what the tool does",
inputSchema: {
param1: z.string().describe("Description of param1"),
param2: z.number().optional().describe("Optional param2")
}
},
handler: async ({ param1, param2 }) => {
// Arguments are passed directly via destructuring
// Tool logic here
return {
content: [{
type: "text",
text: "Tool output"
}]
};
}
};
- 导出到
src/tools/index.js:
export { myNewTool } from './my-new-tool.js';
// Add to registerAllTools function
const tools = [calculateBmiTool, fetchWeatherTool, listFilesTool, myNewTool];
🗂️ 添加新资源
-
增添
src/resources/static-resources.js(对于静态资源)或src/resources/dynamic-resources.js(用于模板化资源) -
资源通过以下方式自动注册
src/resources/index.js
🔒 会话管理
服务器包括强大的会话管理:
- 自动会话清理
- 会话限制(可配置)
- 优雅的会话终止
- 内存泄漏预防
🛠️ 发展特征
- JavaScript ES模块:具有ES模块语法的现代JavaScript
- 热重新加载:使用
npm run dev用于在文件更改时自动重新启动 - 错误处理:使用适当的HTTP状态码进行全面的错误处理
- 日志记录:可配置的请求日志和服务器事件
- 健康监测:内置健康检查端点
- 优雅地关闭:服务器终止时进行适当的清理
- 直接测试执行:使用Node.js内置测试运行器直接从JavaScript源代码运行测试
📋 脚本
npm start-启动服务器npm run dev-从自动重启开始(开发)npm test-运行所有测试npm run test:watch-在监视模式下运行测试(更改后自动重新运行)npm run test:integration-运行HTTP集成测试npm run test:manual-运行手动cURL测试npm run stop-停止正在运行的服务器
🤝 贡献
- 在中添加新工具
src/tools/ - 在中添加新资源
src/resources/ - 更新配置
src/config/ - 遵循现有的JavaScript代码结构和模式
- 使用提供的测试脚本测试您的更改
📖 MCP协议
此服务器使用官方JavaScript SDK实现了模型上下文协议(MCP)2024-11-05版本。有关MCP的更多信息,请访问 官方文件.
MCP SDK集成
- 使用官方
@modelcontextprotocol/sdk包裹 - 带有上下文对象的正确工具处理程序签名
- 工具输入的JSON模式验证
- 具有完成支持的资源模板
- 会话管理与运输处理
备注:本实施中的示例和模式改编自官方 MCP TypeScript SDK 存储库。
📄 许可证
MIT许可证-详见package.json。