FastMCP 案例八(smolagent使用mcp工具)

1、安装smolagent以及依赖

pip install smolagents
pip install smolagents[openai]
pip install smolagents[mcp]
pip install duckduckgo-search

2、创建一个test.py文件

# -*- coding: utf-8 -*-
# @Time : 2025/6/19 10:17
# @Author : yangwenjie
# @Email : 邮箱
# @File : test.py
# @Project : smolagents
from smolagents import CodeAgent, OpenAIServerModel, ToolCollection, MCPClient

model = OpenAIServerModel(
    model_id="Qwen3-32B",
    api_base="http://10.21.0.16:13000/v1",
    api_key="sk-17baz5GWB64XE06E971AfC8A6",
)

with ToolCollection.from_mcp({"url":"http://localhost:3002/sse/","transport":"sse"}, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
    agent.run("Tokyo 天气怎么样?")

3、运行本地的mcp

# -*- coding: utf-8 -*-
# @Time : 2025/7/28 17:09
# @Author : yangwenjie
# @Email : 邮箱
# @File : server-sse.py
# @Project : fastmcp
# weather_sse.py
from fastmcp import FastMCP
import random

from pydantic import BaseModel

# 创建MCP服务器实例,指定端口
mcp = FastMCP("Weather Service", port=3002)

# 模拟的天气数据
weather_data = {
    "New York": {"temp": range(10, 25), "conditions": ["sunny", "cloudy", "rainy"]},
    "London": {"temp": range(5, 20), "conditions": ["cloudy", "rainy", "foggy"]},
    "Tokyo": {"temp": range(15, 30), "conditions": ["sunny", "cloudy", "humid"]},
    "Sydney": {"temp": range(20, 35), "conditions": ["sunny", "clear", "hot"]},
}

class WeatherModel(BaseModel):
    city: str
    temp: str
    condition: str
    unit: str = "celsius"


@mcp.tool()
async def get_weather(city: str) -> dict:
    """获取指定城市的当前天气"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气数据"}

    data = weather_data[city]
    temp = random.choice(list(data["temp"]))
    condition = random.choice(data["conditions"])
    # model = WeatherModel(city=city, temp=temp, condition=condition)
    # return  model.model_dump_json()
    return {
        "city": city,
        "temperature": temp,
        "condition": condition,
        "unit": "celsius"
    }


@mcp.resource("weather://cities")
def get_available_cities() -> list:
    """获取所有可用的城市列表"""
    return list(weather_data.keys())


@mcp.resource("weather://forecast/{city}")
def get_forecast(city: str) -> dict:
    """获取指定城市的天气预报资源"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气预报"}

    forecast = []
    for i in range(5):  # 5天预报
        data = weather_data[city]
        temp = random.choice(list(data["temp"]))
        condition = random.choice(data["conditions"])
        forecast.append({
            "day": i + 1,
            "temperature": temp,
            "condition": condition
        })

    return {
        "city": city,
        "forecast": forecast,
        "unit": "celsius"
    }


if __name__ == "__main__":
    # 使用SSE传输方式启动服务器
    mcp.run(transport="sse",host="0.0.0.0")
View Code

4、运行agent代码

python test.py

image

image

posted @ 2025-08-01 15:04  小白啊小白,Fighting  阅读(91)  评论(0)    收藏  举报