読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
練習ファイルは practice/vol2 にあります。requirements.txt に mcp==2.3.0 を足しました。
server = MCPServer("komorebi-bakery", instructions="パン屋「こもれびベーカリー」の商品・店の案内・予約の下書きの道具")
READ_ONLY = ToolAnnotations(read_only_hint=True)
@server.tool(description="商品名の一部で商品を探す。ID・名前・税込価格・予約できるか・今日の残りの数を返す", annotations=READ_ONLY)
def find_products(
keyword: Annotated[str, Field(description="商品名の一部。例:パン、タルト")],
quantity: Annotated[int | None, Field(description="買いたい個数。質問に個数があるときだけ指定する")] = None,
) -> dict:
return run("find_products", {"keyword": keyword, "quantity": quantity})
if __name__ == "__main__":
server.run()
@server.tool を付けた関数が、道具になります。引数の型(str、int | None)と Field の説明から、SDKが inputSchema を作ります。初期値のある quantity は、必須の一覧(required)に入りません。
関数の中身は、tools.py の道具を呼ぶだけです。run は、DBの接続を開き、LocalToolbox で道具を1回実行して閉じます。道具の中身を2か所に書かないためです。
def run(name: str, arguments: dict) -> dict:
"""tools.py の道具を、DBの接続を開いて1回だけ実行する。"""
arguments = {key: value for key, value in arguments.items() if value is not None}
with Session(engine) as session:
output, _ = LocalToolbox(ToolContext(session, get_llm(), datetime.now())).call(name, arguments)
return output
6 / 22