This technical blog post demonstrates how to create a Model Context Protocol (MCP) server using Spring Boot that interacts with a MongoDB database. We will also build a Spring Boot MCP client to consume the services exposed by this server.
Setting up MongoDB
Before we begin, let's populate our local MongoDB instance with some initial data. Create a collection named siddhucollection
and insert the data as shown in

Creating the MCP Server
Next, we will build a Spring Boot application that will function as our MCP server.
1. pom.xml
This file defines the project dependencies, including Spring Boot Web Starter, Spring AI MCP Server Starter, and Spring Boot Data MongoDB.
XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.4.4</version> <relativePath/> </parent> <groupId>com.bootcamptoprod</groupId> <artifactId>spring-boot-ai-mongo-mcp-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-ai-mongo-mcp-server</name> <description>A Spring Boot AI-powered Model Context Protocol Server for interacting with MongoDB</description> <properties> <java.version>17</java.version> <spring-ai.version>1.0.0-M6</spring-ai.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>${spring-ai.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
2. SpringBootAiMongoMcpServerApplication.java
This is the main entry point for our Spring Boot application.
Java
package com.siddhu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootAiMongoMcpServerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootAiMongoMcpServerApplication.class, args); } }
3. McpServerConfiguration.java
This configuration class defines a ToolCallbackProvider
bean, which registers our MongoDB service as a tool accessible via MCP.
Java
package com.siddhu.config; import org.springframework.ai.tool.ToolCallbackProvider; import org.springframework.ai.tool.method.MethodToolCallbackProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.siddhu.service.MCPServerMongoServiceClient; @Configuration public class McpServerConfiguration { @Bean public ToolCallbackProvider mongoTools(MCPServerMongoServiceClient mongoServiceClient) { return MethodToolCallbackProvider.builder().toolObjects(mongoServiceClient).build(); } }
4. MCPServerMongoServiceClient.java
This service class contains the methods that interact with MongoDB. Each method annotated with @Tool
will be exposed as a function callable through the MCP.
Java
package com.siddhu.service; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.tool.annotation.Tool; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class MCPServerMongoServiceClient { private static final Logger logger = LoggerFactory.getLogger(MCPServerMongoServiceClient.class); private final MongoClient mongoClient; /** * Initializes the MongoDB client with the given URI. */ public MCPServerMongoServiceClient(@Value("${mongodb.uri}") String mongoUri) { logger.info("Initializing MCPServerMongoServiceClient with URI: {}", mongoUri); this.mongoClient = MongoClients.create(mongoUri); } /** * Lists all databases in MongoDB. */ @Tool(description = "Provide he list of all databases in MongoDB.") public List<String> listDatabases() { logger.info("Fetching list of databases."); List<String> databaseNames = new ArrayList<>(); for (Document db : mongoClient.listDatabases()) { databaseNames.add(db.getString("name")); } logger.info("Databases found: {}", databaseNames); return databaseNames; } /** * Lists all collections in the specified database. */ @Tool(description = "Provide the list of all collections in the specified database.") public List<String> listCollections(String dbName) { logger.info("Fetching collections for database: {}", dbName); List<String> collectionNames = new ArrayList<>(); MongoDatabase database = mongoClient.getDatabase(dbName); for (String name : database.listCollectionNames()) { collectionNames.add(name); } logger.info("Collections found in {}: {}", dbName, collectionNames); return collectionNames; } /** * Lists all indexes for a specific collection. */ @Tool(description = "Provie the list of all the indexes for a specific collection.") public List<Document> listIndexes(String dbName, String collectionName) { logger.info("Fetching indexes for {}.{}", dbName, collectionName); MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collectionName); List<Document> indexes = new ArrayList<>(); collection.listIndexes().into(indexes); logger.info("Indexes found: {}", indexes); return indexes; } /** * Creates a new collection in the specified database. */ @Tool(description = "Create a new collection in the specified database.") public String createCollection(String dbName, String collectionName) { logger.info("Creating collection '{}' in database '{}'", collectionName, dbName); MongoDatabase database = mongoClient.getDatabase(dbName); database.createCollection(collectionName); logger.info("Collection '{}' created successfully.", collectionName); return "Collection '" + collectionName + "' created successfully in database '" + dbName + "'."; } }
5. application.properties
This file configures the Spring Boot application, including the MongoDB connection URI and MCP server details. Replace ${MONGO_HOST}
and ${MONGO_PORT}
with your MongoDB instance's host and port.
Properties
spring.application.name=spring-boot-ai-mongo-mcp-server spring.main.banner-mode=off spring.main.web-application-type=none logging.file.name=./logs/spring-boot-ai-mongo-mcp-server.log logging.pattern.console= spring.ai.mcp.server.name=mongo-mcp-server spring.ai.mcp.server.version=0.0.1 # MongoDB connection string mongodb.uri=mongodb://${MONGO_HOST}:${MONGO_PORT}
Now, build the server application and create the JAR file using the command shown in

Creating the MCP Client
Next, we will build a Spring Boot application that acts as an MCP client to interact with our MongoDB MCP server.
1. pom.xml
This file defines the dependencies for the client application, including Spring Boot Web Starter, Spring AI OpenAI Starter (or Ollama), and Spring AI MCP Client Starter.
XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.4.4</version> <relativePath/> </parent> <groupId>com.bootcamptoprod</groupId> <artifactId>spring-boot-ai-mcp-client</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-ai-mcp-client</name> <description>A simple Spring Boot application for interacting with MCP servers using Spring AI Chat Client and Rest Controller</description> <properties> <java.version>17</java.version> <spring-ai.version>1.0.0-M6</spring-ai.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-ollama-spring-boot-starter</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>${spring-ai.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. SpringBootAiMcpClientApplication.java
This is the main entry point for our MCP client application.
Java
package com.siddhu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootAiMcpClientApplication { public static void main(String[] args) { SpringApplication.run(SpringBootAiMcpClientApplication.class, args); } }
3. MCPClientChatClientConfig.java
This configuration class creates a ChatClient
bean, which will be used to interact with the MCP server. It configures the client to use the available tools.
Java
package com.siddhu.config; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.tool.ToolCallbackProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MCPClientChatClientConfig { @Bean public ChatClient chatClient(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools) { return chatClientBuilder.defaultTools(tools).build(); } }
4. ChatController.java
This REST controller exposes an endpoint to send user input to the ChatClient, which will then interact with the MCP server.
Java
package com.siddhu.controller; import org.springframework.ai.chat.client.ChatClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/chat") public class ChatController { private final ChatClient chatClient; @Autowired public ChatController(ChatClient chatClient) { this.chatClient = chatClient; } @PostMapping("/ask") public String chat(@RequestBody String userInput) { return chatClient.prompt(userInput).call().content(); } }
5. application.yml
(for OpenAI)
This configuration file sets up the logging level, Spring application name, OpenAI API key, base URL, model, and the MCP client configuration to connect to our MongoDB MCP server. Replace <your_openrouter_api_key>
with your actual API key.
YAML
logging: level: io: modelcontextprotocol: client: DEBUG spec: DEBUG spring: application: name: spring-boot-ai-mcp-client ai: ollama: base-url: http://localhost:11434 # Default Ollama API base URL chat: options: model: qwen2.5-coder:1.5b # openai: # api-key: "your_openai_api_key" # base-url: https://openrouter.ai/api # chat: # options: # model: google/gemini-2.0-flash-exp:free mcp: client: #stdio: # servers-configuration: classpath:mcp-servers-config.json stdio: connections: mongo-mcp-server: command: java args: - "-jar" - "C:\\STS-Workspace\\spring-boot-ai-mongo-mcp-server\\target\\spring-boot-ai-mongo-mcp-server-0.0.1-SNAPSHOT.jar" env: "MONGO_HOST": "localhost" "MONGO_PORT": "27017"








Also add this in pom.xml
1 2 3 4 5 | <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-ollama-spring-boot-starter</artifactId> </dependency> <dependency> |