一、MCP 客户端注解
MCP 客户端注解提供了一种使用 Java 注解来实现 MCP 客户端处理器的声明式方法。这些注解简化了服务器通知和客户端操作的处理。
所有 MCP 客户端注解必须包含一个 clients 参数,用于将处理器与特定的 MCP 客户端连接关联。该参数必须与应用程序配置文件中配置的连接名称相匹配。
二、客户端注解
2.1 @McpLogging
@McpLogging 注解用于处理来自 MCP 服务器的日志消息通知。
2.1.1 基本用法
@ComponentpublicclassLoggingHandler{@McpLogging(clients="my-mcp-server")publicvoidhandleLoggingMessage(LoggingMessageNotificationnotification){System.out.println("收到日志: "+notification.level()+" - "+notification.data());}}2.1.2 使用独立参数
@McpLogging(clients="my-mcp-server")publicvoidhandleLoggingWithParams(LoggingLevellevel,Stringlogger,Stringdata){System.out.println(String.format("[%s] %s: %s",level,logger,data));}2.2 @McpSampling
@McpSampling 注解用于处理来自 MCP 服务器的大语言模型补全采样请求。
2.2.1 同步实现
@ComponentpublicclassSamplingHandler{@McpSampling(clients="llm-server")publicCreateMessageResulthandleSamplingRequest(CreateMessageRequestrequest){// 处理请求并生成响应Stringresponse=generateLLMResponse(request);returnCreateMessageResult.builder().role(Role.ASSISTANT).content(newTextContent(response)).model("gpt-4").build();}}2.2.2 异步实现
@ComponentpublicclassAsyncSamplingHandler{@McpSampling(clients="llm-server")publicMono<CreateMessageResult>handleAsyncSampling(CreateMessageRequestrequest){returnMono.fromCallable(()->{Stringresponse=generateLLMResponse(request);returnCreateMessageResult.builder().role(Role.ASSISTANT).content(newTextContent(response)).model("gpt-4").build();}).subscribeOn(Schedulers.boundedElastic());}}2.3 @McpElicitation
@McpElicitation 注解用于处理向用户收集额外信息的征询请求。
2.3.1 基本用法
@ComponentpublicclassElicitationHandler{@McpElicitation(clients="interactive-server")publicElicitResulthandleElicitationRequest(ElicitRequestrequest){// 向用户展示请求并收集输入Map<String,Object>userData=