
用户提问→Claude Desktop(Host)→Claude模型→判断需要文件信息→激活MCP Client连接→文件系统MCP Server→执行扫描操作→返回结果→Claude模型生成回答→在Claude Desktop显示答案。

传统API调用方式

Function Calling 实现

MCP 标准化实现

MCP示例代码
1. MCP客户端示例
import { MCPClient } from '@anthropic/mcp-client';
// 初始化MCP客户端
const client = new MCPClient({
serverUrl: 'https://example-mcp-server.com',
authentication: {
type: 'bearer',
token: 'YOUR_ACCESS_TOKEN'
}
});
// 连接到MCP服务器
await client.connect();
// 获取资源
const fileContent = await client.getResource('file:///data/example.txt');
// 调用工具
const weatherData = await client.callTool('getWeather', {
location: 'Beijing',
units: 'celsius'
});
// 使用提示模板
const promptTemplate = await client.getPrompt('summarize');
const filledPrompt = promptTemplate.fill({
text: fileContent,
maxLength: 200
});
// 与LLM一起使用获取的信息
const llmResponse = await model.complete({
prompt: filledPrompt,
contextData: {
weather: weatherData
}
});
2. MCP服务器示例
import { MCPServer } from '@anthropic/mcp-server';
import fs from 'fs/promises';
// 创建MCP服务器实例
const server = new MCPServer({
port: 3000,
authentication: {
type: 'bearer',
validTokens: ['YOUR_ACCESS_TOKEN']
}
});
// 注册资源处理器
server.registerResourceHandler('file', async (path) => {
try {
const content = await fs.readFile(path, 'utf-8');
return {
type: 'text/plain',
content
};
} catch (error) {
throw new Error(`无法读取文件: ${error.message}`);
}
});
// 注册工具
server.registerTool('getWeather', async (params) => {
const { location, units } = params;
// 调用第三方天气API
const response = await fetch(`https://api.weather.com/current?location=${location}&units=${units}`);
const data = await response.json();
return data;
});
// 注册提示模板
server.registerPrompt('summarize', {
template: '请总结以下文本,最多使用{{maxLength}}个字:\n\n{{text}}',
parameters: ['text', 'maxLength']
});
// 启动服务器
server.start().then(() => {
console.log('MCP服务器已启动在端口3000');
});
3. 完整集成示例
import { Claude } from '@anthropic/claude-sdk';
import { MCPClient } from '@anthropic/mcp-client';
async function main() {
// 初始化Claude模型
const claude = new Claude({
apiKey: 'YOUR_CLAUDE_API_KEY'
});
// 初始化MCP客户端
const mcpClient = new MCPClient({
serverUrl: 'https://example-mcp-server.com',
authentication: {
type: 'bearer',
token: 'YOUR_ACCESS_TOKEN'
}
});
// 连接到MCP服务器
await mcpClient.connect();
// 用户查询
const userQuery = '北京今天的天气情况如何?我需要带伞吗?';
// 调用工具获取实时天气数据
const weatherData = await mcpClient.callTool('getWeather', {
location: '北京',
units: 'celsius'
});
// 构建提示
const systemPrompt = `你是一个助手,可以提供天气信息。
以下是当前天气数据:${JSON.stringify(weatherData, null, 2)}`;
// 生成回答
const response = await claude.complete({
system: systemPrompt,
messages: [
{ role: 'user', content: userQuery }
],
max_tokens: 300
});
console.log('Claude的回答:', response.content);
// 断开MCP连接
await mcpClient.disconnect();
}
main().catch(console.error);

991

被折叠的 条评论
为什么被折叠?



