# サーバー開発者向け

- Claude for Desktop やその他のクライアントで使用する独自のサーバーの構築を開始します。

  このチュートリアルでは、シンプルな MCP 天気予報サーバーを構築し、ホストである Claude for Desktop に接続します。まずは基本的なセットアップから始めて、より複雑なユースケースに進みます。

  ### [私たちが構築するもの](https://modelcontextprotocol.io/quickstart/server#what-we’ll-be-building)

  多くの LLMs (Claude を含む) には現在、予報や悪天候警報を取得する機能がありません。MCP を使用してこれを解決しましょう。

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

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png)

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png)

  

> サーバーはどのクライアントにも接続できます。ここではシンプルさのために Claude for Desktop を選択しましたが、[独自のクライアントを構築する](https://modelcontextprotocol.io/quickstart/client)ためのガイドや、[他のクライアントのリストもこちらに](https://modelcontextprotocol.io/clients)あります。
> 
  なぜ Claude for Desktop ではなく、Claude.ai なのでしょうか?

  ### [MCP のコアコンセプト](https://modelcontextprotocol.io/quickstart/server#core-mcp-concepts) 

  MCP サーバーは、主に次の 3 種類の機能を提供できます。

  1. **リソース**: クライアントが読み取ることができるファイルのようなデータ (API 応答やファイルの内容など)
  2. **ツール**: LLM から呼び出せる関数 (ユーザーの承認が必要)
  3. **プロンプト**: ユーザーが特定のタスクを達成するのに役立つ、事前に作成されたテンプレート

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

  Python 

  天気予報サーバーの構築を始めましょう。[ここで構築する完全なコードを見つけることができます。](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)

  ### 前提知識

  このクイックスタートでは、以下の知識があることを前提としています。

  - Python
  - Claude などの LLM

  ### システム要件

  - Python 3.10 以降がインストールされています。
  - Python MCP SDK 1.2.0 以降を使用する必要があります。

  ### 環境を設定する

  まず、 `uv`をインストールし、Python プロジェクトと環境を設定しましょう。

  MacOS/Linux

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

  Windows 

  ```powershell
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  ```

  `uv`コマンドが確実に実行されるように、後でターミナルを再起動してください。

  それでは、プロジェクトを作成して設定しましょう。

  MacOS/Linux 

  ```powershell
  # 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
  ```

  Windows

  ```powershell
  # Create a new directory for our project
  uv init weather
  cd weather
  
  # Create virtual environment and activate it
  uv venv
  .venv\Scripts\activate
  
  # Install dependencies
  uv add mcp[cli] httpx
  
  # Create our server file
  new-item weather.py
  ```

  それでは、サーバーの構築に取り掛かりましょう。

  ## サーバーの構築

  ### パッケージのインポートとインスタンスの設定

  これらを`weather.py`の先頭に追加します:

  ```python
  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 の型ヒントとドキュメント文字列を使用してツール定義を自動的に生成し、MCP ツールの作成と保守を容易にします。

  ### ヘルパー関数

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

  ```python
  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')}
  """
  ```

  ### ツール実行の実装

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

  ```python
  @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)
  ```

  ### サーバーの実行

  最後に、サーバーを初期化して実行します。

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

  サーバーが完成しました。uv `uv run weather.py`を実行して、すべてが動作していることを確認してください。

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

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

  

  Claude for Desktop はまだ Linux では利用できません。Linux ユーザーは[、クライアントの構築](https://modelcontextprotocol.io/quickstart/client)チュートリアルに進み、構築したサーバーに接続する MCP クライアントを構築できます。

  まず、Claude for Desktop がインストールされていることを確認してください。[最新バージョンはここからインストールできます。](https://claude.ai/download)すでに Claude for Desktop をお持ちの場合は、**最新バージョンに更新されていることを確認してください。**

  使用する MCP サーバーに応じて、Claude for Desktop を構成する必要があります。これを行うには、テキスト エディターで `~/Library/Application Support/Claude/claude_desktop_config.json` にある Claude for Desktop アプリの構成を開きます。ファイルが存在しない場合は必ず作成してください。

  たとえば、 [VS Code](https://code.visualstudio.com/)がインストールされている場合は次のようになります。

  MacOS/Linux 

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

  Windows

  ```powershell
  code $env:AppData\Claude\claude_desktop_config.json
  ```

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

  この場合、次のように単一の天気予報サーバーを追加します。

  MacOS/Linux

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

  Windows

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

>   `command`フィールドに`uv`実行可能ファイルへのフル パスを入力する必要がある場合があります。これは、MacOS/Linux では`which uv` 、Windows では`where uv`実行することで取得できます。
> 
 

>   必ずサーバーへの絶対パスを渡してください。

  これはデスクトップの Claude に次のように伝えます。

  1. 「weather」という名前のMCPサーバーがあります
  2. `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py` を実行して起動するには

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

  ### [コマンドでテストする](https://modelcontextprotocol.io/quickstart/server#test-with-commands) 

  Claude for Desktop が`weather`サーバーで公開した 2 つのツールを取得していることを確認しましょう。これを行うには、ハンマー ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg) アイコンを探します。

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png)

  ハンマーアイコンをクリックすると、次の 2 つのツールがリストされます。

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png)

  サーバーが Claude for Desktop によって取得されない場合は、[トラブルシューティング](https://modelcontextprotocol.io/quickstart/server#troubleshooting)セクションに進み、デバッグのヒントを参照してください。

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

  - サクラメントの天気はどうですか?
  - テキサス州で発令中の気象警報は何ですか?

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png)

  ![img](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png)

  

  これは米国国立気象サービスであるため、クエリは米国の場所でのみ機能します。

  ## [ボンネットの下で何が起こっているのか](https://modelcontextprotocol.io/quickstart/server#what’s-happening-under-the-hood)

  質問をするときは：

  1. クライアントはあなたの質問をクロードに送信します
  2. クロードは利用可能なツールを分析し、どのツールを使用するかを決定します
  3. クライアントはMCPサーバーを介して選択されたツールを実行します。
  4. 結果はクロードに送り返される
  5. Claude は自然言語の応答を生成します
  6. 応答が表示されます。

