Rustで書かれた高速なPython用パッケージ・プロジェクト管理ツールです。 従来のpipやvenvなど複数のツールで行っていた仮想環境の作成、パッケージの インストール、バージョン管理などを一つのツールで統合し、 10倍~100倍の速度向上を目指しています。
1. 環境構築:uvパッケージマネージャのインストール powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 2. プロジェクト作成と仮想環境のセットアップ mkdir greet cd greet uv init . uv venv .venv\Scripts\activate 3. 必要なパッケージのインストール uv add "mcp[cli]" 4. 四則演算MCPサーバーの実装 calculator.py 5. 設定ファイル:settings.json ※下記「settings.jsoの設定内容」参照 6. 実行:gemini起動後、以下のプロンプトを入力 5 + 3は? MCPを使って計算して○settings.jsonの設定内容
{
"theme": "Default",
"selectedAuthType": "oauth-personal",
"mcpServers": {
"calculator": {
"command": "uv",
"args": [
"--directory",
"C:\\Users\\shim1",
"run",
"calculator.py"
]
},
"mcp_os_disk": {
"command": "uv",
"args": [
"--directory",
"C:\\Users\\shim1",
"run",
"mcp_os_disk.py"
]
},
"mcp_greet": {
"command": "uv",
"args": [
"--directory",
"C:\\Users\\shim1",
"run",
"mcp_greet.py"
]
}
}
}
uvは2024年の2月中旬に発表されたばかりの新しいパッケージ管理ツールです。 Rustで書かれており、ここ最近で飛躍的に使用されるようになったRust製の Pythonリンター&フォーマッター「Ruff」を開発しているAstral社によって提供されています[1]。
# mcp_greet.py
from mcp.server.fastmcp import FastMCP
import asyncio # 後でクライアント用に必要になります
# サーバーをインスタンス化し、名前を付けます
mcp = FastMCP("mcp_greet")
print("FastMCPサーバーオブジェクトが作成されました。")
@mcp.tool()
def greet(name: str) -> str:
"""シンプルな挨拶を返します。"""
return f"こんにちは、{name}さん!"
@mcp.tool()
def add(a: int, b: int) -> int:
"""二つの数を足し合わせます。"""
return a + b
print("ツール'greet'と'add'が追加されました。")
if __name__ == "__main__":
print("\n--- __main__を介してFastMCPサーバーを開始 ---")
# これによりサーバーが起動し、通常はデフォルトでstdioトランスポートを使用します
mcp.run(transport='stdio')
C:\Users\shim1>python mcp_greet.py FastMCPサーバーオブジェクトが作成されました。 ツール'greet'と'add'が追加されました。 --- __main__を介してFastMCPサーバーを開始 ---
import asyncio
from fastmcp import Client
from fastmcp.client.transports import PythonStdioTransport
###FastMCP 入門 (7) - FastMCPクライアント
###https://note.com/npaka/n/na536ba137e4a
###実行方法:C:\Users\shim1>uv run mcp_greet_client.py
async def main():
# サーバースクリプトのパス
server_script = "C:\\Users\\shim1\\mcp_greet.py"
# PythonStdioTransportを使用してサーバを起動
transport = PythonStdioTransport(script_path=server_script)
# クライアントを作成し、サーバと通信
async with Client(transport) as client:
# 利用可能なツールを取得
tools = await client.list_tools()
print("ツール1-01:" ,tools)
print("ツール1-02:" ,len(tools))
for tool in tools:
print("name:" ,tool.name)
print("description" ,tool.description)
print("")
# greetツールの呼び出し
result = await client.call_tool("greet", {"name": "佳昭"})
print("greetツール結果1:", result.structured_content["result"])
### print("greetツール結果2:", result[0].text)
print("")
# addツールの呼び出し
result = await client.call_tool("add", {"a": 5, "b": 3})
print("addツール結果1:", result.structured_content["result"])
### print("addツール結果2:", result[0].text)
print("")
if __name__ == "__main__":
asyncio.run(main())
C:\Users\shim1>python mcp_greet_client.py
ツール1-01: [Tool(name='greet', title=None, description='シンプルな挨拶を返しま す。', inputSchema={'properties': {'name': {'title': 'Name', 'type': 'string'}}, 'required': ['name'], 'title': 'greetArguments', 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'string'}}, 'required': ['result'], 'title': 'greetOutput', 'type': 'object'}, annotations=None, meta=None),
Tool(name='add', title=None, description='二つの数を足し合わせます。', inputSchema={'properties': {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}, 'required': ['a', 'b'], 'title': 'addArguments', 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'integer'}}, 'required': ['result'], 'title': 'addOutput', 'type': 'object'}, annotations=None, meta=None)]
ツール1-02: 2
name: greet
description シンプルな挨拶を返します。
name: add
description 二つの数を足し合わせます。
greetツール結果1: こんにちは、佳昭さん!
addツール結果1: 8
C:\Users\shim1>npx @modelcontextprotocol/inspector .\calculator.py Starting MCP inspector... ⚙️ Proxy server listening on 127.0.0.1:6277 🔑 Session token: 6daaa319ecf35945d8af3d595a2c7909864c551f708844153a6ef80bd71cacae Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth 🔗 Open inspector with token pre-filled: http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=6daaa319ecf35945d8af3d595a2c7909864c551f708844153a6ef80bd71cacae 🔍 MCP Inspector is up and running at http://127.0.0.1:6274 🚀※ブラウザで「 http://127.0.0.1:6274」アクセスして、Proxy Auth Tokenを設定します。
WindowsのOS名、バージョン、CPU/MEM/DISKを知りたいGeminiCLIは、上記のプロンプトから「mcp_os_disk」MCPサーバーを特定して、各ツールを順次実行します、凄いですね!!!
Allow execution of MCP tool "get_disk_usage" from serve… │ │ │ │ ○ Yes, allow once │ │ ○ Yes, always allow tool "get_disk_usage" from server "… │ │ ● Yes, always allow all tools from server "mcp_os_disk" │ │ ○ No (esc)
import json
import platform
import shutil
import psutil
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("mcp_os_disk")
@mcp.tool()
async def get_os_name() -> str:
"""OSの名前を取得します"""
os_name = platform.system()
return json.dumps({
"type": "text",
"text": os_name,
})
@mcp.tool()
async def get_os_version() -> str:
"""OSの名前を取得します"""
os_version = platform.platform()
return json.dumps({
"type": "text",
"text": os_version,
})
@mcp.tool()
async def get_disk_usage() -> str:
"""ディスク使用量情報を取得します。"""
total, used, free = shutil.disk_usage("/")
total_gb = total / (1024**3)
used_gb = used / (1024**3)
usage_percent = (used / total) * 100
disk_info = {
"total_gb": round(total_gb, 2),
"used_gb": round(used_gb, 2),
"usage_percent": round(usage_percent, 2)
}
result_text = (
f"ディスク使用量:\n"
f" 総容量: {disk_info['total_gb']} GB\n"
f" 使用量: {disk_info['used_gb']} GB\n"
f" 使用率: {disk_info['usage_percent']}%"
)
return json.dumps({
"type": "text",
"text": result_text,
})
@mcp.tool()
async def get_cpu() -> str:
"""CPU使用率情報を取得します。"""
cpu = psutil.cpu_percent(interval=1)
return json.dumps({
"type": "text",
"text": cpu,
})
@mcp.tool()
async def get_mem() -> str:
"""MEM使用率情報を取得します。"""
mem = psutil.virtual_memory()
return json.dumps({
"type": "text",
"text": mem,
})
# メイン実行部分(直接実行する場合)
if __name__ == "__main__":
mcp.run(transport='stdio')
(5 + 3 *11)は?
from typing import Union
from mcp.server.fastmcp import FastMCP
# MCPサーバー初期化
mcp = FastMCP("calculator")
@mcp.tool()
async def add(a: Union[int, float], b: Union[int, float]) -> str:
"""足し算"""
result = float(a + b)
return f"[MCP計算] {a} + {b} = {result}"
@mcp.tool()
async def subtract(a: Union[int, float], b: Union[int, float]) -> str:
"""引き算"""
result = float(a - b)
return f"[MCP計算] {a} - {b} = {result}"
@mcp.tool()
async def multiply(a: Union[int, float], b: Union[int, float]) -> str:
"""掛け算"""
result = float(a * b)
return f"[MCP計算] {a} × {b} = {result}"
@mcp.tool()
async def divide(a: Union[int, float], b: Union[int, float]) -> str:
"""割り算"""
if b == 0:
raise ZeroDivisionError("0で割ることはできません")
result = float(a / b)
return f"[MCP計算] {a} ÷ {b} = {result}"
if __name__ == "__main__":
# サーバー起動
mcp.run(transport='stdio')
著者:志村佳昭(株式会社トリニタス 技術顧問)