MCPSpringBoot
MCPSpringBootは、Javaを使用したSpring Bootフレームワークに基づくプロジェクトです。主にWebアプリケーションの開発を目的としており、RESTful APIの構築やデータベースとの連携が可能です。ドキュメントやサンプルコードが不足しているため、初心者にはやや難易度が高く感じられるかもしれません。
GitHubスター
0
ユーザー評価
未評価
お気に入り
0
閲覧数
23
フォーク
0
イシュー
0
🚀 MCP Server - Spring Boot Implementation
A robust and production-ready Model Context Protocol (MCP) server built with Spring Boot, enabling seamless integration between AI assistants and external data sources.
📋 Table of Contents
🎯 About
The Model Context Protocol (MCP) is Anthropic's open standard for connecting AI assistants to external data sources and tools. This Spring Boot implementation provides a complete, enterprise-ready MCP server that supports both WebSocket and HTTP communication protocols.
Perfect for developers who want to:
- Connect AI assistants to custom business logic
- Expose internal tools and data sources to AI systems
- Build scalable, production-ready AI integrations
- Leverage the power of Spring Boot's ecosystem
✨ Features
🔧 Core Capabilities
- Dual Protocol Support: WebSocket and HTTP REST APIs
- JSON-RPC 2.0 Compliant: Full specification adherence
- Tool Management: Dynamic tool registration and execution
- Resource Handling: File and data resource management
- Error Handling: Comprehensive error responses and logging
🛠️ Built-in Tools
- Calculator: Mathematical expression evaluation
- Weather Service: City weather information (mock implementation)
- Extensible Architecture: Easy addition of custom tools
🔌 Integration Ready
- Spring Boot Ecosystem: Leverage Spring's powerful features
- Production Monitoring: Health checks and metrics endpoints
- Configurable: YAML-based configuration management
- Scalable: Built for enterprise deployment
🚀 Quick Start
Prerequisites
- Java 17+
- Maven 3.6+
Installation
Clone the repository
git clone https://github.com/yourusername/mcp-spring-server.git cd mcp-spring-server
Build the project
mvn clean package
Run the server
java -jar target/mcp-server-0.0.1-SNAPSHOT.jar
Verify installation
curl http://localhost:8080/api/mcp/health # Response: "MCP Server is running"
Docker Support (Optional)
FROM openjdk:17-jdk-slim
COPY target/mcp-server-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
docker build -t mcp-server .
docker run -p 8080:8080 mcp-server
📚 API Documentation
Endpoints
Protocol | Endpoint | Description |
---|---|---|
WebSocket | ws://localhost:8080/mcp |
Real-time MCP communication |
HTTP POST | http://localhost:8080/api/mcp |
JSON-RPC message handling |
HTTP GET | http://localhost:8080/api/mcp/health |
Health check endpoint |
Core MCP Methods
Initialize Connection
{
"jsonrpc": "2.0",
"id": "1",
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {
"name": "your-client",
"version": "1.0.0"
}
}
}
List Available Tools
{
"jsonrpc": "2.0",
"id": "2",
"method": "tools/list",
"params": {}
}
Execute Tool
{
"jsonrpc": "2.0",
"id": "3",
"method": "tools/call",
"params": {
"name": "calculator",
"arguments": {
"expression": "15 + 25"
}
}
}
List Resources
{
"jsonrpc": "2.0",
"id": "4",
"method": "resources/list",
"params": {}
}
⚙️ Configuration
Application Properties
# src/main/resources/application.yml
server:
port: 8080
mcp:
server:
name: "spring-boot-mcp-server"
version: "1.0.0"
logging:
level:
com.example.mcpserver: DEBUG
Custom Tool Configuration
Add your custom tools by extending the McpService
:
@Service
public class CustomMcpService extends McpService {
@Override
protected void initializeTools() {
super.initializeTools();
// Add your custom tool
Map<String, Object> customSchema = Map.of(
"type", "object",
"properties", Map.of(
"input", Map.of("type", "string")
)
);
tools.put("custom-tool", new Tool(
"custom-tool",
"Your custom tool description",
customSchema
));
}
}
💡 Examples
WebSocket Client (JavaScript)
const ws = new WebSocket('ws://localhost:8080/mcp');
ws.onopen = function() {
// Initialize connection
ws.send(JSON.stringify({
jsonrpc: "2.0",
id: "1",
method: "initialize",
params: {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: { name: "js-client", version: "1.0" }
}
}));
};
ws.onmessage = function(event) {
const response = JSON.parse(event.data);
console.log('Response:', response);
};
HTTP Client (Python)
import requests
import json
url = "http://localhost:8080/api/mcp"
# Calculate expression
payload = {
"jsonrpc": "2.0",
"id": "1",
"method": "tools/call",
"params": {
"name": "calculator",
"arguments": {"expression": "100 * 2.5"}
}
}
response = requests.post(url, json=payload)
print(response.json())
cURL Examples
# List available tools
curl -X POST http://localhost:8080/api/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": "1",
"method": "tools/list",
"params": {}
}'
# Execute calculator tool
curl -X POST http://localhost:8080/api/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": "2",
"method": "tools/call",
"params": {
"name": "calculator",
"arguments": {"expression": "42 + 8"}
}
}'
🏗️ Architecture
├── src/main/java/com/example/mcpserver/
│ ├── McpServerApplication.java # Main application class
│ ├── config/
│ │ └── WebSocketConfig.java # WebSocket configuration
│ ├── controller/
│ │ └── McpController.java # REST API endpoints
│ ├── handler/
│ │ └── McpWebSocketHandler.java # WebSocket message handling
│ ├── model/
│ │ ├── McpMessage.java # Core message structure
│ │ ├── Tool.java # Tool definition
│ │ └── Resource.java # Resource definition
│ └── service/
│ └── McpService.java # Business logic
└── src/main/resources/
└── application.yml # Configuration
🔧 Development
Running in Development Mode
mvn spring-boot:run
Running Tests
mvn test
Building for Production
mvn clean package -Pprod
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
Development Setup
# Clone your fork
git clone https://github.com/your-username/mcp-spring-server.git
# Add upstream remote
git remote add upstream https://github.com/original-owner/mcp-spring-server.git
# Create feature branch
git checkout -b feature/your-feature-name
# Make your changes and commit
git commit -am "Add your feature"
# Push to your fork
git push origin feature/your-feature-name
📖 Documentation
- Model Context Protocol Specification
- Spring Boot Documentation
- WebSocket API Reference
- Custom Tool Development Guide
🐛 Troubleshooting
Common Issues
Connection refused error
# Check if server is running
curl http://localhost:8080/api/mcp/health
WebSocket connection fails
- Verify firewall settings
- Check CORS configuration for web clients
- Ensure WebSocket support in your client
JSON parsing errors
- Validate JSON-RPC 2.0 message format
- Check required fields:
jsonrpc
,id
,method
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Anthropic for the Model Context Protocol specification
- Spring Boot team for the amazing framework
- Contributors and the open-source community
📞 Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Wiki
⭐ Star this repository if you find it helpful!
Built with ❤️ using Spring Boot and the Model Context Protocol