MCP 历史资料 · 2024-11-05规范内容保留该历史版本,请对照官方最新文档使用。官方文档 ↗

面向服务器开发者

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

我们将要构建什么#

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

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

weather-alters

current-weather

Note

服务器可以连接到任何客户端。我们在这里选择 Claude for Desktop 是为了简单起见,我们也有关于构建自己的客户端的指南以及其他客户端列表。

为什么选择 Claude for Desktop 而不是 Claude.ai?

因为服务器是本地运行的,MCP 目前只支持桌面宿主程序。远程宿主程序正在积极开发中。

MCP 核心概念#

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

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

本教程将主要关注工具。

让我们开始构建我们的天气服务器吧!你可以在这里找到我们将要构建的完整代码。

前置知识#

本快速入门假设你熟悉:

  • Kotlin
  • LLM(如 Claude)

系统要求#

  • 安装 Java 17 或更高版本。

设置你的环境#

首先,如果你还没有安装 java 和 gradle,让我们先安装它们。 你可以从官方 Oracle JDK 网站下载 java。 验证你的 java 安装:

java --version

现在,让我们创建并设置你的项目:

# 为我们的项目创建一个新目录
mkdir weather
cd weather

# 初始化一个新的 kotlin 项目
gradle init

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

或者,你可以使用 IntelliJ IDEA 项目向导创建一个 Kotlin 应用程序。

创建项目后,添加以下依赖项:

// build.gradle.kts
val mcpVersion = "0.3.0"
val slf4jVersion = "2.0.9"
val ktorVersion = "3.1.1"

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

同时,在你的构建脚本中添加以下插件:

// build.gradle.kts
plugins {
    kotlin("plugin.serialization") version "your_version_of_kotlin"
    id("com.github.johnrengelman.shadow") version "8.1.1"
}

现在让我们深入构建你的服务器。

构建你的服务器#

设置实例#

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

// 运行 MCP 服务器的主函数
fun `run mcp server`() {
    // 使用基本实现创建 MCP 服务器实例
    val server = Server(
        Implementation(
            name = "weather", // 工具名称为 "weather"
            version = "1.0.0" // 实现的版本
        ),
        ServerOptions(
            capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true))
        )
    )

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

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

天气 API 辅助函数#

接下来,让我们添加用于查询和转换国家气象服务 API 响应的函数和数据类:

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

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

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

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

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

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

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

实现工具执行#

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

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

// 注册一个用于按州获取天气预警的工具
server.addTool(
    name = "get_alerts",
    description = """
        获取美国某个州的天气预警。输入为两个字母的美国州代码(例如 CA、NY)
    """.trimIndent(),
    inputSchema = Tool.Input(
        properties = JsonObject(
            mapOf(
                "state" to JsonObject(
                    mapOf(
                        "type" to JsonPrimitive("string"),
                        "description" to JsonPrimitive("两个字母的美国州代码(例如 CA、NY)")
                    )
                ),
            )
        ),
        required = listOf("state")
    )
) { request ->
    val state = request.arguments["state"]?.jsonPrimitive?.content
    if (state == null) {
        return@addTool CallToolResult(
            content = listOf(TextContent("需要提供 'state' 参数。"))
        )
    }

    val alerts = httpClient.getAlerts(state)

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

// 注册一个用于按纬度和经度获取天气预报的工具
server.addTool(
    name = "get_forecast",
    description = """
        获取特定纬度/经度的天气预报
    """.trimIndent(),
    inputSchema = Tool.Input(
        properties = JsonObject(
            mapOf(
                "latitude" to JsonObject(mapOf("type" to JsonPrimitive("number"))),
                "longitude" to JsonObject(mapOf("type" to JsonPrimitive("number"))),
            )
        ),
        required = listOf("latitude", "longitude")
    )
) { request ->
    val latitude = request.arguments["latitude"]?.jsonPrimitive?.doubleOrNull
    val longitude = request.arguments["longitude"]?.jsonPrimitive?.doubleOrNull
    if (latitude == null || longitude == null) {
        return@addTool CallToolResult(
            content = listOf(TextContent("需要提供 'latitude' 和 'longitude' 参数。"))
        )
    }

    val forecast = httpClient.getForecast(latitude, longitude)

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

运行服务器#

最后,实现运行服务器的主函数:

fun main() = `run mcp server`()

确保运行 ./gradlew build 来构建你的服务器。这是让你的服务器能够连接的一个非常重要的步骤。

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

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

Note

Claude for Desktop 目前在 Linux 上尚不可用。Linux 用户可以继续学习构建客户端教程,以构建一个连接到我们刚刚构建的服务器的 MCP 客户端。

首先,确保你已安装 Claude for Desktop。你可以在这里安装最新版本。如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。

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

例如,如果你安装了 VS Code:

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

然后你需要在 mcpServers 键中添加你的服务器。 MCP UI 元素只有在至少正确配置了一个服务器的情况下才会在 Claude for Desktop 中显示。

在这种情况下,我们将添加我们的单个天气服务器,如下所示:

{
    "mcpServers": {
        "weather": {
            "command": "java",
            "args": [
                "-jar",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
            ]
        }
    }
}

这告诉 Claude for Desktop:

  1. 有一个名为 "weather" 的 MCP 服务器
  2. 通过运行 java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar 来启动它

保存文件,然后重启 Claude for Desktop。

测试命令#

让我们确保 Claude for Desktop 能够识别到我们在 weather 服务器中暴露的两个工具。你可以通过查看锤子 图标来确认:

visual-indicator-mcp-tools

点击锤子图标后,你应该能看到列出的两个工具:

available-mcp-tools

如果你的服务器没有被 Claude for Desktop 识别到,请查看故障排除部分获取调试建议。

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

  • 萨克拉门托的天气如何?
  • 德克萨斯州有哪些活跃的天气预警?

current-weather

weather-alerts

Note

由于这是美国国家气象服务,查询只适用于美国地区。

幕后发生了什么#

当你提出一个问题时:

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

故障排除#

Claude for Desktop 集成问题#

Note

获取 Claude for Desktop 的日志

与 MCP 相关的 Claude.app 日志写入到 ~/Library/Logs/Claude 中:

  • mcp.log 包含有关 MCP 连接和连接失败的常规日志。
  • 名为 mcp-server-SERVERNAME.log 的文件包含来自指定服务器的错误(stderr)日志。

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

# 检查 Claude 的错误日志
tail -n 20 -f ~/Library/Logs/Claude/mcp*.log

服务器没有在 Claude 中显示

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

工具调用静默失败

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

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

这些都不起作用,我该怎么办?

请参考我们的调试指南获取更好的调试工具和更详细的指导。

天气 API 问题#

Note

错误:无法获取网格点数据

这通常意味着:

  1. 坐标在美国境外
  2. NWS API 出现问题
  3. 你被限制请求频率

解决方法:

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

错误:[州]没有活跃的预警

这不是错误 - 这只是意味着该州目前没有天气预警。尝试查看其他州或在恶劣天气期间检查。

Tip

要获取更高级的故障排除方法,请查看我们的调试 MCP 指南