SoFunction
Updated on 2025-04-17

Example of implementation of SpringBoot project introducing MCP

During the Spring Boot project development process, the introduction of MCP (specific functions depend on actual conditions) can add powerful functional support to the project. This article will introduce in detail how to introduce MCP into Spring Boot projects, including introducing dependencies in the pom file, configuration files, initializing MCP tools instances through configuration classes, writing business processing classes, generating MCP external interface classes, and self-testing through test classes.

1. Pom introduces dependencies

In the Spring Boot project files, we need to introduce MCP-related dependencies. Here is the specific code for introducing dependencies:

<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId></groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.3</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
    <groupId></groupId>
    <artifactId>mcp-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <>17</>
        <>32.1.2-jre</>
        <>4.4</>
        <>1.0.0-SNAPSHOT</>
    </properties>
    <modules>
        <module>mcp-demo-launcher</module>
    </modules>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId></groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <repositories>
        <!-- Spring Milestone storehouse -->
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId></groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- /artifact//spring-ai-core -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-ai-core</artifactId>
            <version>${}</version>
        </dependency>
        <!-- MCP Server support - WebMVCVersion -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
            <version>${}</version>
        </dependency>
        <!-- Spring Web -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId></groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
    </dependencies>
</project>

In the above code, focus on the bold and green part, which is the newly added MCP-related dependency. The spring-ai-starter-mcp-server-webmvc dependency provides MCP server support (WebMVC version), and also introduces related dependencies such as spring-ai-core, which will lay the foundation for the project to use MCP functionality. In actual projects, you need to adjust other parts according to the actual situation of the project, such as the project's groupId, artifactId, version number, and other dependent versions.

2. Add mcp configuration to file

In the Spring Boot project file, we need to add MCP-related configuration. The following are the specific configuration contents:

=8080
=mcp-demo
-mode=off
# MCP
=true
-change-notification=true
-change-notification=true
-change-notification=true
=mcp-demo-service
=1.0.0
=SYNC
-message-endpoint=/mcp/messages

Similarly, the bold and green part is the newly added MCP configuration. These configuration items are used to enable the MCP server, set the server name, version, type, and related notification functions. =true means that the MCP server is enabled; the server name is set; the server version is set; the server type is set to SYNC, etc. These configurations will affect how the MCP server runs in the project and its features, which you can adjust according to project requirements.

3. Implement MCP tools instance initialization through configuration classes

Next, we need to initialize the MCP tools instance through configuration classes. The following is the specific code implementation:

@Configuration
public class McpServerConfig {
	@Autowired
	private ApplicationContext applicationContext;
	@Bean
	public ToolCallbackProvider autoRegisterTools() {
		// Get all beans with @Component annotations and class names end with Facade		String[] beanNames = ();
		List<Object> facadeBeans = new ArrayList<>();
		for (String beanName : beanNames) {
			if (("Facade")) {
				((beanName));
			}
		}
		// Build all Facades at once		return ()
		.toolObjects(())
		.build();
	}
}

The above code implements the function of automatically building toolObjects based on annotation scanning. It gets all beans with @Component annotations and the class name ends with Facade, and then builds these beans as tool objects in one go. This rule is mainly used to adapt to mcp-facade-generator (see:/James-Zou/mcp-facade-generator) plugin. If you do not use this plugin, the rule can be adjusted according to project requirements. Initializing the MCP tools instance in this way can facilitate the integration of business processing classes in the project into the MCP framework to provide support for subsequent business processing.

4. Write business processing categories

The business processing class is a normal business processing interface implementation class in Java projects. In the project that introduced MCP, we need to make some specific annotations to the business processing class. Here is a sample business processing class:

@MCPService(packageName = "")
@Service
public class WeatherService {
	/**
* Get weather information by city name
* @return
*/
	public String getWeather(String cityName) {
		// Implementation
		return (
		"{"success":true,"data":{"city":"%s","temperature":"25°C","condition":"Sunny"},"message":"Success","code":"200"}",
		cityName
		);
	}
}

In this business processing class, the red @MCPService annotation is provided by the mcp-facade-generator plug-in. This annotation is used to associate the business processing class with the MCP framework, and the packageName property specifies the relevant package name. In actual projects, you can write specific business logic based on business needs. The getWeather method here is just a simple example, returning a fixed format weather information string.

5. Generate mcp external interface class

By executing the mvn compile command, the MCP external interface class can be generated. Here is an example of the generated WeatherServiceFacade class:

public class WeatherServiceFacade {
	@Autowired
	private WeatherService service;
	@Tool(description = "Get weather information by city name")
	public MCPResponse getWeather(MCPRequest request) {
		try {
			// parse request parameters			 cityName = ("cityName", );
			Object result = (cityName);
			return (result);
		}
		catch (Exception e) {
			return (());
		}
	}
}

This class is an interface class exposed by MCP. It injects the WeatherService business processing class through @Autowired. @Tool annotation describes the function of this interface, namely, obtaining weather information of the city. In the getWeather method, it first parses the request parameters, then calls the getWeather method of WeatherService to get the result, and encapsulates the result into MCPResponse to return. If an exception occurs during processing, an error message is returned. By generating such an external interface class, it is possible to easily interact with the external system and provide MCP-related services.

6. Simulate mcp client self-test through test class

Finally, we can simulate the MCP client for self-test by writing test classes. Here are two related test classes examples:

public class ClientSse {
	public static void main(String[] args) {
		var transport = new HttpClientSseClientTransport("http://localhost:19401");
		new SampleClient(transport).run();
	}
}
public class SampleClient {
	private final McpClientTransport transport;
	public SampleClient(McpClientTransport transport) {
		 = transport;
	}
	public void run() {
		try {
			var client = ().build();
			();
			();
			// List and demonstrate tools
			 toolsList = ();
			("Available Tools = " + toolsList);
			// Call the getWeather interface			 weatherResult = (new (
			"getWeather",
			("cityName", "Beijing")
			));
			// Print the complete response object			("Weather Result: {}", weatherResult);
			// Get the response content			for ( content : ()) {
				if (content instanceof ) {
					 textContent = () content;
					("Weather Info: {}", ());
				}
			}
			();
		}
		catch (Exception e) {
			("Error calling weather service", e);
		}
	}
}

In the ClientSse class, it creates an HttpClientSseClientTransport object and executes the test through the SampleClient class. In the SampleClient class, first initialize McpClient, then test the connection through the ping method, then list the available tools and call the getWeather interface to obtain weather information. After calling the interface, it prints the complete response object and extracts the weather information in the response content for printing. If an exception occurs during the test, an error message is logged. Through such a test class, we can verify whether the functions of MCP in the project are normal and ensure that the introduced MCP can meet the needs of the project.

Through the above six steps, we introduce in detail the entire process of introducing MCP into the Spring Boot project, including dependency introduction, configuration, instance initialization, business processing class writing, interface class generation and testing. Hopefully this document can help you introduce and use MCP in your Spring Boot project.

Reference Documents

- [Spring AI Documentation]
- [MCP Facade Generator]
- [MCP Springboot Server]

This is the end of this article about the implementation example of the SpringBoot project introducing MCP. For more related content on SpringBoot, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!