4
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?

Google Gen AI SDK で MCP ツール呼び出しを試してみる!

Posted at

はじめに

Google Gen AI SDK が MCP サポートしていたので試してみました。

試してみた

環境構築

pip install mcp google-genai

実装

Google Gen AI SDK で MCP ツールを呼び出す方法は以下の通りです。

app.py
import asyncio
import argparse

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai

# Gemini Developer API の場合
# client = genai.Client(api_key="GEMINI_API_KEY")

# Vertex AI の場合
client = genai.Client(
    vertexai=True, project='your-project-id', location='us-central1'
)

server_params = StdioServerParameters(
    command="python",
    args=["server.py"], # MCP Server
)

async def run(prompt: str):
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:

            await session.initialize()

            session_tool_list = await session.list_tools()

            print("----- Tool List -----")
            print(f"Tool List: {session_tool_list.tools}")

            response = await client.aio.models.generate_content(
                model="gemini-2.0-flash",
                contents=prompt,
                config=genai.types.GenerateContentConfig(
                    temperature=0,
                    tools=[session],
                ),
            )

            print("----- Response -----")
            print(response.text)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--prompt", type=str, default="東京の天気は?", help="プロンプト文字列")
    args = parser.parse_args()

    asyncio.run(run(args.prompt))

ローカル MCP サーバーとして以下のような簡易的なものを使用します。

server.py
import uuid
from datetime import datetime
from zoneinfo import ZoneInfo

from mcp.server.fastmcp import FastMCP

mcp = FastMCP()


@mcp.tool()
def gen_uuidv4():
    """UUIDv4を生成します。"""
    return str(uuid.uuid4())

@mcp.tool()
def get_current_time() -> str:
    """現在の日本時間を取得します。"""
    return datetime.now(ZoneInfo("Asia/Tokyo")).strftime("%Y-%m-%d %H:%M:%S")

@mcp.tool()
def get_weather(location: str) -> str:
    """指定された場所の天気を取得します。"""
    weather_data = {
        "東京": "晴れ",
        "大阪": "",
    }
    return weather_data.get(location, "天気情報がありません。")


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

実行

以下を実行します。

python app.py --prompt 東京の天気は?
出力結果
----- Tool List -----
Tool List: [Tool(name='gen_uuidv4', description='UUIDv4を生成します。', inputSchema={'properties': {}, 'title': 'gen_uuidv4Arguments', 'type': 'object'}, annotations=None), Tool(name='get_current_time', description='現在の日本時間を取得します。', inputSchema={'properties': {}, 'title': 'get_current_timeArguments', 'type': 'object'}, annotations=None), Tool(name='get_weather', description='指定された場所の天気を取得します。', inputSchema={'properties': {'location': {'title': 'Location', 'type': 'string'}}, 'required': ['location'], 'title': 'get_weatherArguments', 'type': 'object'}, annotations=None)]
----- Response -----
東京の天気は晴れです。

定義した MCP ツールのリストも表示されて、期待した結果が返ってきました!

他の実行結果

python app.py --prompt 大阪の天気は?
出力結果
----- Response -----
大阪の天気は雨です。

get_weatherで定義しなかった地名を聞いてみます。

python app.py --prompt 北海道の天気は?
出力結果
----- Response -----
北海道の天気情報は見つかりませんでした。

しっかりと「天気情報がない」と回答してくれました!

python app.py --prompt UUIDを作成して
出力結果
----- Response -----
UUIDを作成しました。結果は aafdc987-ec1d-456e-a764-db1879e03238 です。

MCP ツールを使用して回答を作っていることが確認できました!

まとめ

Google Gen AI SDK を使用して、Gemini で MCP ツール呼び出しを試してみました。
MCP サポートによりエージェント型アプリケーションの構築が容易になると思います!

4
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
4
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?