MCPSpringBoot

seifLahmer/MCPSpringBoot

3.2

If you are the rightful owner of MCPSpringBoot and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A robust and production-ready Model Context Protocol (MCP) server built with Spring Boot, enabling seamless integration between AI assistants and external data sources.

Tools
2
Resources
0
Prompts
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.

Java Spring Boot

šŸ“‹ 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

  1. Clone the repository

    git clone https://github.com/yourusername/mcp-spring-server.git
    cd mcp-spring-server
    
  2. Build the project

    mvn clean package
    
  3. Run the server

    java -jar target/mcp-server-0.0.1-SNAPSHOT.jar
    
  4. 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

ProtocolEndpointDescription
WebSocketws://localhost:8080/mcpReal-time MCP communication
HTTP POSThttp://localhost:8080/api/mcpJSON-RPC message handling
HTTP GEThttp://localhost:8080/api/mcp/healthHealth 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 for details.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. 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

šŸ› 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 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


⭐ Star this repository if you find it helpful!

Built with ā¤ļø using Spring Boot and the Model Context Protocol