MCP TypeScript沸腾板
用于在TypeScript中创建模型上下文协议(MCP)服务器和客户端的完整样板。
先决条件
- Node.js 18+(推荐:最新LTS)
- npm或yarn包管理器
快速开始
- 克隆或下载此样板
git clone https://github.com/RishabhKodes/tsMCP.git
cd tsMCP- 安装依赖项
npm install- 构建项目
npm run build- 运行服务器
npm run start:server- 与客户进行测试 (在新航站楼)
npm run start:client项目结构
src/
├── server.ts # MCP server implementation
├── client.ts # Example MCP client
└── types/ # Custom type definitions (if needed)
build/ # Compiled JavaScript output
package.json # Dependencies and scripts
tsconfig.json # TypeScript configuration
README.md # This file可用脚本
npm run build-将TypeScript编译为JavaScriptnpm run start:server-启动MCP服务器npm run start:client-运行示例客户端npm run dev:server-在一个命令中构建和运行服务器npm run dev:client-在一个命令中构建和运行客户端npm run clean-删除构建目录
服务器功能
示例服务器包括:
工具
- 计算 -执行基本的算术运算(加、减、乘、除)
- 回声 -回显提供的文本
- get_memory -从内存存储中检索值
- set_memory -将值存储在内存中
资源
- memory://config -配置设置
- memory://data -示例应用程序数据
服务器实现
该服务器使用官方MCP SDK构建,包括:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const server = new Server({
name: 'tsMCP',
version: '1.0.0',
}, {
capabilities: {
resources: {},
tools: {},
},
});添加新工具
要添加新工具,请实现以下处理程序函数:
- 列出工具 在……里面
ListToolsRequestSchema处理程序:
{
name: 'my_new_tool',
description: 'Description of what the tool does',
inputSchema: {
type: 'object',
properties: {
input: { type: 'string', description: 'Input parameter' }
},
required: ['input']
}
}- 处理工具执行 在……里面
CallToolRequestSchema处理程序:
case 'my_new_tool': {
const input = args?.input;
// Your tool logic here
return {
content: [{
type: 'text',
text: `Result: ${result}`
}]
};
}添加新资源
- 列出资源 在……里面
ListResourcesRequestSchema处理程序:
{
uri: 'custom://my-resource',
mimeType: 'application/json',
name: 'My Resource',
description: 'Description of the resource'
}- 处理资源读取 在……里面
ReadResourceRequestSchema处理程序:
if (uri === 'custom://my-resource') {
return {
contents: [{
uri,
mimeType: 'application/json',
text: JSON.stringify(myData, null, 2)
}]
};
}客户端实施
示例客户端演示了如何:
- 连接到MCP服务器
- 列出可用的工具和资源
- 使用参数调用工具
- 阅读资源
- 处理错误和清理
与AI应用程序集成
克劳德桌面
要将MCP服务器与Claude Desktop集成,请将此配置添加到您的 claude_desktop_config.json:
{
"mcpServers": {
"tsMCP": {
"command": "node",
"args": ["/path/to/your/project/build/server.js"]
}
}
}光标
要将MCP服务器与Cursor集成,请将此配置添加到MCP设置中:
{
"mcpServers": {
"tsMCP": {
"command": "node",
"args": ["/path/to/your/project/build/server.js"]
}
}
}其它应用
服务器通过stdio进行通信,使其与支持stdio传输的任何MCP客户端兼容。
错误处理
样板包括全面的错误处理:
- 使用Zod模式进行输入验证
- 正确的MCP错误代码和消息
- 关机时清理得很好
- 类型安全参数处理
环境变量
创建一个 .env 环境特定配置文件:
# Server configuration
MCP_SERVER_NAME=my-custom-server
MCP_SERVER_VERSION=1.0.0
# Application-specific settings
LOG_LEVEL=info高级用法
定制运输
您可以在stdio之外实现自定义传输:
import { WebSocketServerTransport } from '@modelcontextprotocol/sdk/server/websocket.js';
const transport = new WebSocketServerTransport({
port: 8080
});中间件和插件
使用自定义中间件扩展服务器:
server.setRequestHandler(MyCustomRequestSchema, async (request) => {
// Custom handling logic
});