4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

動的にMCPサーバにツールを登録したい

Last updated at Posted at 2025-03-23

前提条件

MCP Python SDK を使用する前提で話します

結論から先にいうと

要は mcp.tool デコレータに関数を渡せればMCPに登録できるので
下記のように、手動で登録しても良い。

from typing import Any
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("hidamari_character")

async def get_users_favorite_hidamari_schetch_character(user_name:str) -> str:
    """get users favorite hidamari schetch character
        (ユーザー名ごとに、ひだまりスケッチの好きなキャラクターを返す)
        Args:
            user_name: ユーザー名
    """
    # Claudeが上記メソッド定義を読み込んで、いい感じに呼び出してくれる。

    if user_name == "masachaco":
        return "宮ちゃんです"

    return "該当のユーザーの情報は見つかりませんでした"

def main():
    # デコレータを手動で呼んで、関数を渡すことでも、MCPサーバーに登録できる
    mcp.tool()(get_users_favorite_hidamari_schetch_character)
    mcp.run(transport='stdio')

if __name__ == "__main__":
    main()

結果

想定通り利用できました。

image.png

image.png

image.png

何に使えるの

自作のAIエージェント用ツールや既存の関数についても、関数定義と、付属するコメントがしっかりしていればいいので、既存のコードを変更せずにツールとして提供することができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?