构建MCP天气服务器并接入桌面客户端
该教程演示如何搭建一个MCP天气服务器,对外暴露get_alerts与get_forecast两个工具,并将其连接到Claude for Desktop等MCP主机。文中还说明了客户端调用工具的基本流程,以及通过日志文件排查连接问题的方法。
将建立一个简单的MCP气象服务器, ### 我们将会建设什么 我们将会建立一个服务器来揭露两个工具: `get_alerts` 财务报告和财务报告 `get_forecast`。然后我们将将服务器连接到一个 MCP 主机(在这种情况下, Claude for Desktop ):  服务器可以连接到任何客户端。 我们在这里选择了 Claude 用于桌面, 简单一些, 但是我们也有一个指南 [新建您的客户端](<https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client>). ### 核心 MCP 概念 MCP服务器可以提供三种主要类型的能力: 1. **[资源](<https://modelcontextprotocol.io/docs/2026-07-28/learn/server-concepts#resources>)**: 客户端可以读取的文件类数据(如API回复或文件内容) 2. **[工具](<https://modelcontextprotocol.io/docs/2026-07-28/learn/server-concepts#tools>)**: 由 LLM 调用(经用户批准)的函数 3. **[提示](<https://modelcontextprotocol.io/docs/2026-07-28/learn/server-concepts#prompts>)**: 帮助用户完成特定任务的预写模板 此教程将主要关注工具. - Python 键 - TypeScript - 爪哇语 - 科特林语Name - C# - 鲁比 - 锈 - 滚开 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python>) ### 必要知识 这个快速开始假设你熟悉: - Python 键 - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要写到 stdout。 写到 stdout 会损坏 JSON - RPC 信件并打破您的服务器 。 `print()` 函数写入默认情况下 stdout, 所以将其完全从 STDIO 服务器中保留 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用标准库 `logging` 模块,它写入 stderr 。 - 每个模块创建一个日志 `logging.getLogger(__name__)` 并用你的工具召唤它。 ### 快速示例 ``` import logging logger = logging.getLogger(__name__) # ❌ Bad (STDIO) print("Processing request") # ✅ Good (STDIO) logger.info("Processing request") # writes to stderr ``` ### 系统要求 - Python 3.10或更高安装. - 您必须使用 Python MCP SDK 2.0.0 或更高. ### 设置您的环境 首先,让我们安装 `uv` 并设立我们的Python项目和环境: ``` curl -LsSf https://astral.sh/uv/install.sh | sh ``` ``` powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` 之后务必重新启动您的终端,以确保 `uv` 命令被接上。 现在, 让我们创建和设定我们的项目 : ``` # 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]" # Create our server file touch weather.py ``` ``` # 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] # Create our server file new-item weather.py ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 导入软件包和设置实例 把这些添加到您的顶部 `weather.py`: ``` from typing import Any import httpx2 from mcp.server import MCPServer from mcp.server.mcpserver.exceptions import ToolError # Initialize MCPServer mcp = MCPServer("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" ``` `httpx2` 是 HTTP 客户端是 SDK 本身所依赖的,所以安装 `mcp` 已将其引入. MCPServer类使用 Python 类型提示和docstrings 自动生成工具定义,使其易于创建和维护 MCP 工具. ### 辅助功能 接下来,让我们加入用于查询和格式化来自国家气象局的数据的辅助功能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 httpx2.AsyncClient(follow_redirects=True) 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.upper()}" data = await make_nws_request(url) if not data or "features" not in data: raise ToolError("Unable to fetch alerts.") 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: raise ToolError("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: raise ToolError("Unable to fetch detailed forecast.") # Format the periods into a readable forecast periods = forecast_data["properties"]["periods"] if not periods: raise ToolError("No forecast periods available.") 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__": mcp.run(transport="stdio") ``` 您的服务器完成 ! 运行 `uv run weather.py` 启动 MCP 服务器,该服务器将收听 MCP 主机发送的信息。让我们现在从现有的 MCP 主机 Claude for Desktop 测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather", "run", "weather.py" ] } } } ``` ``` { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather", "run", "weather.py" ] } } } ``` 你也许需要把 整个路径到 `uv` 可执行文件 `command` 字段。您可以通过运行获得此数据 `which uv` 在macOS/Linux上或 `where uv` 在视窗上。 确定您在绝对路径中通过您的服务器。 您可以通过运行获取此信息 。 `pwd` 在macOS/Linux上或 `cd` 在 Windows 命令提示中。在 Windows 上,请记住使用双反鞭打(`\\`)或前斜线(`/`)在JSON路径中. 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过跑步来启动它 `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py` 保存文件并重新启动 **Claude 用于桌面**. 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript>) ### 必要知识 这个快速开始假设你熟悉: - TypeScript - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `console.log()`,因为它默认情况下会写入标准输出(stdout)。写入 stdout将会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用( U) `console.error()` 写到 stderr , 或者使用日志库写到 stderr 或文件 。 ### 快速示例 ``` // ❌ Bad (STDIO) console.log("Server started"); // ✅ Good (STDIO) console.error("Server started"); // stderr is safe ``` ### 系统要求 对于TypeScript,请确保您安装了最新版本的节点. ### 设置您的环境 首先, 如果您还没有安装节点和npm, 请先安装。 您可以从中下载 。 [节点js.org](<https://nodejs.org/>)。验证您的节点.js安装 : ``` node --version npm --version ``` 对于此教程, 您需要Node. js版本的 20 或更高。 现在, 让我们创建和设置我们的项目 : ``` # Create a new directory for our project mkdir weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/server zod npm install -D @types/node typescript # Create our files mkdir src touch src/index.ts ``` ``` # Create a new directory for our project md weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/server zod npm install -D @types/node typescript # Create our files md src new-item src\index.ts ``` 更新您的软件包. json 以添加类型 : “ 模块 ” 和一个构建脚本 : 软件包.json ``` { "type": "module", "bin": { "weather": "./build/index.js" }, "scripts": { "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"" }, "files": ["build"] } ``` 创建一个 `tsconfig.json` 在您的项目根中: tsconfig.json (英语). ``` { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "types": ["node"], "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 导入软件包和设置常数 把这些添加到您的顶部 `src/index.ts`: ``` import { McpServer } from "@modelcontextprotocol/server"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; import { z } from "zod"; const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; ``` ### 辅助功能 接下来,让我们加入用于查询和格式化来自国家气象局的数据的辅助功能API: ``` // Helper function for making NWS API requests 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; }; } // Format alert data 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[]; }; } ``` ### 执行工具 工具执行处理器负责实际执行每个工具的逻辑。让我们在其中添加 `createServer()` 用于建立服务器实例并将其上的两个工具注册的函数: ``` // Build a server instance and register its tools. serveStdio calls this // whenever it needs an instance, so every call must return a fresh one. function createServer() { const server = new McpServer({ name: "weather", version: "1.0.0", }); server.registerTool( "get_alerts", { description: "Get weather alerts for a state", inputSchema: z.object({ 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/active?area=${stateCode}`; const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl); if (!alertsData) { return { content: [ { type: "text", text: "Failed to retrieve alerts data", }, ], isError: true, }; } const features = alertsData.features || []; if (!features.length) { 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.registerTool( "get_forecast", { description: "Get weather forecast for a location", inputSchema: z.object({ 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).`, }, ], isError: true, }; } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return { content: [ { type: "text", text: "Failed to get forecast URL from grid point data", }, ], isError: true, }; } // Get forecast data const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl); if (!forecastData) { return { content: [ { type: "text", text: "Failed to retrieve forecast data", }, ], isError: true, }; } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return { content: [ { type: "text", text: "No forecast periods available", }, ], isError: true, }; } // 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, }, ], }; }, ); return server; } ``` ### 运行服务器 最后,在Stdio上为服务器服务: ``` serveStdio(createServer, { onerror: (error) => console.error("Weather MCP Server error:", error), }); console.error("Weather MCP Server running on stdio"); ``` `serveStdio` 与每个客户端商谈协议修订,所以同一服务器既回答2026 - 07 - 28客户端,也回答仍然与2025 - era打开的客户端 `initialize` 握个手,它叫... `createServer()` 当它需要实例时,包括一次 `server/discover` 如果客户端返回到 `initialize`,这就是为什么工厂 返回一个新的 `McpServer` 。用手与服务器连接 `server.connect(new StdioServerTransport())` 仍在编译, 但服务器启动时只服务 2025 - era 客户端。 请确定运行 `npm run build` 来构建您的服务器 ! 这是您服务器连接的非常重要的一步 。 要检查服务器是否响应 2026 - 07 - 28 客户端, 请用该程序列出其工具 。 [CLI探长](<https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/cli>) 输入 `modern` [协议时代](<https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/protocol-eras>): ``` npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list ``` 检查官不履行 `legacy` 时,它只练习 2025 - 时代的握手,所以再次使用 `--protocol-era legacy`。两个运行列表 `get_alerts` 财务报告和财务报告 `get_forecast`. 让我们从现有的 MCP 主机Claude 为桌面测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "node", "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"] } } } ``` ``` { "mcpServers": { "weather": { "command": "node", "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"] } } } ``` 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过运行来发射 `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js` 保存文件并重新启动 **Claude 用于桌面**. 此服务器使用MCP协议版本2025 - 11 - 25, 由Java SDK的最新稳定发布支持. 也支持该版本的客户端可以与之连接, 但只支持2026 - 07 - 28的客户端不能连接. See. [向后兼容性](<https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions>). 这是基于 Spring AI MCP 自动配置和启动启动的快速启动演示。 要学习如何创建同步和ASync MCP 服务器, 手动查询 [Java SDK 服务器](<https://java.sdk.modelcontextprotocol.io/>) 文档。 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<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 文档](<https://java.sdk.modelcontextprotocol.io/>). ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `System.out.println()` 或 时 间 `System.out.print()`,当它们写到标准输出( stdout)时。写到 stdout会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用一个日志库来写入 stderr 或文件 。 - 确保任何已配置的日志库不会写入 stdout 。 ### 系统要求 - Java 17 或更高安装. - [春靴 4.1.x](<https://docs.spring.io/spring-boot/installing.html>) 或更高级 ### 设置您的环境 使用该 [春季初始化器](<https://start.spring.io/>) 以拖动工程。您需要添加以下依赖性: ``` <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> ``` ``` dependencies { implementation "org.springframework.ai:spring-ai-starter-mcp-server" implementation "org.springframework:spring-web" } ``` 然后通过设置应用程序属性来配置您的应用程序 : ``` spring.main.bannerMode=off logging.pattern.console= ``` ``` logging: pattern: console: spring: main: banner-mode: off ``` 那个... [服务器配置属性](<https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties>) 记录所有可用的属性。现在让我们潜入您的服务器。 ## 构建您的服务器 ### 气象服务 让我们实施一个 [WeatherService .贾瓦](<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 : ``` @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服务器注册. ### 创建您的靴子应用程序 ``` @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` 转换函数 `@Tool` 将方法输入MCP服务器使用的可操作回调。 ### 运行服务器 最后,让我们建立服务器: ``` ./mvnw clean install ``` 这将生成一个 `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 文件中的 `target` 文件夹。 让我们从现有的 MCP 主机 Claude 为桌面测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "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" ] } } } ``` ``` { "mcpServers": { "spring-ai-mcp-weather": { "command": "java", "args": [ "-Dspring.ai.mcp.server.stdio=true", "-jar", "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar" ] } } } ``` 确定您通过您的服务器的绝对路径 。 告诉 Claude 桌面: 1. 有一个名为“spring-ai-mcp-weather”的MCP服务器。 2. 通过跑步来启动它 `java -Dspring.ai.mcp.server.stdio=true -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 保存文件并重新启动 **Claude 用于桌面**. ## 用 Java 客户端测试您的服务器 ### 手动创建 MCP 客户端 使用该 `McpClient` 连接到服务器 : ``` var stdioParams = ServerParameters.builder("java") .args("-Dspring.ai.mcp.server.stdio=true", "-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar") .build(); var stdioTransport = new StdioClientTransport(stdioParams, McpJsonDefaults.getMapper()); 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` 依赖性 : ``` <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 桌面配置 : ``` spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json ``` 当您启动客户端应用程序时, 自动配置将自动创建MCP客户来自claude_desktop_config.json. 关于更多信息,请参看 [MCP 客户端启动器](<https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html>) 参考文件。 ## 更多 Java MCP 服务器示例 那个... [starter-webflux-server](<https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server>) 演示如何用 WebFlux 启动器创建基于 HTTP 的 MCP 服务器。 设置 `spring.ai.mcp.server.protocol=STREAMABLE` 属性以服务它 超流 HTTP 。 它演示了如何使用 Spring Boot 的自动配置能力定义和注册 MCP 工具、资源和 Points 。 此服务器使用MCP协议版本2025 - 11 - 25, 由Kotlin SDK的最新稳定发布支持. 也支持该版本的客户端可以与之连接,但仅支持2026 - 07 - 28的客户端不能连接. See. [向后兼容性](<https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions>). 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server>) ### 必要知识 这个快速开始假设你熟悉: - 科特林语Name - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `println()`,因为它默认情况下会写入标准输出(stdout)。写入 stdout将会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用一个日志库来写入 stderr 或文件 。 ### 系统要求 - JDK 17或更高安装. ### 设置您的环境 首先,让我们安装 `java` 财务报告和财务报告 `gradle` 如果您尚未下载。 您可以下载 `java` 从 [官方甲骨文JDK网站](<https://www.oracle.com/java/technologies/downloads/>)校验您的 `java` 安装 : ``` java --version ``` 现在,让我们创建和设定您的项目: ``` # Create a new directory for our project mkdir weather cd weather # Initialize a new kotlin project gradle init ``` ``` # Create a new directory for our project md weather cd weather # Initialize a new kotlin project gradle init ``` 运行后 `gradle init`选择 **应用程序** 作为项目类型, **科特林语Name** 作为编程语言。在替代情况下,您可以使用 [IntelliJ IDEA 项目向导](<https://kotlinlang.org/docs/jvm-get-started.html>)创建此工程后, 替换您的 `build.gradle.kts` 改为: 建置. gradle.kts (中文(简体) ). ``` // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases val mcpVersion = "0.16.0" val ktorVersion = "3.2.3" val slf4jVersion = "2.0.17" plugins { kotlin("jvm") version "2.3.20" kotlin("plugin.serialization") version "2.3.20" id("com.gradleup.shadow") version "8.3.9" application } repositories { mavenCentral() } application { mainClass.set("MainKt") } dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion") implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion") implementation("io.ktor:ktor-client-cio:$ktorVersion") implementation("org.slf4j:slf4j-simple:$slf4jVersion") } ``` 校验所有设置是否正确: ``` ./gradlew build ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 设立诉讼机构 添加服务器初始化功能 : ``` fun runMcpServer() { val server = Server( Implementation( name = "weather", version = "1.0.0", ), ServerOptions( capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)), ), ) // register tools on server here val transport = StdioServerTransport( System.`in`.asInput(), System.out.asSink().buffered(), ) runBlocking { val session = server.createSession(transport) val done = Job() session.onClose { done.complete() } done.join() } } ``` ### Weather API 帮助函数 接下来,让我们加入用于查询和转换国家气象局答复的功能和数据分类API: ``` val httpClient = HttpClient(CIO) { defaultRequest { url("https://api.weather.gov") headers { append("Accept", "application/geo+json") append("User-Agent", "WeatherApiClient/1.0") } contentType(ContentType.Application.Json) } install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } } // Extension function to fetch weather alerts for a given state suspend fun HttpClient.getAlerts(state: String): List<String> { val alerts = this.get("/alerts/active/area/${state.uppercase()}").body<AlertsResponse>() return alerts.features.map { feature -> """ Event: ${feature.properties.event} Area: ${feature.properties.areaDesc} Severity: ${feature.properties.severity} Status: ${feature.properties.status} Headline: ${feature.properties.headline} """.trimIndent() } } // Extension function to fetch forecast information for given latitude and longitude suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> { val points = this.get("/points/$latitude,$longitude").body<PointsResponse>() val forecastUrl = points.properties.forecast ?: error("No forecast URL available") val forecast = this.get(forecastUrl).body<ForecastResponse>() return forecast.properties.periods.map { period -> """ ${period.name}: Temperature: ${period.temperature}°${period.temperatureUnit} Wind: ${period.windSpeed} ${period.windDirection} ${period.shortForecast} """.trimIndent() } } @Serializable data class PointsResponse(val properties: PointsProperties) @Serializable data class PointsProperties(val forecast: String? = null) @Serializable data class ForecastResponse(val properties: ForecastProperties) @Serializable data class ForecastProperties(val periods: List<ForecastPeriod> = emptyList()) @Serializable data class ForecastPeriod( val name: String? = null, val temperature: Int? = null, val temperatureUnit: String? = null, val windSpeed: String? = null, val windDirection: String? = null, val shortForecast: String? = null, ) @Serializable data class AlertsResponse(val features: List<AlertFeature> = emptyList()) @Serializable data class AlertFeature(val properties: AlertProperties) @Serializable data class AlertProperties( val event: String? = null, val areaDesc: String? = null, val severity: String? = null, val status: String? = null, val headline: String? = null, ) ``` ### 执行工具 工具执行处理器负责实际执行每个工具的逻辑。让我们添加: ``` // Register weather tools server.addTool( name = "get_alerts", description = "Get weather alerts for a US state. Input is a two-letter US state code (e.g. CA, NY)", inputSchema = ToolSchema( 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?.get("state")?.jsonPrimitive?.content ?: return@addTool CallToolResult( content = listOf(TextContent("The 'state' parameter is required.")), isError = true, ) val alerts = httpClient.getAlerts(state) CallToolResult(content = alerts.map { TextContent(it) }) } server.addTool( name = "get_forecast", description = "Get weather forecast for a location. Note: only US locations are supported by the NWS API.", inputSchema = ToolSchema( properties = buildJsonObject { putJsonObject("latitude") { put("type", "number") put("description", "Latitude of the location") } putJsonObject("longitude") { put("type", "number") put("description", "Longitude of the location") } }, required = listOf("latitude", "longitude"), ), ) { request -> val latitude = request.arguments?.get("latitude")?.jsonPrimitive?.doubleOrNull val longitude = request.arguments?.get("longitude")?.jsonPrimitive?.doubleOrNull if (latitude == null || longitude == null) { return@addTool CallToolResult( content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")), isError = true, ) } val forecast = httpClient.getForecast(latitude, longitude) CallToolResult(content = forecast.map { TextContent(it) }) } ``` ### 运行服务器 最后,执行运行服务器的主要功能: ``` fun main() = runMcpServer() ``` 您可以在开发过程中直接运行服务器 : ``` ./gradlew run ``` 用于生产,构建阴影JAR : ``` ./gradlew build java -jar build/libs/weather-all.jar ``` 让我们从现有的 MCP 主机Claude 为桌面测试您的服务器。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "java", "args": [ "-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-all.jar" ] } } } ``` ``` { "mcpServers": { "weather": { "command": "java", "args": [ "-jar", "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-all.jar" ] } } } ``` 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过运行来发射 `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-all.jar` 保存文件并重新启动 **Claude 用于桌面**. 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer>) ### 必要知识 这个快速开始假设你熟悉: - C# - 克劳德等法学硕士 - .NET 10 或 以上 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `Console.WriteLine()` 或 时 间 `Console.Write()`,当它们写到标准输出( stdout)时。写到 stdout会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用一个日志库来写入 stderr 或文件 。 ### 系统要求 - [.NET 10 SDK (英语).](<https://dotnet.microsoft.com/download/dotnet/10.0>) 已安装或已安装 。 ### 设置您的环境 首先,让我们安装 `dotnet` 如果您尚未下载。 您可以下载 `dotnet` 从 [官方微软.NET网站](<https://dotnet.microsoft.com/download/>)校验您的 `dotnet` 安装 : ``` dotnet --version ``` 现在,让我们创建和设定您的项目: ``` # Create a new directory for our project mkdir weather cd weather # Initialize a new C# project dotnet new console ``` ``` # Create a new directory for our project mkdir weather cd weather # Initialize a new C# project dotnet new console ``` 运行后 `dotnet new console`,您将获得一个新的 C# 项目。您可以在您最喜欢的 IDE 中打开项目,例如 [视觉工作室](<https://visualstudio.microsoft.com/>) 或 时 间 [骑手](<https://www.jetbrains.com/rider/>)或者,您可以使用 [Visual Studio 工程向导](<https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022>)。在创建项目后,添加NuGet用于模式上下文协议的软件包SDK和东道主: ``` # Add the Model Context Protocol SDK NuGet package dotnet add package ModelContextProtocol # Add the .NET Hosting NuGet package dotnet add package Microsoft.Extensions.Hosting ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 打开 `Program.cs` 在工程中将其内容替换为以下代码: ``` 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(); ``` 创建时 `ApplicationHostBuilder`,确保您使用 `CreateEmptyApplicationBuilder` 改为 `CreateDefaultBuilder`。这可以确保服务器不向控制台写任何额外消息。这仅对使用 STDIO 传输的服务器是必要的。 这个代码设置了一个基本的控制台应用程序,使用模型上下文协议SDK来创建一个带有标准I/O传输的MCP服务器. ### Weather API 帮助函数 创建扩展类 `HttpClient` 帮助简化 JSON 请求处理 : ``` using System.Text.Json; internal static class HttpClientExt { public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri) { using var response = await client.GetAsync(requestUri); response.EnsureSuccessStatusCode(); return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()); } } ``` 下, 定义一个类, 包含工具执行处理器, 用于查询和转换来自国家气象局的回复 API : ``` using ModelContextProtocol.Server; using System.ComponentModel; using System.Globalization; using System.Text.Json; namespace QuickstartWeatherServer.Tools; [McpServerToolType] public static class WeatherTools { [McpServerTool, Description("Get weather alerts for a US state code.")] public static async Task<string> GetAlerts( HttpClient client, [Description("The US state code to get alerts for.")] string state) { using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state.ToUpperInvariant()}"); var jsonElement = jsonDocument.RootElement; 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 pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}"); using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl); var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString() ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}"); using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl); var periods = forecastDocument.RootElement.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()} """)); } } ``` ### 运行服务器 最后,使用以下命令运行服务器: ``` dotnet run ``` 这将启动服务器并按标准输入/输出来听收到的请求 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。** 我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确定创建文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当,MCP UI 元素将只在 Claude 为桌面显示。在这种情况下,我们将像这样添加我们的单一天气服务器: ``` { "mcpServers": { "weather": { "command": "dotnet", "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"] } } } ``` ``` { "mcpServers": { "weather": { "command": "dotnet", "args": [ "run", "--project", "C:\\ABSOLUTE\\PATH\\TO\\PROJECT", "--no-build" ] } } } ``` 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过跑步来启动它 `dotnet run --project /ABSOLUTE/PATH/TO/PROJECT --no-build` 保存文件并重新启动 **Claude 用于桌面**. 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby>) ### 必要知识 这个快速开始假设你熟悉: - 鲁比 - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `puts` 或 时 间 `print`,因为默认情况下它们会写入标准输出(stdout)。写入 stdout将损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用一个日志库来写入 stderr 或文件 。 ### 快速示例 ``` # ❌ Bad (STDIO) puts "Processing request" # ✅ Good (STDIO) require "logger" logger = Logger.new($stderr) logger.info("Processing request") ``` ### 系统要求 - 已经安装了 Ruby 2.7 或更高。 ### 设置您的环境 首先,让我们确定你安装了Ruby。您可以通过运行检查 : ``` ruby --version ``` 现在,让我们创造和建立我们的项目: ``` # Create a new directory for our project mkdir weather cd weather # Create a Gemfile bundle init # Add the MCP SDK dependency bundle add mcp # Create our server file touch weather.rb ``` ``` # Create a new directory for our project mkdir weather cd weather # Create a Gemfile bundle init # Add the MCP SDK dependency bundle add mcp # Create our server file new-item weather.rb ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 导入软件包和设置常数 打开 `weather.rb` 并在顶端添加这些要求和常数: ``` require "json" require "mcp" require "net/http" require "uri" NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" ``` 那个... `mcp` gem为Ruby提供模型背景协议SDK,有用于服务器执行和stdio传输的类. ### 帮助方法 接下来,让我们加入国家气象局数据的查询和格式化的帮助方法API: ``` module HelperMethods def make_nws_request(url) uri = URI(url) request = Net::HTTP::Get.new(uri) request["User-Agent"] = USER_AGENT request["Accept"] = "application/geo+json" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess) JSON.parse(response.body) end def format_alert(feature) properties = feature["properties"] <<~ALERT Event: #{properties["event"] || "Unknown"} Area: #{properties["areaDesc"] || "Unknown"} Severity: #{properties["severity"] || "Unknown"} Description: #{properties["description"] || "No description available"} Instructions: #{properties["instruction"] || "No specific instructions provided"} ALERT end end ``` ### 执行工具 现在让我们定义工具类。每个工具子类 `MCP::Tool` 并执行工具逻辑: ``` class GetAlerts < MCP::Tool extend HelperMethods tool_name "get_alerts" description "Get weather alerts for a US state" input_schema( properties: { state: { type: "string", description: "Two-letter US state code (e.g. CA, NY)" } }, required: ["state"] ) def self.call(state:) url = "#{NWS_API_BASE}/alerts/active/area/#{state.upcase}" data = make_nws_request(url) if data["features"].empty? return MCP::Tool::Response.new([{ type: "text", text: "No active alerts for this state." }]) end alerts = data["features"].map { |feature| format_alert(feature) } MCP::Tool::Response.new([{ type: "text", text: alerts.join("\n---\n") }]) end end class GetForecast < MCP::Tool extend HelperMethods tool_name "get_forecast" description "Get weather forecast for a location" input_schema( properties: { latitude: { type: "number", description: "Latitude of the location" }, longitude: { type: "number", description: "Longitude of the location" } }, required: ["latitude", "longitude"] ) def self.call(latitude:, longitude:) # First get the forecast grid endpoint. points_url = "#{NWS_API_BASE}/points/#{latitude},#{longitude}" points_data = make_nws_request(points_url) # Get the forecast URL from the points response. forecast_url = points_data["properties"]["forecast"] forecast_data = make_nws_request(forecast_url) # Format the periods into a readable forecast. periods = forecast_data["properties"]["periods"] forecasts = periods.first(5).map do |period| <<~FORECAST #{period["name"]}: Temperature: #{period["temperature"]}°#{period["temperatureUnit"]} Wind: #{period["windSpeed"]} #{period["windDirection"]} Forecast: #{period["detailedForecast"]} FORECAST end MCP::Tool::Response.new([{ type: "text", text: forecasts.join("\n---\n") }]) end end ``` ### 运行服务器 最后,初始化并运行服务器: ``` server = MCP::Server.new( name: "weather", version: "1.0.0", tools: [GetAlerts, GetForecast] ) transport = MCP::Server::Transports::StdioTransport.new(server) transport.open ``` 您的服务器完成 ! 运行 `bundle exec ruby weather.rb` 启动 MCP 服务器,该服务器将收听 MCP 主机发送的信息。让我们现在从现有的 MCP 主机 Claude for Desktop 测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "bundle", "args": ["exec", "ruby", "weather.rb"], "cwd": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather" } } } ``` ``` { "mcpServers": { "weather": { "command": "bundle", "args": ["exec", "ruby", "weather.rb"], "cwd": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather" } } } ``` 确定您在绝对路径中通过您的工程目录 `cwd` 字段。您可以通过运行获得此数据 `pwd` 在macOS/Linux上或 `cd` 在 Windows 命令提示中从项目目录中查找。在 Windows 上,请记住使用双反鞭打(`\\`)或前斜线(`/`)在JSON路径中. 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过运行来发射 `bundle exec ruby weather.rb` 在指定的目录中 保存文件并重新启动 **Claude 用于桌面**. 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust>) ### 必要知识 这个快速开始假设你熟悉: - Rust 编程语言 - Async/ 等待在 Rust 中进行 - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `println!()` 或 时 间 `print!()`,当它们写到标准输出( stdout)时。写到 stdout会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用一个日志库来写入 stderr 或文件, 例如 `tracing` 或 时 间 `log` 在鲁斯特。 - 配置您的日志框架以避免 stdout 输出 。 ### 快速示例 ``` // ❌ Bad (STDIO) println!("Processing request"); // ✅ Good (STDIO) eprintln!("Processing request"); // writes to stderr ``` ### 系统要求 - 已安装 Rust 1.88 或更高版本。 这是最小版本 。 `rmcp` 箱子申报. - 货物(随Rust安装而来). ### 设置您的环境 首先,如果你还没有安装 Rust , 请先安装 Rust 。 您可以安装 Rust 从 [rust-lang.org (英语).](<https://www.rust-lang.org/tools/install>): ``` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ``` # Download and run rustup-init.exe from https://rustup.rs/ ``` 校验您的 Rust 安装 : ``` rustc --version cargo --version ``` 现在,让我们创造和建立我们的项目: ``` # Create a new Rust project cargo new weather cd weather ``` ``` # Create a new Rust project cargo new weather cd weather ``` 更新您的 `Cargo.toml` 添加所需的依赖性: 货物.toml ``` [package] name = "weather" version = "0.1.0" edition = "2024" [dependencies] rmcp = { version = "3.4", features = ["server", "macros", "transport-io"] } tokio = { version = "1.53", features = ["full"] } reqwest = { version = "0.13", features = ["json"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0" ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 导入软件包和常数 打开 `src/main.rs` 并在顶端添加这些导入和常数: ``` use anyhow::Result; use rmcp::{ ErrorData, ServerHandler, ServiceExt, handler::server::{router::tool::ToolRouter, tool::schema_for_output, wrapper::Parameters}, model::*, schemars::{self, JsonSchema}, tool, tool_handler, tool_router, transport::stdio, }; use serde::Deserialize; use serde::de::DeserializeOwned; use serde::Serialize; const NWS_API_BASE: &str = "https://api.weather.gov"; const USER_AGENT: &str = "weather-app/1.0"; ``` 那个... `rmcp` 板条箱提供了用于Rust的模型上下文协议SDK,具有服务器执行,程序宏,以及stdio迁移的特性. `Parameters` 解除客户端发送到工具的参数, `schema_for_output` 建立 JSON Schema 工具广告, `stdio` 是标准输入和输出传输。 ### 数据结构 定义国家气象局(API)的响应解析数据结构: ``` #[derive(Debug, Deserialize)] struct AlertsResponse { features: Vec<AlertFeature>, } #[derive(Debug, Deserialize)] struct AlertFeature { properties: AlertProperties, } #[derive(Debug, Deserialize)] struct AlertProperties { event: Option<String>, #[serde(rename = "areaDesc")] area_desc: Option<String>, severity: Option<String>, description: Option<String>, instruction: Option<String>, } #[derive(Debug, Deserialize)] struct PointsResponse { properties: PointsProperties, } #[derive(Debug, Deserialize)] struct PointsProperties { forecast: String, } #[derive(Debug, Deserialize)] struct ForecastResponse { properties: ForecastProperties, } #[derive(Debug, Deserialize)] struct ForecastProperties { periods: Vec<ForecastPeriod>, } #[derive(Debug, Deserialize)] struct ForecastPeriod { name: String, temperature: i32, #[serde(rename = "temperatureUnit")] temperature_unit: String, #[serde(rename = "windSpeed")] wind_speed: String, #[serde(rename = "windDirection")] wind_direction: String, #[serde(rename = "detailedForecast")] detailed_forecast: String, } ``` 每个工具还返回文本旁边的结构化内容。定义描述它的类型。Deciving `JsonSchema` 让服务器以工具的输出策略来宣传它们的形状, 并且 Doc 的评论成为该策略中的属性描述 : ``` /// One element of `get_alerts`' structured content. Declaring `Vec<Alert>` as /// the output schema makes `structuredContent` a top-level JSON array rather /// than an object wrapping one, which revision 2026-07-28 is the first to allow. #[derive(Debug, Serialize, JsonSchema)] pub struct Alert { /// The kind of weather event. event: String, /// The area the alert covers. area: String, /// How severe the event is. severity: String, /// What is happening. description: String, /// What people in the area should do. instructions: String, } /// `get_forecast`' structured content: the object case. #[derive(Debug, Serialize, JsonSchema)] pub struct Forecast { /// Latitude the forecast is for. latitude: f32, /// Longitude the forecast is for. longitude: f32, /// The forecast periods, soonest first. periods: Vec<Period>, } #[derive(Debug, Serialize, JsonSchema)] pub struct Period { name: String, temperature: i32, temperature_unit: String, wind_speed: String, wind_direction: String, detailed_forecast: String, } ``` ### 辅助功能 添加帮助功能, 用于生成 API 请求, 格式化文本, 以及构建一个同时包含文本和结构化内容的工具结果 : ``` async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> { let client = reqwest::Client::new(); let rsp = client .get(url) .header(reqwest::header::USER_AGENT, USER_AGENT) .header(reqwest::header::ACCEPT, "application/geo+json") .send() .await? .error_for_status()?; Ok(rsp.json::<T>().await?) } fn format_alert(alert: &Alert) -> String { format!( "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}", alert.event, alert.area, alert.severity, alert.description, alert.instructions ) } fn format_period(period: &Period) -> String { format!( "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}", period.name, period.temperature, period.temperature_unit, period.wind_speed, period.wind_direction, period.detailed_forecast ) } /// Build a result carrying both channels. fn dual_channel_result( text: String, structured: impl Serialize, ) -> Result<CallToolResult, ErrorData> { let value = serde_json::to_value(structured).map_err(|e| { ErrorData::internal_error(format!("failed to serialize structured content: {e}"), None) })?; let mut result = CallToolResult::success(vec![ContentBlock::text(text)]); result.structured_content = Some(value); Ok(result) } ``` `dual_channel_result` 构建一个 `CallToolResult` 其专辑 `content` 拥有人可读的文本 `structured_content` 持有匹配工具输出计划的 JSON 。 ### 实施天气服务器和工具 现在定义MCP客户端发送的请求类型 : ``` #[derive(serde::Deserialize, JsonSchema)] pub struct MCPForecastRequest { /// Latitude of the location. latitude: f32, /// Longitude of the location. longitude: f32, } #[derive(serde::Deserialize, JsonSchema)] pub struct MCPAlertRequest { /// Two-letter US state code (e.g. CA, NY). state: String, } ``` 现在让我们用工具处理器执行主天气服务器结构: ``` #[derive(Clone)] pub struct Weather { tool_router: ToolRouter<Weather>, } #[tool_router(router = tool_router)] impl Weather { fn new() -> Self { Self { tool_router: Self::tool_router(), } } #[tool( description = "Get weather alerts for a US state.", output_schema = schema_for_output::<Vec<Alert>>() )] async fn get_alerts( &self, Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>, ) -> Result<CallToolResult, ErrorData> { let state = state.to_uppercase(); let url = format!("{NWS_API_BASE}/alerts/active/area/{state}"); let Ok(data) = make_nws_request::<AlertsResponse>(&url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text(format!( "Unable to fetch alerts for {state}." ))])); }; // An empty result is an empty array, not an error. let alerts: Vec<Alert> = data .features .into_iter() .map(|feature| { let props = feature.properties; Alert { event: props.event.unwrap_or_else(|| "Unknown".into()), area: props.area_desc.unwrap_or_else(|| "Unknown".into()), severity: props.severity.unwrap_or_else(|| "Unknown".into()), description: props .description .unwrap_or_else(|| "No description available".into()), instructions: props .instruction .unwrap_or_else(|| "No specific instructions provided".into()), } }) .collect(); let text = if alerts.is_empty() { "No active alerts for this state.".to_string() } else { alerts .iter() .map(format_alert) .collect::<Vec<_>>() .join("\n---\n") }; dual_channel_result(text, &alerts) } #[tool( description = "Get weather forecast for a location.", output_schema = schema_for_output::<Forecast>() )] async fn get_forecast( &self, Parameters(MCPForecastRequest { latitude, longitude, }): Parameters<MCPForecastRequest>, ) -> Result<CallToolResult, ErrorData> { let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}"); let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text( "Unable to fetch forecast data for this location.", )])); }; let forecast_url = points_data.properties.forecast; let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text( "Unable to fetch detailed forecast.", )])); }; let forecast = Forecast { latitude, longitude, periods: forecast_data .properties .periods .into_iter() .take(5) // Next 5 periods only .map(|p| Period { name: p.name, temperature: p.temperature, temperature_unit: p.temperature_unit, wind_speed: p.wind_speed, wind_direction: p.wind_direction, detailed_forecast: p.detailed_forecast, }) .collect(), }; let text = forecast .periods .iter() .map(format_period) .collect::<Vec<_>>() .join("\n---\n"); dual_channel_result(text, &forecast) } } ``` 那个... `#[tool_router]` 宏自动生成路由逻辑,并且 `#[tool]` 属性标记方法作为 MCP 工具。每个工具声明一个 `output_schema` 返回时 `Result<CallToolResult, ErrorData>`。向气象服务处提出的请求失败时,报告有: `CallToolResult::error`,客户端作为工具失败接收。 ### 实施ServerHandler 执行 `ServerHandler` 声明服务器的名称、版本和能力: ``` #[tool_handler(router = self.tool_router)] impl ServerHandler for Weather { fn get_info(&self) -> ServerConfig { let mut info = ServerConfig::default(); // Without this the server reports rmcp's own crate name and version // rather than its own. info.server_info = Implementation::new("weather", "1.0.0"); info.capabilities = ServerCapabilities::builder().enable_tools().build(); info } } ``` `get_info` 返回 a `ServerConfig`设置 `server_info` 使服务器报告它自己的名字和版本,而不是那些 `rmcp` 货箱。 ### 运行服务器 最后,执行主要功能,以 stdio 传输方式运行服务器: ``` #[tokio::main] async fn main() -> Result<()> { let service = Weather::new().serve(stdio()).await?; service.waiting().await?; Ok(()) } ``` 将服务器构建为 : ``` cargo build --release ``` 编译的二进制将会在 `target/release/weather`. 让我们从现有的 MCP 主机Claude 为桌面测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/target/release/weather" } } } ``` ``` { "mcpServers": { "weather": { "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\target\\release\\weather.exe" } } } ``` 请确保您通过您编译的二进制的绝对路径。 您可以通过运行获取此功能 `pwd` 在macOS/Linux上或 `cd` 在 Windows 命令提示中从项目目录中查找。在 Windows 上,请记住使用双反鞭打(`\\`)或前斜线(`/`)在JSON路径中,并添加 `.exe` 扩展名。 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过在指定路径运行编译的二进制启动 保存文件并重新启动 **Claude 用于桌面**. 让我们开始建立气象服务机吧! [你可以找到我们在此构建的完整代码。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-go>) ### 必要知识 这个快速开始假设你熟悉: - 滚开 - 克劳德等法学硕士 ### 在 MCP 服务器中登录 实施 MCP 服务器时, 请注意您如何处理日志 :**对于基于STIO的服务器:** 永远不要使用 `fmt.Println()` 或 时 间 `fmt.Printf()`,当它们写到标准输出( stdout)时。写到 stdout会损坏 JSON - RPC 消息并打破您的服务器 。**对于基于 HTTP 的服务器 :** 因为不会干扰HTTP响应, ### 最佳做法 - 使用( U) `log.Println()` (默认为 stderr) 或写到 stderr 或文件的日志库 。 - 使用( U) `fmt.Fprintf(os.Stderr, ...)` 明确写给 Stderr 。 ### 快速示例 ``` // ❌ Bad (STDIO) fmt.Println("Processing request") // ✅ Good (STDIO) log.Println("Processing request") // defaults to stderr // ✅ Good (STDIO) fmt.Fprintln(os.Stderr, "Processing request") ``` ### 系统要求 - Go 1.25 或更高安装. ### 设置您的环境 首先, 如果您还没有安装, 请安装 Go。 您可以下载并安装 Go [开始. deve](<https://go.dev/dl/>).验证您的 Go 安装 : ``` go version ``` 现在,让我们创造和建立我们的项目: ``` # Create a new directory for our project mkdir weather cd weather # Initialize Go module go mod init weather # Install dependencies go get github.com/modelcontextprotocol/go-sdk/mcp # Create our server file touch main.go ``` ``` # Create a new directory for our project md weather cd weather # Initialize Go module go mod init weather # Install dependencies go get github.com/modelcontextprotocol/go-sdk/mcp # Create our server file new-item main.go ``` 现在让我们潜入你的服务器。 ## 构建您的服务器 ### 导入软件包和常数 把这些添加到您的顶部 `main.go`: ``` package main import ( "cmp" "context" "encoding/json" "fmt" "io" "log" "net/http" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" ) const ( NWSAPIBase = "https://api.weather.gov" UserAgent = "weather-app/1.0" ) ``` ### 数据结构 接下来,让我们定义我们的工具所使用的数据结构: ``` type PointsResponse struct { Properties struct { Forecast string `json:"forecast"` } `json:"properties"` } type ForecastResponse struct { Properties struct { Periods []ForecastPeriod `json:"periods"` } `json:"properties"` } type ForecastPeriod struct { Name string `json:"name"` Temperature int `json:"temperature"` TemperatureUnit string `json:"temperatureUnit"` WindSpeed string `json:"windSpeed"` WindDirection string `json:"windDirection"` DetailedForecast string `json:"detailedForecast"` } type AlertsResponse struct { Features []AlertFeature `json:"features"` } type AlertFeature struct { Properties AlertProperties `json:"properties"` } type AlertProperties struct { Event string `json:"event"` AreaDesc string `json:"areaDesc"` Severity string `json:"severity"` Description string `json:"description"` Instruction string `json:"instruction"` } type ForecastInput struct { Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"` Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"` } type AlertsInput struct { State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"` } ``` ### 辅助功能 接下来,让我们加入用于查询和格式化来自国家气象局的数据的辅助功能API: ``` func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("User-Agent", UserAgent) req.Header.Set("Accept", "application/geo+json") client := http.DefaultClient resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to make request to %s: %w", url, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) } var result T if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return nil, fmt.Errorf("failed to decode response: %w", err) } return &result, nil } func formatAlert(alert AlertFeature) string { props := alert.Properties event := cmp.Or(props.Event, "Unknown") areaDesc := cmp.Or(props.AreaDesc, "Unknown") severity := cmp.Or(props.Severity, "Unknown") description := cmp.Or(props.Description, "No description available") instruction := cmp.Or(props.Instruction, "No specific instructions provided") return fmt.Sprintf(` Event: %s Area: %s Severity: %s Description: %s Instructions: %s `, event, areaDesc, severity, description, instruction) } func formatPeriod(period ForecastPeriod) string { return fmt.Sprintf(` %s: Temperature: %d°%s Wind: %s %s Forecast: %s `, period.Name, period.Temperature, period.TemperatureUnit, period.WindSpeed, period.WindDirection, period.DetailedForecast) } ``` ### 执行工具 工具执行处理器负责实际执行每个工具的逻辑。让我们添加: ``` func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) ( *mcp.CallToolResult, any, error, ) { // Get points data pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude) pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL) if err != nil { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Unable to fetch forecast data for this location."}, }, IsError: true, }, nil, nil } // Get forecast data forecastURL := pointsData.Properties.Forecast if forecastURL == "" { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Unable to fetch forecast URL."}, }, IsError: true, }, nil, nil } forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL) if err != nil { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Unable to fetch detailed forecast."}, }, IsError: true, }, nil, nil } // Format the periods periods := forecastData.Properties.Periods if len(periods) == 0 { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "No forecast periods available."}, }, IsError: true, }, nil, nil } // Show next 5 periods var forecasts []string for i := range min(5, len(periods)) { forecasts = append(forecasts, formatPeriod(periods[i])) } result := strings.Join(forecasts, "\n---\n") return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: result}, }, }, nil, nil } func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) ( *mcp.CallToolResult, any, error, ) { // Build alerts URL stateCode := strings.ToUpper(input.State) alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode) alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL) if err != nil { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Unable to fetch alerts."}, }, IsError: true, }, nil, nil } // Check if there are any alerts if len(alertsData.Features) == 0 { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "No active alerts for this state."}, }, }, nil, nil } // Format alerts var alerts []string for _, feature := range alertsData.Features { alerts = append(alerts, formatAlert(feature)) } result := strings.Join(alerts, "\n---\n") return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: result}, }, }, nil, nil } ``` ### 运行服务器 最后,执行运行服务器的主要功能: ``` func main() { // Create MCP server server := mcp.NewServer(&mcp.Implementation{ Name: "weather", Version: "1.0.0", }, nil) // Add get_forecast tool mcp.AddTool(server, &mcp.Tool{ Name: "get_forecast", Description: "Get weather forecast for a location", }, getForecast) // Add get_alerts tool mcp.AddTool(server, &mcp.Tool{ Name: "get_alerts", Description: "Get weather alerts for a US state", }, getAlerts) // Run server on stdio transport if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil { log.Fatal(err) } } ``` 将服务器构建为 : ``` go build -o weather . ``` 编译的二进制将会在 `./weather`. 让我们从现有的 MCP 主机Claude 为桌面测试您的服务器 。 ## 用 Claude 为桌面测试您的服务器 首先,确保您安装了用于桌面的Claude. [您可以在此安装最新版本 。](<https://claude.ai/download>) 如果你已经有克劳德的桌面, **请确保更新到最新版本。**我们需要为您想要使用的 MCP 服务器配置 Claude 桌面。 要做到这一点, 请打开您的 Claude 桌面 App 配置 。 `~/Library/Application Support/Claude/claude_desktop_config.json` 在文本编辑器中。如果文件不存在,请确保创建该文件。例如,如果您有 [VS 代码](<https://code.visualstudio.com/>) 已安装 : ``` code ~/.config/Claude/claude_desktop_config.json ``` ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ``` code $env:AppData\Claude\claude_desktop_config.json ``` 然后您会将您的服务器添加到 `mcpServers` 键。如果至少一个服务器配置得当, MCP UI 元素将只在 Claude 为桌面显示。 在这种情况下, 我们将像这样添加我们的单一天气服务器 : ``` { "mcpServers": { "weather": { "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/weather" } } } ``` ``` { "mcpServers": { "weather": { "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\weather.exe" } } } ``` 请确保您通过您编译的二进制的绝对路径。 您可以通过运行获取此功能 `pwd` 在macOS/Linux上或 `cd` 在 Windows 命令提示中从项目目录中查找。在 Windows 上,请记住使用双反鞭打(`\\`)或前斜线(`/`)在JSON路径中,并添加 `.exe` 扩展名。 告诉 Claude 桌面: 1. 有一个名为“天气”的 MCP 服务器 2. 通过在指定路径运行编译的二进制启动 保存文件并重新启动 **Claude 用于桌面**. ### 使用命令进行测试 让我们确定Claude的桌面正在取回我们曝光的两种工具。 `weather` 服务器。您可以通过查找“添加文件、连接器和更多 /”来做到这一点。  图标 :  点击加号图标后, 请在“ 连接器” 菜单上徘徊。 您应该看到您的气象服务器列表 :  如果您的服务器没有被 Claude 为桌面取回, 请前往 [解决问题](<https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server#troubleshooting>) 用于调试提示的段落。如果服务器在“连接器”菜单中显示,您现在可以在 Claude 为桌面运行以下命令来测试您的服务器 : - 萨克拉门托的天气如何? - 德克萨斯州有哪些活跃的天气警报?   由于这是US国家气象服务,因此查询将只为US位置工作. ## 盖子下到底发生了什么? 当你问一个问题: 1. 客户把你的问题寄给克劳德 2. Claude分析可用的工具并决定使用哪一种工具 3. 客户端通过 MCP 服务器执行所选工具 4. 将结果发回克劳德 5. Claude提出一种自然语言的反应 6. 反应会显示给你! ## 解决问题 Claude 桌面整合问题组织 **从 Claude 获取桌面日志**Claude. app记录与 MCP 相关的文件 `~/Library/Logs/Claude` (macOS) 或 (中文(简体) ). `~/.config/Claude/logs/` (林诺): - `mcp.log` 将包含有关 MCP 连接和连接失败的常规日志 。 - 名为文件 `mcp-server-SERVERNAME.log` 将包含命名服务器的 stderr 输出。 Stdio 服务器可以使用 stderr 进行全部记录,所以这些文件并不限于错误。 您可以运行以下命令以列出最近的日志, 并跟随任何新的日志 : ``` # Check Claude's logs for errors tail -n 20 -f ~/Library/Logs/Claude/mcp*.log ``` ``` # Check Claude's logs for errors tail -n 20 -f ~/.config/Claude/logs/mcp*.log ``` **服务器未在克劳德出现** 1. 检查你的 `claude_desktop_config.json` 文件语法 2. 确定您的项目路径是绝对的而不是相对的 3. 完全恢复 Claude 桌面功能 要正确重启 Claude 桌面, 您必须完全退出应用程序 : - **窗口**: 右键单击系统托盘中的克劳德图标(可能隐藏在“隐藏图标”菜单中),并选择“退出”或“退出”。 - **macOS**: 使用 CmdQQ 或从菜单栏中选择“ 退出克劳德 ” 。 - **链接( L)**: 右键单击系统托盘中的克劳德图标并选择“退出”,或运行 `pkill -f claude-desktop` 从终端。 简单地关闭窗口不会完全退出应用程序,而您的 MCP 服务器配置更改将不会生效 。 **工具调用失败 。**如果克劳德试图使用这些工具,但失败了: 1. 检查 Claude 日志是否出错 2. 校验您的服务器构建和运行没有出错 3. 尝试重启 Claude 桌面 **这些都没用,我该怎么办?**请参看我们 [调试指南](<https://modelcontextprotocol.io/docs/2026-07-28/tools/debugging>) 用于更好的调试工具和更详细的指导。 天气 API 问题 **错误: 检索网格点数据失败**这通常是指: 1. 坐标在US之外 2. NWS API有问题 3. 您的利率有限 修补 : - 校验您正在使用 US 坐标 - 在请求之间添加一个小的延迟 - 请检查access-date=中的日期值 (帮助) NWS API状态页面 **错误: 没有活动提醒 [STATE]**这不是一个错误 — — 它只是意味着没有当前该状态的天气警报。 尝试不同的状态或者在恶劣天气中检查。 更高级的故障排除,请检查我们的指南 [调试 MCP](<https://modelcontextprotocol.io/docs/2026-07-28/tools/debugging>) ## 今后的步骤 ## 建立客户端 学习如何构建可以连接到您的服务器的 MCP 客户端 ## 示例服务器 请检查access-date=中的日期值 (帮助) 官方MCP服务器与执行 ## 调试指南 学习如何有效调试 MCP 服务器和集成 ## 使用代理技能构建 使用代理技能通过服务器设计引导 AI 编码助理 这页有用吗?
查看原始来源