# Directory Structure
```
├── .gitignore
├── pom.xml
├── README.md
└── src
└── main
├── java
│ └── com
│ └── bootcamptoprod
│ ├── config
│ │ └── McpConfiguration.java
│ ├── service
│ │ └── MongoServiceClient.java
│ └── SpringBootAiMongoMcpServerApplication.java
└── resources
└── application.properties
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 | replay_pid*
25 |
26 | .idea
27 | target
28 |
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Mongo MCP Server
2 |
3 | This project is a Mongo MCP Server built with Spring Boot AI. It is designed to interact with a local MongoDB instance and expose various database operations as callable tools. The server can be tested using any MCP client, including the Claude desktop app.
4 |
5 | For a detailed explanation on how to build an MCP server, check out our blog:
6 | **[Build MCP Servers with Spring Boot AI: A Beginner’s Guide](https://bootcamptoprod.com/build-mcp-servers-with-spring-boot-ai/)**
7 |
8 | ---
9 |
10 | ## Features
11 |
12 | - **MongoDB Integration:** Connects to a local MongoDB instance to perform various operations.
13 | - **Callable Tools:** Exposes methods using the `@Tool` annotation, making them accessible as services.
14 | - **Tool Registration:** Uses `ToolCallbackProvider` to register and expose the available functionalities.
15 | - **Testable with MCP Clients:** Easily test the server using any MCP client, including the Claude desktop app.
16 |
17 | ---
```
--------------------------------------------------------------------------------
/src/main/java/com/bootcamptoprod/SpringBootAiMongoMcpServerApplication.java:
--------------------------------------------------------------------------------
```java
1 | package com.bootcamptoprod;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringBootAiMongoMcpServerApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringBootAiMongoMcpServerApplication.class, args);
11 | }
12 |
13 | }
14 |
```
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
```
1 | spring.application.name=spring-boot-ai-mongo-mcp-server
2 |
3 | spring.main.banner-mode=off
4 | spring.main.web-application-type=none
5 | logging.file.name=./logs/spring-boot-ai-mongo-mcp-server.log
6 | logging.pattern.console=
7 |
8 | spring.ai.mcp.server.name=mongo-mcp-server
9 | spring.ai.mcp.server.version=0.0.1
10 |
11 | # MongoDB connection string
12 | mongodb.uri=mongodb://${MONGO_HOST}:${MONGO_PORT}
13 |
```
--------------------------------------------------------------------------------
/src/main/java/com/bootcamptoprod/config/McpConfiguration.java:
--------------------------------------------------------------------------------
```java
1 | package com.bootcamptoprod.config;
2 |
3 | import com.bootcamptoprod.service.MongoServiceClient;
4 | import org.springframework.ai.tool.ToolCallbackProvider;
5 | import org.springframework.ai.tool.method.MethodToolCallbackProvider;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 |
9 | @Configuration
10 | public class McpConfiguration {
11 |
12 | @Bean
13 | public ToolCallbackProvider mongoTools(MongoServiceClient mongoServiceClient) {
14 | return MethodToolCallbackProvider.builder().toolObjects(mongoServiceClient).build();
15 | }
16 | }
17 |
```
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
```
1 | <?xml version="1.0" encoding="UTF-8"?>
2 | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4 | <modelVersion>4.0.0</modelVersion>
5 | <parent>
6 | <groupId>org.springframework.boot</groupId>
7 | <artifactId>spring-boot-starter-parent</artifactId>
8 | <version>3.4.5</version>
9 | <relativePath/> <!-- lookup parent from repository -->
10 | </parent>
11 |
12 | <groupId>com.bootcamptoprod</groupId>
13 | <artifactId>spring-boot-ai-mongo-mcp-server</artifactId>
14 | <version>0.0.1-SNAPSHOT</version>
15 |
16 | <name>spring-boot-ai-mongo-mcp-server</name>
17 | <description>A Spring Boot AI-powered Model Context Protocol Server for interacting with MongoDB</description>
18 |
19 | <properties>
20 | <java.version>21</java.version>
21 | <spring-ai.version>1.0.0-M7</spring-ai.version>
22 | </properties>
23 |
24 | <dependencies>
25 | <dependency>
26 | <groupId>org.springframework.boot</groupId>
27 | <artifactId>spring-boot-starter-web</artifactId>
28 | </dependency>
29 | <dependency>
30 | <groupId>org.springframework.ai</groupId>
31 | <artifactId>spring-ai-starter-mcp-server</artifactId>
32 | </dependency>
33 | <dependency>
34 | <groupId>org.springframework.boot</groupId>
35 | <artifactId>spring-boot-starter-data-mongodb</artifactId>
36 | </dependency>
37 | </dependencies>
38 | <dependencyManagement>
39 | <dependencies>
40 | <dependency>
41 | <groupId>org.springframework.ai</groupId>
42 | <artifactId>spring-ai-bom</artifactId>
43 | <version>${spring-ai.version}</version>
44 | <type>pom</type>
45 | <scope>import</scope>
46 | </dependency>
47 | </dependencies>
48 | </dependencyManagement>
49 |
50 | <build>
51 | <plugins>
52 | <plugin>
53 | <groupId>org.springframework.boot</groupId>
54 | <artifactId>spring-boot-maven-plugin</artifactId>
55 | </plugin>
56 | </plugins>
57 | </build>
58 |
59 | </project>
60 |
```
--------------------------------------------------------------------------------
/src/main/java/com/bootcamptoprod/service/MongoServiceClient.java:
--------------------------------------------------------------------------------
```java
1 | package com.bootcamptoprod.service;
2 |
3 | import com.mongodb.client.MongoClient;
4 | import com.mongodb.client.MongoClients;
5 | import com.mongodb.client.MongoCollection;
6 | import com.mongodb.client.MongoDatabase;
7 | import org.bson.Document;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.ai.tool.annotation.Tool;
11 | import org.springframework.beans.factory.annotation.Value;
12 | import org.springframework.stereotype.Service;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | @Service
18 | public class MongoServiceClient {
19 |
20 | private static final Logger logger = LoggerFactory.getLogger(MongoServiceClient.class);
21 | private final MongoClient mongoClient;
22 |
23 | /**
24 | * Initializes the MongoDB client with the given URI.
25 | */
26 | public MongoServiceClient(@Value("${mongodb.uri}") String mongoUri) {
27 | logger.info("Initializing MongoServiceClient with URI: {}", mongoUri);
28 | this.mongoClient = MongoClients.create(mongoUri);
29 | }
30 |
31 | /**
32 | * Lists all databases in MongoDB.
33 | */
34 | @Tool(description = "List all databases in MongoDB.")
35 | public List<String> listDatabases() {
36 | logger.info("Fetching list of databases.");
37 | List<String> databaseNames = new ArrayList<>();
38 | for (Document db : mongoClient.listDatabases()) {
39 | databaseNames.add(db.getString("name"));
40 | }
41 | logger.info("Databases found: {}", databaseNames);
42 | return databaseNames;
43 | }
44 |
45 | /**
46 | * Lists all collections in the specified database.
47 | */
48 | @Tool(description = "List all collections in the specified database.")
49 | public List<String> listCollections(String dbName) {
50 | logger.info("Fetching collections for database: {}", dbName);
51 | List<String> collectionNames = new ArrayList<>();
52 | MongoDatabase database = mongoClient.getDatabase(dbName);
53 | for (String name : database.listCollectionNames()) {
54 | collectionNames.add(name);
55 | }
56 | logger.info("Collections found in {}: {}", dbName, collectionNames);
57 | return collectionNames;
58 | }
59 |
60 | /**
61 | * Executes a simple query on a collection.
62 | */
63 | @Tool(description = "Execute a simple query on a collection.")
64 | public List<Document> simpleQuery(String dbName, String collectionName, String field, Object value) {
65 | logger.info("Executing simple query on {}.{} where {} = {}", dbName, collectionName, field, value);
66 | MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
67 | List<Document> results = new ArrayList<>();
68 | collection.find(new Document(field, value)).into(results);
69 | logger.info("Query returned {} results.", results.size());
70 | return results;
71 | }
72 |
73 | /**
74 | * Executes a complex query on a collection.
75 | */
76 | @Tool(description = "Execute a complex query on a collection.")
77 | public List<Document> complexQuery(String dbName, String collectionName, String jsonQuery) {
78 | logger.info("Executing complex query on {}.{} with query: {}", dbName, collectionName, jsonQuery);
79 | MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
80 | Document query = Document.parse(jsonQuery);
81 | List<Document> results = new ArrayList<>();
82 | collection.find(query).into(results);
83 | logger.info("Complex query returned {} results.", results.size());
84 | return results;
85 | }
86 |
87 | /**
88 | * Lists all indexes for a specific collection.
89 | */
90 | @Tool(description = "List all indexes for a specific collection.")
91 | public List<Document> listIndexes(String dbName, String collectionName) {
92 | logger.info("Fetching indexes for {}.{}", dbName, collectionName);
93 | MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
94 | List<Document> indexes = new ArrayList<>();
95 | collection.listIndexes().into(indexes);
96 | logger.info("Indexes found: {}", indexes);
97 | return indexes;
98 | }
99 |
100 | /**
101 | * Creates a new collection in the specified database.
102 | */
103 | @Tool(description = "Create a new collection in the specified database.")
104 | public String createCollection(String dbName, String collectionName) {
105 | logger.info("Creating collection '{}' in database '{}'", collectionName, dbName);
106 | MongoDatabase database = mongoClient.getDatabase(dbName);
107 | database.createCollection(collectionName);
108 | logger.info("Collection '{}' created successfully.", collectionName);
109 | return "Collection '" + collectionName + "' created successfully in database '" + dbName + "'.";
110 | }
111 |
112 | /**
113 | * Inserts a document into a collection.
114 | */
115 | @Tool(description = "Insert a document into a collection.")
116 | public String insertDocument(String dbName, String collectionName, String jsonDocument) {
117 | logger.info("Inserting document into {}.{}: {}", dbName, collectionName, jsonDocument);
118 | MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
119 | Document document = Document.parse(jsonDocument);
120 | collection.insertOne(document);
121 | logger.info("Document inserted successfully into {}.{}", dbName, collectionName);
122 | return "Document inserted successfully into collection '" + collectionName + "'.";
123 | }
124 | }
125 |
```