内容
# 🦄 Unicorn MCP 服务器
一款 Spring AI MCP(模型上下文协议)服务器,通过 **可流式传输的 HTTP** 传输,暴露了 Unicorn 租赁工具 — 包括价格计算器、预订管理和日期/时间实用程序。
## 技术栈
- Java 21, Spring Boot 3.5.0, Spring AI 1.1.2
- MCP 服务器(WebMVC / 可流式传输的 HTTP)
- H2 数据库(基于文件)+ Spring Data JPA
## 暴露的工具
| 工具 | 描述 |
|------|-------------|
| `calculatePrice` | 返回 Unicorn 租赁的完整成本明细 |
| `createBooking` | 预订 Unicorn 租赁并将其持久化到 H2 |
| `getBookings` | 检索客户的所有预订 |
| `getCurrentDateTime` | 获取给定时区的当前日期/时间 |
| `hoursUntil` | 计算现在和未来日期之间的小时数 |
| `resolveRelativeDate` | 将“明天”、“星期六”等解析为日期 |
## 先决条件
- Java 21+
- Maven 3.9+
- Node.js(用于 MCP 检验器)
## 快速入门
```bash
# 1. 克隆并启动服务器
git clone https://github.com/VarshaDas/unicorn-mcp-server.git
cd unicorn-mcp-server
./mvnw spring-boot:run
```
等待日志中出现 `Started McpServerApplication`。服务器在 **http://localhost:8083** 上运行,MCP 端点在 `http://localhost:8083/mcp`。
```bash
# 2. 在单独的终端中 — 启动 MCP 检验器
npx @modelcontextprotocol/inspector
```
3. 在浏览器中打开 http://localhost:6274
4. 选择传输方式:**可流式传输的 HTTP**
5. 输入 URL:`http://localhost:8083/mcp`
6. 点击 **连接** → 您将看到所有 6 个工具
7. 点击任何工具 → 填写参数 → **运行**
就这样。您正在与 MCP 服务器进行通信。
---
## 如何构建 MCP 服务器(或转换现有代码库)
> 如果您在这里将现有的 Spring Boot 应用程序转换为 MCP 服务器 — 您只需 3 步即可完成。您不需要重写代码 — 只需将其暴露。
### 步骤 1:添加 MCP 服务器依赖项
交换(或添加)Spring AI MCP 服务器启动器。这为您的应用程序提供了一个 `/mcp` 端点,该端点通过 **JSON-RPC 2.0** 和 **可流式传输的 HTTP** 进行通信 — MCP 在后台使用的线协议。
```xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
```
```properties
spring.ai.mcp.server.name=my-mcp-server
spring.ai.mcp.server.version=1.0.0
spring.ai.mcp.server.protocol=STREAMABLE
```
这就是整个基础设施变更。无需自定义控制器,无需手动 JSON-RPC 处理。
### 步骤 2:用 `@Tool` 注释您的方法
采用任何现有的 Spring Bean 方法并添加 `@Tool` + `@ToolParam`。这使得您的逻辑可以被任何 MCP 客户端发现。
```java
@Component
public class PricingCalculatorTool {
@Tool(description = "计算 Unicorn 租赁的总成本")
public String calculatePrice(
@ToolParam(description = "租赁套餐名称") String packageName,
@ToolParam(description = "每单位价格") int pricePerUnit,
@ToolParam(description = "小时或天数") int duration,
@ToolParam(description = "包含可选保险") boolean includeInsurance) {
// 您现有的业务逻辑 — 不变
}
}
```
已经有包含业务逻辑的服务类?只需添加注释。方法签名成为工具的输入模式 — MCP 客户端自动看到参数名称、类型和描述。
### 步骤 3:使用 `ToolCallbackProvider` 注册工具
告诉 Spring AI 要通过 MCP 暴露哪些 Bean:
```java
@Configuration
public class McpServerConfig {
@Bean
public ToolCallbackProvider toolCallbackProvider(DateTimeTool dateTimeTool,
PricingCalculatorTool pricingCalculatorTool,
BookingTool bookingTool) {
return MethodToolCallbackProvider.builder()
.toolObjects(dateTimeTool, pricingCalculatorTool, bookingTool)
.build();
}
}
```
完成。Spring Boot 自动配置 MCP 端点。任何 MCP 客户端现在都可以连接、发现您的工具并调用它们。
### 背后发生了什么
MCP 使用 **JSON-RPC 2.0** 作为其线格式 — 每个消息都是一个带有 `method`、`params` 和 `id` 的 JSON 对象:
| 客户端发送 | 服务器响应 |
|---|---|
| `"method": "initialize"` | 会话 ID + 服务器功能 |
| `"method": "tools/list"` | 所有已注册的工具及其模式 |
| `"method": "tools/call"` | 工具执行结果 |
会话是有状态的 — 服务器在初始化时返回一个 `Mcp-Session-Id` 头部,客户端在后续每个请求中传递它。Spring AI 处理所有这些管道;您永远不会自己编写 JSON-RPC 代码。
### 关键思想
您不是在构建新应用程序。您正在通过标准协议公开现有的逻辑。相同的 `@Tool` 方法在本地使用 `ChatClient.defaultTools()` 时起作用,现在可以通过 MCP 在远程工作 — 可供任何语言的任何客户端访问。
---
## 测试 MCP 服务器
### 1. curl — 原始 MCP 协议(可流式传输的 HTTP)
MCP 协议在 HTTP 上使用 JSON-RPC 2.0。
**初始化会话:**
```bash
curl -s -D - http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": { "name": "curl-test", "version": "1.0.0" }
}
}'
```
保存响应中的 `Mcp-Session-Id` 头部,然后在后续调用中使用它。
**列出可用工具:**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}'
```
**调用工具(例如 calculatePrice):**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "calculatePrice",
"arguments": {
"packageName": "SPARKLE",
"pricePerUnit": 150,
"duration": 3,
"includeInsurance": true
}
}
}'
```
**调用 createBooking:**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "createBooking",
"arguments": {
"customerName": "Alice",
"packageName": "RAINBOW",
"bookingDate": "2025-08-15",
"duration": 2,
"includeInsurance": false
}
}
}'
```
**调用 getBookings:**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "getBookings",
"arguments": { "customerName": "Alice" }
}
}'
```
**调用 getCurrentDateTime:**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "getCurrentDateTime",
"arguments": { "timezone": "America/New_York" }
}
}'
```
**调用 resolveRelativeDate:**
```bash
curl -s http://localhost:8083/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SESSION_ID>" \
-d '{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "resolveRelativeDate",
"arguments": { "dayReference": "Saturday" }
}
}'
```
---
### 2. MCP 检验器(官方 GUI 工具)
[MCP 检验器](https://github.com/modelcontextprotocol/inspector) 是一个用于 MCP 服务器的基于 Web 的调试工具。
```bash
npx @modelcontextprotocol/inspector
```
1. 打开检验器 UI(通常在 http://localhost:6274)
2. 选择传输类型:**可流式传输的 HTTP**
3. 输入 URL:`http://localhost:8083/mcp`
4. 点击 **连接** → 您将看到所有 6 个工具列表
5. 点击任何工具 → 填写参数 → **运行** 进行测试
---
### 3. Claude 桌面版
将以下内容添加到您的 Claude 桌面版配置中(`~/Library/Application Support/Claude/claude_desktop_config.json` 在 macOS 上):
```json
{
"mcpServers": {
"unicorn-mcp-server": {
"url": "http://localhost:8083/mcp"
}
}
}
```
重启 Claude 桌面版。然后,您可以询问类似的问题:
- *"3 小时 SPARKLE Unicorn 租赁的费用是多少(含保险)?*"
- *"为 Alice 预订 RAINBOW 套餐,日期为 2025 年 8 月 15 日,时长 2 小时"*
- *"本周六的日期是?*"*
---
### 4. Amazon Q 开发者 CLI
将服务器添加到 `~/.aws/amazonq/mcp.json`:
```json
{
"mcpServers": {
"unicorn-mcp-server": {
"url": "http://localhost:8083/mcp"
}
}
}
```
然后使用 `q chat` 以对话方式与工具交互。
---
### 5. 带有 Copilot(MCP 支持)的 VS Code
将以下内容添加到您工作区中的 `.vscode/mcp.json`:
```json
{
"servers": {
"unicorn-mcp-server": {
"type": "http",
"url": "http://localhost:8083/mcp"
}
}
}
```
使用 Copilot Chat 的 Agent 模式与工具交互。
---
### 6. Cursor IDE
将以下内容添加到 Cursor 的 MCP 设置(`.cursor/mcp.json`):
```json
{
"mcpServers": {
"unicorn-mcp-server": {
"url": "http://localhost:8083/mcp"
}
}
}
```
使用 Cursor 的 Agent 模式调用 Unicorn 租赁工具。
---
### 7. H2 控制台(验证预订持久性)
创建预订后,直接验证数据:
1. 打开 http://localhost:8083/h2-console
2. JDBC URL:`jdbc:h2:file:/tmp/unicorn-bookings`
3. 用户名:`sa`,密码:*(空)*
4. 运行:`SELECT * FROM UNICORN_BOOKINGS;`
---
## 快速参考 — 所有工具参数
| 工具 | 参数 |
|------|-----------|
| `calculatePrice` | `packageName`(字符串),`pricePerUnit`(整数),`duration`(整数),`includeInsurance`(布尔值) |
| `createBooking` | `customerName`(字符串),`packageName`(字符串),`bookingDate`(字符串,YYYY-MM-DD),`duration`(整数),`includeInsurance`(布尔值) |
| `getBookings` | `customerName`(字符串) |
| `getCurrentDateTime` | `timezone`(字符串,例如 "America/New_York") |
| `hoursUntil` | `futureDateTime`(字符串,ISO 格式,例如 "2025-07-20T14:00") |
| `resolveRelativeDate` | `dayReference`(字符串,例如 "Saturday", "tomorrow") |