基于MCP协议使用python实现天气预报接口实时查询全国各地天气情况

Mcp_Server端:python脚本

import json
from fastmcp import FastMCP
from dashscope import Generation
import httpx
from typing import Any

# 初始化服务器
mcp=FastMCP('WeatherServer')

def chat(system_prompt: str, user_prompt: str) -> str:
    messages = [
        {"role": "system", "content": system_prompt},
        {"role":"user", "content": user_prompt}
    ]

    response=Generation.call(
        model='qwen-long',
        messages=messages,
        api_key='自己通义千问的密钥!'
    )
    replay = response['output']['choices'][0]['message']['content']
    return replay


async def fetch_weather(city: str) -> dict[str, Any] | None:
    '''
    获取目标城市天气信息
    :param city:目标城市
    :return:天气信息
    '''

    # 获取城市编码
    from data.get_citycode import getweather_info
    city_code=getweather_info(city)

    headers = {'User-Agent': "weather-app/1.0"}
    url = f"http://t.weather.itboy.net/api/weather/city/{city_code}"

    async with httpx.AsyncClient(timeout=10) as client:
        try:
            response = await client.get(url, headers=headers)
            return response.json()
        except httpx.HTTPStatusError as e:
            return {"error": f"HTTP错误:{e.response.status_code}"}
        except Exception as e:
            return {"error": f"请求失败:{str(e)}"}


def format_weather(data: dict[str, Any] | str) -> str:
    """
    将天气数据格式化易读数据
    :param data:天气数据
    :return:格式化之后的易读数据
    """
    if isinstance(data, str):
        try:
            data=json.loads(data)
        except Exception as e:
            return f'无法解析天气数据:{e}'

    if "error" in data:
        return f"❗{data['error']}"

    city = data.get('cityInfo',{}).get('city')
    country = '中国'
    temp = data.get('data',{}).get('wendu','N/A')
    humidity =data.get('data',{}).get('shidu','N/A')
    wind_x = data.get('data',{}).get('forecast',{})[0].get('fx')
    wind_speed = data.get('data',{}).get('forecast',{})[0].get('fl')
    description =data.get('data',{}).get('ganmao')

    return (
       f"国家:{country}\n"
       f"城市:{city}\n"
       f"️温度:{temp}摄氏度\n"
       f"湿度:{humidity}%\n"
       f"️风速:{wind_x},{wind_speed}\n"
       f'❄️建议:{description}\n'
    )


@mcp.tool()
async def query_weather(prompt: str) -> str:
    '''
    从一句话中识别城市名称!
    :param prompt:一句话
    :return:城市名称!
    '''
    city = chat('你是一个专业的地理老师,请帮我从客人的问题中提炼出地域,只要输出结果。请勿总结,不要废话连篇。比如识出来的结果是 苏州,那么直接回复 苏州 如果识别出来 苏州市,那么直接回复 苏州 不要带市', prompt)
    data = await fetch_weather(city)
    result = format_weather(data)
    return chat('你是一个天气预报员,请基于{}上下文内容来回答客人的提问!'.format(result), prompt)


if __name__ == '__main__':
    mcp.run(transport='stdio')

Mcp_Client端:python脚本

from fastmcp import Client
import asyncio

async def run(prom):
    client = Client('server.py')
    async with client:
        tools = await client.list_tools()
        response = await client.call_tool(tools[0].name,{'prompt':prom})
        print(response.content[0].text)

if __name__ == '__main__':
    asyncio.run(run("拉萨今天气温多少度,有风吗?湿度多少?"))```

你可能感兴趣的:(python,开发语言)