当前位置: 首页 > article >正文

MCP-代码解读TypeScript版本

MCP-代码解读TypeScript版本

文章目录

  • MCP-代码解读TypeScript版本
    • 1-参考网址
    • 2-TypeScript代码
    • 3-代码解读
      • 1-[非重点]定义函数
      • 2-[非重点]定义工具说明
      • 3-[重点]运行MCP服务

1-参考网址

  • B站视频参考

2-TypeScript代码

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// 定义天气数据类型
interface WeatherInfo {
    temperature: number;
    condition: string;
    humidity: number;
    windSpeed: number;
}

// 模拟城市天气数据
const weatherData = {
    "北京": { temperature: 20, condition: "晴朗", humidity: 45, windSpeed: 8 },
    "上海": { temperature: 25, condition: "多云", humidity: 60, windSpeed: 12 },
    "广州": { temperature: 28, condition: "小雨", humidity: 75, windSpeed: 6 },
    "深圳": { temperature: 27, condition: "阴天", humidity: 70, windSpeed: 10 },
    "杭州": { temperature: 22, condition: "多云", humidity: 65, windSpeed: 9 }
} as const satisfies Record<string, WeatherInfo>;

// 模拟函数调用和数据返回
function getWeatherInfo(city: string): { content: Array<{ type: "text"; text: string }> } {
    const weather = weatherData[city as keyof typeof weatherData];
    
    if (!weather) {
        const availableCities = Object.keys(weatherData).join("、");
        return {
            content: [{
                type: "text",
                text: `未找到城市 ${city} 的天气信息。支持的城市包括:${availableCities}`
            }]
        };
    }

    // 模板字符串格式
    const weatherText = `${city}的天气信息:
        温度:${weather.temperature}°C
        天气:${weather.condition}
        湿度:${weather.humidity}%
        风速:${weather.windSpeed}m/s`.replace(/^\s+/gm, "");  // 使用正则移除行首空格
    return {
        content: [{
            type: "text",
            text: weatherText
        }]
    };
}

// 创建 MCP 服务器
const server = new McpServer({
    name: "weather-server",
    version: "1.0.0",
    description: "城市天气信息服务"
});

// 注册天气查询工具
server.tool(
    "get-weather",
    "获取指定城市的天气信息",
    {
        city: z.string().describe("城市名称(如:北京、上海、广州、深圳)")
    },
    async ({ city }) => {
        return getWeatherInfo(city);
    }
);

// 启动服务器
async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
}

main().catch((error) => {
    console.error("初始化失败:", error);
    process.exit(1);
});

3-代码解读

1-[非重点]定义函数

这个地方填写你的业务逻辑:函数/API/数据库等业务逻辑

// 定义天气数据类型
interface WeatherInfo {
    temperature: number;
    condition: string;
    humidity: number;
    windSpeed: number;
}

// 模拟城市天气数据
const weatherData = {
    "北京": { temperature: 20, condition: "晴朗", humidity: 45, windSpeed: 8 },
    "上海": { temperature: 25, condition: "多云", humidity: 60, windSpeed: 12 },
    "广州": { temperature: 28, condition: "小雨", humidity: 75, windSpeed: 6 },
    "深圳": { temperature: 27, condition: "阴天", humidity: 70, windSpeed: 10 },
    "杭州": { temperature: 22, condition: "多云", humidity: 65, windSpeed: 9 }
} as const satisfies Record<string, WeatherInfo>;

// 模拟函数调用和数据返回
function getWeatherInfo(city: string): { content: Array<{ type: "text"; text: string }> } {
    const weather = weatherData[city as keyof typeof weatherData];
    
    if (!weather) {
        const availableCities = Object.keys(weatherData).join("、");
        return {
            content: [{
                type: "text",
                text: `未找到城市 ${city} 的天气信息。支持的城市包括:${availableCities}`
            }]
        };
    }

    // 模板字符串格式
    const weatherText = `${city}的天气信息:
        温度:${weather.temperature}°C
        天气:${weather.condition}
        湿度:${weather.humidity}%
        风速:${weather.windSpeed}m/s`.replace(/^\s+/gm, "");  // 使用正则移除行首空格
    return {
        content: [{
            type: "text",
            text: weatherText
        }]
    };
}

2-[非重点]定义工具说明

这个过程有点类似FunctionCall的【函数描述】+【JsonSchema】定义的过程

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

// 创建 MCP 服务器
const server = new McpServer({
    name: "weather-server",
    version: "1.0.0",
    description: "城市天气信息服务"
});

// 注册天气查询工具
server.tool(
    "get-weather",
    "获取指定城市的天气信息",
    {
        city: z.string().describe("城市名称(如:北京、上海、广州、深圳)")
    },
    async ({ city }) => {
        return getWeatherInfo(city);
    }
);

3-[重点]运行MCP服务

import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

// 启动服务器
async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("天气服务器已启动");
}

main().catch((error) => {
    console.error("服务器启动失败:", error);
    process.exit(1);
});

http://www.kler.cn/a/580835.html

相关文章:

  • (二分 数学推导区间 两个数组的距离值)leetcode 1385
  • 【第21节】C++设计模式(行为模式)-Chain of Responsibility(责任链)模式
  • Redis7——进阶篇(五)
  • Consensus 大会全观察:政策、生态与技术交汇,香港能否抢占 Web3 先机?
  • 【网络编程】WSAAsyncSelect 模型
  • redis 用来实现排行榜的功能
  • Qt 中实现自定义控件子类化
  • scala传递匿名函数简化的原则
  • Android 低功率蓝牙之BluetoothGattCharacteristic详解
  • linux下文件读写操作
  • 探索CAMEL:揭开多智能体系统的神秘面纱
  • upload-labs(1-20)详解(专业版)
  • JVM参数调整
  • Linux——基础IO【3万字大章】
  • 第四次CCF-CSP认证(含C++源码)
  • 构建服务器--在线单词查询
  • Ubuntu 22.04 升级到 Ubuntu 24.04 全流程指南
  • tcc编译器教程6 进一步学习编译gmake源代码
  • Unity2017打包出来后的场景一片红
  • P8630 [蓝桥杯 2015 国 B] 密文搜索--map、substr