MCP和FunctionCall的关系

AI 时代程序员必备技能

Codex、Claude Code、Cursor、Hermes Agent、OpenClaw等工程化实战专栏 ,讲透 AI 如何接管脏活累活

用户提问→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);

 

AI 时代程序员必备技能

Codex、Claude Code、Cursor、Hermes Agent、OpenClaw等工程化实战专栏 ,讲透 AI 如何接管脏活累活

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值