76_Spring AI 干货笔记之 MCP 服务器注解
一、MCP 服务器注解
MCP 服务器注解提供了一种使用 Java 注解来实现 MCP 服务器功能的声明式方法。这些注解简化了工具、资源、提示词和补全处理器的创建。
二、服务器注解
2.1 @McpTool
@McpTool 注解将一个方法标记为 MCP 工具实现,并自动生成 JSON 架构。
2.1.1 基本用法
@Component
public class CalculatorTools {
@McpTool(name = "add", description = "将两个数字相加")
public int add(
@McpToolParam(description = "第一个数字", required = true) int a,
@McpToolParam(description = "第二个数字", required = true) int b) {
return a + b;
}
}
2.1.2 高级功能
@McpTool(name = "calculate-area",
description = "计算矩形面积",
annotations = McpTool.McpAnnotations(
title = "矩形面积计算器",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true
))
public AreaResult calculateRectangleArea(
@McpToolParam(description = "宽度", required = true) double width,
@McpToolParam(description = "高度", required = true) double height) {
return new AreaResult(width * height, "平方单位");
}
2.1.3 使用请求上下文
工具可以访问请求上下文以进行高级操作:
@McpTool(name = "process-data", description = "使用请求上下文处理数据")
public String processData(
McpSyncRequestContext context,
@McpToolParam(description = "要处理的数据", required = true) String data) {
// 发送日志通知
context.info("正在处理数据: " + data);
// 发送进度通知(使用便捷方法)
context.progress(p -> p.progress(0.5).total(1.0).message("处理中..."));
// 向客户端发送 ping
context.ping();
return "已处理: " + data.toUpperCase();
}
2.1.4 动态架构支持
工具可以接受 CallToolRequest 以进行运行时架构处理:
@McpTool(name = "flexible-tool", description = "处理动态架构")
public CallToolResult processDynamic(CallToolRequest request) {
Map<String, Object> args = request.arguments();
// 基于运行时架构进行处理
String result = "动态处理了 " + args.size() + " 个参数";
return CallToolResult.builder()
.addTextContent(result)
.build();
}
2.1.5 进度跟踪
工具可以接收进度令牌来跟踪长时间运行的操作:
@McpTool(name = "long-task", description = "带有进度的长时间运行任务")
public String performLongTask(
McpSyncRequestContext context,
@McpToolParam(description = "任务名称", required = true) String taskName) {
// 从上下文中访问进度令牌
String progressToken = context.request().progressToken();
if (progressToken != null) {
context.progress(p -> p.progress(0.0).total(1.0).message("开始任务"));
// 执行工作...
context.progress(p -> p.progress(1.0).total(1.0).message("任务完成")








