MCP服务器启动器(TypeScript)
  ](https://nodejs.org/) 
用于构建的最小、生产就绪的TypeScript入门模板 模型上下文协议(MCP) 服务器。
🎯 动机
模型上下文协议(MCP)是一种开放协议,规范了人工智能应用程序如何连接到数据源和工具。将其视为“USB-C for AI”-一种通用标准,允许任何AI模型通过一致的接口与任何数据源或工具连接。
graph LR
A[AI] |MCP| B[Server]
B C[Tools]
B D[Resources]此入门模板提供:
- ✅ 最小样板 让你快速开始
- ✅ 自动加载架构 用于工具、资源和提示
- ✅ TypeScript最佳实践 严格打字
- ✅ 生产就绪结构 这与你的项目相称
- ✅ 工作实例 (回声工具)演示模式
无论您是为数据库、API、文件系统还是自定义业务工具构建集成,此模板都可以帮助您创建可由任何MCP兼容客户端(如Claude Desktop、IDE或自定义应用程序)使用的MCP服务器。
📋 目录
- 使用代码生成器 - 添加新工具 - 添加资源 - 添加提示
✨ 特性
- 🚀 自动加载模块系统 -将新的工具、资源或提示放入其目录中,它们将自动注册
- 🛠️ TypeScript优先 -具有严格TypeScript配置的完全类型安全
- 📦 最小依赖性 -仅包括基本套餐
- 🧪 内置测试 -使用Node.js原生测试运行器
- 🔍 MCP检查员支持 -使用官方MCP检查器测试您的服务器
- 📝 可扩展架构 -添加新功能的清晰模式
- 🎯 示例实现 -工作回声工具演示了该模式
- ⚡ 代码生成器 -用于快速创建模块的Hygen脚手架
- 🌐 双重运输支持 -stdio和HTTP(SSE+JSON-RPC)传输
- 🐳 Docker就绪 -具有多阶段构建的容器化部署
📚 先决条件
\[!重要\] 在继续之前,请确保已安装Node.js 20.11.0或更高版本。
- Node.js>=20.11.0
- npm或纱线
- 对TypeScript的基本理解
- 熟悉 模型上下文协议 概念
📦 安装
克隆和设置
# Clone the repository
git clone https://github.com/alexanderop/mcp-server-starter-ts.git
cd mcp-server-starter-ts
# Install dependencies
npm install
# Build the project
npm run build用作模板
您也可以将其用作GitHub模板:
- 在GitHub上点击“使用此模板”
- 创建新存储库
- 克隆并开始构建MCP服务器
🚀 快速开始
\[!提示\] 在开发过程中,使用MCP检查器以交互方式测试您的服务器!
- 构建服务器:
npm run build- MCP检验员测试:
npm run inspect这将打开MCP检查器,您可以在其中与服务器的工具、资源和提示进行交互。
- 运行测试:
npm test🚀 运输方式
此服务器支持两种传输模式: 标准输入输出 (默认)和 超文本传输协议 (流式SSE+JSON-RPC)。
标准模式(默认)
用于本地开发和桌面客户端的传统stdio传输:
# Run with stdio transport
npm run serve:stdio
# Or simply (defaults to stdio)
npm run build && node build/index.jsHTTP模式(SSE+JSON-RPC)
用于web部署和远程访问的流式HTTP传输:
# Run with HTTP transport on port 3000
npm run serve:http
# Test with MCP Inspector
npm run inspect:httpHTTP传输公开了:
- SSE 终端 (获取):
http://localhost:3000/mcp-对于服务器发送的事件 - JSON-RPC端点 (职位):
http://localhost:3000/mcp-对于请求
环境变量
使用环境变量配置服务器行为:
| 变量 | 描述 | 默认值 |
|---|---|---|
STARTER_TRANSPORT | 运输方式: stdio 或 http | stdio |
PORT | HTTP服务器端口(仅限HTTP模式) | 3000 |
CORS_ORIGIN | CORS允许的源(仅限HTTP模式) | * |
配置示例
VS代码(mcp.json 或 .vscode/mcp.json)
{
"servers": {
"starter-stdio": {
"type": "stdio",
"command": "node",
"args": ["./build/index.js"]
},
"starter-http": {
"type": "http",
"url": "http://localhost:3000/mcp"
}
}
}克劳德桌面
添加到您的Claude Desktop配置中:
{
"mcpServers": {
"mcp-server-starter": {
"command": "node",
"args": ["/path/to/mcp-server-starter/build/index.js"]
}
}
}🐳 Docker支持
服务器包括Docker支持,便于部署:
Docker快速入门
# Build and run with Docker Compose
docker compose up --build
# Or run the pre-built image
docker run -p 3000:3000 ghcr.io/alexanderopalic/mcp-server-starter-ts:latestDocker配置
默认情况下,Docker容器以HTTP模式运行。用环境变量覆盖设置:
docker run -p 3000:3000 \
-e CORS_ORIGIN="https://example.com" \
-e PORT=3000 \
ghcr.io/alexanderopalic/mcp-server-starter-ts:latestDocker开发
使用开发配置文件进行热重新加载:
docker compose --profile dev up mcp-server-starter-dev这将挂载您的源代码,并在端口3001上启用实时重新加载。
📁 项目结构
mcp-server-starter-ts/
├── src/
│ ├── index.ts # Main entry point
│ ├── registry/ # Auto-loading system
│ │ ├── auto-loader.ts # Module auto-discovery
│ │ └── types.ts # TypeScript interfaces
│ ├── tools/ # Tool implementations
│ │ └── echo.ts # Example echo tool
│ ├── resources/ # Resource implementations (empty by default)
│ └── prompts/ # Prompt implementations (empty by default)
├── tests/ # Test files
├── _templates/ # Hygen generator templates
│ ├── tool/new/ # Tool generator
│ ├── prompt/new/ # Prompt generator
│ └── resource/new/ # Resource generator
├── build/ # Compiled JavaScript (generated)
├── mcp.json # MCP server configuration
├── package.json # Node.js dependencies
├── tsconfig.json # TypeScript configuration
├── eslint.config.js # ESLint configuration
└── README.md自动加载的工作原理
flowchart TB
A[Start] --> B[Scan]
B --> C[Register]
C --> D[Ready]\[!提示\] 只需将模块文件放入相应的目录即可(tools/,resources/,或prompts/)服务器启动时,它们将自动加载!
🛠️ 开发指南
使用代码生成器
\[!提示\] 创建新模块的最快方法是使用内置的Hygen生成器!
该项目包括用于快速创建模块的Hygen脚手架。每个生成器都创建实现文件和相应的测试文件。
生成新工具
npm run gen:tool系统将提示您:
- 名字:输入烤肉串大小写(例如。,
text-transform) - 描述:工具功能的简要说明
生成新提示
npm run gen:prompt系统将提示您:
- 名字:输入烤肉串大小写(例如。,
code-review) - 描述:提示模板的简要说明
生成新资源
npm run gen:resource系统将提示您:
- 名字:输入烤肉串大小写(例如。,
app-status) - 描述:资源简介
命令行用法
您也可以直接提供参数:
npx hygen tool new --name my-tool --description "Does something useful"
npx hygen prompt new --name my-prompt --description "Generates helpful text"
npx hygen resource new --name my-resource --description "Provides data"生成的文件:
- 实施:
src/{tools|prompts|resources}/[name].ts - 测试:
tests/[name].test.ts
自动加载器会自动发现并注册所有生成的模块,无需额外配置!
模块类型概述
graph TD
A[MCP] --> B[Tools]
A --> C[Resources]
A --> D[Prompts]添加新工具
\[!注意\] 工具是AI可以调用以执行特定操作或计算的函数。
工具允许您的MCP服务器执行操作。在中创建新文件 src/tools/:
// src/tools/calculate.ts
import { z } from "zod";
import type { RegisterableModule } from "../registry/types.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const calculateModule: RegisterableModule = {
type: "tool",
name: "calculate",
description: "Perform basic arithmetic calculations",
register(server: McpServer) {
server.tool(
"calculate",
"Perform basic arithmetic calculations",
{
operation: z.enum(["add", "subtract", "multiply", "divide"])
.describe("The arithmetic operation to perform"),
a: z.number().describe("First number"),
b: z.number().describe("Second number"),
},
(args) => {
let result: number;
switch (args.operation) {
case "add": result = args.a + args.b; break;
case "subtract": result = args.a - args.b; break;
case "multiply": result = args.a * args.b; break;
case "divide":
if (args.b === 0) throw new Error("Division by zero");
result = args.a / args.b;
break;
}
return {
content: [
{
type: "text",
text: `Result: ${result}`,
},
],
};
}
);
}
};
export default calculateModule;添加资源
\[!注意\] 资源提供对AI客户端可以使用的数据的只读访问。
资源提供客户端可以读取的数据。在中创建新文件 src/resources/:
// src/resources/config.ts
import type { RegisterableModule } from "../registry/types.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const configResource: RegisterableModule = {
type: "resource",
name: "config",
description: "Application configuration",
register(server: McpServer) {
server.resource(
"config://app/settings",
"Application settings",
"application/json",
async () => {
const settings = {
version: "1.0.0",
environment: process.env.NODE_ENV || "development",
features: {
autoSave: true,
darkMode: false,
}
};
return {
contents: [
{
uri: "config://app/settings",
mimeType: "application/json",
text: JSON.stringify(settings, null, 2),
}
]
};
}
);
}
};
export default configResource;添加提示
\[!注意\] 提示是可重用的模板,有助于构建与AI模型的交互。
提示是可重用的提示模板。在中创建新文件 src/prompts/:
// src/prompts/code-review.ts
import { z } from "zod";
import type { RegisterableModule } from "../registry/types.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const codeReviewPrompt: RegisterableModule = {
type: "prompt",
name: "code-review",
description: "Generate a code review prompt",
register(server: McpServer) {
server.prompt(
"code-review",
"Generate a comprehensive code review",
{
language: z.string().describe("Programming language"),
code: z.string().describe("Code to review"),
focus: z.string().optional().describe("Specific areas to focus on"),
},
(args) => {
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Please review the following ${args.language} code:
\`\`\`${args.language}
${args.code}
\`\`\`
${args.focus ? `Focus areas: ${args.focus}` : ""}
Please provide:
1. Code quality assessment
2. Potential bugs or issues
3. Performance considerations
4. Security concerns
5. Suggestions for improvement`,
},
},
],
};
}
);
}
};
export default codeReviewPrompt;🔍 MCP检验员测试
MCP检查器是测试服务器的强大工具:
npm run inspect此命令:
- 构建你的TypeScript代码
- 启动MCP检查器
- 连接到您的服务器
- 提供交互式UI以测试工具、资源和提示
互动式开发模式
为了快速测试和开发,请使用交互式开发模式:
npm run dev这将启动一个交互式REPL,您可以在其中直接粘贴JSON-RPC消息并实时查看响应。非常适合在开发过程中测试您的MCP服务器!
开发模式的JSON-RPC示例
一旦你跑了 npm run dev,您可以直接粘贴这些JSON-RPC消息。
\[!重要\] 需要MCP协议握手 MCP协议需要特定的初始化序列,然后才能使用工具、资源或提示: 1. 初始化请求 -客户端发送功能并接收服务器功能 1. 已初始化通知 -客户确认已准备就绪(预期无响应) 为什么需要初始化通知? - 它确认客户端已处理初始化响应并准备就绪 - 它支持双向通信-在此之后,服务器可以向客户端发送请求 - 没有它,服务器将不会发送通知(如tools/list_changed)或提出请求(如sampling/createMessage) - 这遵循类似于TCP握手的模式,确保双方在实际通信开始之前都已准备就绪 开发服务器不会自动执行此握手。您必须先手动发送这些消息。
1.初始化连接(必须先初始化!)
步骤1-发送初始化请求:
{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"1.0.0","capabilities":{},"clientInfo":{"name":"dev-client","version":"1.0.0"}},"id":1}步骤2-收到响应后,发送初始化通知:
{"jsonrpc":"2.0","method":"notifications/initialized"}现在服务器已经准备好处理请求了!
2.列出可用工具
{"jsonrpc":"2.0","method":"tools/list","params":{},"id":2}3.调用回声工具
{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"text":"Hello, MCP!"}},"id":3}4.列出资源
{"jsonrpc":"2.0","method":"resources/list","params":{},"id":4}5.阅读资源
{"jsonrpc":"2.0","method":"resources/read","params":{"uri":"timestamp://current/iso"},"id":5}6.列表提示
{"jsonrpc":"2.0","method":"prompts/list","params":{},"id":6}7.获得提示
{"jsonrpc":"2.0","method":"prompts/get","params":{"name":"generate-readme","arguments":{"projectName":"My Project","description":"A cool project"}},"id":7}\[!提示\] 使用开发模式: 1. 跑npm run dev启动交互式服务器 1. 复制上面的任何JSON-RPC消息并将其粘贴到终端中 1. 服务器将以语法高亮显示响应 1. 类型help对于可用命令或exit退出 重要提示: 始终先发送初始化消息以建立连接!
⚙️ 配置
TypeScript配置
该项目使用严格的TypeScript设置来实现最大的类型安全性。关键配置 tsconfig.json:
- 目标:ES2022
- 模块:ES2022,具有节点模块分辨率
- 严格模式已启用
- 用于调试的源代码映射
可用脚本
| 命令 | 描述 |
|---|---|
npm run build | 将TypeScript编译为JavaScript |
npm run lint | 运行ESLint检查 |
npm run lint:fix | 自动修复ESLint问题 |
npm run typecheck | 无建筑类型检查 |
npm test | 运行测试 |
npm run test:watch | 在监视模式下运行测试 |
npm run inspect | 启动MCP检查器 |
npm run dev | 互动式开发模式 |
npm run gen:tool | 使用测试生成新工具 |
npm run gen:prompt | 使用测试生成新提示 |
npm run gen:resource | 使用测试生成新资源 |
🔌 整合
MCP集成如何工作
sequenceDiagram
IDE->>MCP: Connect
MCP-->>IDE: Ready
IDE->>MCP: Call
MCP-->>IDE: Response使用VS代码(推荐)
\[!提示\] 使用MCP服务器的最简单方法是通过带有MCP支持扩展的VS Code。
- 构建您的服务器:
npm run build- 在VS Code中打开项目:
code .- 使用随附的
mcp.json配置:
该项目包括 mcp.json VS Code MCP扩展可以用来自动启动服务器的文件:
{
"servers": {
"starter": {
"type": "stdio",
"command": "node",
"args": [
"./build/index.js"
]
}
}
}- 安装VS Code MCP扩展:
- 打开VS代码扩展(macOS上的X,Windows/Linux上的Ctrl+Shift+X) - 搜索“MCP”或“模型上下文协议” - 安装MCP兼容扩展 - 扩展程序将自动检测并使用您的 mcp.json 配置
\[!注意\] 这 mcp.json 文件告诉VS Code如何启动MCP服务器。当您使用此文件打开项目时,兼容的扩展名将自动将其识别为MCP服务器项目。使用克劳德桌面
\[!重要\] 请确保在配置Claude Desktop之前构建服务器。服务器必须编译为JavaScript。
- 构建您的服务器:
npm run build- 添加到Claude桌面配置:
> \[!警告\] > 配置文件位置因操作系统而异: > > - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json > - 视窗: %APPDATA%\Claude\claude_desktop_config.json > - Linux: ~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["/path/to/your/server/build/index.js"]
}
}
}- 重新启动克劳德桌面
\[!小心\] 在配置中始终使用绝对路径。相对路径可能无法正常工作。
使用自定义客户端
使用MCP SDK连接到您的服务器:
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const transport = new StdioClientTransport({
command: "node",
args: ["/path/to/your/server/build/index.js"],
});
const client = new Client({
name: "my-client",
version: "1.0.0",
}, { capabilities: {} });
await client.connect(transport);🤝 贡献
欢迎投稿!请随时提交拉取请求。对于重大更改,请先打开一个问题来讨论您想要更改的内容。
- 分叉存储库
- 创建功能分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add some AmazingFeature') - 推到分支(
git push origin feature/AmazingFeature) - 打开拉取请求
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🔗 资源
🐛 故障排除
\[!警告\] 常见问题及其解决方案:
| 问题 | 解决方案 |
|---|---|
Cannot find module 错误 | 确保您已运行 npm run build 启动服务器之前 |
| 服务器未连接 | 检查配置中是否使用了绝对路径 |
| 工具未加载 | 验证您的模块导出是否与 RegisterableModule 接口 |
| TypeScript错误 | 运行 npm run typecheck 识别类型问题 |
| 自动加载失败 | 检查文件名并确保模块位于正确的目录中 |
发展
- ✅ 类型安全:使用TypeScript的严格模式尽早捕获错误
- ✅ 模块化设计:将工具、资源和提示集中在单一职责上
- ✅ 错误处理:始终优雅地处理错误并提供有意义的消息
- ✅ 验证:使用Zod模式验证所有输入
- ✅ 测试:编写关键功能的测试
______________________________________________________________________
内置于❤️ 对于MCP社区
