1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenAI Agents SDKでMCPをやってみる

Last updated at Posted at 2025-04-10

MCPは、Anthropicの提唱するLLMから別のシステムを呼び出す方法のひとつです。OpenAI Agents SDKも対応したことで話題になりました。

環境

  • uv 0.6.6
  • Python 3.13.2
  • mcp[cli]>=1.6.0
  • openai-agents>=0.0.9

ディレクトリ構成(一部抜粋)

.
├── .env
├── main.py
├── pyproject.toml
├── src
│   ├── __init__.py
│   └── whattime.py
└── uv.lock

実装

現在時刻を返すMCPサーバーを実装し、AIに「いま何時?」と聞いて現在時刻を教えてくれるエージェントを実装します。

まずMCP無しの挙動を確認します。なんらかのツールが無いとうまく答えてくれません。

def whattime():
    agent = Agent(
        name="Assistant",
        model="gpt-4o-mini",
    )
    result = Runner.run_sync(agent, "いま何時?")
    print(result.final_output)

if __name__ == "__main__":
    whattime()

.envOPENAI_API_KEYを置いて、$ uv run main.pyで実行します。

ごめんなさい、リアルタイムの情報を提供することはできませんが、あなたの現在の時間を知りたい場合は、お手元の時計やスマートフォンをご確認ください。何か他にお手伝いできることがあれば教えてください!

という感じで、答えてくれません。

MCPサーバーの構築

まずエージェントから呼び出すためのMCPサーバーを用意します。$ uv add "mcp[cli]"したあと、src/whattime.pyに以下の記述をします。

src/whattime.py
from mcp.server.fastmcp import FastMCP
from datetime import datetime

mcp = FastMCP("whattime")

@mcp.tool()
async def get_time() -> str:
    """現在時刻を取得する関数"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

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

$ uv run src/whattime.py しても、何かを待ち受けたまま何も起きません。

MCPホスト・クライアントの構築

OpenAI Agents SDKでMCPのクライアント側を用意します。$ uv add openai-agentsして、main.pyに以下の記述をします。

main.py
from datetime import datetime
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStdio

async def whattime_mcp():
    async with MCPServerStdio(
        params={
            "command": "uv",
            "args": ["run", "src/whattime.py"],
        }
    ) as server:
        tools = await server.list_tools()
        print(tools)
        agent = Agent(
            name="Assistant",
            model="gpt-4o-mini",
            mcp_servers=[server],
        )
        result = await Runner.run(agent, "いま何時?")
        print(result.final_output)

if __name__ == "__main__":
    asyncio.run(whattime_mcp())

$ uv run main.pyで実行します。

現在の時刻は2025年4月10日21時40分です。

成功しました。

余談: MCPを使わずにツールを呼び出す

このように、LLMを呼び出すクライアント側のプログラムとツール用プログラムとが同一のシステムに存在して実行できるのであれば、MCPを使う必要はとくにありません。今回の例のようにOpenAI Agents SDKを使っているならばSDKの関数ツール機能を使う方が簡潔に記述できると思います。

main.py
from datetime import datetime
from agents import Agent, Runner, function_tool

@function_tool
async def get_time() -> str:
    """現在時刻を取得する関数"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def whattime():
    agent = Agent(
        name="Assistant",
        model="gpt-4o-mini",
        tools=[get_time],
    )
    result = Runner.run_sync(agent, "いま何時?")
    print(result.final_output)

if __name__ == "__main__":
    whattime()

参考文献

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?