1 前言

Model Context Protocol(MCP)为我们提供了一种优雅的方式来扩展AI助手的能力。今天,我们将一起学习如何构建自己的MCP Server,让AI助手可以调用我们自定义的工具和资源。

通过本文,你将学会使用FastMCP库快速创建一个功能完整的MCP Server,并了解如何在实际项目中进行调试和应用。

1.1 FastMCP 库简介

Avatar of jlowin

jlowin/fastmcp

🚀 The fast, Pythonic way to build MCP servers and clients

Stars: 14748
🍴 Forks: 921
💻 Language: Python
📄 License: Apache License 2.0

FastMCP是一个非常实用的Python库,它让我们可以轻松地将代码功能暴露为Tools、Resources和Prompts,供MCP Client调用。这大大简化了MCP Server的开发过程。

想要深入了解FastMCP的更多特性,可以查看官方文档:Welcome to FastMCP 2.0! - FastMCP

2 实战案例:天气查询服务

让我们通过一个简单而实用的例子来理解MCP Server的构建过程。这里我们将实现一个天气查询服务:

2.1 服务端代码

PYTHON
from mcp.server.fastmcp import FastMCP

# 创建MCP服务器实例
mcp = FastMCP("Weather Server")

@mcp.tool()
def weather(location: str) -> str:
    """
    Get the weather for a given location.

    Args:
        location: The location to get the weather for.

    Returns:
        The weather in the location.
    """
    return f"The weather in {location} is sunny."

if __name__ == "__main__":
    print("Starting MCP server...")
    mcp.run(transport="stdio")
点击展开查看更多

这段代码做了以下几件事:

2.2 客户端配置

要在Cursor或Cherry Studio中使用我们的MCP Server,需要创建相应的配置文件:

JSON
{
  "mcpServers": {
    "weather-server": {
      "command": "uv",
      "args": [
        "--directory",
        "/Users/liuyao/MyProjects/AiProjects/mcp-demo",
        "run",
        "weather.py"
      ]
    }
  }
}
点击展开查看更多

配置文件中指定了:

2.3 实际使用效果

配置完成后,你就可以在Cursor中通过自然语言来调用天气查询功能了:

3 本地调试与开发

在开发MCP Server时,调试是必不可少的环节。官方为我们提供了一个非常好用的调试工具。

3.1 MCP Inspector 介绍

Avatar of modelcontextprotocol

modelcontextprotocol/inspector

Visual testing tool for MCP servers

Stars: 5026
🍴 Forks: 641
💻 Language: TypeScript
📄 License: MIT License

MCP Inspector是官方提供的调试工具,它可以帮助我们:

3.2 安装与使用

首次使用时,通过npx安装MCP Inspector:

BASH
npx @modelcontextprotocol/inspector
点击展开查看更多

安装完成后,日常调试只需一个简单命令:

BASH
mcp dev weather.py
点击展开查看更多

3.3 调试界面

启动后,你会看到一个直观的Web界面。在Tools选项卡中,可以查看所有可用的工具,并进行交互式测试:

这个界面让你可以:

4 总结

通过本文的学习,我们掌握了:

  1. FastMCP库的使用:了解了如何快速创建MCP Server
  2. 实际案例开发:从零开始构建了一个天气查询服务
  3. 配置与集成:学会了如何将MCP Server集成到AI助手中
  4. 调试技巧:掌握了使用MCP Inspector进行本地调试的方法

版权声明

作者: Yao

链接: https://yaoliu.site/posts/build-mcp-server/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

评论

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键