> ## Documentation Index
> Fetch the complete documentation index at: https://startai.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 面向服务器开发者

> 学习如何构建自己的服务器以在 Claude for Desktop 和其他客户端中使用。

在本教程中，我们将构建一个简单的 MCP 天气服务器并将其连接到宿主程序 Claude for Desktop。我们将从基本设置开始，然后逐步过渡到更复杂的用例。

### 我们要构建什么

许多 LLM 目前还没有获取天气预报和严重天气预警的能力。让我们用 MCP 来解决这个问题！

我们将构建一个暴露两个工具的服务器：`get-alerts` 和 `get-forecast`。然后我们将服务器连接到 MCP 宿主程序（在本例中是 Claude for Desktop）：

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/weather-alerts.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=7fac7a3f4c29f344ab85219b76849c7d" width="2809" height="1850" data-path="images/weather-alerts.png" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/current-weather.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=b39e7cfc3ae15d8d4f5ae9f0e2ddb399" width="2780" height="1849" data-path="images/current-weather.png" />
</Frame>

<Note>
  服务器可以连接到任何客户端。我们在这里选择 Claude for Desktop 是为了简单起见，但我们也有关于[构建自己的客户端](/quickstart/client)的指南以及[其他客户端列表](/clients)。
</Note>

<Accordion title="为什么选择 Claude for Desktop 而不是 Claude.ai?">
  因为服务器是本地运行的，MCP 目前只支持桌面宿主程序。远程宿主程序正在积极开发中。
</Accordion>

### MCP 核心概念

MCP 服务器可以提供三种主要类型的功能：

1. **资源**：客户端可以读取的类文件数据（如 API 响应或文件内容）
2. **工具**：可以被 LLM 调用的函数（需要用户批准）
3. **提示**：帮助用户完成特定任务的预写模板

本教程将主要关注工具。

<Tabs>
  <Tab title="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 项目和环境：

    <CodeGroup>
      ```bash MacOS/Linux theme={null}
      curl -LsSf https://astral.sh/uv/install.sh | sh
      ```

      ```powershell Windows theme={null}
      powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
      ```
    </CodeGroup>

    之后请务必重启终端，以确保 `uv` 命令被识别。

    现在，让我们创建并设置我们的项目：

    <CodeGroup>
      ```bash MacOS/Linux theme={null}
      # 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
      ```

      ```powershell Windows theme={null}
      # 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
      ```
    </CodeGroup>

    现在让我们开始构建你的服务器。

    ## Building your server

    ### 导入包并设置实例

    将这些添加到 `weather.py` 的顶部：

    ```python theme={null}
    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 工具变得容易。

    ### 辅助函数

    接下来，让我们添加用于查询和格式化来自国家气象局 API 数据的辅助函数：

    ```python theme={null}
    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 theme={null}
    @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 theme={null}
    if __name__ == "__main__":
        # Initialize and run the server
        mcp.run(transport='stdio')
    ```

    你的服务器已完成！运行 `uv run weather.py` 来确认一切正常。

    现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。

    ## 使用 Claude for Desktop 测试你的服务器

    <Note>
      Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读[构建客户端](/quickstart/client)教程，以构建连接到我们刚刚构建的服务器的 MCP 客户端。
    </Note>

    首先，确保你已经安装了 Claude for Desktop。[你可以在这里安装最新版本。](https://claude.ai/download) 如果你已经安装了 Claude for Desktop，**请确保它已更新到最新版本。**

    我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。为此，请在文本编辑器中打开你的 Claude for Desktop 应用配置，路径为 `~/Library/Application Support/Claude/claude_desktop_config.json`。如果文件不存在，请确保创建它。

    例如，如果你安装了 [VS Code](https://code.visualstudio.com/)：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```bash theme={null}
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```
      </Tab>

      <Tab title="Windows">
        ```powershell theme={null}
        code $env:AppData\Claude\claude_desktop_config.json
        ```
      </Tab>
    </Tabs>

    然后你将在 `mcpServers` 键中添加你的服务器。只有当至少一个服务器被正确配置时，MCP UI 元素才会显示在 Claude for Desktop 中。

    在这种情况下，我们将像这样添加我们的单个天气服务器：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```json Python theme={null}
        {
            "mcpServers": {
                "weather": {
                    "command": "uv",
                    "args": [
                        "--directory",
                        "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
                        "run",
                        "weather.py"
                    ]
                }
            }
        }
        ```
      </Tab>

      <Tab title="Windows">
        ```json Python theme={null}
        {
            "mcpServers": {
                "weather": {
                    "command": "uv",
                    "args": [
                        "--directory",
                        "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
                        "run",
                        "weather.py"
                    ]
                }
            }
        }
        ```
      </Tab>
    </Tabs>

    <Warning>
      你可能需要在 `command` 字段中放入 `uv` 可执行文件的完整路径。你可以通过在 MacOS/Linux 上运行 `which uv` 或在 Windows 上运行 `where uv` 来获取此路径。
    </Warning>

    <Note>
      确保你传入服务器的绝对路径。
    </Note>

    这告诉 Claude for Desktop：

    1. 有一个名为 "weather" 的 MCP 服务器
    2. 通过运行 `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py` 来启动它

    保存文件，并重启 **Claude for Desktop**。
  </Tab>

  <Tab title="Node">
    让我们开始构建我们的天气服务器！[你可以在这里找到我们将要构建的完整代码。](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)

    ### 前置知识

    本快速入门假设你熟悉：

    * TypeScript
    * Claude 等 LLM

    ### 系统要求

    对于 TypeScript，请确保你已安装最新版本的 Node。

    ### 设置你的环境

    首先，如果你还没有安装 Node.js 和 npm，请先安装它们。你可以从 [nodejs.org](https://nodejs.org/) 下载。
    验证你的 Node.js 安装：

    ```bash theme={null}
    node --version
    npm --version
    ```

    对于本教程，你需要 Node.js 16 或更高版本。

    现在，让我们创建并设置我们的项目：

    <CodeGroup>
      ```bash MacOS/Linux theme={null}
      # Create a new directory for our project
      mkdir weather
      cd weather

      # Initialize a new npm project
      npm init -y

      # Install dependencies
      npm install @modelcontextprotocol/sdk zod
      npm install -D @types/node typescript

      # Create our files
      mkdir src
      touch src/index.ts
      ```

      ```powershell Windows theme={null}
      # Create a new directory for our project
      md weather
      cd weather

      # Initialize a new npm project
      npm init -y

      # Install dependencies
      npm install @modelcontextprotocol/sdk zod
      npm install -D @types/node typescript

      # Create our files
      md src
      new-item src\index.ts
      ```
    </CodeGroup>

    更新你的 package.json 以添加 type: "module" 和一个构建脚本：

    ```json package.json theme={null}
    {
      "type": "module",
      "bin": {
        "weather": "./build/index.js"
      },
      "scripts": {
        "build": "tsc && chmod 755 build/index.js"
      },
      "files": [
        "build"
      ],
    }
    ```

    在你的项目根目录下创建一个 `tsconfig.json`：

    ```json tsconfig.json theme={null}
    {
      "compilerOptions": {
        "target": "ES2022",
        "module": "Node16",
        "moduleResolution": "Node16",
        "outDir": "./build",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    ```

    现在让我们开始构建你的服务器。

    ## Building your server

    ### 导入包并设置实例

    将这些添加到你的 `src/index.ts` 文件的顶部：

    ```typescript theme={null}
    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    import { z } from "zod";

    const NWS_API_BASE = "https://api.weather.gov";
    const USER_AGENT = "weather-app/1.0";

    // Create server instance
    const server = new McpServer({
      name: "weather",
      version: "1.0.0",
      capabilities: {
        resources: {},
        tools: {},
      },
    });
    ```

    ### 辅助函数

    接下来，让我们添加用于查询和格式化来自国家气象局 API 数据的辅助函数：

    ```typescript theme={null}
    // 用于发出 NWS API 请求的辅助函数
    async function makeNWSRequest<T>(url: string): Promise<T | null> {
      const headers = {
        "User-Agent": USER_AGENT,
        Accept: "application/geo+json",
      };

      try {
        const response = await fetch(url, { headers });
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return (await response.json()) as T;
      } catch (error) {
        console.error("Error making NWS request:", error);
        return null;
      }
    }

    interface AlertFeature {
      properties: {
        event?: string;
        areaDesc?: string;
        severity?: string;
        status?: string;
        headline?: string;
      };
    }

    // 格式化警报数据
    function formatAlert(feature: AlertFeature): string {
      const props = feature.properties;
      return [
        `Event: ${props.event || "Unknown"}`,
        `Area: ${props.areaDesc || "Unknown"}`,
        `Severity: ${props.severity || "Unknown"}`,
        `Status: ${props.status || "Unknown"}`,
        `Headline: ${props.headline || "No headline"}`,
        "---",
      ].join("\n");
    }

    interface ForecastPeriod {
      name?: string;
      temperature?: number;
      temperatureUnit?: string;
      windSpeed?: string;
      windDirection?: string;
      shortForecast?: string;
    }

    interface AlertsResponse {
      features: AlertFeature[];
    }

    interface PointsResponse {
      properties: {
        forecast?: string;
      };
    }

    interface ForecastResponse {
      properties: {
        periods: ForecastPeriod[];
      };
    }
    ```

    ### 实现工具执行

    工具执行处理程序负责实际执行每个工具的逻辑。让我们添加它：

    ```typescript theme={null}
    // 注册天气工具
    server.tool(
      "get-alerts",
      "Get weather alerts for a state",
      {
        state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"),
      },
      async ({ state }) => {
        const stateCode = state.toUpperCase();
        const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
        const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);

        if (!alertsData) {
          return {
            content: [
              {
                type: "text",
                text: "Failed to retrieve alerts data",
              },
            ],
          };
        }

        const features = alertsData.features || [];
        if (features.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: `No active alerts for ${stateCode}`,
              },
            ],
          };
        }

        const formattedAlerts = features.map(formatAlert);
        const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;

        return {
          content: [
            {
              type: "text",
              text: alertsText,
            },
          ],
        };
      },
    );

    server.tool(
      "get-forecast",
      "Get weather forecast for a location",
      {
        latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
        longitude: z.number().min(-180).max(180).describe("Longitude of the location"),
      },
      async ({ latitude, longitude }) => {
        // Get grid point data
        const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
        const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);

        if (!pointsData) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
              },
            ],
          };
        }

        const forecastUrl = pointsData.properties?.forecast;
        if (!forecastUrl) {
          return {
            content: [
              {
                type: "text",
                text: "Failed to get forecast URL from grid point data",
              },
            ],
          };
        }

        // Get forecast data
        const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
        if (!forecastData) {
          return {
            content: [
              {
                type: "text",
                text: "Failed to retrieve forecast data",
              },
            ],
          };
        }

        const periods = forecastData.properties?.periods || [];
        if (periods.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: "No forecast periods available",
              },
            ],
          };
        }

        // Format forecast periods
        const formattedForecast = periods.map((period: ForecastPeriod) =>
          [
            `${period.name || "Unknown"}:`,
            `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
            `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
            `${period.shortForecast || "No forecast available"}`,
            "---",
          ].join("\n"),
        );

        const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;

        return {
          content: [
            {
              type: "text",
              text: forecastText,
            },
          ],
        };
      },
    );
    ```

    ### 运行服务器

    最后，实现运行服务器的主函数：

    ```typescript theme={null}
    async function main() {
      const transport = new StdioServerTransport();
      await server.connect(transport);
      console.error("Weather MCP Server running on stdio");
    }

    main().catch((error) => {
      console.error("Fatal error in main():", error);
      process.exit(1);
    });
    ```

    请确保运行 `npm run build` 来构建你的服务器！这是让你的服务器成功连接的关键一步。

    现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。

    ## 使用 Claude for Desktop 测试你的服务器

    <Note>
      Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读[构建客户端](/quickstart/client)教程，以构建连接到我们刚刚构建的服务器的 MCP 客户端。
    </Note>

    首先，确保你已经安装了 Claude for Desktop。[你可以在这里安装最新版本。](https://claude.ai/download) 如果你已经安装了 Claude for Desktop，**请确保它已更新到最新版本。**

    我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。为此，请在文本编辑器中打开你的 Claude for Desktop 应用配置，路径为 `~/Library/Application Support/Claude/claude_desktop_config.json`。如果文件不存在，请确保创建它。

    例如，如果你安装了 [VS Code](https://code.visualstudio.com/)：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```bash theme={null}
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```
      </Tab>

      <Tab title="Windows">
        ```powershell theme={null}
        code $env:AppData\Claude\claude_desktop_config.json
        ```
      </Tab>
    </Tabs>

    然后你将在 `mcpServers` 键中添加你的服务器。只有当至少一个服务器被正确配置时，MCP UI 元素才会显示在 Claude for Desktop 中。

    在这种情况下，我们将像这样添加我们的单个天气服务器：

    <Tabs>
      <Tab title="MacOS/Linux">
        <CodeGroup>
          ```json Node theme={null}
          {
              "mcpServers": {
                  "weather": {
                      "command": "node",
                      "args": [
                          "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"
                      ]
                  }
              }
          }
          ```
        </CodeGroup>
      </Tab>

      <Tab title="Windows">
        <CodeGroup>
          ```json Node theme={null}
          {
              "mcpServers": {
                  "weather": {
                      "command": "node",
                      "args": [
                          "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"
                      ]
                  }
              }
          }
          ```
        </CodeGroup>
      </Tab>
    </Tabs>

    这告诉 Claude for Desktop：

    1. 有一个名为 "weather" 的 MCP 服务器
    2. 通过运行 `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js` 来启动它

    保存文件，并重启 **Claude for Desktop**。
  </Tab>

  <Tab title="Java">
    <Note>
      这是一个基于 Spring AI MCP 自动配置和启动器的快速入门演示。
      要了解如何手动创建同步和异步 MCP 服务器，请查阅 [Java SDK 服务器](/sdk/java/mcp-server) 文档。
    </Note>

    让我们开始构建我们的天气服务器！
    [你可以在这里找到我们将要构建的完整代码。](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)

    更多信息，请参阅 [MCP 服务器启动器](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) 参考文档。
    对于手动 MCP 服务器实现，请参阅 [MCP 服务器 Java SDK 文档](/sdk/java/mcp-server)。

    ### 系统要求

    * 已安装 Java 17 或更高版本。
    * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) 或更高版本

    ### 设置你的环境

    使用 [Spring Initializer](https://start.spring.io/) 来引导项目。

    你需要添加以下依赖项：

    <Tabs>
      <Tab title="Maven">
        ```xml theme={null}
        <dependencies>
              <dependency>
                  <groupId>org.springframework.ai</groupId>
                  <artifactId>spring-ai-starter-mcp-server</artifactId>
              </dependency>

              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-web</artifactId>
              </dependency>
        </dependencies>
        ```
      </Tab>

      <Tab title="Gradle">
        ```groovy theme={null}
        dependencies {
          implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
          implementation platform("org.springframework:spring-web")   
        }
        ```
      </Tab>
    </Tabs>

    然后通过设置应用程序属性来配置你的应用程序：

    <CodeGroup>
      ```bash application.properties theme={null}
      spring.main.bannerMode=off
      logging.pattern.console=
      ```

      ```yaml application.yml theme={null}
      logging:
        pattern:
          console:
      spring:
        main:
          banner-mode: off
      ```
    </CodeGroup>

    [服务器配置属性](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) 文档列出了所有可用的属性。

    现在让我们开始构建你的服务器。

    ## Building your server

    ### 天气服务

    让我们实现一个 [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java)，它使用 REST 客户端从国家气象局 API 查询数据：

    ```java theme={null}
    @Service
    public class WeatherService {

    	private final RestClient restClient;

    	public WeatherService() {
    		this.restClient = RestClient.builder()
    			.baseUrl("https://api.weather.gov")
    			.defaultHeader("Accept", "application/geo+json")
    			.defaultHeader("User-Agent", "WeatherApiClient/1.0 (your@email.com)")
    			.build();
    	}

      @Tool(description = "Get weather forecast for a specific latitude/longitude")
      public String getWeatherForecastByLocation(
          double latitude,   // Latitude coordinate
          double longitude   // Longitude coordinate
      ) {
          // Returns detailed forecast including:
          // - Temperature and unit
          // - Wind speed and direction
          // - Detailed forecast description
      }
    	
      @Tool(description = "Get weather alerts for a US state")
      public String getAlerts(
          @ToolParam(description = "Two-letter US state code (e.g. CA, NY)" String state
      ) {
          // Returns active alerts including:
          // - Event type
          // - Affected area
          // - Severity
          // - Description
          // - Safety instructions
      }

      // ......
    }
    ```

    `@Service` 注解会自动在你的应用程序上下文中注册该服务。
    Spring AI `@Tool` 注解使得创建和维护 MCP 工具变得容易。

    自动配置将自动向 MCP 服务器注册这些工具。

    ### 创建你的 Boot 应用程序

    ```java theme={null}
    @SpringBootApplication
    public class McpServerApplication {

    	public static void main(String[] args) {
    		SpringApplication.run(McpServerApplication.class, args);
    	}

    	@Bean
    	public ToolCallbackProvider weatherTools(WeatherService weatherService) {
    		return  MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
    	}
    }
    ```

    使用 `MethodToolCallbackProvider` 工具将 `@Tools` 转换为 MCP 服务器使用的可操作回调。

    ### 运行服务器

    最后，让我们构建服务器：

    ```bash theme={null}
    ./mvnw clean install
    ```

    这将在 `target` 文件夹内生成一个 `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 文件。

    现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。

    ## 使用 Claude for Desktop 测试你的服务器

    <Note>
      Claude for Desktop 尚未在 Linux 上可用。
    </Note>

    首先，确保你已经安装了 Claude for Desktop。
    [你可以在这里安装最新版本。](https://claude.ai/download) 如果你已经安装了 Claude for Desktop，**请确保它已更新到最新版本。**

    我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
    为此，请在文本编辑器中打开你的 Claude for Desktop 应用配置，路径为 `~/Library/Application Support/Claude/claude_desktop_config.json`。
    如果文件不存在，请确保创建它。

    例如，如果你安装了 [VS Code](https://code.visualstudio.com/)：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```bash theme={null}
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```
      </Tab>

      <Tab title="Windows">
        ```powershell theme={null}
        code $env:AppData\Claude\claude_desktop_config.json
        ```
      </Tab>
    </Tabs>

    然后你将在 `mcpServers` 键中添加你的服务器。
    只有当至少一个服务器被正确配置时，MCP UI 元素才会显示在 Claude for Desktop 中。

    在这种情况下，我们将像这样添加我们的单个天气服务器：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```json java theme={null}
        {
          "mcpServers": {
            "spring-ai-mcp-weather": {
              "command": "java",
              "args": [
                "-Dspring.ai.mcp.server.stdio=true",
                "-jar",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
              ]
            }
          }
        }
        ```
      </Tab>

      <Tab title="Windows">
        ```json java theme={null}
        {
          "mcpServers": {
            "spring-ai-mcp-weather": {
              "command": "java",
              "args": [
                "-Dspring.ai.mcp.server.transport=STDIO",
                "-jar",
                "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
              ]
            }
          }
        }
        ```
      </Tab>
    </Tabs>

    <Note>
      确保你传入服务器的绝对路径。
    </Note>

    这告诉 Claude for Desktop：

    1. 有一个名为 "my-weather-server" 的 MCP 服务器
    2. 通过运行 `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 来启动它

    保存文件，并重启 **Claude for Desktop**。

    ## 使用 Java 客户端测试你的服务器

    ### 手动创建 MCP 客户端

    使用 `McpClient` 连接到服务器：

    ```java theme={null}
    var stdioParams = ServerParameters.builder("java")
      .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
      .build();

    var stdioTransport = new StdioClientTransport(stdioParams);

    var mcpClient = McpClient.sync(stdioTransport).build();

    mcpClient.initialize();

    ListToolsResult toolsList = mcpClient.listTools();

    CallToolResult weather = mcpClient.callTool(
      new CallToolRequest("getWeatherForecastByLocation",
          Map.of("latitude", "47.6062", "longitude", "-122.3321")));

    CallToolResult alert = mcpClient.callTool(
      new CallToolRequest("getAlerts", Map.of("state", "NY")));

    mcpClient.closeGracefully();
    ```

    ### 使用 MCP 客户端启动器

    使用 `spring-ai-starter-mcp-client` 依赖项创建一个新的启动器应用程序：

    ```xml theme={null}
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-mcp-client</artifactId>
    </dependency>
    ```

    并将 `spring.ai.mcp.client.stdio.servers-configuration` 属性设置为指向你的 `claude_desktop_config.json`。
    你可以重用现有的 Anthropic Desktop 配置：

    ```properties theme={null}
    spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
    ```

    当你启动客户端应用程序时，自动配置将自动从 claude\_desktop\_config.json 创建 MCP 客户端。

    更多信息，请参阅 [MCP 客户端启动器](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-client-docs.html) 参考文档。

    ## 更多 Java MCP 服务器示例

    [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) 演示了如何使用 SSE 传输创建 MCP 服务器。
    它展示了如何使用 Spring Boot 的自动配置功能来定义和注册 MCP 工具、资源和提示。
  </Tab>

  <Tab title="Kotlin">
    让我们开始构建我们的天气服务器！[你可以在这里找到我们将要构建的完整代码。](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)

    ### 前置知识

    本快速入门假设你熟悉：

    * Kotlin
    * Claude 等 LLM

    ### 系统要求

    * 已安装 Java 17 或更高版本。

    ### 设置你的环境

    首先，如果你还没有安装 `java` 和 `gradle`，请先安装它们。
    你可以从 [Oracle 官方 JDK 网站](https://www.oracle.com/java/technologies/downloads/) 下载 `java`。
    验证你的 `java` 安装：

    ```bash theme={null}
    java --version
    ```

    现在，让我们创建并设置你的项目：

    <CodeGroup>
      ```bash MacOS/Linux theme={null}
      # Create a new directory for our project
      mkdir weather
      cd weather

      # Initialize a new kotlin project
      gradle init
      ```

      ```powershell Windows theme={null}
      # Create a new directory for our project
      md weather
      cd weather

      # Initialize a new kotlin project
      gradle init
      ```
    </CodeGroup>

    运行 `gradle init` 后，你将看到创建项目的选项。
    选择 **Application** 作为项目类型，**Kotlin** 作为编程语言，**Java 17** 作为 Java 版本。

    或者，你可以使用 [IntelliJ IDEA 项目向导](https://kotlinlang.org/docs/jvm-get-started.html) 创建 Kotlin 应用程序。

    创建项目后，添加以下依赖项：

    <CodeGroup>
      ```kotlin build.gradle.kts theme={null}
      val mcpVersion = "0.4.0"
      val slf4jVersion = "2.0.9"
      val ktorVersion = "3.1.1"

      dependencies {
          implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
          implementation("org.slf4j:slf4j-nop:$slf4jVersion")
          implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
          implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
      }
      ```

      ```groovy build.gradle theme={null}
      dependencies {
          implementation "io.modelcontextprotocol:kotlin-sdk:$mcpVersion"
          implementation "org.slf4j:slf4j-nop:$slf4jVersion"
          implementation "io.ktor:ktor-client-content-negotiation:$ktorVersion"
          implementation "io.ktor:ktor-serialization-kotlinx-json:$ktorVersion"
      }
      ```
    </CodeGroup>

    此外，将以下插件添加到你的构建脚本中：

    <CodeGroup>
      ```kotlin build.gradle.kts theme={null}
      plugins {
          kotlin("plugin.serialization") version "your_version_of_kotlin"
          id("com.github.johnrengelman.shadow") version "8.1.1"
      }
      ```

      ```groovy build.gradle theme={null}
      plugins {
          id 'org.jetbrains.kotlin.plugin.serialization' version 'your_version_of_kotlin'
          id 'com.github.johnrengelman.shadow' version '8.1.1'
      }
      ```
    </CodeGroup>

    现在让我们开始构建你的服务器。

    ## Building your server

    ### 设置实例

    添加一个服务器初始化函数：

    ```kotlin theme={null}
    // 运行 MCP 服务器的主函数
    fun `run mcp server`() {
        // 使用基本实现创建 MCP 服务器实例
        val server = Server(
            Implementation(
                name = "weather", // Tool name is "weather"
                version = "1.0.0" // Version of the implementation
            ),
            ServerOptions(
                capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true))
            )
        )

        // 使用标准 IO 创建用于服务器通信的传输
        val transport = StdioServerTransport(
            System.`in`.asInput(),
            System.out.asSink().buffered()
        )

        runBlocking {
            server.connect(transport)
            val done = Job()
            server.onClose {
                done.complete()
            }
            done.join()
        }
    }
    ```

    ### 天气 API 辅助函数

    接下来，让我们添加用于查询和转换来自国家气象局 API 响应的函数和数据类：

    ```kotlin theme={null}
    // 用于获取给定纬度和经度的天气预报信息的扩展函数
    suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
        val points = this.get("/points/$latitude,$longitude").body<Points>()
        val forecast = this.get(points.properties.forecast).body<Forecast>()
        return forecast.properties.periods.map { period ->
            """
                ${period.name}:
                Temperature: ${period.temperature} ${period.temperatureUnit}
                Wind: ${period.windSpeed} ${period.windDirection}
                Forecast: ${period.detailedForecast}
            """.trimIndent()
        }
    }

    // 用于获取给定州的天气警报的扩展函数
    suspend fun HttpClient.getAlerts(state: String): List<String> {
        val alerts = this.get("/alerts/active/area/$state").body<Alert>()
        return alerts.features.map { feature ->
            """
                Event: ${feature.properties.event}
                Area: ${feature.properties.areaDesc}
                Severity: ${feature.properties.severity}
                Description: ${feature.properties.description}
                Instruction: ${feature.properties.instruction}
            """.trimIndent()
        }
    }

    @Serializable
    data class Points(
        val properties: Properties
    ) {
        @Serializable
        data class Properties(val forecast: String)
    }

    @Serializable
    data class Forecast(
        val properties: Properties
    ) {
        @Serializable
        data class Properties(val periods: List<Period>)

        @Serializable
        data class Period(
            val number: Int, val name: String, val startTime: String, val endTime: String,
            val isDaytime: Boolean, val temperature: Int, val temperatureUnit: String,
            val temperatureTrend: String, val probabilityOfPrecipitation: JsonObject,
            val windSpeed: String, val windDirection: String,
            val shortForecast: String, val detailedForecast: String,
        )
    }

    @Serializable
    data class Alert(
        val features: List<Feature>
    ) {
        @Serializable
        data class Feature(
            val properties: Properties
        )

        @Serializable
        data class Properties(
            val event: String, val areaDesc: String, val severity: String,
            val description: String, val instruction: String?,
        )
    }
    ```

    ### 实现工具执行

    工具执行处理程序负责实际执行每个工具的逻辑。让我们添加它：

    ```kotlin theme={null}
    // 创建一个具有默认请求配置和 JSON 内容协商的 HTTP 客户端
    val httpClient = HttpClient {
        defaultRequest {
            url("https://api.weather.gov")
            headers {
                append("Accept", "application/geo+json")
                append("User-Agent", "WeatherApiClient/1.0")
            }
            contentType(ContentType.Application.Json)
        }
        // 安装用于 JSON 序列化/反序列化的内容协商插件
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    }

    // 注册一个按州获取天气警报的工具
    server.addTool(
        name = "get_alerts",
        description = """
            Get weather alerts for a US state. Input is Two-letter US state code (e.g. CA, NY)
        """.trimIndent(),
        inputSchema = Tool.Input(
            properties = buildJsonObject {
                putJsonObject("state") {
                    put("type", "string")
                    put("description", "Two-letter US state code (e.g. CA, NY)")
                }
            },
            required = listOf("state")
        )
    ) { request ->
        val state = request.arguments["state"]?.jsonPrimitive?.content
        if (state == null) {
            return@addTool CallToolResult(
                content = listOf(TextContent("The 'state' parameter is required."))
            )
        }

        val alerts = httpClient.getAlerts(state)

        CallToolResult(content = alerts.map { TextContent(it) })
    }

    // 注册一个按纬度和经度获取天气预报的工具
    server.addTool(
        name = "get_forecast",
        description = """
            Get weather forecast for a specific latitude/longitude
        """.trimIndent(),
        inputSchema = Tool.Input(
            properties = buildJsonObject {
                putJsonObject("latitude") { put("type", "number") }
                putJsonObject("longitude") { put("type", "number") }
            },
            required = listOf("latitude", "longitude")
        )
    ) { request ->
        val latitude = request.arguments["latitude"]?.jsonPrimitive?.doubleOrNull
        val longitude = request.arguments["longitude"]?.jsonPrimitive?.doubleOrNull
        if (latitude == null || longitude == null) {
            return@addTool CallToolResult(
                content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required."))
            )
        }

        val forecast = httpClient.getForecast(latitude, longitude)

        CallToolResult(content = forecast.map { TextContent(it) })
    }
    ```

    ### 运行服务器

    最后，实现运行服务器的主函数：

    ```kotlin theme={null}
    fun main() = `run mcp server`()
    ```

    请确保运行 `./gradlew build` 来构建你的服务器。这是让你的服务器成功连接的关键一步。

    现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。

    ## 使用 Claude for Desktop 测试你的服务器

    <Note>
      Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读[构建客户端](/quickstart/client)教程，以构建连接到我们刚刚构建的服务器的 MCP 客户端。
    </Note>

    首先，确保你已经安装了 Claude for Desktop。[你可以在这里安装最新版本。](https://claude.ai/download) 如果你已经安装了 Claude for Desktop，**请确保它已更新到最新版本。**

    我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
    为此，请在文本编辑器中打开你的 Claude for Desktop 应用配置，路径为 `~/Library/Application Support/Claude/claude_desktop_config.json`。
    如果文件不存在，请确保创建它。

    例如，如果你安装了 [VS Code](https://code.visualstudio.com/)：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```bash theme={null}
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```
      </Tab>

      <Tab title="Windows">
        ```powershell theme={null}
        code $env:AppData\Claude\claude_desktop_config.json
        ```
      </Tab>
    </Tabs>

    然后你将在 `mcpServers` 键中添加你的服务器。
    只有当至少一个服务器被正确配置时，MCP UI 元素才会显示在 Claude for Desktop 中。

    在这种情况下，我们将像这样添加我们的单个天气服务器：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```json java theme={null}
        {
          "mcpServers": {
            "spring-ai-mcp-weather": {
              "command": "java",
              "args": [
                "-jar",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
              ]
            }
          }
        }
        ```
      </Tab>

      <Tab title="Windows">
        ```json java theme={null}
        {
          "mcpServers": {
            "spring-ai-mcp-weather": {
              "command": "java",
              "args": [
                "-jar",
                "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
              ]
            }
          }
        }
        ```
      </Tab>
    </Tabs>

    这告诉 Claude for Desktop：

    1. 有一个名为 "my-weather-server" 的 MCP 服务器
    2. 通过运行 `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 来启动它

    保存文件，并重启 **Claude for Desktop**。
  </Tab>

  <Tab title="C#">
    让我们开始构建我们的天气服务器！[你可以在这里找到我们将要构建的完整代码。](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)

    ### 前置知识

    本快速入门假设你熟悉：

    * C#
    * Claude 等 LLM
    * .NET 8 或更高版本

    ### 系统要求

    * 已安装 [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) 或更高版本。

    ### 设置你的环境

    首先，如果你还没有安装 `dotnet`，请先安装它。你可以从 [微软官方 .NET 网站](https://dotnet.microsoft.com/download/) 下载 `dotnet`。验证你的 `dotnet` 安装：

    ```bash theme={null}
    dotnet --version
    ```

    现在，让我们创建并设置你的项目：

    <CodeGroup>
      ```bash MacOS/Linux theme={null}
      # Create a new directory for our project
      mkdir weather
      cd weather
      # Initialize a new C# project
      dotnet new console
      ```

      ```powershell Windows theme={null}
      # Create a new directory for our project
      mkdir weather
      cd weather
      # Initialize a new C# project
      dotnet new console
      ```
    </CodeGroup>

    运行 `dotnet new console` 后，你将看到一个新的 C# 项目。
    你可以在你喜欢的 IDE 中打开该项目，例如 [Visual Studio](https://visualstudio.microsoft.com/) 或 [Rider](https://www.jetbrains.com/rider/)。
    或者，你可以使用 [Visual Studio 项目向导](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022) 创建 C# 应用程序。
    创建项目后，为模型上下文协议 SDK 和托管添加 NuGet 包：

    ```bash theme={null}
    # Add the Model Context Protocol SDK NuGet package
    dotnet add package ModelContextProtocol --prerelease
    # Add the .NET Hosting NuGet package
    dotnet add package Microsoft.Extensions.Hosting
    ```

    现在让我们开始构建你的服务器。

    ## Building your server

    打开项目中的 `Program.cs` 文件，并将其内容替换为以下代码：

    ```csharp theme={null}
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using ModelContextProtocol;
    using System.Net.Http.Headers;

    var builder = Host.CreateEmptyApplicationBuilder(settings: null);

    builder.Services.AddMcpServer()
        .WithStdioServerTransport()
        .WithToolsFromAssembly();

    builder.Services.AddSingleton(_ =>
    {
        var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
        client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
        return client;
    });

    var app = builder.Build();

    await app.RunAsync();
    ```

    <Note>
      创建 `ApplicationHostBuilder` 时，请确保使用 `CreateEmptyApplicationBuilder` 而不是 `CreateDefaultBuilder`。这可以确保服务器不会向控制台写入任何额外的消息。这仅对于使用 STDIO 传输的服务器是必需的。
    </Note>

    此代码设置了一个基本的控制台应用程序，该应用程序使用模型上下文协议 SDK 创建具有标准 I/O 传输的 MCP 服务器。

    ### 天气 API 辅助函数

    接下来，定义一个包含工具执行处理程序的类，用于查询和转换来自国家气象局 API 的响应：

    ```csharp theme={null}
    using ModelContextProtocol.Server;
    using System.ComponentModel;
    using System.Net.Http.Json;
    using System.Text.Json;

    namespace QuickstartWeatherServer.Tools;

    [McpServerToolType]
    public static class WeatherTools
    {
        [McpServerTool, Description("Get weather alerts for a US state.")]
        public static async Task<string> GetAlerts(
            HttpClient client,
            [Description("The US state to get alerts for.")] string state)
        {
            var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/alerts/active/area/{state}");
            var alerts = jsonElement.GetProperty("features").EnumerateArray();

            if (!alerts.Any())
            {
                return "No active alerts for this state.";
            }

            return string.Join("\n--\n", alerts.Select(alert =>
            {
                JsonElement properties = alert.GetProperty("properties");
                return $"""
                        Event: {properties.GetProperty("event").GetString()}
                        Area: {properties.GetProperty("areaDesc").GetString()}
                        Severity: {properties.GetProperty("severity").GetString()}
                        Description: {properties.GetProperty("description").GetString()}
                        Instruction: {properties.GetProperty("instruction").GetString()}
                    """;
            }));
        }

        [McpServerTool, Description("Get weather forecast for a location.")]
        public static async Task<string> GetForecast(
            HttpClient client,
            [Description("Latitude of the location.")] double latitude,
            [Description("Longitude of the location.")] double longitude)
        {
            var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/points/{latitude},{longitude}");
            var periods = jsonElement.GetProperty("properties").GetProperty("periods").EnumerateArray();

            return string.Join("\n---\n", periods.Select(period => $"""
                    {period.GetProperty("name").GetString()}
                    Temperature: {period.GetProperty("temperature").GetInt32()}°F
                    Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
                    Forecast: {period.GetProperty("detailedForecast").GetString()}
                    """));
        }
    }
    ```

    ### 运行服务器

    最后，使用以下命令运行服务器：

    ```bash theme={null}
    dotnet run
    ```

    这将启动服务器并在标准输入/输出上侦听传入请求。

    ## 使用 Claude for Desktop 测试你的服务器

    <Note>
      Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读[构建客户端](/quickstart/client)教程，以构建连接到我们刚刚构建的服务器的 MCP 客户端。
    </Note>

    首先，确保你已经安装了 Claude for Desktop。[你可以在这里安装最新版本。](https://claude.ai/download) 如果你已经安装了 Claude for Desktop，**请确保它已更新到最新版本。**

    我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
    为此，请在文本编辑器中打开你的 Claude for Desktop 应用配置，路径为 `~/Library/Application Support/Claude/claude_desktop_config.json`。
    如果文件不存在，请确保创建它。

    例如，如果你安装了 [VS Code](https://code.visualstudio.com/)：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```bash theme={null}
        code ~/Library/Application\ Support/Claude/claude_desktop_config.json
        ```
      </Tab>

      <Tab title="Windows">
        ```powershell theme={null}
        code $env:AppData\Claude\claude_desktop_config.json
        ```
      </Tab>
    </Tabs>

    然后你将在 `mcpServers` 键中添加你的服务器。
    只有当至少一个服务器被正确配置时，MCP UI 元素才会显示在 Claude for Desktop 中。

    在这种情况下，我们将像这样添加我们的单个天气服务器：

    <Tabs>
      <Tab title="MacOS/Linux">
        ```json theme={null}
        {
          "mcpServers": {
              "weather": {
                  "command": "dotnet",
                  "args": [
                      "run",
                      "--project",
                      "/ABSOLUTE/PATH/TO/PROJECT",
                      "--no-build"
                  ]
              }
          }
        }
        ```
      </Tab>

      <Tab title="Windows">
        ```json theme={null}
        {
          "mcpServers": {
              "weather": {
                  "command": "dotnet",
                  "args": [
                      "run",
                      "--project",
                      "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
                      "--no-build"
                  ]
              }
          }
        }
        ```
      </Tab>
    </Tabs>

    这告诉 Claude for Desktop：

    1. 有一个名为 "weather" 的 MCP 服务器
    2. 通过运行 `dotnet run /ABSOLUTE/PATH/TO/PROJECT` 来启动它
       保存文件，并重启 **Claude for Desktop**。
  </Tab>
</Tabs>

### 使用命令测试

让我们确保 Claude for Desktop 能够识别我们在 `weather` 服务器中暴露的两个工具。你可以通过查找锤子 <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/claude-desktop-mcp-hammer-icon.svg?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=e050ecae01ce5b5b8b694ec5749ab3d5" style={{display: 'inline', margin: 0, height: '1.3em'}} width="32" height="32" data-path="images/claude-desktop-mcp-hammer-icon.svg" /> 图标来做到这一点：

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/visual-indicator-mcp-tools.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=a0083689185f46fa8af66a118523e4fa" width="1358" height="272" data-path="images/visual-indicator-mcp-tools.png" />
</Frame>

点击锤子图标后，你应该会看到列出的两个工具：

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/available-mcp-tools.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=4fa3a660d9ec216a52c20a6ebcc4cf26" width="1048" height="604" data-path="images/available-mcp-tools.png" />
</Frame>

如果 Claude for Desktop 没有识别你的服务器，请转到 [故障排除](#troubleshooting) 部分查看调试提示。

如果锤子图标已显示，你现在可以通过在 Claude for Desktop 中运行以下命令来测试你的服务器：

* 萨克拉门托的天气怎么样？
* 得克萨斯州有哪些活跃的天气警报？

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/current-weather.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=b39e7cfc3ae15d8d4f5ae9f0e2ddb399" width="2780" height="1849" data-path="images/current-weather.png" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/startai/kcnYHWUolkPHxvpx/images/weather-alerts.png?fit=max&auto=format&n=kcnYHWUolkPHxvpx&q=85&s=7fac7a3f4c29f344ab85219b76849c7d" width="2809" height="1850" data-path="images/weather-alerts.png" />
</Frame>

<Note>
  由于这是美国国家气象局的服务，查询仅适用于美国地点。
</Note>

## 幕后发生了什么

当你提问时：

1. 客户端将你的问题发送给 Claude
2. Claude 分析可用的工具并决定使用哪一个（或多个）
3. 客户端通过 MCP 服务器执行选定的工具
4. 结果被发送回 Claude
5. Claude 形成自然语言响应
6. 响应显示给你！

## 故障排除

<AccordionGroup>
  <Accordion title="Claude for Desktop 集成问题">
    **从 Claude for Desktop 获取日志**

    与 MCP 相关的 Claude.app 日志被写入 `~/Library/Logs/Claude` 中的日志文件：

    * `mcp.log` 将包含有关 MCP 连接和连接失败的一般日志记录。
    * 名为 `mcp-server-SERVERNAME.log` 的文件将包含来自指定服务器的错误 (stderr) 日志记录。

    你可以运行以下命令来列出最近的日志并跟踪任何新的日志：

    ```bash theme={null}
    # 检查 Claude 的日志以查找错误
    tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
    ```

    **服务器未在 Claude 中显示**

    1. 检查你的 `claude_desktop_config.json` 文件语法
    2. 确保你的项目路径是绝对路径而不是相对路径
    3. 完全重启 Claude for Desktop

    **工具调用静默失败**

    如果 Claude 尝试使用工具但失败了：

    1. 检查 Claude 的日志以查找错误
    2. 验证你的服务器构建和运行没有错误
    3. 尝试重启 Claude for Desktop

    **这些都不起作用。我该怎么办？**

    请参阅我们的[调试指南](/docs/tools/debugging)以获取更好的调试工具和更详细的指导。
  </Accordion>

  <Accordion title="天气 API 问题">
    **错误：未能检索网格点数据**

    这通常意味着：

    1. 坐标在美国境外
    2. NWS API 出现问题
    3. 你受到了速率限制

    修复：

    * 验证你使用的是美国坐标
    * 在请求之间添加少量延迟
    * 检查 NWS API 状态页面

    **错误：\[州名] 没有活动警报**

    这不是错误 - 这只是意味着该州当前没有天气警报。尝试不同的州或在恶劣天气期间检查。
  </Accordion>
</AccordionGroup>

<Note>
  有关更高级的故障排除，请查看我们的 [调试 MCP](/docs/tools/debugging) 指南
</Note>

## 后续步骤

<CardGroup cols={2}>
  <Card title="Building a client" icon="outlet" href="/quickstart/client">
    学习如何构建你自己的可以连接到你的服务器的 MCP 客户端
  </Card>

  <Card title="查看我们的官方 MCP 服务器和实现示例库" icon="grid" href="/examples">
    查看我们的官方 MCP 服务器和实现示例库
  </Card>

  <Card title="调试指南" icon="bug" href="/docs/tools/debugging">
    学习如何有效调试 MCP 服务器和集成
  </Card>

  <Card title="使用LLMs构建MCP" icon="comments" href="/tutorials/building-mcp-with-llms">
    学习如何使用 Claude 等 LLM 加速 MCP 开发
  </Card>
</CardGroup>
