AI超级助手开发起步:轻松掌握MCP协议(Python篇)

🚀 AI超级助手开发入门:用 Python 和 Java 快速实现 MCP 协议服务

随着大模型时代到来,AI 应用正在迈向更高层次的“协作智能”。要想让 LLM 更聪明地访问工具、数据和服务,MCP(Model Context Protocol)应运而生。

本文以 MCP 官方协议为基础,结合 Server Quickstart 教程 和规范文档,带你使用 Python 和 Java 快速搭建一个支持 Claude、ChatGPT 等客户端调用的 MCP 服务。


🔍 什么是 MCP?

MCP 是一个开放协议,旨在定义 LLM 与外部系统(如文件、数据库、工具函数)进行交互的标准通信方式。你可以把它理解为:

“AI 的 USB-C 协议”

它让你的 AI 模型像插上“万能扩展坞”一样,调用各种本地和远程能力。

✅ MCP 基础能力

MCP 服务器可向 LLM 提供:

  • 资源 Resources:提供上下文信息(如文件、数据库记录)
  • 提示 Prompts:模板化消息提示或工作流
  • 工具 Tools:函数调用接口
  • 采样 Sampling:支持代理/递归调用
  • 💡 架构图(来自官方)


    🧰 开发 MCP 服务端(Python 示例)

    我们以“天气查询服务”为例,使用 FastMCP 框架快速搭建符合 MCP 规范的服务。

    ✅ 环境准备

  • Python >= 3.10
  • MCP SDK >= 1.2.0
  • 使用 uv 初始化项目(推荐):

    curl -LsSf https://astral.sh/uv/install.sh | sh
    uv init weather
    cd weather
    uv venv
    source .venv/bin/activate
    uv add "mcp[cli]" httpx
    

    创建主程序文件:

    touch weather.py
    

    ✅ 创建 MCP 服务

    from typing import Any
    import httpx
    from mcp.server.fastmcp import FastMCP
    
    mcp = FastMCP("weather")
    
    NWS_API_BASE = "https://api.weather.gov"
    USER_AGENT = "weather-app/1.0"
    
    async def make_nws_request(url: str) -> dict[str, Any] | None:
        headers = {
            "User-Agent": USER_AGENT,
            "Accept": "application/geo+json"
        }
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(url, headers=headers, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except Exception:
                return None
    
    def format_alert(feature: dict) -> str:
        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}"
        data = await make_nws_request(url)
        if not data or "features" not in data:
            return "Unable to fetch alerts or no alerts found."
        if not data["features"]:
            return "No active alerts for this state."
        alerts = [format_alert(feature) for feature in data["features"]]
        return "\n---\n".join(alerts)
    
    @mcp.tool()
    async def get_forecast(latitude: float, longitude: float) -> str:
        """Get weather forecast for a location.
    
        Args:
            latitude: Latitude of the location
            longitude: Longitude of the location
        """
        points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
        points_data = await make_nws_request(points_url)
        if not points_data:
            return "Unable to fetch forecast data for this location."
        forecast_url = points_data["properties"]["forecast"]
        forecast_data = await make_nws_request(forecast_url)
        if not forecast_data:
            return "Unable to fetch detailed forecast."
        periods = forecast_data["properties"]["periods"]
        forecasts = []
        for period in periods[:5]:
            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
    

    🧪 配置 Claude for Desktop 测试

    修改:~/Library/Application Support/Claude/claude_desktop_config.json

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

    保存后重启 Claude for Desktop,即可调用天气工具。


    ☕ Java 实现(基于 Spring AI Boot Starter)

    Spring AI 团队与 Anthropic 合作推出的官方 Java SDK,基于 Spring Boot 自动配置机制,支持快速构建企业级 MCP 服务。

    ✅ 环境准备

  • Java 17+
  • Spring Boot 3.3.x+
  • 推荐使用 Spring Initializr 快速生成项目,添加以下依赖:

    <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>
    

    ✅ 配置 application.properties

    spring.main.bannerMode=off
    logging.pattern.console=
    

    ✅ 编写天气服务 WeatherService.java

    @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
    	  }
    }
    

    ✅ 启动类 McpServerApplication.java

    @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();
        }
    }
    

    ✅ 构建与运行

    ./mvnw clean install
    

    生成文件路径示例:

    target/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar
    

    🧪 测试服务:配置 Claude for Desktop

    编辑:~/Library/Application Support/Claude/claude_desktop_config.json

    {
      "mcpServers": {
        "spring-ai-mcp-weather": {
          "command": "java",
          "args": [
            "-Dspring.ai.mcp.server.stdio=true",
            "-jar",
            "/ABSOLUTE/PATH/TO/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
          ]
        }
      }
    }
    

    保存后重启 Claude,即可识别 MCP 工具。


    ✅ 使用 Java 客户端测试(可选)

    var stdioParams = ServerParameters.builder("java")
        .args("-jar", "/ABSOLUTE/PATH/TO/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
        .build();
    
    var mcpClient = McpClient.sync(new StdioClientTransport(stdioParams)).build();
    mcpClient.initialize();
    
    CallToolResult forecast = mcpClient.callTool(
        new CallToolRequest("getWeatherForecastByLocation", Map.of("latitude", "47.6", "longitude", "-122.3")));
    
    CallToolResult alerts = mcpClient.callTool(
        new CallToolRequest("getAlerts", Map.of("state", "NY")));
    
    System.out.println(forecast.getResult());
    System.out.println(alerts.getResult());
    mcpClient.closeGracefully();
    

    你也可以使用 spring-ai-starter-mcp-client 自动配置客户端,重用 claude_desktop_config.json

    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-starter-mcp-client</artifactId>
    </dependency>
    
    spring.ai.mcp.client.stdio.servers-configuration=file:/PATH/TO/claude_desktop_config.json
    

    更多示例可查看:starter-webflux-server—

    🔒 安全与用户控制

    MCP 的设计核心是安全透明、用户可控

    官方要求每个 MCP 工具都应:

  • 明确声明输入参数及说明
  • 提示模型说明该操作内容及风险
  • 用户明确授权后才能调用
  • 📖 详见:Security and Trust


    📦 官方资源推荐

  • MCP 规范文档
  • 服务端快速入门
  • Python SDK
  • Java SDK

  • ✨ 总结

    通过 MCP 协议,AI 模型可以真正成为你的“数字员工”,按需调用各种函数、操作数据、生成结果。

    无论你使用 Python 还是 Java,借助 MCP SDK 都能快速构建出 Claude、ChatGPT 可连接的智能服务。

    赶快动手试试,让你的 AI 有手有眼会用工具吧!🛠️

    作者:风千叶

    物联沃分享整理
    物联沃-IOTWORD物联网 » AI超级助手开发起步:轻松掌握MCP协议(Python篇)

    发表回复