×
Community Blog Java Development with MCP: From Claude Automation to Spring AI Alibaba Ecosystem Integration

Java Development with MCP: From Claude Automation to Spring AI Alibaba Ecosystem Integration

By Xia Dong, Spring AI Alibaba Committer This article explains how Java developers can leverage the Spring AI Alibaba framework to work with MCP, combining principles and examples.

By Xia Dong, Spring AI Alibaba Committer

This article explains how Java developers can leverage the Spring AI Alibaba framework to work with MCP, combining principles and examples.

Abstract

This article includes the following contents:

1.  Some Basics of MCP and Quick Experience (familiar readers can skip this section)

2.  How to publish your developed Spring application as an MCP Server and verify the use of Claude or Spring applications as clients to connect to your published Java MCP Server.

● Publish an MCP Server in stdio mode

● Publish an MCP Server in SSE mode

● Develop another Spring application as an MCP Client to call MCP Server services

● Use the Claude desktop application to connect to our Java MCP Server

3.  How to use your developed Spring application to call MCP Server, including calling your published Java MCP Server and other general MCP Servers available in the market.

● Configure and call an MCP Server in stdio mode

● Configure and call an MCP Server in SSE mode

4.  How to use MCP services in the Spring AI Alibaba Open Manus implementation.

5.  Regarding how existing applications can be called as MCP services by agents without changing a single line of code, please look forward to subsequent articles for solutions.

Introduction to Model Context Protocol (MCP)

In November 2024, Anthropic introduced an interesting new concept - Model Context Protocol (MCP). Simply put, it provides a standardized "bridge" between AI and various tool data, alleviating developers from worries about integration issues.

Large model applications can utilize MCP services shared by others to accomplish various tasks. You can obtain MCP services from the following sources:

● awesome-mcp-servers

● mcp.so

MCP protocol is widely applicable in practical scenarios. Here are some common use cases:

● Use Baidu or GaoDe Map to analyze travel time calculations

● Use Puppeteer for automated web operations

● Use Github/Gitlab to allow large models to take over code repositories

● Use database components to operate on MySQL, ES, Redis, etc.

● Use search components to expand data search capabilities of large models.

1.1 Experience MCP in Claude Desktop

Next, we will rapidly connect to GitHub services using Claude (apply for token in advance) and edit the configuration file for Claude Desktop:

macOS:

~/Library/Application Support/Claude/claude_desktop_config.json

Windows:

%APPDATA%\Claude\claude_desktop_config.json

Add the following content, making sure to replace <YOUR_TOKEN> with your own applied token:

{  "mcpServers": {    "github": {      "command": "npx",      "args": [        "-y",        "@modelcontextprotocol/server-github"      ],      "env": {        "GITHUB_PERSONAL_ACCESS_TOKEN": "`"      }    }  }

After restarting Claude, you should see that the MCP corresponding tools are already loaded:

1

After clicking, you can see the specific tool content:

2

At this point, we can enjoy the ability to operate on repositories provided by GitHub services

we can see that by creating a repository named test-mcp, Claude's large model autonomously determines that it needs to use the create_repository capability provided by MCP, thus completing the creation of the repository. Next, we open GitHub and indeed find the repository we created.

3

This way, the large model can leverage MCP to connect with a variety of capabilities and complete more complex tasks.

1.2 MCP Architecture

MCP mainly consists of MCP services and MCP clients:

Client: Generally refers to large model applications, such as Claude, AI applications developed using Spring AI Alibaba, Langchain, etc.

Server: Services and tools that connect various data sources.

The overall architecture is as follows:

4

The overall workflow is as follows: the AI application integrates the MCP client, sending requests to the MCP server via the MCP protocol. The MCP server can connect to local/remote data sources or access other services via APIs, retrieving data to return to the AI application for use.

Using MCP Server in Spring AI

2.1 Introduction to Spring AI MCP

Spring AI MCP provides Java and Spring framework integration for the Model Context Protocol. It enables Spring AI applications to interact with different data sources and tools through standardized interfaces, supporting both synchronous and asynchronous communication modes. The overall architecture is as follows:

5

Spring AI MCP adopts a modular architecture, including the following components:

Spring AI Applications: Generative AI applications built using the Spring AI framework that want to access data through MCP.

Spring MCP Client: The Spring AI implementation of the MCP protocol, maintaining a 1:1 connection with the server.

With Spring AI MCP, you can quickly set up MCP client and server applications.

2.2 Quickly Building MCP Server with Spring AI MCP

Spring AI provides two mechanisms for quickly building MCP Server, through which developers can rapidly expose their capabilities to AI applications. These two mechanisms are:

Inter-process communication transmission based on stdio, running in an independent process locally in the AI application, suitable for relatively lightweight tools.

Remote service access based on SSE (Server-Sent Events), requiring the service to be deployed separately, with clients accessing remotely through the server's URL, suitable for relatively heavyweight tools.

Next, we will introduce the implementation of these two approaches, and sample code can be obtained from the following link: https://github.com/springaialibaba/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-mcp-example/starter-example/server

2.2.1 Implementing MCP Server Based on stdio

The stdio-based MCP server communicates with clients via standard input-output streams, suitable for scenarios where it is started and managed as a subprocess by the client.

Adding Dependencies

First, add the Spring AI MCP Server Starter dependency in your project:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
</dependency>

Configuring MCP Server

Configure the MCP Server in application.yml. This time, we are implementing a weather service:

spring:
  main:
    web-application-type: none  # Must disable web application type
    banner-mode: off            # Disable banner
  ai:
    mcp:
      server:
        stdio: true              # Enable stdio mode
        name: my-weather-server   # Server name
        version: 0.0.1           # Server version

Implementing MCP Tools

Use the @Tool annotation to mark methods so they can be discovered and called by the MCP client, and use the @ToolParameter annotation for the specific parameters of the tool:

@Service
public class OpenMeteoService {
    private final WebClient webClient;

    public OpenMeteoService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder
                .baseUrl("https://api.open-meteo.com/v1")
                .build();
    }

    @Tool(description = "Get weather forecast by latitude and longitude")
    public String getWeatherForecastByLocation(
            @ToolParameter(description = "Latitude, e.g., 39.9042") String latitude,
            @ToolParameter(description = "Longitude, e.g., 116.4074") String longitude) {
        try {
            String response = webClient.get()
                .uri(uriBuilder -> uriBuilder
                    .path("/forecast")
                    .queryParam("latitude", latitude)
                    .queryParam("longitude", longitude)
                    .queryParam("current", "temperature_2m,wind_speed_10m")
                    .queryParam("timezone", "auto")
                    .build())
                .retrieve()
                .bodyToMono(String.class)
                .block();

            // Parse the response and return formatted weather information
            return "Weather information for location (latitude: " + latitude + ", longitude: " + longitude + "):\n" + response;
        } catch (Exception e) {
            return "Failed to retrieve weather information: " + e.getMessage();
        }
    }

    @Tool(description = "Get air quality information by latitude and longitude")
    public String getAirQuality(
            @ToolParameter(description = "Latitude, e.g., 39.9042") String latitude,
            @ToolParameter(description = "Longitude, e.g., 116.4074") String longitude) {
        // Simulated data; in a real application, call the actual API
        return "Air quality for location (latitude: " + latitude + ", longitude: " + longitude + "):\n" +
               "- PM2.5: 15 μg/m³ (Good)\n" +
               "- PM10: 28 μg/m³ (Fair)\n" +
               "- Air Quality Index (AQI): 42 (Good)\n" +
               "- Main Pollutant: None";
    }
}

In this example, we are using OpenMeteo, which is an open-source weather API providing free access for non-commercial use without requiring an API key.

Registering MCP Tools

Register the tools in the application entry class:

@SpringBootApplication
public class McpServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }

    @Bean
    public ToolCallbackProvider weatherTools(OpenMeteoService openMeteoService) {
        return MethodToolCallbackProvider.builder()
                .toolObjects(openMeteoService)
                .build();
    }
}

Running the Server

Execute the following command in the console to compile and package the application:

Terminal window

mvn clean package -DskipTests

2.2.2 Implementing MCP Server Based on SSE

The SSE-based MCP server communicates with clients via the HTTP protocol and is suitable for scenarios where the MCP server is deployed as a standalone service, allowing multiple clients to access it remotely. The specific approach is very similar to stdio.

Adding Dependencies

First, add the Spring AI MCP starter dependency in your project:

<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-mcp-server-webflux-spring-boot-starter</artifactId>
</dependency>

Configuring MCP Server

Configure the MCP server in application.yml:

server:
  port: 8080  # Server port configuration
spring:
  ai:
    mcp:
      server:
        name: my-weather-server    # MCP Server name
        version: 0.0.1            # Server version number

Implementing MCP Tools

The implementation is identical to that based on stdio:

@Service
public class OpenMeteoService {
    private final WebClient webClient;

    public OpenMeteoService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder
                .baseUrl("https://api.open-meteo.com/v1")
                .build();
    }

    @Tool(description = "Get weather forecast by latitude and longitude")
    public String getWeatherForecastByLocation(
            @ToolParameter(description = "Latitude, e.g., 39.9042") String latitude,
            @ToolParameter(description = "Longitude, e.g., 116.4074") String longitude) {
        try {
            String response = webClient.get()
                .uri(uriBuilder -> uriBuilder
                    .path("/forecast")
                    .queryParam("latitude", latitude)
                    .queryParam("longitude", longitude)
                    .queryParam("current", "temperature_2m,wind_speed_10m")
                    .queryParam("timezone", "auto")
                    .build())
                .retrieve()
                .bodyToMono(String.class)
                .block();

            // Parse the response and return formatted weather information
            return "Weather information for location (latitude: " + latitude + ", longitude: " + longitude + "):\n" + response;
        } catch (Exception e) {
            return "Failed to retrieve weather information: " + e.getMessage();
        }
    }

    @Tool(description = "Get air quality information by latitude and longitude")
    public String getAirQuality(
            @ToolParameter(description = "Latitude, e.g., 39.9042") String latitude,
            @ToolParameter(description = "Longitude, e.g., 116.4074") String longitude) {
        // Simulated data; in a real application, call the actual API
        return "Air quality for location (latitude: " + latitude + ", longitude: " + longitude + "):\n" +
               "- PM2.5: 15 μg/m³ (Good)\n" +
               "- PM10: 28 μg/m³ (Fair)\n" +
               "- Air Quality Index (AQI): 42 (Good)\n" +
               "- Main Pollutant: None";
    }
}

Registering MCP Tools

Register the tools in the application entry class:

@SpringBootApplication
public class McpServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }

    @Bean
    public ToolCallbackProvider weatherTools(OpenMeteoService openMeteoService) {
        return MethodToolCallbackProvider.builder()
                .toolObjects(openMeteoService)
                .build();
    }

    @Bean
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }
}

Running the Server

Execute the command in the console to run the server:

Terminal window

mvn spring-boot:run

The server will start at http://localhost:8080.

2.3 Testing MCP Service in Claude

In the previous section, we completed the writing of the MCP service. But do these services operate correctly? We can test them in Claude Desktop.

Modify the configuration file to add the weather configuration, making sure to use the full path for the jar file:

{  
  "mcpServers": {  
    "github": {  
      "command": "npx",  
      "args": [  
        "-y",  
        "@modelcontextprotocol/server-github"  
      ],  
      "env": {  
        "GITHUB_PERSONAL_ACCESS_TOKEN": "your token"  
      }  
    },  
    "weather": {  
      "command": "java",  
      "args": [  
        "-Dspring.ai.mcp.server.stdio=true",  
        "-Dspring.main.web-application-type=none",  
        "-Dlogging.pattern.console=",  
        "-jar",  
        "<replace with full path to jar after stdio compilation>"  
      ],  
      "env": {}  
    }  
  }  
}

After restarting Claude, you will see that the two tools we wrote have been loaded:

Input the prompt to query the air quality in Beijing today:

6

Claude triggered the weather service we wrote, displaying the complete data:

According to the data obtained, today (March 31, 2025), the air quality in Beijing is as follows:

● European Air Quality Index: 78 (Fair)

● U.S. Air Quality Index: 117 (Unhealthy for Sensitive Groups)

● PM10 Level: 26.0 μg/m³

● PM2.5 Level: 9.2 μg/m³

● Carbon Monoxide (CO): 313.1 μg/m³

● Nitrogen Dioxide (NO2): 21.6 μg/m³

● Sulfur Dioxide (SO2): 9.1 μg/m³

● Ozone (O3): 32.2 μg/m³

Data updated on: March 31, 2025, at 17:30

Please note that sensitive groups (such as the elderly, children, pregnant women, and those with respiratory or heart conditions) should take precautions when going outside today.

We used the stdio method in Claude Desktop to access our own MCP service, but unfortunately, Claude Desktop does not support direct access to MCP services via the SSE mode; it must use mcp-proxy as an intermediary. Therefore, we will not demonstrate connecting Claude Desktop to the SSE-mode MCP service here.

Integrating MCP Client in Spring AI Alibaba

For the client side, Spring AI also provides mechanisms for quickly integrating MCP Server via both stdio and SSE, corresponding to the stdio and SSE modes of the MCP Server. The reference code is as follows: https://github.com/springaialibaba/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-mcp-example/starter-example/client

3.1 Implementing MCP Client Based on stdio

The stdio-based implementation is the most common MCP client implementation method. It communicates with the MCP server via standard input-output streams. This method is suitable for locally deployed MCP servers using stdio and allows the MCP server process to be started directly on the same machine.

Adding Dependencies

First, add the Spring AI MCP Server Starter dependency in your project:

<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
</dependency>

Configuring MCP Server

Configure the MCP server in application.yml:

spring:
  main:
    web-application-type: none  # Must disable web application type
    banner-mode: off            # Disable banner
  ai:
    mcp:
      server:
        stdio: true              # Enable stdio mode
        name: my-weather-server   # Server name
        version: 0.0.1           # Server version

This configuration file sets the basic configuration of the MCP client, including the API key and the location of the server configuration file. You can choose to directly define the server configuration in the configuration file, but it is recommended to manage MCP configurations using JSON files. Create the mcp-servers-config.json configuration file in the resources directory:

{
    "mcpServers": {
        // Define the MCP server named "weather"
        "weather": {
            // Specify the command to run as java
            "command": "java",
            // Define the startup arguments
            "args": [
                "-Dspring.ai.mcp.server.stdio=true",
                "-Dspring.main.web-application-type=none",
                "-jar",
                "<replace with the full path to the jar file compiled with stdio>"
            ],
            // Environment variable configuration (optional)
            "env": {}
        }
    }
}

This JSON configuration file defines the detailed configuration of the MCP server, including how to start the server process, the necessary arguments to be passed, and the environment variable settings. Make sure that the referenced jar package must be the full path.

Write a startup class for testing:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        // Start Spring Boot application
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public CommandLineRunner predefinedQuestions(
            ChatClient.Builder chatClientBuilder,
            ToolCallbackProvider tools,
            ConfigurableApplicationContext context) {
        return args -> {
            // Build ChatClient and inject MCP tools
            var chatClient = chatClientBuilder
                    .defaultTools(tools)
                    .build();
            
            // Define user input
            String userInput = "How is the weather in Beijing?";
            // Print the question
            System.out.println("\n>>> QUESTION: " + userInput);
            // Call LLM and print the response
            System.out.println("\n>>> ASSISTANT: " +
                chatClient.prompt(userInput).call().content());
            
            // Close application context
            context.close();
        };
    }
}

This code demonstrates how to use the MCP client in a Spring Boot application. It creates a command line runner, builds a ChatClient, and injects MCP tools, then uses this client to send queries and get responses. Using MCP tools in Spring AI Alibaba is very simple; you just need to pass the ToolCallbackProvider to the defaultTools method of chatClientBuilder for automatic adaptation.

Test the program by starting it with the command:

Terminal window

mvn spring-boot:run

After starting, the result displayed shows that the MCP server we developed was called, returning data:

>>> QUESTION: How is the weather in Beijing?
2025-03-31T17:56:17.931+08:00 DEBUG 23455 --- [mcp] [pool-1-thread-1] io.modelcontextprotocol.spec.McpSchema: Received JSON message: 
{"jsonrpc":"2.0","id":"60209de5-3","result":{"content":[{"type":"text","text":"\"Current Weather:\\nTemperature: 18.6°C (Feels like: 15.1°C)\\nWeather: Cloudy\\nWind: South (4.7 km/h)\\nHumidity: 18%\\nPrecipitation: 0.0 mm\\n\\nFuture Weather Forecast:\\n2025-03-31 (Monday):\\nTemperature: 2.4°C ~ 19.5°C\\nWeather: Cloudy\\nWind: South (8.4 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-01 (Tuesday):\\nTemperature: 7.6°C ~ 20.6°C\\nWeather: Cloudy\\nWind: Northwest (19.1 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-02 (Wednesday):\\nTemperature: 6.9°C ~ 18.4°C\\nWeather: Sunny\\nWind: Northwest (12.8 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-03 (Thursday):\\nTemperature: 7.0°C ~ 19.8°C\\nWeather: Cloudy\\nWind: South (16.3 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-04 (Friday):\\nTemperature: 7.5°C ~ 21.6°C\\nWeather: Cloudy\\nWind: Northwest (19.6 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-05 (Saturday):\\nTemperature: 5.6°C ~ 20.7°C\\nWeather: Cloudy\\nWind: West (16.5 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-06 (Sunday):\\nTemperature: 8.4°C ~ 22.3°C\\nWeather: Sunny\\nWind: South (9.4 km/h)\\nPrecipitation: 0.0 mm\\n\\n\""}],"isError":false}}
2025-03-31T17:56:17.932+08:00 DEBUG 23455 --- [mcp] [pool-1-thread-1] i.m.spec.McpClientSession: Received Response: JSONRPCResponse[jsonrpc=2.0, id=60209de5-3, result={content=[{type=text, text="Current Weather:\\nTemperature: 18.6°C (Feels like: 15.1°C)\\nWeather: Cloudy\\nWind: South (4.7 km/h)\\nHumidity: 18%\\nPrecipitation: 0.0 mm\\n\\nFuture Weather Forecast:\\n2025-03-31 (Monday):\\nTemperature: 2.4°C ~ 19.5°C\\nWeather: Cloudy\\nWind: South (8.4 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-01 (Tuesday):\\nTemperature: 7.6°C ~ 20.6°C\\nWeather: Cloudy\\nWind: Northwest (19.1 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-02 (Wednesday):\\nTemperature: 6.9°C ~ 18.4°C\\nWeather: Sunny\\nWind: Northwest (12.8 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-03 (Thursday):\\nTemperature: 7.0°C ~ 19.8°C\\nWeather: Cloudy\\nWind: South (16.3 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-04 (Friday):\\nTemperature: 7.5°C ~ 21.6°C\\nWeather: Cloudy\\nWind: Northwest (19.6 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-05 (Saturday):\\nTemperature: 5.6°C ~ 20.7°C\\nWeather: Cloudy\\nWind: West (16.5 km/h)\\nPrecipitation: 0.0 mm\\n\\n2025-04-06 (Sunday):\\nTemperature: 8.4°C ~ 22.3°C\\nWeather: Sunny\\nWind: South (9.4 km/h)\\nPrecipitation: 0.0 mm\\n\\n"}], isError=false}, error=null]

3.2 SSE-Based MCP Client Implementation

In addition to the stdio-based implementation, Spring AI Alibaba also provides an SSE-based MCP client implementation. This approach is suitable for remotely deployed MCP servers and allows communication with the MCP server via the HTTP protocol.

Adding Dependencies

First, add the Spring AI MCP starter dependency to your project:

<dependency>  
    <groupId>org.springframework.ai</groupId>  
    <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>  
    <version>${spring-ai.version}</version>  
</dependency>  

Configuring the MCP Server

In the application.yml, configure the MCP server. Here, you need to specify the SSE service address, which we previously started on port 8080:

spring:   
  ai:    
    dashscope:      
      api-key: ${DASH_SCOPE_API_KEY}    
    mcp:      
      client:        
        sse:          
          connections:            
            server1:              
              url: http://localhost:8080  # Service Address

Using the MCP Client

The usage is the same as the stdio-based implementation; just inject the ToolCallbackProvider and ChatClient.Builder:

@SpringBootApplication  
public class Application {  
    public static void main(String[] args) {        
        SpringApplication.run(Application.class, args);    
    }  

    @Bean    
    public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder,                                                 ToolCallbackProvider tools,                                                 ConfigurableApplicationContext context) {        
        return args -> {            
            // Build ChatClient and inject MCP tools            
            var chatClient = chatClientBuilder                    
                .defaultTools(tools)                    
                .build();  

            // Interact with LLM using ChatClient            
            String userInput = "北京的天气如何?";            
            System.out.println("\n>>> QUESTION: " + userInput);            
            System.out.println("\n>>> ASSISTANT: " + chatClient.prompt(userInput).call().content());  
            context.close();        
        };    
    }}  

Start the program for testing via command:

Terminal window

mvn spring-boot:run

After starting, there will be an error:

Caused by: java.lang.IllegalStateException: Multiple tools with the same name (spring-ai-mcp-client-getWeatherForecastByLocation, spring-ai-mcp-client-getAirQuality)        at org.springframework.ai.mcp.SyncMcpToolCallbackProvider.validateToolCallbacks(SyncMcpToolCallbackProvider.java:126) ~[spring-ai-mcp-1.0.0-20250325.064812-147.jar:1.0.0-SNAPSHOT]        at org.springframework.ai.mcp.SyncMcpToolCallbackProvider.getToolCallbacks(SyncMcpToolCallbackProvider.java:110) ~[spring-ai-mcp-1.0.0-20250325.064812-147.jar:1.0.0-SNAPSHOT]        at org.springframework.ai.autoconfigure.mcp.client.McpClientAutoConfiguration.toolCallbacksDeprecated(McpClientAutoConfiguration.java:196) ~[spring-ai-mcp-client-spring-boot-autoconfigure-1.0.0-M6.jar:1.0.0-M6]        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]        at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.lambda$instantiate$0(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.2.0.jar:6.2.0]        ... 23 common frames omitted

From the log analysis, it is caused by registering the same service names: spring-ai-mcp-client-getWeatherForecastByLocation and spring-ai-mcp-client-getAirQuality. However, from the code analysis, we see that these two services are only registered once, so why is there an error?

This is actually a bug in Spring AI. Spring AI provides two auto-configuration classes to generate client tools for handling Tool acquisition in the MCP service, namely SseHttpClientTransportAutoConfiguration and SseWebFluxTransportAutoConfiguration. These two auto-configuration classes offer synchronous and asynchronous modes and should be mutually exclusive, but there is an issue in how Spring AI handles exclusivity, causing both auto-configuration classes to load.

Loading of SseWebFluxTransportAutoConfiguration:

7

Loading of SseHttpClientTransportAutoConfiguration:

8

Once both auto-configuration classes are loaded, they will request Tools from the MCP service that provides SSE services, which leads to the same Tool being requested twice, causing duplication. The solution is straightforward: exclude the SseHttpClientTransportAutoConfiguration implementation in the startup class.

@SpringBootApplication(exclude = {        
    org.springframework.ai.autoconfigure.mcp.client.SseHttpClientTransportAutoConfiguration.class})  
public class Application {  
    ...  
}  

Start the program again using the command for testing:

Terminal window

mvn spring-boot:run

This time, it produced the correct output:

Temperature: 18.5°C (Feels like: 14.9°C)
Weather: Partly Cloudy
Wind: South (4.7 km/h)
Humidity: 18%
Precipitation: 0.0 mm

Experience MCP in Spring AI Alibaba's Open Manus

Spring AI Alibaba offers an implementation of Open Manus.

During the execution phase, various Tools are called to complete tasks. If we can enhance the capabilities of Tools using MCP, it will greatly benefit Open Manus. Next, let's look at how to use MCP in Open Manus.

The source code is as follows: https://github.com/alibaba/spring-ai-alibaba/tree/main/community/openmanus

Adding Dependencies

First, add the Spring AI MCP starter dependency to the project:

<dependency>    
    <groupId>org.springframework.ai</groupId>    
    <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>    
    <version>${spring-ai.version}</version>  
</dependency>  

Configuring the MCP Server

The MCP server is already configured in the application.yml, setting the timeout for client requests to the server to 1 minute:

9

Add mcp-servers-config.json, configuring Baidu Map in the JSON. Baidu Map's core APIs are now fully compatible with the MCP protocol, making it the first domestic map service provider to support the MCP protocol. Baidu Map has integrated 8 core API interfaces with the MCP protocol, covering reverse geocoding, place retrieval, route planning, and more.

To use Baidu Map’s MCP, you need to apply for an AK: https://lbsyun.baidu.com/apiconsole/key

{  
    "mcpServers": {        
        "baidu-map": {            
            "command": "npx",            
            "args": [                
                "-y",                
                "@baidumap/mcp-server-baidu-map"            
            ],            
            "env": {                
                "BAIDU_MAP_API_KEY": "your_baidu_AK"            
            }        
        }    
    }  
}  

Modify BAIDU_MAP_API_KEY to your applied AK.

Using MCP Tools

Modify the constructor source code of LlmService, directly getting ToolCallbackProvider from the Spring container and adding it to ChatClient.builder:

public LlmService(ChatModel chatModel, ToolCallbackProvider toolCallbackProvider) {  
    this.chatModel = chatModel;  
    this.planningChatClient = ChatClient.builder(chatModel)       
        .defaultSystem(PLANNING_SYSTEM_PROMPT)       
        .defaultAdvisors(new MessageChatMemoryAdvisor(planningMemory))       
        .defaultAdvisors(new SimpleLoggerAdvisor())       
        .defaultTools(ToolBuilder.getPlanningAgentToolCallbacks())       
        .defaultTools(toolCallbackProvider)       
        .build();  
        
    this.chatClient = ChatClient.builder(chatModel)       
        .defaultSystem(MANUS_SYSTEM_PROMPT)       
        .defaultAdvisors(new MessageChatMemoryAdvisor(memory))       
        .defaultAdvisors(new SimpleLoggerAdvisor())       
        .defaultTools(ToolBuilder.getManusAgentToolCalls())       
        .defaultTools(toolCallbackProvider)       
        .defaultOptions(OpenAiChatOptions.builder().internalToolExecutionEnabled(false).build())       
        .build();  

    this.finalizeChatClient = ChatClient.builder(chatModel)       
        .defaultSystem(FINALIZE_SYSTEM_PROMPT)       
        .defaultAdvisors(new MessageChatMemoryAdvisor(finalizeMemory))       
        .defaultAdvisors(new SimpleLoggerAdvisor())       
        .build();  
}  

Pass the tools provided by the MCP service to be handled by the ChatClient through defaultTools.

Testing the Effects

Start OpenManus and execute the prompt: Plan a route from Shanghai to Beijing. However, if we write it this way, it may trigger a Google search, so we can optimize the prompt to specifically choose Baidu Maps.

Use Baidu Maps to plan a route from Beijing to Shanghai.

After executing the program, the planned steps are as follows:

Steps:  
0. [ ] [MANUS] Use Baidu Map's geocoding service to obtain the latitude and longitude coordinates for Beijing and Shanghai.  
1. [ ] [MANUS] Use Baidu Map's route planning service to calculate the driving route from Beijing to Shanghai.  
2. [ ] [MANUS] Analyze and provide the final route information, including distance and estimated travel time.  

Clearly, this time OpenManus selected our integrated Baidu Map MCP server. Let's look at the results.

We obtained the latitude and longitude coordinates for Beijing and Shanghai:

Here is a summary of what we accomplished in this step:  
- For Beijing, we received the coordinates: Longitude (lng): 116.4133836971231, Latitude (lat): 39.910924547299565.  
- For Shanghai, we received the coordinates: Longitude (lng): 121.48053886017651, Latitude (lat): 31.235929042252014.  

Calculating the driving route from Beijing to Shanghai:

Distance: The total distance of the route is 1,223,200 meters (approximately 1,223 kilometers).  
Duration: The estimated travel time is 50,592 seconds (approximately 14 hours and 3 minutes).

Results:

Total distance: Approximately 1,223 kilometers

Estimated duration: Approximately 12 hours and 45 minutes

Main route: Jinghu Expressway (G2)

Conclusion

As a revolutionary breakthrough in the AI development field, the Model Context Protocol (MCP) redefines the interactive paradigm between agents and tool ecosystems. By standardizing protocols that connect core toolchains such as mapping services, code repositories, and databases, MCP not only resolves the fragmentation problem of cross-platform integration in traditional AI development but also provides a "plug-and-play" lightweight integration mode that enables developers to quickly build intelligent applications with multimodal capabilities.

In the future, as more tools integrate into the MCP ecosystem, developers will only need to focus on innovating business logic while the complex integration of toolchains becomes an "invisible underlying capability"—this may represent the most significant technological leap in the process of making AI accessible to all.

The MCP support in Spring AI allows Java developers to easily publish their applications as MCP Servers or integrate any MCP Server as a consumer.


Scan the QR code for the WeChat group below or add the DingTalk group to obtain more first-hand updates from Spring AI Alibaba.

Spring AI Alibaba Community Group 3:61290041831

10

● Spring AI Alibaba Open Source Project Address:https://github.com/alibaba/spring-ai-alibaba

● Spring AI Alibaba Official Website Address:https://java2ai.com/

● Source Code Address for This Example:https://github.com/springaialibaba/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-mcp-example

0 1 0
Share on

You may also like

Comments