新闻搜索 MCP Server 开发秘籍:Python - SDK 携手 SerpApi,融入 Trae 不再难

1. 通过 sdk 开发 mcp server

本例需要 SerpApi

SerpApi 是一个专门针对Google搜索结果页面(SERP)的API服务。通过这个API,我们可以获取到Google搜索的各种数据,包括但不限于搜索结果、位置、时间等信息。

需要去官网申请 API Key。SerpApi 官网:serper.dev/

python 复制代码
import os
import json
from datetime import datetime

import httpx
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 初始化 MCP 服务器
mcp = FastMCP("NewsServer")

@mcp.tool()
async def search_google_news(keyword: str) -> str:
    """
        使用 Serper API(Google Search 封装)根据关键词搜索新闻内容,返回前5条标题、描述和链接。

        参数:
            keyword (str): 关键词,如 "小米汽车"

        返回:
            str: JSON 字符串,包含新闻标题、描述、链接
        """

    # 从环境中获取 API 密钥并进行检查
    api_key = os.getenv("SERPER_API_KEY")
    if not api_key:
        return "❌ 未配置 SERPER_API_KEY,请在 .env 文件中设置"

    # 设置请求参数并发送请求
    url = "https://google.serper.dev/news"
    headers = {
        "X-API-KEY": api_key,
        "Content-Type": "application/json"
    }
    payload = {"q": keyword}

    async with httpx.AsyncClient() as client:
        response = await client.post(url, headers=headers, json=payload)
        data = response.json()

    # 检查数据,并按照格式提取新闻,返回前五条新闻
    if "news" not in data:
        return "❌ 未获取到搜索结果"

    articles = [
        {
            "title": item.get("title"),
            "desc": item.get("snippet"),
            "url": item.get("link")
        } for item in data["news"][:5]
    ]

    # 将新闻结果以带有时间戳命名后的 JSON 格式文件的形式保存在本地指定的路径
    output_dir = "./google_news"
    os.makedirs(output_dir, exist_ok=True)
    filename = f"google_news_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    file_path = os.path.join(output_dir, filename)

    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(articles, f, ensure_ascii=False, indent=2)

    return (
        f"✅ 已获取与 [{keyword}] 相关的前5条 Google 新闻:\n"
        f"{json.dumps(articles, ensure_ascii=False, indent=2)}\n"
        f"📄 已保存到:{file_path}"
    )

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

2. 添加到 trae 中

json 复制代码
{
  "mcpServers": {
    "my_news": {
      "command": "uv",
      "args": [
        "--directory",
        "D:/project/AI/MCP/mcpserver/python_simple",
        "run",
        "server.py"
      ]
    }
  }
}

添加成功后,添加到智能体

3. 对话测试

提示词:

请分析一下马斯克近期的热点新闻

相关推荐
GitLqr1 小时前
AI洞察 | 新一代 Agent 框架与 3D 桌面伴侣智能体
agent·ai编程·mcp
大模型教程1 小时前
12天带你速通大模型基础应用(一)Prompt提示词工程
程序员·llm·agent
yaocheng的ai分身1 小时前
Browser MCP扩展
cursor·mcp
coder_pig3 小时前
👦抠腚男孩的AI学习之旅 | 6、玩转 LangChain (二)
langchain·aigc·agent
大模型真好玩4 小时前
深入浅出LangGraph AI Agent智能体开发教程(四)—LangGraph全生态开发工具使用与智能体部署
人工智能·python·mcp
量子位5 小时前
18岁女孩做养老机器人,上线2天卖爆了
人工智能·llm
大模型教程5 小时前
12天带你速通大模型基础应用(二)自动化调优Prompt
程序员·llm·agent
AI大模型6 小时前
无所不能的Embedding(02) - 词向量三巨头之FastText详解
程序员·llm·agent
AI大模型6 小时前
无所不能的Embedding(03) - word2vec->Doc2vec[PV-DM/PV-DBOW]
程序员·llm·agent
悟乙己6 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n