MCP框架fastmcp的使用方法

github: https://github.com/jlowin/fastmcp

官方文档: https://gofastmcp.com/getting-started/installation

1. 框架引入

#在项目目录下克隆
git clone git@github.com:jlowin/fastmcp.git

2.创建虚拟环境

如果需要更详细过程,可以查看另外一个文档文档:
Python虚拟环境搭建

#查看当前项目路径
pwd 
#创建虚拟环境
python3 -m venv /项目路径/.venv
#激活环境
source /项目路径/.venv/bin/activate  # 激活环境

3. 安装fastmcp依赖

uv pip install fastmcp

#检查是否成功
fastmcp version

4. 编写mcp服务

例如:my_service.py 放到fastmcp根目录下

只需要在文件中引入FastMCP并使用

from fastmcp import FastMCP
mcp = FastMCP(“My MCP Server”)

在mcp逻辑方法上添加标识代码

@mcp.tool

且使用mcp.run()方式启动

if name == “main”:
mcp.run()

1. mcp服务-文件模式
完整示例
from fastmcp import FastMCP

mcp = FastMCP("My MCP Server")

#当前服务的业务逻辑方法,即mcp会直接调用的方法
@mcp.tool
def greet(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run()
以mcp方式运行my_service.py
fastmcp run my_service.py:mcp

在trae等工具中配置mcp

{
  "mcpServers": {
    "products": {
      "command": "uv",
      "args": [
        "--directory",
        "项目目录",
        "run",
        "my_service.py"
      ]
    }
  }
}
2. mcp服务-服务端口模式
完整示例
from fastmcp import FastMCP

mcp = FastMCP("My MCP Server")

#当前服务的业务逻辑方法,即mcp会直接调用的方法
@mcp.tool
def greet(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run(
    transport="streamable-http",
    host="0.0.0.0",           # Bind to all interfaces
    port=9000,                # Custom port
    log_level="DEBUG",        # Override global log level
)
以mcp方式运行my_service.py
fastmcp run my_service.py:mcp

如果运行后,transport不是streamable-http,则可以以手动指定模式的方式运行

fastmcp run my_service.py:mcp --transport=streamable-http --port=9000

在trae等工具中配置mcp

{
  "mcpServers": {
    "fastmcp": {
      "url": "http://localhost:9000/mcp"
    }
  }
}

5. (加入智能体)在ai窗口直接根据相关服务提问即可

Logo

一站式 AI 云服务平台

更多推荐