MCP SSE协议发送注意

springAI代码

mcp server

复制代码
@Service
public class WeatherService {

    @Tool(name = "getWeather", description = "根据城市名称获取天气预报信息")
    public String getWeather(@ToolParam(description = "城市") String cityName) {
        return cityName + "天气阳光明媚~";
    }
}

Toolconfig

复制代码
@Component
public class ToolConfig {

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

配置

复制代码
spring:
  ai:
    mcp:
      server:
        name: my-business-mcp-server
        version: 1.0.0
        # 启用 Streamable HTTP 协议
#        streamable-http:
#          enabled: true
#          endpoint: /mcp
        # 如果也想兼容老客户端,可以顺便开启 SSE
        sse:
          enabled: true
          endpoint: /sse

调试

第一步:拿到新的 Session ID

刷新你的浏览器 http://localhost:8004/sse,在 EventStream 里复制最新的 sessionId(假设是 abc-123)。

第二步:发送初始化请求(必须发!)
复制代码
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"curl-test\",\"version\":\"1.0.0\"}}}"

(这个命令应该很快就会返回一个包含协议版本的 JSON)

第三步:发送确认通知(必须发!)
复制代码
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"

(这个命令会返回 HTTP 200,但可能没有内容)

第四步:正式调用天气工具
复制代码
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":\"2\",\"method\":\"tools/call\",\"params\":{\"name\":\"getWeather\",\"arguments\":{\"cityName\":\"北京\"}}}"

就可以收到结果了,这个是针对相同sessionID得

建议使用人家封装好的工具省的自己搞

相关推荐
Flittly2 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了2 天前
Java 生成二维码解决方案
java·后端
人活一口气2 天前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP2 天前
Vibe Coding -- 完整项目案例实操
java
荣码2 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing2 天前
Google第三方授权登录
java·后端·程序员
明月光8182 天前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑2 天前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯2 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
青石路2 天前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java