Skip to main content

Command Palette

Search for a command to run...

Building an MCP Server with Spring Boot and Java

Updated
•4 min read•View as Markdown
Building an MCP Server with Spring Boot and Java
A

𝗪𝗔𝗥𝗥𝗜𝗢𝗥! Full Stack Developer | SDE Reliance Jio 🖥️ Tech Enthusiastic 💻 Man Utd 🔴 Sachin & Dravid fan! ⚾ Photography 📸 Get Hands Dirty on Keyboard!

Model Context Protocol (MCP) is an emerging protocol that standardizes the way AI assistants communicate with external tools and services. In this blog post, we'll explore how to build and use an MCP server using Spring Boot and Java, making it easy for AI assistants to access structured tools.

What is Model Context Protocol (MCP)?

MCP is a protocol that enables AI assistants to invoke tools and access information from external servers in a standardized way. It provides:

  • A consistent interface for AI assistants to call external tools

  • Structured communication between AI models and servers

  • Tool discovery and documentation capabilities

Why Spring Boot for MCP?

Spring Boot offers several advantages for building MCP servers:

  • Robust REST API capabilities

  • Dependency injection and auto-configuration

  • Easy integration with various data sources

  • Spring AI's built-in MCP server support

Prerequisites

To follow along with this tutorial, you'll need:

  • Java 21 or higher

  • Maven

  • An IDE (IntelliJ IDEA, Eclipse, or VS Code)

  • Basic knowledge of Spring Boot

Project Setup

Let's start by setting up a new Spring Boot project:

  1. Create a new Spring Boot project using Spring Initializer or your IDE

  2. Add the Spring AI MCP Server Starter dependency to your pom.xml:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mcp-server-webmvc-spring-boot-starter</artifactId>
</dependency>
  1. Create a basic project structure:
src/main/java/com/example/mcpserver/
├── config/
├── model/
├── service/
└── McpServerApplication.java

Configuring the MCP Server

First, let's configure our MCP server in application.yml:

spring:
  application:
    name: mcp-demo-server
  main:
    banner-mode: off
  ai:
    mcp:
      server:
        name: my-tool-server
        version: 0.0.1
        type: SYNC
        stdio: true
        sse-message-endpoint: /mcp/message
        resource-change-notification: true
        tool-change-notification: true
        prompt-change-notification: true

server:
  port: 8090

This configuration:

  • Names our server "my-tool-server"

  • Sets up synchronous communication mode

  • Enables Standard I/O (STDIO) for terminal-based communication

  • Exposes the /mcp/message endpoint for Server-Sent Events (SSE)

  • Sets the server port to 8090

Creating Model Classes

Let's create model classes for our domain. In this example, we'll build a user management service:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
  private int id;
  private String firstName;
  private String lastName;
  private String email;
  private String username;
  // Additional fields as needed
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UsersResponse {
  private List<User> users;
  private int total;
  private int skip;
  private int limit;
}

Implementing Service Layer with Tool Annotations

The core of our MCP server lies in the service layer where we define tools using the @Tool annotation:

@Service
@Slf4j
public class UserService {

  private final RestTemplate restTemplate;
  private final String BASE_URL = "https://dummyjson.com";

  public UserService(RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = restTemplateBuilder.build();
  }

  @Tool(name = "getAllUsers", description = "Get all users")
  public UsersResponse getAllUsers(int limit, int skip) {
    String url = BASE_URL + "/users?limit=" + limit + "&skip=" + skip;
    return restTemplate.getForObject(url, UsersResponse.class);
  }

  @Tool(name = "getUserById", description = "Get a single user by ID")
  public User getUserById(int id) {
    String url = BASE_URL + "/users/" + id;
    return restTemplate.getForObject(url, User.class);
  }

  @Tool(name = "searchUsers", description = "Search for users by query")
  public UsersResponse searchUsers(String query) {
    String url = BASE_URL + "/users/search?q=" + query;
    return restTemplate.getForObject(url, UsersResponse.class);
  }

  // Additional tool methods...
}

Each @Tool annotation defines a tool that an AI assistant can invoke. The annotation specifies:

  • A name for the tool

  • A description that helps the AI understand what the tool does

  • Parameters that can be extracted from the AI's request

Registering Tools with MCP

To make our tools available to the MCP server, we need to register them using a configuration class:

@Configuration
public class MCPConfig {

    private final UserService userService;

    @Autowired
    public MCPConfig(UserService userService) {
        this.userService = userService;
    }

    @Bean
    ToolCallbackProvider userTools() {
        return MethodToolCallbackProvider
                .builder()
                .toolObjects(userService)
                .build();
    }
}

This configuration creates a ToolCallbackProvider that registers all methods annotated with @Tool in the UserService class.

Using the MCP Server with AI Assistants

To use your MCP server with an AI assistant, you'll need to configure the MCP client. This typically involves:

  1. Creating an MCP configuration file (e.g., mcp-config.json):
{
  "mcpServers": {
    "user-tools-server": {
      "command": "java",
      "args": [
        "-Dspring.ai.mcp.server.stdio=true",
        "-Dspring.main.web-application-type=none",
        "-Dlogging.pattern.console=",
        "-jar",
        "path/to/your-mcp-server.jar"
      ]
    }
  }
}
  1. Referencing this configuration when starting your AI assistant

Code

You can find the source code here: mtwn105/mcp-server-spring-java: MCP Server using Spring Boot Java

Conclusion

Building an MCP server with Spring Boot and Java provides a powerful way to expose your services to AI assistants. By leveraging Spring's robust ecosystem and the standardized MCP protocol, you can create tools that enhance AI capabilities while maintaining control over your business logic.

The MCP approach offers several benefits:

  • Clear separation between AI and business logic

  • Standardized communication protocol

  • Tool discovery and documentation

  • Secure execution of sensitive operations

As AI assistants become more integrated into our workflows, MCP servers will play a crucial role in extending their capabilities while keeping sensitive operations secure and controlled.

Resources