OpenAI Agent SDK 快速接入MCP

Openai Agent SDK 集成MCP

作为全球领先的 AI 研究机构,OpenAI 此次通过 Agent SDK 的升级,将 MCP 协议打造为连接智能体与外部工具的标准化桥梁。这一协议通过构建分层架构,实现了模型逻辑、运行环境与工具调用的解耦,为开发者提供了前所未有的自由度。

代码实战

环境准备

1、创建虚拟环境

uv venv .venv

2、编写pyproject.toml

[project]
name = "openai-agent-mcp-test"
version = "0.1.0"
description = "Your project description"
authors = [
    {name = "Your Name", email = "your.email@example.com"},
]
requires-python = ">=3.10"
dependencies = [
    "openai>=1.66.5",
    "pydantic>=2.10,<3",
    "griffe>=1.5.6,<2",
    "typing-extensions>=4.12.2,<5",
    "requests>=2.0,<3",
    "types-requests>=2.0,<3",
    "mcp; python_version >= '3.10'",
    "openai-agents==0.0.7",
]


3、激活环境

.\.venv\Scripts\activate.bat

4、安装依赖

uv run python script.py

5、编写MCP server:
server.py

import random

import requests
from mcp.server.fastmcp import FastMCP

# Create server
mcp = FastMCP("Echo Server")


@mcp.tool()
def add(a: int, b: int) -> int:
    print(f"[debug-server] add({a}, {b})")
    return a + b


@mcp.tool()
def get_secret_word() -> str:
    print("[debug-server] get_secret_word()")
    return random.choice(["apple", "banana", "cherry"])


@mcp.tool()
def get_current_weather(city: str) -> str:
    print(f"[debug-server] get_current_weather({city})")

    endpoint = "https://wttr.in"
    response = requests.get(f"{endpoint}/{city}")
    return response.text


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

6、准备env文件:
.env

OPENAI_API_KEY= 'sk-'
OPENAI_API_BASE='https://xxx.openai.com'

7、启动server.py

python server.py
?[32mINFO?[0m:     Started server process [?[36m1684?[0m]
?[32mINFO?[0m:     Waiting for application startup.
?[32mINFO?[0m:     Application startup complete.
?[32mINFO?[0m:     Uvicorn running on ?[1mhttp://0.0.0.0:8000?[0m (Press CTRL+C to quit)

8、编写mcp client端代码
使用Openai agent sdk mcp快速接入mcp server实现工具调用。

import asyncio
import os

from agents import Agent, OpenAIProvider, RunConfig, Runner
from agents.mcp import MCPServer, MCPServerSse
from agents.model_settings import ModelSettings
from dotenv import load_dotenv

load_dotenv()

async def run(mcp_server: MCPServer):
    agent = Agent(
        name="Assistant",
        instructions="Use the tools to answer the questions.",
        mcp_servers=[mcp_server],
        model_settings=ModelSettings(tool_choice="required"),
    )

    run_config = RunConfig(
        model="gpt-4o",
        model_settings=ModelSettings(tool_choice="required"),
        model_provider=OpenAIProvider(
            api_key=os.environ.get("OPENAI_API_KEY"),
            base_url=os.environ.get("OPENAI_API_BASE"),
        ),
    )

    message = "7+324等于多少"
    print(f"Running: {message}")
    result = await Runner.run(starting_agent=agent, input=message, run_config=run_config)
    print(result.final_output)

    message = "What's the weather in Tokyo?"
    print(f"\n\nRunning: {message}")
    result = await Runner.run(starting_agent=agent, input=message, run_config=run_config)
    print(result.final_output)

    message = "What's the secret word?"
    print(f"\n\nRunning: {message}")
    result = await Runner.run(starting_agent=agent, input=message, run_config=run_config)
    print(result.final_output)


async def main():
    async with MCPServerSse(
        name="SSE Python Server",
        params={
            "url": "http://localhost:8000/sse",
        },
    ) as server:

        await run(server)


if __name__ == "__main__":
    asyncio.run(main())
Running: 7+324等于多少
使用计算器工具计算...
331

Running: What's the weather in Tokyo?
正在获取东京天气信息...
Error: Unable to connect to weather service at http://localhost:8000/sse
Connection refused

Running: What's the secret word?
抱歉,我没有被授权访问任何秘密信息。我无法告诉您密码。
  • 从 agents 包中导入了 Agent、OpenAIProvider、RunConfig 和 Runner 类,这些类应该是自定义的,用于构建和运行智能代理。
  • 从 agents.mcp 模块导入了 MCPServer 和 MCPServerSse 类,可能用于与服务器进行通信。
  • 从 agents.model_settings 模块导入 ModelSettings 类,用于配置模型的设置。
  • 创建智能代理 agent:
    name:代理的名称为 “Assistant”。
    instructions:给代理的指令是使用工具来回答问题。
    mcp_servers:指定代理使用的服务器。
    model_settings:设置模型的工具选择为必需
### 小智AI接入MCP平台的方法 要将小智AI接入MCP平台,可以通过以下方法实现。具体过程涉及使用 `fastapi-mcp` 库来集成 FastAPI 和 MCP 服务,并通过 `/mcp` 端点向 AI 智能体公开 API 功能。 #### 使用FastAPI-MCP库进行集成 为了使小智AI能够被其他智能体识别和调用,需利用 `fastapi-mcp` 提供的功能创建一个支持 MCP 协议的服务端点。以下是具体的实现步骤: 1. 安装依赖项 需安装 `fastapi-mcp` 库以便于简化 MCP 的集成工作流[^1]。 ```bash pip install fastapi-mcp ``` 2. 创建FastAPI应用并定义路由 下面是一个简单的例子,展示如何定义一个计算 BMI 值的工具,并将其作为 MCP 工具发布: ```python from fastapi import FastAPI from fastapi_mcp import FastApiMCP app = FastAPI() @app.get("/bmi", operation_id="calculate_bmi", summary="This tool calculates the Body Mass Index (BMI).") def calculate_bmi(weight_kg: float, height_m: float): """Calculate BMI based on weight and height.""" return {"bmi": weight_kg / (height_m ** 2)} mcp = FastApiMCP( app, name="SmartAI-BMI", description="A simple application that integrates with MCP services." ) mcp.mount() ``` 上述代码片段展示了如何定义一个名为 `calculate_bmi` 的功能,并通过 `FastApiMCP` 类将其注册为 MCP 工具[^1]。 3. 向外部暴露/MCP端点 当前的应用程序会在根路径下挂载一个专门用于 MCP 查询的 `/mcp` 端口。此端点允许任何兼容 MCP 的客户端(如 Claude 或 GPT)发现可用的工具及其接口说明[^1]。 4. 测试与验证 可以通过发送 HTTP 请求至 `/mcp` 来确认一切正常运行。例如,使用 curl 或 Postman 访问该 URL 地址即可查看返回的结果数据结构。 #### 关键参数配置指导 除了基本框架外,还需要注意一些额外的关键设置选项,比如指定 LLM 参数以及调整性能优化等方面的内容[^5]。这些细节可能因实际项目需求而有所不同,因此建议开发者仔细阅读官方文档或者参考类似案例研究材料进一步深入理解其内部机制原理。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值