TypeScript MCP入门套件🚀
一个功能齐全的入门模板,用于使用TypeScript构建模型上下文协议(MCP)服务器,支持HTTP/SSE和stdio传输,与AI应用程序无缝集成。
✨ 特性
- TypeScript就绪:完全支持TypeScript,具有严格的类型检查
- 苏格兰和南方能源公司运输:使用服务器发送事件进行实时双向通信
- Zod验证:运行时类型验证和架构解析
- RESTful集成:使用REST国家/地区API的示例实现
- 会话管理:用于多个并发连接的内置会话处理
- CORS支持:配置了跨源资源共享
- 热重载:开发服务器
tsx用于即时反馈
🏗️ 建筑
src/
├── index.ts # HTTP server & SSE transport setup
├── server.ts # MCP server configuration & tool registration
├── types.ts # TypeScript type definitions
├── api/ # External API integrations
│ └── fetchRestCountries.ts
├── parser/ # Zod schema validators
│ └── index.ts
└── resources/ # MCP resources configurations
│ └── index.ts
└── tools/ # MCP tool configurations
└── index.ts🚀 快速开始
- 克隆和安装依赖关系:
pnpm install- 启动开发服务器:
pnpm start- 服务器终结点:
- SSE流: GET http://localhost:8000/mcp - 消息终结点: POST http://localhost:8000/mcp/messages?sessionId={id}
🔧 配置
环境变量
创建一个 .env 文件:
PORT=8000 # Optional, defaults to 8000添加新工具
- 定义工具配置 在
src/tools/index.ts:
export const myNewToolConfig = (): TRegisterTool => ({
title: "My New Tool",
description: "Description of what it does",
inputSchema: {
param1: z.string().describe("Parameter description")
},
outputSchema: {
result: z.any()
}
});- 注册该工具 在
src/server.ts:
server.registerTool(
"my_new_tool",
myNewToolConfig(),
async ({ param1 }) => {
// Tool implementation
return {
content: [{ type: "text", text: "Result" }],
structuredContent: { result: "data" }
};
}
);🛠️ 内置示例:国家数据工具
启动器包括一个获取国家信息的完整示例:
- 工具名称:
get_country_data - 输入:
countryName(字符串) - API: REST国家/地区API
- 验证:Zod模式
src/parser/index.ts
用途:
// The tool accepts a country name and returns detailed country data
{ "countryName": "Germany" }🔍 关键组件
McpServer
核心MCP服务器设置,包括工具注册和功能配置。
SSEServerTransport
处理服务器发送事件传输层,用于客户端和服务器之间的实时通信。
StdioTransport
处理无法使用SSEServerTransport的客户端AI应用程序
SessionRecord
用于处理多个并发连接的类型安全会话管理。
fetchRestCountries
API与错误处理和响应格式的集成示例。
📊 传输层
此实现使用 SSE(服务器发送事件) 代替stdio传输:
- ✅ 实时:即时双向通信
- ✅ 网络兼容:与web客户端无缝协作
- ✅ 基于会话:支持多个并发连接
- ✅ 错误处理:强大的连接管理
🧪 发展
类型安全
所有模式都使用验证 萨德 与TypeScript集成:
import z from "zod";
export const mySchema = z.object({
field: z.string().describe("Field description")
});添加外部API
遵循中的模式 src/api/fetchRestCountries.ts:
const fetchMyAPI = async (param: string) => {
try {
const res = await fetch(`https://api.example.com/${param}`);
return await res.json();
} catch (err) {
console.error(`API Error: ${err}`);
return "Error message";
}
};📦 依赖项
- @模型上下文协议/sdk:核心MCP功能
- 黄道带:运行时类型验证
- TSX:TypeScript执行引擎
- Dotenv。:环境变量管理
🌐 使用AI客户端
此MCP服务器支持两种传输方式:
选项1:HTTP/SSE传输(通过ngrok用于ChatGPT)
- 启动HTTP服务器:
pnpm start- 使用ngrok暴露您的服务器:
ngrok http 8000- 配置ChatGPT:
- 复制ngrok HTTPS URL(例如。, https://abc123.ngrok.io) - 在ChatGPT中,使用SSE端点添加MCP服务器: - SSE流: https://abc123.ngrok.io/mcp - 消息终结点: https://abc123.ngrok.io/mcp/messages
选项2:Stdio传输(适用于Claude桌面和本地AI应用程序)
- 配置Claude桌面 (或其他本地AI应用程序):
编辑您的 claude_desktop_config.json 文件:
{
"mcpServers": {
"ts_mcp_starter": {
"command": "C:\\Users\\YOUR_USERNAME\\Development\\mcp\\YOUR_MCP_FOLDER\\node_modules\\.bin\\tsx.cmd",
"args": ["C:\\Users\\YOUR_USERNAME\\Development\\mcp\\YOUR_MCP_FOLDER\\src\\stdio.ts"],
"cwd": "C:\\Users\\YOUR_USERNAME\\Development\\mcp\\YOUR_MCP_FOLDER"
}
}
}重要提示: 替换 YOUR_USERNAME 使用您的实际用户名,并根据需要调整路径。
对于macOS/Linux:
{
"mcpServers": {
"ts_mcp_starter": {
"command": "node",
"args": ["/absolute/path/to/YOUR_MCP_FOLDER/node_modules/.bin/tsx", "src/stdio.ts"],
"cwd": "/absolute/path/to/YOUR_MCP_FOLDER"
}
}
}- 重新启动克劳德桌面 加载MCP服务器
- 验证连接:
- 检查Claude Desktop日志以确保连接成功 - 服务器将向stderr输出:“MCP服务器在stdio上运行”
我应该使用哪种交通工具?
| 运输 | 用例 | 优点 | 缺点 |
|---|---|---|---|
| HTTP/SSE | ChatGPT、web客户端、远程访问 | 多个并发连接、web兼容、易于调试 | 需要ngrok进行ChatGPT和端口管理 |
| 工作室 | Claude Desktop,本地AI应用程序 | 直接集成,无需网络设置,安全 | 单连接,仅限本地 |
🚀 生产部署
在生产环境中构建和运行:
# Build the project
npx tsc
# Run the built server
node build/index.js对于容器化部署,服务器在配置的端口上运行,并接受MCP通信的HTTP连接。
______________________________________________________________________
准备好构建下一个MCP服务器了吗? 这个入门套件提供了使用现代TypeScript工具创建健壮、类型安全的MCP应用程序所需的一切! 🎉
