0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HostedMCPTool で外部ツールをAgent に接続する

0
Posted at

MCPとHostedMCPTool とは

MCP(Model Context Protocol) は、LLM が外部ツールやデータソースと標準化された方法で通信するためのプロトコルです。Cursor IDE の MCP 連携と同様、Agent も MCP サーバー経由で「ドキュメント検索」「API 呼び出し」などの機能を拡張できます。

HostedMCPTool は、OpenAI側が 公開 URL のリモート MCP サーバー に直接接続してくれる Hosted tool です。開発者が MCP プロトコルを自前実装する必要はなく、tool_config にサーバー URL を渡すだけで、モデルが自動的に:

  1. サーバーのツール一覧を取得(mcp_list_tools
  2. 必要なツールを呼び出す(mcp_call
コンポーネント 役割
HostedMCPTool リモート MCP サーバーを Agent に接続
mcp_list_tools サーバーが提供するツール一覧
mcp_call 特定ツールの実行記録
FunctionTool Python 関数で直接定義するローカルツール

HostedMCPTool は外部サービスの能力を取り込み、Function Tool は自分で書いた Python ロジックを Agent に載せる方式です。両方を組み合わせると「公式 docs 参照(MCP)+ 自前 API 呼び出し(関数)」が可能になります。


HostedMCPTool の使い方

1. import

クラス名は HostedMCPTool です(MCP は大文字)。

from agents import Agent, HostedMCPTool, Runner

2. Agent に追加

tool_config必須 です。OpenAI Responses API の Mcp 型に合わせた dict を渡します。

agent = Agent(
    name="ChatGPT Clone Agent",
    instructions="...",
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_url": "https://mcp.context7.com/mcp",
                "server_label": "Context7",
                "server_description": "Context7 MCPはプロジェクトのdocsを参照して回答します。",
                "require_approval": "never",
            }
        ),
    ],
)
設定 説明
type: "mcp" ツール種別(必須)
server_url MCP サーバーの URL
server_label サーバー識別ラベル(UI・tool call で使用)
server_description モデル向けの説明(任意)
require_approval ツール実行前の承認要否("never" / "always"

server_url の代わりに Gmail・Google Drive など SaaS 連携用の connector_id、または tunnel_id も指定できます。


例 1 — 使える MCP ツールの確認

Context7 MCP を Agent に接続したうえで、どんなツールが使えるか聞いてみました。

プロンプト

あなたが使えるMCPツールは何ですか?

Agent の回答

image.png

Context7 ツール 役割
resolve-library-id ライブラリ名 → Context7 library ID への変換
query-docs 該当ライブラリの公式ドキュメント検索・参照

Agent が HostedMCPTool 経由で Context7 サーバーに接続すると、初回リクエスト時に mcp_list_tools で上記ツールを自動探索します。「どんな MCP が使える?」と聞くと、モデルはこの一覧をもとに説明してくれます。


例 2 — Context7 + 天気 Function Tool Agent

2 つ目の例は、MCP(docs 参照)と Function Tool(自前実装)を 1 つの Agent に載せる パターンです。

プロンプト

Context7ツールを使って、最新のOpenAI Agents SDKのドキュメントを参照し、天気情報を取得するFunction Toolを持つAgentの実装方法を教えてください。

Agent は Context7 で OpenAI Agents SDK の最新ドキュメントを参照し、@function_tool で天気取得関数を作る方法を案内します。

2026-08-2323.16.05-ezgif.com-video-to-gif-converter.gif

コード

import httpx
from agents import Agent, HostedMCPTool, Runner, function_tool


@function_tool
def get_weather(city: str) -> str:
    """指定された都市の現在の天気情報を取得する。"""
    geo_resp = httpx.get(
        "https://geocoding-api.open-meteo.com/v1/search",
        params={"name": city, "count": 1, "language": "ja"},
        timeout=10.0,
    )
    geo_resp.raise_for_status()
    results = geo_resp.json().get("results")
    if not results:
        return f"{city}」の位置情報が見つかりませんでした。"

    lat = results[0]["latitude"]
    lon = results[0]["longitude"]
    name = results[0]["name"]

    weather_resp = httpx.get(
        "https://api.open-meteo.com/v1/forecast",
        params={
            "latitude": lat,
            "longitude": lon,
            "current": "temperature_2m,relative_humidity_2m,weather_code",
        },
        timeout=10.0,
    )
    weather_resp.raise_for_status()
    current = weather_resp.json()["current"]

    return (
        f"{name}の現在の天気:\n"
        f"- 気温: {current['temperature_2m']}°C\n"
        f"- 湿度: {current['relative_humidity_2m']}%\n"
        f"- 天気コード: {current['weather_code']}"
    )


agent = Agent(
    name="Docs + Weather Agent",
    instructions="""
    あなたはOpenAI Agents SDKに詳しいアシスタントです。

    - OpenAI Agents SDKの使い方やAPIについて質問されたら、Context7 MCPで最新ドキュメントを参照して回答してください。
    - 天気の質問には get_weather ツールを使ってください。
    - Function Toolの実装方法を聞かれたら、Context7で取得した最新ドキュメントに基づいて @function_tool の書き方を説明してください。
    """,
    tools=[
        get_weather,
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_url": "https://mcp.context7.com/mcp",
                "server_label": "Context7",
                "server_description": "ライブラリの公式ドキュメントを参照するMCPサーバー",
                "require_approval": "never",
            }
        ),
    ],
)


async def main():
    result = await Runner.run(
        agent,
        "Context7ツールを使って、最新のOpenAI Agents SDKのドキュメントを参照し、"
        "天気情報を取得するFunction Toolを持つAgentの実装方法を教えてください。",
    )
    print(result.final_output)


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

この例で起きること

  1. HostedMCPTool(Context7) — OpenAI Agents SDK の最新 docs から @function_tool の使い方を参照
  2. Function Tool(get_weather — Open-Meteo API で実際の天気データを取得する Python 関数
  3. モデルは 2 つのツールを使い分ける: 「docs の質問 → Context7」「天気の質問 → get_weather」

Function Tool のポイント

@function_tool デコレータを関数に付けると、型ヒントと docstring から JSON Schema が自動生成されます。

from agents import function_tool

@function_tool
def get_weather(city: str) -> str:
    """指定された都市の現在の天気情報を取得する。"""
    ...
項目 説明
関数シグネチャ LLM が渡すパラメータのスキーマに変換
docstring ツールの説明(モデルがいつ使うか判断)
戻り値 str または structured output

Context7 で取得した最新 SDK docs を参照すれば、Runner.runAgent(tools=[...])@function_tool の組み合わせが公式パターンと一致しているか確認できます。


HostedMCPTool vs Function Tool

HostedMCPTool Function Tool
定義場所 外部 MCP サーバー Python 関数(@function_tool
接続方法 tool_config + URL デコレータ
実行主体 OpenAI → MCP サーバー 自分の Python コード
向いている用途 公式 docs、SaaS 連携 自前 API、DB、ビジネスロジック

Context7 + get_weather の組み合わせは、この違いをよく示しています。docs は外部 MCP が、天気 API 呼び出しは自分の関数が担当します。


まとめ

  • HostedMCPTool はリモート MCP サーバーを Agent に接続する Hosted tool
  • Context7 を使えば resolve-library-id / query-docs でライブラリの公式 docs を参照できる
  • Function Tool@function_tool)と組み合わせれば、外部 docs(MCP)+ 自前ロジック(関数)を 1 つの Agent で扱える

参考リンク

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?