如何构建 Spring Boot MCP Server (2026)
使用 Spring Boot 构建 Java 版 Model Context Protocol 服务端
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
如何构建 Spring Boot MCP 服务器 (2026)
Model Context Protocol (MCP) 是由 Anthropic 创建的一种开放标准,它使 Claude 等 AI 助手能够与外部工具和数据源进行交互。虽然大多数 MCP 服务器示例使用 TypeScript 或 Python,但 Java 开发者可以使用官方的 MCP Java SDK,结合 Spring Boot 构建 MCP 服务器。本指南将带你从零开始构建一个功能齐全的 MCP 服务器。
什么是 MCP?
MCP (Model Context Protocol) 为 AI 助手定义了一种标准方式来:
- 调用工具 (Call tools) —— 执行诸如查询数据库、调用 API 或进行计算等函数
- 读取资源 (Read resources) —— 访问诸如文件、数据库记录或 API 响应等数据
- 使用提示词 (Use prompts) —— 获取预构建的提示词模板
可以将其视为 AI 的插件系统。当 Claude 连接到你的 MCP 服务器时,它会发现哪些工具可用,并在对话过程中调用它们。
MCP 架构
┌─────────────┐ MCP 协议 ┌──────────────┐
│ Claude │ ◄──────────────────► │ MCP 服务器 │
│ Desktop │ (基于 stdio 或 │ (Spring Boot)│
│ 或 IDE │ SSE 的 JSON-RPC) │ │
└─────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ 你的工具 │
│ - 数据库 │
│ - API │
│ - 文件 │
└──────────────┘
前置条件
- Java 17 或更高版本
- Maven 或 Gradle
- Spring Boot 3.2+
- Claude Desktop 或任何兼容 MCP 的客户端
验证你的 Java 版本:
java --version
# 应输出 java 17.x.x 或更高版本
mvn --version
# Apache Maven 3.9.x 或更高版本
第 1 步:创建 Spring Boot 项目
使用 Spring Initializr 或手动创建项目。
使用 Spring Initializr
curl https://start.spring.io/starter.zip \
-d type=maven-project \
-d language=java \
-d bootVersion=3.4.2 \
-d baseDir=mcp-server \
-d groupId=com.example \
-d artifactId=mcp-server \
-d name=mcp-server \
-d packageName=com.example.mcpserver \
-d javaVersion=17 \
-d dependencies=web \
-o mcp-server.zip
unzip mcp-server.zip
cd mcp-server
添加 MCP 依赖
在你的 pom.xml 中添加 MCP Java SDK:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MCP Java SDK -->
<dependency>
<groupId>io.modelcontextprotocol</groupId>
<artifactId>mcp-spring-boot-starter</artifactId>
<version>0.6.0</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
第 2 步:配置 MCP 服务器
在 src/main/resources/application.yml 中创建应用配置:
server:
port: 8080
mcp:
server:
name: "my-spring-mcp-server"
version: "1.0.0"
transport: sse # 对于命令行客户端使用 "stdio"
第 3 步:定义你的工具
MCP 工具是 Claude 可以调用的函数。每个工具都有名称、描述、输入 Schema 和处理器。
创建工具配置类
package com.example.mcpserver.tools;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
@Configuration
public class ToolConfiguration {
private final ObjectMapper objectMapper = new ObjectMapper();
@Bean
public McpServer.ToolRegistration weatherTool() {
// 定义输入 Schema
String inputSchema = """
{
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "要获取天气的城市名称"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位",
"default": "celsius"
}
},
"required": ["city"]
}
""";
Tool tool = new Tool(
"get_weather",
"获取指定城市的当前天气",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String city = (String) arguments.get("city");
String units = (String) arguments.getOrDefault("units", "celsius");
// 在真实应用中,在此处调用天气 API
String weather = fetchWeather(city, units);
return new CallToolResult(
List.of(new TextContent(weather)),
false // isError
);
});
}
@Bean
public McpServer.ToolRegistration calculatorTool() {
String inputSchema = """
{
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["add", "subtract", "multiply", "divide"],
"description": "要执行的数学运算"
},
"a": {
"type": "number",
"description": "第一个操作数"
},
"b": {
"type": "number",
"description": "第二个操作数"
}
},
"required": ["operation", "a", "b"]
}
""";
Tool tool = new Tool(
"calculate",
"执行基础数学计算",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String operation = (String) arguments.get("operation");
double a = ((Number) arguments.get("a")).doubleValue();
double b = ((Number) arguments.get("b")).doubleValue();
double result = switch (operation) {
case "add" -> a + b;
case "subtract" -> a - b;
case "multiply" -> a * b;
case "divide" -> {
if (b == 0) throw new ArithmeticException("除数不能为零");
yield a / b;
}
default -> throw new IllegalArgumentException(
"未知运算: " + operation
);
};
return new CallToolResult(
List.of(new TextContent(String.valueOf(result))),
false
);
});
}
private String fetchWeather(String city, String units) {
// 占位符 - 替换为实际的 API 调用
return String.format(
"%s 的天气:22%s,多云,湿度 65%%",
city,
units.equals("celsius") ? "°C" : "°F"
);
}
}
第 4 步:添加资源提供者
资源允许 Claude 从你的服务器读取数据:
package com.example.mcpserver.resources;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema.Resource;
import io.modelcontextprotocol.spec.McpSchema.ResourceContents;
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class ResourceConfiguration {
@Bean
public McpServer.ResourceRegistration configResource() {
Resource resource = new Resource(
"config://app/settings",
"应用设置",
"当前应用程序的配置和设置",
"application/json"
);
return new McpServer.ResourceRegistration(resource, (uri) -> {
String configJson = """
{
"app_name": "My MCP Server",
"version": "1.0.0",
"features": ["weather", "calculator"],
"max_requests_per_minute": 60
}
""";
return new ResourceContents(
List.of(new TextResourceContents(uri, "application/json", configJson))
);
});
}
}
第 5 步:添加数据库工具(实际案例)
这是一个更真实的例子 —— 一个查询数据库的工具:
@Bean
public McpServer.ToolRegistration databaseQueryTool(JdbcTemplate jdbcTemplate) {
String inputSchema = """
{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "要执行的 SQL SELECT 查询(只读)"
},
"limit": {
"type": "integer",
"description": "返回的最大行数",
"default": 10
}
},
"required": ["query"]
}
""";
Tool tool = new Tool(
"query_database",
"对应用程序数据库执行只读 SQL 查询",
objectMapper.readTree(inputSchema)
);
return new McpServer.ToolRegistration(tool, (arguments) -> {
String query = (String) arguments.get("query");
int limit = ((Number) arguments.getOrDefault("limit", 10)).intValue();
// 安全性:仅允许 SELECT 语句
if (!query.trim().toUpperCase().startsWith("SELECT")) {
return new CallToolResult(
List.of(new TextContent("错误:仅允许 SELECT 查询")),
true // isError
);
}
// 如果不存在则添加 LIMIT
if (!query.toUpperCase().contains("LIMIT")) {
query += " LIMIT " + limit;
}
List<Map<String, Object>> results = jdbcTemplate.queryForList(query);
String json = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(results);
return new CallToolResult(
List.of(new TextContent(json)),
false
);
});
}
第 6 步:运行与测试
构建并运行
mvn clean package
java -jar target/mcp-server-0.0.1-SNAPSHOT.jar
服务器将在 8080 端口启动,并在 /sse 路径提供 SSE 端点。
使用 cURL 测试
# 检查服务器是否正在运行
curl http://localhost:8080/sse
# 列出可用工具(通过 MCP 协议)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}'
第 7 步:连接到 Claude Desktop
将你的 MCP 服务器添加到 Claude Desktop 的配置文件中。
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
对于 SSE 传输方式
{
"mcpServers": {
"spring-mcp": {
"url": "http://localhost:8080/sse"
}
}
}
对于 stdio 传输方式
如果你构建的服务器使用 stdio 传输,请封装 jar 执行方案:
{
"mcpServers": {
"spring-mcp": {
"command": "java",
"args": [
"-jar",
"/path/to/mcp-server-0.0.1-SNAPSHOT.jar"
]
}
}
}
更新配置后重启 Claude Desktop。你的工具应该会出现在 Claude 的工具列表中。
故障排除
| 问题 | 原因 | 解决方案 |
|---|---|---|
| Claude 中找不到服务器 | 配置文件语法错误 | 校验 JSON;重启 Claude Desktop |
| "Connection refused" | 服务器未运行 | 先启动 Spring Boot 应用 |
| 工具未显示 | 缺少 @Bean 注解 |
确保工具 Bean 位于 @Configuration 类中 |
| SSE 连接断开 | 超时设置 | 配置 server.servlet.session.timeout |
| JSON 解析错误 | Schema 不匹配 | 根据 MCP 规范校验你的输入 Schema |
项目结构
mcp-server/
├── pom.xml
├── src/
│ └── main/
│ ├── java/com/example/mcpserver/
│ │ ├── McpServerApplication.java
│ │ ├── tools/
│ │ │ └── ToolConfiguration.java
│ │ └── resources/
│ │ └── ResourceConfiguration.java
│ └── resources/
│ └── application.yml
结论
使用 Spring Boot 构建 MCP 服务器可以让 Java 开发者将现有的服务、数据库和 API 开放给 Claude 等 AI 助手。MCP Java SDK 与 Spring Boot 的依赖注入和配置系统自然结合,使得注册工具和资源变得非常简单。
对于希望通过视觉内容生成来扩展其启用 MCP 的 AI 工作流的团队——例如创建产品视频、根据描述生成图像或构建会话数字人界面——Hypereal AI 提供了统一的视频、图像和数字人生成 API,你可以轻松地将其封装为额外的 MCP 工具。
