### Initialize and Configure Python Project Source: https://model-context-protocol.mintlify.app/quickstart/server Sets up a new Python project directory, creates and activates a virtual environment, installs MCP and httpx dependencies, and prepares the project structure for the weather server. ```bash # 创建一个新目录用于我们的项目 uv init weather cd weather # 创建虚拟环境并激活它 uv venv source .venv/bin/activate # 安装依赖项 uv add mcp httpx # 删除模板文件 rm hello.py # 创建我们的文件 mkdir -p src/weather touch src/weather/__init__.py touch src/weather/server.py ``` ```powershell # 创建一个新目录用于我们的项目 uv init weather cd weather # 创建虚拟环境并激活它 uv venv .venv\Scripts\activate # 安装依赖项 uv add mcp httpx # 清理样板代码 rm hello.py # 创建我们的文件 md src md src\weather new-item src\weather\__init__.py new-item src\weather\server.py ``` -------------------------------- ### Implement Basic MCP Server in Python Source: https://model-context-protocol.mintlify.app/docs/concepts/architecture This Python example demonstrates setting up a basic MCP server using the mcp library. It includes a handler for listing resources and connects via stdio. ```python import asyncio import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="example://resource", name="Example Resource" ) ] async def main(): async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) if __name__ == "__main__": asyncio.run(main) ``` -------------------------------- ### Implement Basic MCP Server in TypeScript Source: https://model-context-protocol.mintlify.app/docs/concepts/architecture Use this to set up a basic MCP server. Ensure you have the necessary SDK imports. This example handles a ListResourcesRequest. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // 处理请求 server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "example://resource", name: "Example Resource" } ] }; }); // 连接传输 const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Launch Server from NPM Package Source: https://model-context-protocol.mintlify.app/docs/tools/inspector Start an MCP server package from NPM using the inspector. Replace `` and `` with the actual package name and its arguments. The `-y` flag ensures npx installs the package if it's not already present. ```bash npx -y @modelcontextprotocol/inspector npx # 例如 npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` -------------------------------- ### Run Server with stdio Source: https://model-context-protocol.mintlify.app/quickstart/server This function demonstrates how to run the server using standard input and output streams. It initializes the server with basic options like server name, version, and capabilities. Use this as the entry point for starting the server. ```python async def main(): # 使用 stdin/stdout 流运行服务器 async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="weather", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), ``` -------------------------------- ### Launch Server from PyPi Package Source: https://model-context-protocol.mintlify.app/docs/tools/inspector Start an MCP server package from PyPi using the inspector. Replace `` and `` with the actual package name and its arguments. The `uvx` command is used to execute Python packages. ```bash npx @modelcontextprotocol/inspector uvx # 例如 npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ``` -------------------------------- ### Run the MCP Server Source: https://model-context-protocol.mintlify.app/quickstart/server This TypeScript code snippet demonstrates how to start the MCP server using the StdioServerTransport and logs a message to the console upon successful connection. It includes error handling for the main function. ```typescript // 启动服务器 async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("Weather MCP 服务器在 stdio 上运行"); } main().catch((error) => { console.error("main() 中的致命错误:", error); process.exit(1); }); ``` -------------------------------- ### Get Specific Prompt Details Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts To use a prompt, clients issue a `prompts/get` request with the prompt's name and any required arguments. The response includes a description and the messages to be sent to the LLM. ```json // 请求 { method: "prompts/get", params: { name: "analyze-code", arguments: { language: "python" } } } // 响应 { description: "分析 Python 代码以寻找潜在的改进", messages: [ { role: "user", content: { type: "text", text: "请分析以下 Python 代码以寻找潜在的改进:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result) ```" } } ] } ``` -------------------------------- ### Install uv Package Manager Source: https://model-context-protocol.mintlify.app/quickstart/server Installs the 'uv' package manager for Python. Ensure your terminal is restarted after installation for the 'uv' command to be recognized. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Run MCP Inspector from npx Source: https://model-context-protocol.mintlify.app/docs/tools/inspector Run the inspector directly via npx without installation. Replace `` with the desired inspector command. ```bash npx @modelcontextprotocol/inspector ``` ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Multi-Step Debugging Workflow Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts Defines a multi-step workflow for debugging errors, allowing for a conversational approach where the assistant guides the user through troubleshooting steps. ```typescript const debugWorkflow = { name: "debug-error", async getMessages(error: string) { return [ { role: "user", content: { type: "text", text: `这是我看到的一个错误:${error}` } }, { role: "assistant", content: { type: "text", text: "我会帮助分析这个错误。你已经尝试了什么?" } }, { role: "user", content: { type: "text", text: "我已经尝试重新启动服务,但错误仍然存在。" } } ]; } }; ``` -------------------------------- ### Implement NWS API Request Helper Function Source: https://model-context-protocol.mintlify.app/quickstart/server Provides a utility function `make_nws_request` to handle GET requests to the NWS API, including setting necessary headers and performing basic error handling. ```python async def make_nws_request(client: httpx.AsyncClient, url: str) -> dict[str, Any] | None: """向 NWS API 发出请求并进行适当的错误处理。""" headers = { "User-Agent": USER_AGENT, "Accept": "application/geo+json" } try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None ``` -------------------------------- ### Launch Local Server (Python) Source: https://model-context-protocol.mintlify.app/docs/tools/inspector Inspect a locally developed Python server using `uv`. Specify the directory containing the server, the package name, and any arguments. ```bash npx @modelcontextprotocol/inspector \ uv \ --directory path/to/server \ run \ package-name \ args... ``` -------------------------------- ### Launch Local Server (TypeScript) Source: https://model-context-protocol.mintlify.app/docs/tools/inspector Inspect a locally developed server using Node.js. Specify the path to your server's entry point script and any necessary arguments. ```bash npx @modelcontextprotocol/inspector node path/to/server/index.js args... ``` -------------------------------- ### Initialize Package Entry Point Source: https://model-context-protocol.mintlify.app/quickstart/server Defines the main entry point for the Python package in `__init__.py`, which runs the server asynchronously. ```python from . import server import asyncio def main(): """包的主入口点。""" asyncio.run(server.main()) # 可选地在包级别公开其他重要项目 __all__ = ['main', 'server'] ``` -------------------------------- ### Initialize MCP Server Instance Source: https://model-context-protocol.mintlify.app/quickstart/server Sets up the MCP server instance with a unique name and defines the base URL for the National Weather Service (NWS) API. ```python NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" server = Server("weather") ``` -------------------------------- ### Run Filesystem Server on Windows Source: https://model-context-protocol.mintlify.app/quickstart/user Manually run the filesystem server from the command line on Windows. Ensure the paths provided are absolute. ```bash npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads ``` -------------------------------- ### 配置 API 密钥 Source: https://model-context-protocol.mintlify.app/quickstart/client 创建 .env 文件来存储您的 Anthropic API 密钥,并将其添加到 .gitignore 文件中以防止提交。 ```bash # 创建 .env 文件 touch .env ``` ```bash ANTHROPIC_API_KEY= ``` ```bash echo ".env" >> .gitignore ``` -------------------------------- ### Initialize NWS API and Server Instance Source: https://model-context-protocol.mintlify.app/quickstart/server Sets up the base URL for the NWS API, defines validation schemas using Zod, and creates a server instance for handling requests. ```typescript const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // 定义 Zod 验证模式 const AlertsArgumentsSchema = z.object({ state: z.string().length(2), }); const ForecastArgumentsSchema = z.object({ latitude: z.number().min(-90).max(90), longitude: z.number().min(-180).max(180), }); // 创建服务器实例 const server = new Server( { name: "weather", version: "1.0.0", }, { capabilities: { tools: {}, }, } ); ``` -------------------------------- ### Use Prompt Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts To use a prompt, clients issue a `prompts/get` request with the prompt name and any required arguments. ```APIDOC ## Use Prompt ### Description To use a prompt, clients issue a `prompts/get` request with the prompt name and any required arguments. ### Method POST ### Endpoint `prompts/get` ### Parameters #### Request Body - **method** (string) - Required - The name of the method, which is `prompts/get`. - **params** (object) - Required - An object containing the prompt name and its arguments. - **name** (string) - Required - The name of the prompt to retrieve. - **arguments** (object) - Required - An object containing the arguments for the prompt. ### Request Example ```json { "method": "prompts/get", "params": { "name": "analyze-code", "arguments": { "language": "python" } } } ``` ### Response #### Success Response (200) - **description** (string) - A description of the prompt. - **messages** (array) - A list of messages representing the prompt's content, which can include text and resource types. - **role** (string) - The role of the message sender (e.g., "user", "assistant"). - **content** (object) - The content of the message. - **type** (string) - The type of content (e.g., "text", "resource"). - **text** (string, optional) - The text content of the message. - **resource** (object, optional) - Resource object for resource content. - **uri** (string) - The URI of the resource. - **text** (string) - The content of the resource. - **mimeType** (string) - The MIME type of the resource. ### Response Example ```json { "description": "Analyze Python code for potential improvements", "messages": [ { "role": "user", "content": { "type": "text", "text": "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```" } } ] } ``` ``` -------------------------------- ### Discover Available Prompts Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts Clients can discover available prompts by querying the `prompts/list` endpoint. The response includes the prompt's name, description, and a list of its arguments. ```json // 请求 { method: "prompts/list" } // 响应 { prompts: [ { name: "analyze-code", description: "分析代码以寻找潜在的改进", arguments: [ { name: "language", description: "编程语言", required: true } ] } ] } ``` -------------------------------- ### Run Filesystem Server on MacOS/Linux Source: https://model-context-protocol.mintlify.app/quickstart/user Manually run the filesystem server from the command line on MacOS or Linux. Ensure the paths provided are absolute. ```bash npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads ``` -------------------------------- ### Configure Project Build System Source: https://model-context-protocol.mintlify.app/quickstart/server Adds build system configuration to `pyproject.toml` to define the project's scripts, ensuring the 'weather' command can be executed. ```toml ...rest of config [build-system] requires = [ "hatchling",] build-backend = "hatchling.build" [project.scripts] weather = "weather:main" ``` -------------------------------- ### 设置 Python 环境 Source: https://model-context-protocol.mintlify.app/quickstart/client 使用 uv 初始化项目,创建和激活虚拟环境,然后安装必要的包。删除样板文件并创建主文件。 ```bash # 创建项目目录 uv init mcp-client cd mcp-client # 创建虚拟环境 uv venv # 激活虚拟环境 # 在 Windows 上: .venv\Scripts\activate # 在 Unix 或 MacOS 上: source .venv/bin/activate # 安装所需的包 uv add mcp anthropic python-dotenv # 删除样板文件 rm hello.py # 创建我们的主文件 touch client.py ``` -------------------------------- ### Open Configuration File (macOS/Linux) Source: https://model-context-protocol.mintlify.app/quickstart/server Command to open the Claude for Desktop configuration file in VS Code on macOS or Linux. ```bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` -------------------------------- ### Open Configuration File (Windows) Source: https://model-context-protocol.mintlify.app/quickstart/server Command to open the Claude for Desktop configuration file in VS Code on Windows. ```powershell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Configure MCP Server (Windows) Source: https://model-context-protocol.mintlify.app/quickstart/server JSON configuration for adding a weather MCP server to Claude for Desktop on Windows, specifying the Node.js command and the path to the server's build file. ```json { "mcpServers": { "weather": { "command": "node", "args": [ "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js" ] } } } ``` -------------------------------- ### Register Available Tools with Server Source: https://model-context-protocol.mintlify.app/quickstart/server Configures the server to handle `ListToolsRequestSchema` by defining available tools, their descriptions, and input schemas. ```typescript // 列出可用工具 server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "get-alerts", description: "获取某个州的天气警报", inputSchema: { type: "object", properties: { state: { type: "string", description: "两字母州代码(例如 CA,NY)", }, }, required: ["state"], }, }, { name: "get-forecast", description: "获取某个位置的天气预报", inputSchema: { type: "object", properties: { latitude: { type: "number", description: "位置的纬度", }, longitude: { type: "number", description: "位置的经度", }, }, required: ["latitude", "longitude"], }, }, ], }; }); ``` -------------------------------- ### Define Available Tools for MCP Server Source: https://model-context-protocol.mintlify.app/quickstart/server Registers the available tools (`get-alerts` and `get-forecast`) with their respective descriptions and input schemas using the `@server.list_tools()` decorator. ```python @server.list_tools() async def handle_list_tools() -> list[types.Tool]: """ 列出可用工具。 每个工具使用 JSON Schema 验证指定其参数。 """ return [ types.Tool( name="get-alerts", description="获取某个州的天气警报", inputSchema={ "type": "object", "properties": { "state": { "type": "string", "description": "两字母州代码(例如 CA,NY)", }, }, "required": ["state"], }, ), types.Tool( name="get-forecast", description="获取某个位置的天气预报", inputSchema={ "type": "object", "properties": { "latitude": { "type": "number", "description": "位置的纬度", }, "longitude": { "type": "number", "description": "位置的经度", }, }, "required": ["latitude", "longitude"], }, ), ] ``` -------------------------------- ### Configure MCP Server (macOS/Linux) Source: https://model-context-protocol.mintlify.app/quickstart/server JSON configuration for adding a weather MCP server to Claude for Desktop on macOS/Linux, specifying the Node.js command and the absolute path to the server's build file. ```json { "mcpServers": { "weather": { "command": "node", "args": [ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js" ] } } } ``` -------------------------------- ### Discover Prompts Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts Clients can discover available prompts by querying the `prompts/list` endpoint. ```APIDOC ## Discover Prompts ### Description Clients can discover available prompts by querying the `prompts/list` endpoint. ### Method POST ### Endpoint `prompts/list` ### Request Body ```json { "method": "prompts/list" } ``` ### Response #### Success Response (200) - **prompts** (array) - A list of available prompts. - **name** (string) - The unique identifier of the prompt. - **description** (string) - A human-readable description of the prompt. - **arguments** (array, optional) - An optional list of arguments the prompt accepts. - **name** (string) - The identifier for the argument. - **description** (string, optional) - A description of the argument. - **required** (boolean, optional) - Indicates if the argument is mandatory. ### Response Example ```json { "prompts": [ { "name": "analyze-code", "description": "Analyze code for potential improvements", "arguments": [ { "name": "language", "description": "Programming language", "required": true } ] } ] } ``` ``` -------------------------------- ### Import Necessary Packages for Server Source: https://model-context-protocol.mintlify.app/quickstart/server Imports required modules for building the MCP server, including asyncio, httpx for HTTP requests, and various components from the mcp library. ```python from typing import Any import asyncio import httpx from mcp.server.models import InitializationOptions import mcp.types as types from mcp.server import NotificationOptions, Server import mcp.server.stdio ``` -------------------------------- ### 连接到 MCP 服务器 Source: https://model-context-protocol.mintlify.app/quickstart/client 实现连接到 MCP 服务器的方法,根据文件扩展名选择正确的命令(python 或 node),并初始化客户端会话。 ```python async def connect_to_server(self, server_script_path: str): """连接到 MCP 服务器 参数: server_script_path: 服务器脚本的路径 (.py 或 .js) """ is_python = server_script_path.endswith('.py') is_js = server_script_path.endswith('.js') if not (is_python or is_js): raise ValueError("服务器脚本必须是 .py 或 .js 文件") command = "python" if is_python else "node" server_params = StdioServerParameters( command=command, args=[server_script_path], env=None ) stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) self.stdio, self.write = stdio_transport self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write)) await self.session.initialize() # 列出可用工具 response = await self.session.list_tools() tools = response.tools print("\n已连接到具有工具的服务器:", [tool.name for tool in tools]) ``` -------------------------------- ### Implement Tool Execution Handler Source: https://model-context-protocol.mintlify.app/quickstart/server Handles the execution of tools like `get-alerts` by parsing arguments, making NWS API requests, and formatting the results. ```typescript // 处理工具执行 server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { if (name === "get-alerts") { const { state } = AlertsArgumentsSchema.parse(args); const stateCode = state.toUpperCase(); const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`; const alertsData = await makeNWSRequest(alertsUrl); if (!alertsData) { return { content: [ { type: "text", text: "无法检索警报数据", }, ], }; } const features = alertsData.features || []; if (features.length === 0) { return { content: [ { type: "text", text: `${stateCode} 没有活动警报`, }, ], }; } const formattedAlerts = features.map(formatAlert).slice(0, 20); // 仅取前 20 个警报; const alertsText = `${stateCode} 的活动警报:\n\n${formattedAlerts.join( "\n" )}`; return { content: [ { type: "text", text: alertsText, }, ], }; } else if (name === "get-forecast") { ``` -------------------------------- ### MCP Architecture Diagram Source: https://model-context-protocol.mintlify.app/introduction Visual representation of the MCP client-server architecture, illustrating connections between hosts, servers, local data sources, and remote services. ```mermaid flowchart LR subgraph "您的计算机" Host["具有 MCP 客户端的主机 (Claude, IDEs, 工具)"] S1["MCP 服务器 A"] S2["MCP 服务器 B"] S3["MCP 服务器 C"] Host <-->|"MCP 协议"| S1 Host <-->|"MCP 协议"| S2 Host <-->|"MCP 协议"| S3 S1 <--> D1[("本地\n数据源 A")] S2 <--> D2[("本地\n数据源 B")] end subgraph "互联网" S3 <-->|"Web APIs"| D3[("远程\n服务 C")] end ``` -------------------------------- ### Prompt with Embedded Resource Context Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts Prompts can dynamically include context from resources, such as logs or code files, by specifying their URIs and content. This allows for richer, context-aware LLM interactions. ```json { "name": "analyze-project", "description": "分析项目日志和代码", "arguments": [ { "name": "timeframe", "description": "分析日志的时间段", "required": true }, { "name": "fileUri", "description": "要审查的代码文件的 URI", "required": true } ] } ``` ```json { "messages": [ { "role": "user", "content": { "type": "text", "text": "分析这些系统日志和代码文件是否有任何问题:" } }, { "role": "user", "content": { "type": "resource", "resource": { "uri": "logs://recent?timeframe=1h", "text": "[2024-03-14 15:32:11] 错误:network.py:127 中的连接超时\n[2024-03-14 15:32:15] 警告:重试连接(尝试 2/3)\n[2024-03-14 15:32:20] 错误:超出最大重试次数", "mimeType": "text/plain" } } }, { "role": "user", "content": { "type": "resource", "resource": { "uri": "file:///path/to/code.py", "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n def establish_connection(timeout):\n # 连接实现\n pass", "mimeType": "text/x-python" } } } ] } ``` -------------------------------- ### 初始化 MCP 客户端 Source: https://model-context-protocol.mintlify.app/quickstart/client 设置导入并创建基本的客户端类,包括初始化会话、客户端对象和 Anthropic API 客户端。 ```python import asyncio from typing import Optional from contextlib import AsyncExitStack from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from anthropic import Anthropic from dotenv import load_dotenv load_dotenv() # 从 .env 加载环境变量 class MCPClient: def __init__(self): # 初始化会话和客户端对象 self.session: Optional[ClientSession] = None self.exit_stack = AsyncExitStack() self.anthropic = Anthropic() # 方法将在这里添加 ``` -------------------------------- ### 处理查询和工具调用 Source: https://model-context-protocol.mintlify.app/quickstart/client 实现核心功能来处理用户查询,与 Claude API 进行交互以获取工具调用,并使用工具结果继续对话。 ```python async def process_query(self, query: str) -> str: """使用 Claude 和可用工具处理查询""" messages = [ { "role": "user", "content": query } ] response = await self.session.list_tools() available_tools = [{ "name": tool.name, "description": tool.description, "input_schema": tool.inputSchema } for tool in response.tools] # 初始 Claude API 调用 response = self.anthropic.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1000, messages=messages, tools=available_tools ) # 处理响应并处理工具调用 tool_results = [] final_text = [] for content in response.content: if content.type == 'text': final_text.append(content.text) elif content.type == 'tool_use': tool_name = content.name tool_args = content.input # 执行工具调用 result = await self.session.call_tool(tool_name, tool_args) tool_results.append({"call": tool_name, "result": result}) final_text.append(f"[调用工具 {tool_name},参数 {tool_args}]") # 使用工具结果继续对话 if hasattr(content, 'text') and content.text: messages.append({ "role": "assistant", "content": content.text }) messages.append({ "role": "user", "content": result.content }) # 获取 Claude 的下一个响应 response = self.anthropic.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1000, messages=messages, ``` -------------------------------- ### Prompt Structure Definition Source: https://model-context-protocol.mintlify.app/docs/concepts/prompts Defines the structure of a prompt, including its unique identifier, an optional description, and a list of optional arguments with their own descriptions and required status. ```typescript { name: string; // 提示的唯一标识符 description?: string; // 人类可读的描述 arguments?: [ // 可选的参数列表 { name: string; // 参数标识符 description?: string; // 参数描述 required?: boolean; // 参数是否必需 } ] } ``` -------------------------------- ### Fetch and Format Weather Forecasts Source: https://model-context-protocol.mintlify.app/quickstart/server This TypeScript code fetches grid point data and forecast data from the NWS API, then formats the forecast periods into a human-readable string. It includes error handling for API requests and data parsing. ```typescript const { latitude, longitude } = ForecastArgumentsSchema.parse(args); // 获取网格点数据 const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed( 4 )},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest(pointsUrl); if (!pointsData) { return { content: [ { type: "text", text: `无法检索坐标的网格点数据:${latitude}, ${longitude}。此位置可能不受 NWS API 支持(仅支持美国位置)。`, }, ], }; } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return { content: [ { type: "text", text: "无法从网格点数据中获取预报 URL", }, ], }; } // 获取预报数据 const forecastData = await makeNWSRequest(forecastUrl); if (!forecastData) { return { content: [ { type: "text", text: "无法检索预报数据", }, ], }; } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return { content: [ { type: "text", text: "没有可用的预报期", }, ], }; } // 格式化预报期 const formattedForecast = periods.map((period: ForecastPeriod) => [ `${period.name || "未知"}:`, `温度: ${period.temperature || "未知"}°${period.temperatureUnit || "F"}`, `风: ${period.windSpeed || "未知"} ${period.windDirection || ""}`, `${period.shortForecast || "无可用预报"}`, "---", ].join("\n") ); const forecastText = `${latitude}, ${longitude} 的预报:\n\n${formattedForecast.join("\n")}`; return { content: [ { type: "text", text: forecastText, }, ], }; } else { throw new Error(`未知工具:${name}`); } } catch (error) { if (error instanceof z.ZodError) { throw new Error( `无效的参数:${error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ")}` ); } throw error; } }); ``` -------------------------------- ### View MCP Logs on Windows Source: https://model-context-protocol.mintlify.app/quickstart/user View recent MCP log entries on Windows. This command displays the content of the mcp log files. ```bash type "%APPDATA%\Claude\logs\mcp*.log" ``` -------------------------------- ### Tail MCP Logs on MacOS/Linux Source: https://model-context-protocol.mintlify.app/quickstart/user Check Claude's logs for errors by tailing the MCP log files on MacOS or Linux. This command shows the last 20 lines and follows new log entries. ```bash # Check Claude's logs for errors tail -n 20 -f ~/Library/Logs/Claude/mcp*.log ``` -------------------------------- ### Tool Execution Handler Source: https://model-context-protocol.mintlify.app/quickstart/server This handler processes requests to execute tools, specifically for fetching weather alerts and forecasts. It includes input validation for arguments like state codes and coordinates, and makes requests to the NWS API. Use this for implementing weather-related tool functionalities. ```python f"标题: {props.get('headline', '无标题')}\n" "---" ) ``` ```python @server.call_tool() async def handle_call_tool( name: str, arguments: dict | None ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: """ 处理工具执行请求。 工具可以获取天气数据并通知客户端更改。 """ if not arguments: raise ValueError("缺少参数") if name == "get-alerts": state = arguments.get("state") if not state: raise ValueError("缺少 state 参数") # 将 state 转换为大写以确保格式一致 state = state.upper() if len(state) != 2: raise ValueError("state 必须是两字母代码(例如 CA,NY)") async with httpx.AsyncClient() as client: alerts_url = f"{NWS_API_BASE}/alerts?area={state}" alerts_data = await make_nws_request(client, alerts_url) if not alerts_data: return [types.TextContent(type="text", text="无法检索警报数据")] features = alerts_data.get("features", []) if not features: return [types.TextContent(type="text", text=f"{state} 没有活动警报")] # 将每个警报格式化为简洁的字符串 formatted_alerts = [format_alert(feature) for feature in features[:20]] # 仅取前 20 个警报 alerts_text = f"{state} 的活动警报:\n\n" + "\n".join(formatted_alerts) return [ types.TextContent( type="text", text=alerts_text ) ] elif name == "get-forecast": try: latitude = float(arguments.get("latitude")) longitude = float(arguments.get("longitude")) except (TypeError, ValueError): return [types.TextContent( type="text", text="无效的坐标。请提供有效的纬度和经度数字。" )] # 基本坐标验证 if not (-90 <= latitude <= 90) 或 not (-180 <= longitude <= 180): return [types.TextContent( type="text", text="无效的坐标。纬度必须在 -90 到 90 之间,经度在 -180 到 180 之间。" )] async with httpx.AsyncClient() as client: # 首先获取网格点 lat_str = f"{latitude}" lon_str = f"{longitude}" points_url = f"{NWS_API_BASE}/points/{lat_str},{lon_str}" points_data = await make_nws_request(client, points_url) if not points_data: return [types.TextContent(type="text", text=f"无法检索坐标的网格点数据:{latitude}, {longitude}。此位置可能不受 NWS API 支持(仅支持美国位置)。")] # 从响应中提取预报 URL properties = points_data.get("properties", {}) forecast_url = properties.get("forecast") if not forecast_url: return [types.TextContent(type="text", text="无法从网格点数据中获取预报 URL")] # 获取预报 forecast数据 = await make_nws_request(client, forecast_url) if not forecast数据: return [types.TextContent(type="text", text="无法检索预报数据")] # 格式化预报期 periods = forecast数据.get("properties", {}).get("periods", []) if not periods: return [types.TextContent(type="text", text="没有可用的预报期")] # 将每个期格式化为简洁的字符串 formatted_forecast = [] for period in periods: forecast_text = ( f"{period.get('name', '未知')}:\n" f"温度: {period.get('temperature', '未知')}°{period.get('temperatureUnit', 'F')}\n" f"风: {period.get('windSpeed', '未知')} {period.get('windDirection', '')}\n" f"{period.get('shortForecast', '无可用预报')}\n" "---" ) formatted_forecast.append(forecast_text) forecast_text = f"{latitude}, {longitude} 的预报:\n\n" + "\n".join(formatted_forecast) return [types.TextContent( type="text", text=forecast_text )] else: raise ValueError(f"未知工具: {name}") ``` -------------------------------- ### Helper Functions for NWS API Interaction Source: https://model-context-protocol.mintlify.app/quickstart/server Provides utility functions for making requests to the NWS API and formatting the received data, including alerts and forecast periods. ```typescript // 用于发出 NWS API 请求的辅助函数 async function makeNWSRequest(url: string): Promise { const headers = { "User-Agent": USER_AGENT, Accept: "application/geo+json", }; try { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP 错误!状态:${response.status}`); } return (await response.json()) as T; } catch (error) { console.error("发出 NWS 请求时出错:", 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 [ `事件: ${props.event || "未知"}`, `区域: ${props.areaDesc || "未知"}`, `严重性: ${props.severity || "未知"}`, `状态: ${props.status || "未知"}`, `标题: ${props.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[]; }; } ``` -------------------------------- ### Format NWS Alert Data Source: https://model-context-protocol.mintlify.app/quickstart/server A helper function to format individual alert features from the NWS API response into a concise, human-readable string. ```python def format_alert(feature: dict) -> str: """将警报功能格式化为简洁的字符串。""" props = feature["properties"] return ( f"事件: {props.get('event', '未知')}\n" f"区域: {props.get('areaDesc', '未知')}\n" f"严重性: {props.get('severity', '未知')}\n" f"状态: {props.get('status', '未知')}\n" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.