Helidon Base MCP 服务器
使用Helidon框架实现的一个基础MCP(模型上下文协议)服务器,通过Docker进行容器化,以便于部署和测试。
概述
该项目为使用Java和Helidon构建MCP服务器提供了基础。它包含一个简单的ping工具作为示例,并展示了如何实现MCP协议以进行工具发现和执行。
特点/特性
- MCP协议支持实现了工具发现和执行的模型上下文协议
- Docker 容器化带有多阶段构建的即用型Docker镜像
- Java 21使用现代Java特性和Helidon 4.0.7构建
- 自包含的JAR文件所有依赖项均包含在一个可执行的单个JAR文件中
- HTTP服务器用于MCP协议通信的RESTful API端点
- JSON-RPC 支持完整的JSON-RPC 2.0协议实现
项目结构
helidon-base-mcp-server/
├── src/
│ └── main/
│ └── java/
│ └── io/
│ └── helidon/
│ └── McpServer.java # Main MCP server implementation
├── pom.xml # Maven configuration
├── Dockerfile # Multi-stage Docker build
└── README.md # This file先决条件
- Java 21 或更高
- Maven 3.6及以上版本 (用于本地开发)
- Docker (适用于容器化部署)
🚀 完整的Docker部署与测试指南
先决条件检查清单
在开始之前,请确保您已具备:
- \[ \] Docker Desktop(中文可译为“Docker 桌面版”) 已安装并运行
- \[ \] PowerShell (Windows) 或 Bash(巴斯) (Linux/Mac) 终端
- \[ \] 网络连接 用于下载基础镜像
- \[ \] 端口8080 在您的系统上可用
步骤1:构建Docker镜像
# Navigate to project directory
cd helidon-base-mcp-server
# Build the Docker image with verbose output
docker build -t helidon-base-mcp . --progress=plain
# Verify image was created
docker images | grep helidon-base-mcp预期输出:
REPOSITORY TAG IMAGE ID CREATED SIZE
helidon-base-mcp latest abc123def456 2 minutes ago 200MB步骤2:部署容器
# Run the container in detached mode with proper naming
docker run -d \
--name helidon-mcp-server \
-p 8080:8080 \
--restart unless-stopped \
helidon-base-mcp
# Verify container is running
docker ps --filter name=helidon-mcp-server预期输出:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
134e7fda648f helidon-base-mcp "java -jar app.jar" 3 minutes ago Up 3 minutes 0.0.0.0:8080->8080/tcp helidon-mcp-server第三步:健康检查与监测
# Check container health
docker ps --filter name=helidon-mcp-server
# View container logs
docker logs helidon-mcp-server
# Monitor logs in real-time
docker logs -f helidon-mcp-server预期的日志输出:
Oct 23, 2025 4:47:48 PM io.helidon.common.features.HelidonFeatures features
INFO: Helidon SE 4.0.7 features: [WebServer]
Oct 23, 2025 4:47:48 PM io.helidon.webserver.ServerListener start
INFO: [0x77aaa2fc] http://0.0.0.0:8080 bound for socket '@default'
Oct 23, 2025 4:47:48 PM io.helidon.webserver.LoomServer startIt
INFO: Started all channels in 41 milliseconds. 273 milliseconds since JVM startup. Java 21.0.8+9-LTS步骤4:全面测试套件
4.1 基本连接性测试
# Test 1: Basic HTTP connectivity
curl -v http://localhost:8080/
# Test 2: MCP endpoint availability
curl -v http://localhost:8080/mcp
# Test 3: Server response time
time curl -s http://localhost:8080/ > /dev/null预期回复:
GET /→"Helidon MCP Server is running!"GET /mcp→"MCP endpoint available"
4.2 JSON-RPC协议测试
PowerShell(Windows):
# Test MCP list-tools
$body = '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'
$response = Invoke-WebRequest -Uri "http://localhost:8080/mcp" -Method POST -ContentType "application/json" -Body $body
Write-Host "Status: $($response.StatusCode)"
Write-Host "Response: $($response.Content)"
# Test MCP ping
$pingBody = '{"jsonrpc":"2.0","method":"mcp/ping","id":2}'
$pingResponse = Invoke-WebRequest -Uri "http://localhost:8080/mcp" -Method POST -ContentType "application/json" -Body $pingBody
Write-Host "Ping Response: $($pingResponse.Content)"Bash/cURL(Linux/Mac):
# Test MCP list-tools
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}' \
-w "\nHTTP Status: %{http_code}\nResponse Time: %{time_total}s\n"
# Test MCP ping
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/ping","id":2}' \
-w "\nHTTP Status: %{http_code}\nResponse Time: %{time_total}s\n"预期的JSON-RPC响应:
{"jsonrpc":"2.0","result":"MCP server response","id":1}4.3 性能与负载测试
# Concurrent request testing
for i in {1..10}; do
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d "{\"jsonrpc\":\"2.0\",\"method\":\"mcp/ping\",\"id\":$i}" &
done
wait
# Response time analysis
echo "Testing response times..."
for i in {1..5}; do
echo "Test $i:"
time curl -s -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}' > /dev/null
done4.4 错误处理测试
# Test invalid JSON
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"invalid":"json"}' \
-v
# Test malformed JSON-RPC
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"unknown-method","id":999}' \
-v
# Test wrong content type
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: text/plain" \
-d "plain text" \
-v第五步:容器管理
5.1 容器生命周期管理
# Stop the container
docker stop helidon-mcp-server
# Start the container
docker start helidon-mcp-server
# Restart the container
docker restart helidon-mcp-server
# Remove the container (stops it first)
docker rm -f helidon-mcp-server5.2 资源监控
# Monitor container resource usage
docker stats helidon-mcp-server
# Check container details
docker inspect helidon-mcp-server
# View container processes
docker exec helidon-mcp-server ps aux5.3 日志管理
# View last 50 log lines
docker logs --tail 50 helidon-mcp-server
# View logs with timestamps
docker logs -t helidon-mcp-server
# Save logs to file
docker logs helidon-mcp-server > server-logs.txt
# Follow logs in real-time
docker logs -f --tail 10 helidon-mcp-server步骤6:生产部署考虑事项
6.1 环境配置
# Run with custom environment variables
docker run -d \
--name helidon-mcp-server \
-p 8080:8080 \
-e JAVA_OPTS="-Xmx512m -Xms256m" \
-e SERVER_PORT=8080 \
--restart unless-stopped \
helidon-base-mcp6.2 网络配置
# Create custom network
docker network create mcp-network
# Run container on custom network
docker run -d \
--name helidon-mcp-server \
--network mcp-network \
-p 8080:8080 \
helidon-base-mcp6.3 卷挂载(用于持久数据)
# Run with volume for logs
docker run -d \
--name helidon-mcp-server \
-p 8080:8080 \
-v $(pwd)/logs:/app/logs \
helidon-base-mcp步骤7:故障排除与调试
7.1 常见问题及解决方案
| 问题 | 症状 | 解决方案 |
|---|---|---|
| 端口冲突 | bind: address already in use | 更改端口: -p 8081:8080 |
| 内存问题 | 容器立即退出 | 增加内存: -e JAVA_OPTS="-Xmx1g" |
| 网络问题 | 连接被拒绝 | 检查防火墙和端口转发设置 |
| 图片未找到 | Unable to find image | 重建: docker build -t helidon-base-mcp . |
7.2 调试命令
# Check container status
docker ps -a --filter name=helidon-mcp-server
# Inspect container configuration
docker inspect helidon-mcp-server
# Check container logs for errors
docker logs helidon-mcp-server 2>&1 | grep -i error
# Test connectivity from inside container
docker exec helidon-mcp-server curl http://localhost:8080/
# Check Java process
docker exec helidon-mcp-server jps -v步骤8:清理与维护
# Stop and remove container
docker stop helidon-mcp-server
docker rm helidon-mcp-server
# Remove image (if needed)
docker rmi helidon-base-mcp
# Clean up unused resources
docker system prune -f
# Remove all stopped containers
docker container prune -f步骤9:自动化测试脚本
创建一个全面的测试脚本:
#!/bin/bash
# test-mcp-server.sh
echo "🚀 Starting Helidon MCP Server Testing Suite"
echo "=============================================="
# Test 1: Basic connectivity
echo "📡 Testing basic connectivity..."
if curl -s http://localhost:8080/ > /dev/null; then
echo "✅ Basic connectivity: PASS"
else
echo "❌ Basic connectivity: FAIL"
exit 1
fi
# Test 2: MCP endpoint
echo "🔧 Testing MCP endpoint..."
if curl -s http://localhost:8080/mcp > /dev/null; then
echo "✅ MCP endpoint: PASS"
else
echo "❌ MCP endpoint: FAIL"
exit 1
fi
# Test 3: JSON-RPC protocol
echo "📋 Testing JSON-RPC protocol..."
response=$(curl -s -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}')
if echo "$response" | grep -q "jsonrpc"; then
echo "✅ JSON-RPC protocol: PASS"
echo " Response: $response"
else
echo "❌ JSON-RPC protocol: FAIL"
echo " Response: $response"
exit 1
fi
echo "🎉 All tests passed! MCP server is working correctly."用法:
chmod +x test-mcp-server.sh
./test-mcp-server.sh快速入门
为了快速上手,请使用以下基本命令:
# Build and run
docker build -t helidon-base-mcp .
docker run -d -p 8080:8080 --name helidon-mcp-server helidon-base-mcp
# Test
curl http://localhost:8080/
curl -X POST http://localhost:8080/mcp -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'本地开发
- 构建项目:
mvn clean package- 运行服务器:
java -jar target/helidon-base-mcp-server-1.0.0.jar- 测试服务器:
# Test basic endpoint
curl http://localhost:8080/
# Test MCP endpoint
curl http://localhost:8080/mcp
# Test with MCP client (PowerShell)
Invoke-WebRequest -Uri "http://localhost:8080/mcp" -Method POST -ContentType "application/json" -Body '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'
# Test with MCP client (curl)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'MCP协议实现
服务器实现了带有HTTP端点的基本MCP协议:
可用的终端节点
- GET
/返回“Helidon MCP 服务器正在运行!” - 获取
/mcp返回“MCP端点可用” - POST(邮政/邮寄)
/mcp处理JSON-RPC请求
JSON-RPC 支持
服务器对JSON-RPC请求的响应为:
{"jsonrpc":"2.0","result":"MCP server response","id":1}示例请求
- 工具发现:
{"jsonrpc":"2.0","method":"mcp/list-tools","id":1} - Ping:
{"jsonrpc":"2.0","method":"mcp/ping","id":2}
Docker 详情
多阶段构建
Dockerfile 使用了多阶段构建过程:
- 构建阶段用途
maven:3.9.6-eclipse-temurin-21编译并打包应用程序 - 运行时阶段用途
eclipse-temurin:21-jre为了得到更小的最终图像
图像优化
- 基础镜像Eclipse Temurin JRE 21(精简版)
- 最终尺寸优化以实现最小占地面积
- 安全非root用户执行
- 端口暴露端口8080以供HTTP端点使用
测试
该项目包含一个全面的测试套件,包括单元测试、集成测试和性能测试,以确保MCP服务器正常运行。
测试套件概述
测试套件包括:
- 单元测试 (
McpServerTest.java): 测试单个组件和终端点 - 集成测试 (
McpServerIntegrationTest.java):使用 Testcontainers 测试整个系统行为 - 性能测试 (
McpServerPerformanceTest.java): 测试服务器性能及负载处理能力 - 测试工具 (
TestUtils.java): 用于测试MCP协议功能的辅助类
运行测试
测试的前提条件
- Java 21 或更高
- Maven 3.6及以上版本
- Docker (用于与Testcontainers进行集成测试)
运行所有测试
# Run all tests
mvn test
# Run tests with coverage report
mvn test jacoco:report
# Run tests with verbose output
mvn test -X运行特定的测试套件
# Run only unit tests
mvn test -Dtest=McpServerTest
# Run only integration tests
mvn test -Dtest=McpServerIntegrationTest
# Run only performance tests
mvn test -Dtest=McpServerPerformanceTest
# Run tests matching a pattern
mvn test -Dtest="*Test"测试类别
单元测试 - 快速、独立的测试:
- 服务器启动和关闭
- HTTP端点功能
- JSON-RPC 响应验证
- 错误处理(404错误、格式错误的请求)
- 端口配置
集成测试 - 全系统测试:
- 并发请求处理
- MCP协议合规性
- 处理大载荷
- 处理格式错误的JSON
- 服务器状态持久化
性能测试 - 负载和压力测试:
- 高吞吐量测试(1000+请求)
- 持续负载测试
- 内存效率测试
- 响应时间分析
测试配置
测试已配置在 pom.xml 与:
- JUnit Jupiter 5.10.1 用于单元测试
- Testcontainers 1.19.3 用于集成测试
- REST Assured 5.3.2(可译为“REST Assured 5.3.2版本”或保持原样,根据上下文判断是否需要具体翻译软件名称) 用于HTTP测试
- JaCoCo 0.8.11 用于代码覆盖率(分析)
- Maven Surefire 插件 用于单元测试
- Maven Failsafe 插件 用于集成测试
测试示例
单元测试示例
@Test
@DisplayName("Should respond to MCP POST endpoint with JSON")
void shouldRespondToMcpPostEndpoint() throws Exception {
startServer(0);
int port = server.port();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/mcp"))
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"method\":\"test\",\"id\":1}"))
.header("Content-Type", "application/json")
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
assertEquals("application/json", response.headers().firstValue("content-type").orElse(""));
assertTrue(response.body().contains("\"jsonrpc\":\"2.0\""));
}集成测试示例
@Test
@DisplayName("Should handle concurrent requests")
void shouldHandleConcurrentRequests() throws Exception {
startServer(0);
int port = server.port();
// Create multiple concurrent requests
int numberOfRequests = 10;
// ... test implementation
}性能测试示例
@Test
@DisplayName("Should handle high throughput requests")
@Disabled("Performance test - run manually when needed")
void shouldHandleHighThroughputRequests() throws Exception {
// Test with 1000+ concurrent requests
// Measure response times and success rates
}测试工具
该(或“这个”) TestUtils 该类提供了以下方面的辅助方法:
- 构建HTTP请求:
createGetRequest(),createPostRequest() - MCP协议助手:
createMcpInitRequest(),createMcpRequest() - 并发测试:
sendConcurrentRequests() - 服务器准备就绪:
waitForServer() - JSON-RPC 验证:
isValidJsonRpcResponse()
持续集成
该测试套件旨在与CI/CD流水线配合使用:
# Example GitHub Actions workflow
name: Test Suite
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
java-version: '21'
- name: Run tests
run: mvn test
- name: Generate coverage report
run: mvn jacoco:report手动测试
你也可以使用以下方法手动测试服务器:
- 基本HTTP测试:
# Test server is running
curl http://localhost:8080/
# Test MCP endpoint
curl http://localhost:8080/mcp- JSON-RPC 测试:
# PowerShell
Invoke-WebRequest -Uri "http://localhost:8080/mcp" -Method POST -ContentType "application/json" -Body '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'
# curl
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'- Docker 容器测试:
# Check container status
docker ps
# View container logs
docker logs helidon-mcp-server
# Test container endpoints
docker exec helidon-mcp-server curl http://localhost:8080/测试要求
- Docker容器化测试所需
- 网络访问互联网以下载Docker镜像
- PowerShell用于Windows的测试命令
故障排除测试
常见的测试问题
| 问题 | 症状 | 解决方案 |
|---|---|---|
| Testcontainers 失败 | Could not find a valid Docker environment | 确保 Docker Desktop 正在运行 |
| 端口冲突 | Address already in use | 在测试中使用随机端口 (startServer(0)) |
| 内存问题 | OutOfMemoryError | 增加 Maven 堆内存: export MAVEN_OPTS="-Xmx2g" |
| 超时错误 | TimeoutException | 增加测试超时时间 @Test 方法 |
测试调试命令
# Run tests with debug output
mvn test -X
# Run specific test with debug
mvn test -Dtest=McpServerTest -X
# Run tests with increased memory
export MAVEN_OPTS="-Xmx2g -XX:+UseG1GC"
mvn test
# Check test dependencies
mvn dependency:tree
# Clean and rebuild before testing
mvn clean test测试最佳实践
- 隔离每个测试都应独立进行,不依赖于其他测试
- 清理始终清理资源
@AfterEach方法 - 随机端口使用
startServer(0)避免端口冲突 - 超时为HTTP请求设置适当的超时时间
- 断言使用描述性断言消息
- 演出为性能测试标记
@Disabled用于常规跑步
测试覆盖率
生成并查看测试覆盖率报告:
# Generate coverage report
mvn test jacoco:report
# View coverage report
open target/site/jacoco/index.html
# Check coverage threshold
mvn jacoco:check测试环境设置
为了在不同环境中保持测试的一致性:
# Set up test environment variables
export TEST_CONTAINERS_RYUK_DISABLED=true
export DOCKER_HOST=tcp://localhost:2375
# Run tests in parallel (faster)
mvn test -T 4
# Run tests with specific profile
mvn test -P integration-tests发展
添加新工具
要在MCP服务器上添加一个新工具,请修改 McpServer.java 文件:
- 添加新端点 在路由配置中:
.get("/your-endpoint", (req, res) -> res.send("Your tool response"))
.post("/your-endpoint", (req, res) -> {
// Handle JSON-RPC requests for your tool
res.headers().add(HeaderNames.CONTENT_TYPE, "application/json");
res.send("{\"jsonrpc\":\"2.0\",\"result\":\"Your tool result\",\"id\":1}");
})- 实现工具逻辑 在POST处理程序中:
.post("/your-endpoint", (req, res) -> {
// Parse JSON-RPC request
// Implement your tool logic
// Return JSON-RPC response
res.headers().add(HeaderNames.CONTENT_TYPE, "application/json");
res.send("{\"jsonrpc\":\"2.0\",\"result\":\"Your tool result\",\"id\":1}");
})- 测试你的工具:
# Test GET endpoint
curl http://localhost:8080/your-endpoint
# Test POST endpoint with JSON-RPC
curl -X POST http://localhost:8080/your-endpoint \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"your-method","id":1}'构建与测试
# Clean and compile
mvn clean compile
# Package application
mvn package
# Build Docker image
docker build -t helidon-base-mcp .
# Test Docker image
docker run -d -p 8080:8080 --name helidon-mcp-server helidon-base-mcp
# Test the server
curl http://localhost:8080/
curl http://localhost:8080/mcp
# Test JSON-RPC (PowerShell)
Invoke-WebRequest -Uri "http://localhost:8080/mcp" -Method POST -ContentType "application/json" -Body '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'
# Test JSON-RPC (curl)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"mcp/list-tools","id":1}'配置
Maven 配置
该项目使用Maven,并包含以下关键配置:
- Java 版本21
- Helidon 版本4.0.7
- 包装带有用于构建胖JAR的shade插件的JAR文件
- 依赖项Helidon WebServer 用于提供HTTP服务器功能
- 主类:
io.helidon.McpServer
Docker 配置
- 基础镜像Maven 3.9.6 + Eclipse Temurin 21
- 工作目录:
/app - JAR 文件位置:
app.jar - 入口点:
java -jar app.jar - 港口8080(HTTP服务器)
故障排除
常见问题
- ClassNotFoundException(类未找到异常)确保主类名在
pom.xml匹配实际的类名 - Docker 构建失败检查Docker Desktop是否正在运行且资源充足
- Java版本问题确保使用Java 21以兼容Helidon 4.0.7
- MCP协议问题验证JSON-RPC格式和方法名称
- 端口冲突确保端口8080未被占用
调试模式
以调试模式运行:
# Local
java -Ddebug=true -jar target/helidon-base-mcp-server-1.0.0.jar
# Docker
docker run -e DEBUG=true -p 8080:8080 --name helidon-mcp-server helidon-base-mcp
# Check container logs
docker logs helidon-mcp-server
# Check container status
docker ps贡献
- 为仓库创建分支(或:克隆仓库)
- 创建一个特性分支
- 进行你的更改
- 使用 Docker 进行测试
- 提交拉取请求
关于创作者
苏伦·K - 创建者和维护者
这个MCP服务器项目由Suren K创建,旨在为使用Java和Helidon构建模型上下文协议(Model Context Protocol)服务器提供一个全面的基础。该项目展示了以下最佳实践:
- 现代Java开发使用 Java 21 配合 Helidon 4.0.7 框架
- 集装箱化基于Docker的部署,采用多阶段构建
- 卓越测试包含单元测试、集成测试和性能测试的全面测试套件
- 文档详细的README文件,包含部署指南和故障排除方法
- 代码质量适当的JavaDoc文档说明和作者署名
该项目既是一个可运行的MCP服务器实现,也是为希望了解MCP协议实现、现代Java网络服务以及容器化应用开发的开发者提供的教育资源。
联系方式与投稿
这个项目欢迎贡献和改进。请随意:
- 报告问题和错误
- 建议新功能
- 提交拉取请求
- 将其用作您自己的MCP服务器的模板
许可证
此项目作为MCP服务器开发的基础模板提供。请根据您的需求自由修改和扩展。
