第 1 章:MCP协议基础入门
2025/9/1大约 7 分钟
第 1 章:MCP协议基础入门
学习目标
- 理解MCP协议的基本概念和设计理念
- 掌握MCP协议的架构和核心组件
- 了解MCP与传统API的区别和优势
- 熟悉MCP的应用场景和生态系统
1.1 MCP协议概述
什么是MCP协议
Model Context Protocol (MCP) 是一个开放标准协议,旨在为AI模型提供安全、标准化的方式来连接外部数据源和工具。MCP由Anthropic开发,解决了AI应用中上下文获取和工具调用的标准化问题。
MCP的核心设计理念
// MCP的核心设计原则示例
interface MCPDesignPrinciples {
// 1. 安全第一 - 所有操作都需要明确授权
security: 'explicit-permissions';
// 2. 标准化 - 统一的接口和协议
standardization: 'unified-interface';
// 3. 可扩展性 - 支持插件和扩展
extensibility: 'plugin-architecture';
// 4. 类型安全 - 强类型定义
typeSafety: 'schema-validation';
}
// MCP的核心价值主张
const mcpValueProposition = {
forDevelopers: [
'统一的开发接口',
'丰富的生态系统',
'强大的安全机制',
'易于集成和扩展'
],
forAIModels: [
'标准化的工具访问',
'结构化的数据获取',
'安全的外部交互',
'动态的上下文更新'
],
forUsers: [
'更强大的AI能力',
'安全可靠的服务',
'丰富的应用场景',
'一致的用户体验'
]
};
1.2 MCP协议架构
核心组件架构
// MCP协议的核心架构
interface MCPArchitecture {
// 客户端 - AI模型或应用
client: {
role: 'consumer';
capabilities: ['call-tools', 'read-resources', 'use-prompts'];
responsibilities: ['authenticate', 'make-requests', 'handle-responses'];
};
// 服务器 - 提供功能和数据
server: {
role: 'provider';
capabilities: ['expose-tools', 'serve-resources', 'provide-prompts'];
responsibilities: ['validate-requests', 'execute-operations', 'return-results'];
};
// 传输层 - 通信协议
transport: {
protocol: 'JSON-RPC 2.0';
methods: ['stdio', 'websocket', 'http'];
features: ['bidirectional', 'real-time', 'streaming'];
};
}
// MCP消息流示例
class MCPMessageFlow {
// 初始化握手
async initialize(): Promise<void> {
const initRequest = {
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {
tools: {},
resources: { subscribe: true },
prompts: {}
},
clientInfo: {
name: 'example-client',
version: '1.0.0'
}
}
};
console.log('发送初始化请求:', JSON.stringify(initRequest, null, 2));
}
// 工具调用
async callTool(toolName: string, args: any): Promise<any> {
const toolRequest = {
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: toolName,
arguments: args
}
};
console.log('调用工具:', JSON.stringify(toolRequest, null, 2));
// 模拟响应
return {
jsonrpc: '2.0',
id: 2,
result: {
content: [
{
type: 'text',
text: '工具执行成功'
}
]
}
};
}
}
MCP的三大核心组件
// 1. Tools - 工具系统
interface MCPTool {
name: string;
description: string;
inputSchema: {
type: 'object';
properties: Record<string, any>;
required?: string[];
};
}
// 工具示例:文件读取
const fileReadTool: MCPTool = {
name: 'read_file',
description: '读取指定路径的文件内容',
inputSchema: {
type: 'object',
properties: {
path: {
type: 'string',
description: '文件路径'
},
encoding: {
type: 'string',
description: '文件编码,默认为utf-8',
default: 'utf-8'
}
},
required: ['path']
}
};
// 2. Resources - 资源系统
interface MCPResource {
uri: string;
name: string;
description?: string;
mimeType?: string;
}
// 资源示例:配置文件
const configResource: MCPResource = {
uri: 'config://app.json',
name: 'Application Configuration',
description: '应用程序的配置信息',
mimeType: 'application/json'
};
// 3. Prompts - 提示模板系统
interface MCPPrompt {
name: string;
description?: string;
arguments?: Array<{
name: string;
description: string;
required?: boolean;
}>;
}
// 提示模板示例:代码审查
const codeReviewPrompt: MCPPrompt = {
name: 'code_review',
description: '代码审查提示模板',
arguments: [
{
name: 'code',
description: '要审查的代码内容',
required: true
},
{
name: 'language',
description: '编程语言',
required: false
}
]
};
1.3 MCP与传统API的区别
传统API vs MCP协议对比
// 传统REST API方式
class TraditionalAPI {
async getUser(id: string) {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
async createUser(userData: any) {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
return response.json();
}
}
// MCP协议方式
class MCPProtocol {
// 通过工具调用实现用户操作
async getUser(id: string) {
return await this.callTool('get_user', { id });
}
async createUser(userData: any) {
return await this.callTool('create_user', userData);
}
// 通过资源获取数据
async getUserResource(id: string) {
return await this.readResource(`user://${id}`);
}
private async callTool(name: string, args: any) {
// MCP工具调用逻辑
return { success: true, data: {} };
}
private async readResource(uri: string) {
// MCP资源读取逻辑
return { content: 'resource data' };
}
}
// 主要区别对比
const comparisonTable = {
aspects: {
purpose: {
traditional: '通用的网络服务接口',
mcp: '专为AI模型设计的上下文协议'
},
dataFlow: {
traditional: '请求-响应模式',
mcp: '双向通信,支持订阅和通知'
},
security: {
traditional: 'HTTP认证、API密钥',
mcp: '明确的权限模型和安全沙箱'
},
typeSystem: {
traditional: '通常基于JSON Schema或OpenAPI',
mcp: '内建的强类型系统和验证'
},
extensibility: {
traditional: '版本控制和向后兼容',
mcp: '插件架构和动态扩展'
}
}
};
1.4 MCP的应用场景
主要应用场景
// 1. 文件系统集成
class FileSystemMCPServer {
tools = [
{
name: 'read_file',
description: '读取文件内容',
handler: async (args: { path: string }) => {
// 实际的文件读取逻辑
return { content: 'file content' };
}
},
{
name: 'write_file',
description: '写入文件',
handler: async (args: { path: string; content: string }) => {
// 实际的文件写入逻辑
return { success: true };
}
}
];
}
// 2. 数据库集成
class DatabaseMCPServer {
tools = [
{
name: 'query_database',
description: '执行数据库查询',
handler: async (args: { sql: string; params?: any[] }) => {
// 数据库查询逻辑
return { rows: [], count: 0 };
}
}
];
resources = [
{
uri: 'db://users/schema',
name: 'Users Table Schema',
handler: async () => ({
content: JSON.stringify({
table: 'users',
columns: ['id', 'name', 'email']
})
})
}
];
}
// 3. API代理服务
class APIProxyMCPServer {
tools = [
{
name: 'call_external_api',
description: '调用外部API',
handler: async (args: { endpoint: string; method: string; data?: any }) => {
// API调用逻辑
return { response: 'api response' };
}
}
];
}
// 4. 内容管理系统
class CMSMCPServer {
resources = [
{
uri: 'cms://articles',
name: 'Articles List',
handler: async () => ({
content: JSON.stringify([
{ id: 1, title: 'First Article' },
{ id: 2, title: 'Second Article' }
])
})
}
];
prompts = [
{
name: 'generate_article',
description: '生成文章内容的提示模板',
handler: async (args: { topic: string; style: string }) => ({
messages: [
{
role: 'user',
content: {
type: 'text',
text: `请写一篇关于${args.topic}的${args.style}风格文章`
}
}
]
})
}
];
}
1.5 MCP生态系统
MCP技术栈
// MCP技术栈概览
interface MCPEcosystem {
// 核心协议
protocol: {
specification: 'MCP Protocol Specification v1.0';
transport: ['stdio', 'websocket', 'http'];
messageFormat: 'JSON-RPC 2.0';
};
// 官方SDK
officialSDKs: {
typescript: '@modelcontextprotocol/sdk';
python: 'mcp';
// 更多语言支持正在开发中
};
// 开发工具
devTools: {
inspector: 'MCP Inspector';
testing: 'MCP Test Suite';
debugging: 'MCP Debug Tools';
};
// 社区生态
community: {
servers: 'Community MCP Servers';
tools: 'Third-party Tools';
examples: 'Code Examples and Templates';
};
}
// MCP服务器示例目录
const mcpServerExamples = {
filesystem: {
name: 'File System Server',
description: '提供文件操作能力',
features: ['read', 'write', 'list', 'delete']
},
database: {
name: 'Database Server',
description: '数据库操作接口',
features: ['query', 'insert', 'update', 'schema']
},
web: {
name: 'Web Scraping Server',
description: '网页内容抓取',
features: ['fetch', 'parse', 'search', 'monitor']
},
git: {
name: 'Git Server',
description: 'Git版本控制操作',
features: ['clone', 'commit', 'push', 'status']
},
memory: {
name: 'Memory Server',
description: '持久化记忆系统',
features: ['store', 'retrieve', 'search', 'organize']
}
};
1.6 MCP的优势和特点
核心优势
// MCP协议的核心优势
class MCPAdvantages {
// 1. 安全性
security = {
explicitPermissions: '每个操作都需要明确授权',
sandboxExecution: '工具在安全沙箱中执行',
inputValidation: '严格的输入验证和类型检查',
auditTrail: '完整的操作审计日志'
};
// 2. 标准化
standardization = {
unifiedInterface: '统一的协议接口',
consistentAPI: '一致的API设计',
interoperability: '跨平台和跨语言兼容',
versionControl: '协议版本管理'
};
// 3. 扩展性
extensibility = {
pluginArchitecture: '插件化架构设计',
customTools: '自定义工具开发',
dynamicLoading: '动态加载和卸载',
protocolExtensions: '协议扩展机制'
};
// 4. 开发体验
developerExperience = {
typeScript: '完整的TypeScript支持',
documentation: '丰富的文档和示例',
tooling: '强大的开发工具链',
community: '活跃的社区支持'
};
}
// 实际应用效果对比
const impactComparison = {
beforeMCP: {
challenges: [
'每个AI应用都需要自定义集成',
'缺乏统一的安全标准',
'工具和资源访问不一致',
'开发和维护成本高'
]
},
withMCP: {
benefits: [
'一次开发,多处使用',
'统一的安全和权限模型',
'标准化的接口和协议',
'丰富的生态系统支持'
]
}
};
1.7 快速上手示例
最简单的MCP Server
// 一个最简单的MCP Server示例
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
// 创建MCP服务器
const server = new Server(
{
name: 'hello-world-server',
version: '1.0.0'
},
{
capabilities: {
tools: {},
resources: {},
prompts: {}
}
}
);
// 添加一个简单的工具
server.setRequestHandler(
'tools/list',
async () => ({
tools: [
{
name: 'say_hello',
description: '说hello的简单工具',
inputSchema: {
type: 'object',
properties: {
name: {
type: 'string',
description: '要问候的名字'
}
}
}
}
]
})
);
// 实现工具调用
server.setRequestHandler(
'tools/call',
async (request) => {
if (request.params.name === 'say_hello') {
const name = request.params.arguments?.name || 'World';
return {
content: [
{
type: 'text',
text: `Hello, ${name}!`
}
]
};
}
throw new Error(`Unknown tool: ${request.params.name}`);
}
);
// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);
console.log('Hello World MCP Server is running!');
项目结构示例
hello-world-mcp-server/
├── package.json
├── tsconfig.json
├── src/
│ ├── index.ts # 主入口文件
│ ├── tools/ # 工具定义
│ │ └── hello.ts
│ ├── resources/ # 资源定义
│ │ └── static.ts
│ └── prompts/ # 提示模板
│ └── greeting.ts
├── dist/ # 编译输出
├── tests/ # 测试文件
└── README.md # 项目说明
小结
MCP协议为AI应用开发带来了标准化、安全性和扩展性的解决方案。通过学习本章,我们了解了:
- MCP协议的核心概念:为AI模型提供标准化的外部交互能力
- 架构设计:客户端-服务器模式,基于JSON-RPC 2.0
- 三大核心组件:Tools(工具)、Resources(资源)、Prompts(提示模板)
- 与传统API的区别:专为AI设计,更强的安全性和类型系统
- 应用场景:文件系统、数据库、API代理、内容管理等
- 生态系统:SDK、开发工具、社区资源
接下来我们将学习如何搭建MCP Server开发环境,开始实际的开发实践。