MCP : クイックスタート : サーバ開発者向け (Python SDK)

Python SDK を使用して単純な MCP 天気予報サーバを構築し、それをホスト Claude for Desktop に接続します。基本的なセットアップから始めて、より複雑なユースケースへと進みます。

Model Context Protocol (MCP) : クイックスタート : サーバ開発者向け (Python SDK)

作成 : クラスキャット・セールスインフォメーション
作成日時 : 05/04/2025

* 本記事は github modelcontextprotocol の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

クラスキャット は人工知能に関する各種サービスを提供しています。お気軽にご相談ください :

  • 人工知能導入個別相談会(無償)実施中! [詳細]

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • PoC(概念実証)を失敗させないための支援 [詳細]

お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • sales-info@classcat.com
  • ClassCatJP

 

 

Model Context Protocol (MCP) : クイックスタート : サーバ開発者向け (Python SDK)

Claude for Desktop やその他のクライアントで使用するあなた自身のサーバを構築することから始めましょう。

このチュートリアルでは、単純な MCP 天気予報サーバ (weather server) を構築してそれをホスト Claude for Desktop に接続します。基本的なセットアップから始めて、より複雑なユースケースへと進みます。

 

構築していくもの

多くの LLM は現在、天気予報と重大な天気警報を取得する機能を持ちません。MCP を使用してそれを解決しましょう!

2 つのツール: get-alerts と get-forecast を公開するサーバを構築します。それからそのサーバを MCP ホスト (この場合、Claude for Desktop) に接続します :

 
Note : サーバは任意のクライアントに接続できます。ここでは単純化のために Claude for Desktop を選択しましたが、独自のクライアントを構築する ためのガイドや その他のクライアントのリスト もあります。

 
Why Claude for Desktop and not Claude.ai?

サーバがローカルで実行されるため、現在 MCP はデスクトップホストだけをサポートしています。Remote hosts are in active development.

 

中核の MCP コンセプト

MCP サーバは 3 つの種類の主な機能を提供できます :

  1. Resources : クライアントが読めるファイルのようなデータ (API レスポンスやファイルコンテンツのような)

  2. Tools : LLM により呼び出せる関数 (ユーザ承認を伴う)

  3. Prompts : ユーザが特定のタスクを達成するのに役立つ事前作成されたテンプレート

このチュートリアルは主としてツールに焦点を当てます。

天気予報サーバを構築することから始めましょう!構築していくものの完全なコードは こちら にあります。

 

前提知識

このクイックスタートは以下に精通していることを仮定しています :

  • Python
  • Claude のような LLM

 

システム要件

  • Python 3.10 以降がインストールされていること。

  • Python MCP SDK 1.2.0 以降を使用する必要があります。

 

環境のセットアップ

最初に、uv をインストールして Python プロジェクトと環境をセットアップします :

MacOS/Linux

curl -LsSf https://astral.sh/uv/install.sh | sh

Now, let’s create and set up our project:

# Create a new directory for our project
uv init weather
cd weather

# Create virtual environment and activate it
uv venv
source .venv/bin/activate

# Install dependencies
uv add "mcp[cli]" httpx

# Create our server file
touch weather.py

Now let’s dive into building your server.

 

サーバの構築

パッケージのインポートとインスタンスのセットアップ

weather.py の先頭に以下を追加します :

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

# Initialize FastMCP server
mcp = FastMCP("weather")

# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"

FastMCP クラスは Python の型ヒントと docstring を使用してツール定義を自動生成し、MCP ツールの作成と保守を簡単にします。

 

ヘルパー関数

次に、National Weather Service API からのデータをクエリーしてフォーマットするヘルパー関数を追加しましょう :

async def make_nws_request(url: str) -> dict[str, Any] | None:
    """Make a request to the NWS API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/geo+json"
    }
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

def format_alert(feature: dict) -> str:
    """Format an alert feature into a readable string."""
    props = feature["properties"]
    return f"""
Event: {props.get('event', 'Unknown')}
Area: {props.get('areaDesc', 'Unknown')}
Severity: {props.get('severity', 'Unknown')}
Description: {props.get('description', 'No description available')}
Instructions: {props.get('instruction', 'No specific instructions provided')}
"""

 

ツール実行の実装

ツール実行ハンドラは各ツールのロジックを実際に実行する役割を担います。それを追加しましょう :

@mcp.tool()
async def get_alerts(state: str) -> str:
    """Get weather alerts for a US state.

    Args:
        state: Two-letter US state code (e.g. CA, NY)
    """
    url = f"{NWS_API_BASE}/alerts/active/area/{state}"
    data = await make_nws_request(url)

    if not data or "features" not in data:
        return "Unable to fetch alerts or no alerts found."

    if not data["features"]:
        return "No active alerts for this state."

    alerts = [format_alert(feature) for feature in data["features"]]
    return "\n---\n".join(alerts)

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    """Get weather forecast for a location.

    Args:
        latitude: Latitude of the location
        longitude: Longitude of the location
    """
    # First get the forecast grid endpoint
    points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
    points_data = await make_nws_request(points_url)

    if not points_data:
        return "Unable to fetch forecast data for this location."

    # Get the forecast URL from the points response
    forecast_url = points_data["properties"]["forecast"]
    forecast_data = await make_nws_request(forecast_url)

    if not forecast_data:
        return "Unable to fetch detailed forecast."

    # Format the periods into a readable forecast
    periods = forecast_data["properties"]["periods"]
    forecasts = []
    for period in periods[:5]:  # Only show next 5 periods
        forecast = f"""
{period['name']}:
Temperature: {period['temperature']}°{period['temperatureUnit']}
Wind: {period['windSpeed']} {period['windDirection']}
Forecast: {period['detailedForecast']}
"""
        forecasts.append(forecast)

    return "\n---\n".join(forecasts)

 

サーバの実行

最後に、サーバを初期化して実行しましょう :

if __name__ == "__main__":
    # Initialize and run the server
    mcp.run(transport='stdio')

Your server is complete! “uv run weather.py” を実行してすべてが動作することを確認してください。

次に、既存の MCP ホスト、Claude for Desktop からサーバをテストしてみましょう。

 

Claude for Desktop でサーバをテストする

Note : Claude for Desktop is NOT yet available on Linux. Linux users can proceed to the Building a client tutorial to build an MCP client that connects to the server we just built.

最初に、Claude for Desktop がインストールされていることを確認してください。最新版は こちら でインストールできます。既に Claude for Desktop を持っているなら、最新版に更新されていることを確認しましょう。

使用したい MCP サーバが何であれ、そのために Claude for Desktop を設定する必要があります。そのため、テキストエディタで “~/Library/Application Support/Claude/claude_desktop_config.json” にある Claude for Desktop App の設定ファイルを開いてください。存在しないなら必ずファイルを作成してください。

For example, if you have VS Code installed:

code ~/Library/Application\ Support/Claude/claude_desktop_config.json

それから mcpServers キーにサーバを追加します。MCP UI 要素は、少なくとも 1 つのサーバが正しく構成されている場合に Claude for Desktop に表示されます。

In this case, we’ll add our single weather server like so:

{
    "mcpServers": {
        "weather": {
            "command": "uv",
            "args": [
                "--directory",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
                "run",
                "weather.py"
            ]
        }
    }
}

これは Claude for Desktop に以下を伝えます :

  • “weather” という名前の MCP サーバがある

  • それを起動するには “uv –directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py” を実行する。

ファイルを保存して、Claude for Desktop を再起動します。

 

コマンドでテストする

Claude for Desktop が、weather サーバで公開した 2 つのツールをピックアップしていることを確認しましょう。ハンマー アイコンを探すことでこれを行うことができます :

ハンマーアイコンをクリックすると、2 つのツールがリストされるのを見るはずです :

サーバが Claude for Desktop によりピックアップされていない場合、Troubleshooting section for debugging tips に進んでください。

ハンマーアイコンが表示されている場合は、Claude for Desktop で次のコマンドを実行してサーバをテストすることができます :

  • What’s the weather in Sacramento?

  • What are the active weather alerts in Texas?

 

What’s happening under the hood

あなたが質問すると :

  1. クライアントは質問を Claude に送信します

  2. Claude は利用可能なツールを分析してどれを使用するか決定します。

  3. クライアントは選択されたツールを MCP サーバ経由で実行します。

  4. 結果は Claude に送り返されます。

  5. Claude は自然言語のレスポンスを作成します。

  6. レスポンスがあなたに表示されます!

 

以上