Model Context Protocol Resources & Guides
通过我在学习这个新协议时构建的实用指南、客户端和服务器来探索模型上下文协议(MCP)。
什么是MCP?
模型上下文协议(MCP)是一种标准化通信协议,使大语言模型(LLMs)能够与外部系统交互,提供:
- 一致接口:标准化访问工具和资源
- 增强功能:与数据库、API和本地系统交互
- 安全控制:结构化访问和内置验证
快速开始
1. 克隆模板仓库
git clone https://github.com/cyanheads/mcp-ts-template.git
cd mcp-ts-template
npm install
npm run build
2. 基本架构
MCP系统包含三层:
- API层: 处理MCP协议、验证和数据清理
- 核心组件: 配置、日志、错误处理和服务器逻辑
- 实现层: 你的工具、资源和实用功能
3. 创建你的第一个MCP工具
import { McpTool } from '@modelcontextprotocol/sdk';
const calculatorTool: McpTool = {
name: 'calculator',
description: '执行基本数学计算',
parameters: {
type: 'object',
properties: {
operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] },
a: { type: 'number' },
b: { type: 'number' }
},
required: ['operation', 'a', 'b']
},
handler: async (params) => {
const { operation, a, b } = params;
switch (operation) {
case 'add': return { result: a + b };
case 'subtract': return { result: a - b };
case 'multiply': return { result: a * b };
case 'divide':
if (b === 0) throw new Error('Division by zero');
return { result: a / b };
default:
throw new Error('Invalid operation');
}
}
};
4. 注册并启动服务器
import { McpServer } from '@modelcontextprotocol/sdk';
const server = new McpServer({
tools: [calculatorTool],
port: 3000
});
server.start().then(() => {
console.log('MCP服务器运行在 http://localhost:3000');
});
5. 在客户端使用MCP服务器
// 在支持MCP的AI客户端中添加服务器URL
const serverURL = "http://localhost:3000";
// 使用工具示例: {{calculator(operation="add", a=5, b=3)}}
可用的MCP服务器
- Atlas: 文件系统导航和操作
- Toolkit: 实用工具集合(日期、网络请求等)
- Mentor: AI编码辅助工具
- Obsidian: 知识库集成
- Git/GitHub: 代码版本控制集成
资源
进阶学习
完整的MCP客户端开发指南和MCP服务器开发指南可提供更详细的实现信息和最佳实践。