Mastering MCP in Java: From Claude Automation to Spring AI Alibaba Integration

This article walks Java developers through the Model Context Protocol (MCP) by first explaining its fundamentals, then showing how to publish an MCP server in stdio and SSE modes, integrate it with Claude Desktop, consume it from Spring AI Alibaba applications, fix a known Spring AI bug, and finally leverage MCP within the OpenManus framework for advanced AI workflows.

Alibaba Middleware
Alibaba Middleware
Alibaba Middleware
Mastering MCP in Java: From Claude Automation to Spring AI Alibaba Integration

Overview

The article demonstrates how Java developers can use the Model Context Protocol (MCP) with Spring AI Alibaba to publish MCP servers and consume them from AI applications, covering both stdio and Server‑Sent Events (SSE) deployment modes and real‑world examples such as weather lookup and Baidu Map routing.

1. MCP Basics

MCP defines a client‑server contract where the client (e.g., Claude, a Spring AI application, or LangChain) sends a JSON‑RPC request and the server accesses external data sources or APIs. Public MCP server registries include awesome-mcp-servers and mcp.so. Typical use cases are map travel‑time calculation, Puppeteer automation, GitHub/GitLab repository management, database operations, and search extensions.

2. Publishing an MCP Server with Spring AI Alibaba

2.1 Server Architecture

The server receives MCP requests, invokes registered tools, and returns JSON results. Two communication modes are supported:

stdio mode – the server runs as a local subprocess communicating via standard input/output.

SSE mode – the server runs as an independent HTTP service exposing an SSE endpoint.

2.2 Implementing a Weather Service (stdio)

Add the starter dependency:

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

Configure the server in application.yml:

spring:
  main:
    web-application-type: none
    banner-mode: off
  ai:
    mcp:
      server:
        stdio: true
        name: my-weather-server
        version: 0.0.1

Define tools with @Tool and @ToolParameter annotations:

@Service
public class OpenMeteoService {
    private final WebClient webClient;
    public OpenMeteoService(WebClient.Builder builder) {
        this.webClient = builder.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();
            return "Location (lat:" + latitude + ", lng:" + longitude + ") weather:
" + response;
        } catch (Exception e) {
            return "Failed to fetch weather: " + e.getMessage();
        }
    }
    @Tool(description = "Get air quality by latitude and longitude")
    public String getAirQuality(@ToolParameter(description = "Latitude") String latitude,
                                @ToolParameter(description = "Longitude") String longitude) {
        return "Location (lat:" + latitude + ", lng:" + longitude + ") air quality:
- PM2.5: 15 μg/m³ (Good)
- PM10: 28 μg/m³ (Fair)
- AQI: 42 (Good)
- Main pollutant: None";
    }
}

Register the tools in the Spring Boot entry point:

@SpringBootApplication
public class McpServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }
    @Bean
    public ToolCallbackProvider weatherTools(OpenMeteoService service) {
        return MethodToolCallbackProvider.builder()
            .toolObjects(service)
            .build();
    }
}

Build and run:

mvn clean package -DskipTests
java -jar target/my-weather-server.jar

The server starts on http://localhost:8080 when SSE is enabled, otherwise it runs as a stdio subprocess.

2.3 Testing with Claude Desktop

Edit Claude’s configuration file ( claude_desktop_config.json) to add a server entry that launches the compiled jar via java. After restarting Claude, the two tools appear in the UI and can be invoked directly (e.g., “Beijing’s weather?”). The response contains the full JSON payload from the MCP server.

3. Consuming an MCP Server from a Spring AI Application

3.1 stdio Client

Add the client starter:

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

Configure the client to load a JSON file that describes how to start the stdio server:

spring:
  ai:
    mcp:
      client:
        stdio:
          servers-configuration: classpath:/mcp-servers-config.json

Example mcp-servers-config.json for the weather server:

{
  "mcpServers": {
    "weather": {
      "command": "java",
      "args": ["-Dspring.ai.mcp.server.stdio=true","-Dspring.main.web-application-type=none","-jar","/full/path/to/weather-server.jar"],
      "env": {}
    }
  }
}

Use the tools in a Spring Boot application:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public CommandLineRunner demo(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools) {
        return args -> {
            var client = chatClientBuilder.defaultTools(tools).build();
            String answer = client.prompt("Beijing's weather?").call().content();
            System.out.println(answer);
        };
    }
}

3.2 SSE Client

Add the SSE client starter:

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

Configure the remote endpoint:

spring:
  ai:
    mcp:
      client:
        sse:
          connections:
            server1:
              url: http://localhost:8080

The same ChatClient usage works, but communication occurs over HTTP.

3.3 Resolving a Spring AI Duplicate‑Tool Bug

When both SseHttpClientTransportAutoConfiguration and SseWebFluxTransportAutoConfiguration are loaded, the same tool is registered twice, causing:

java.lang.IllegalStateException: Multiple tools with the same name (spring-ai-mcp-client-getWeatherForecastByLocation, ...)

Fix by excluding the unwanted auto‑configuration class:

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

4. Using MCP Inside Spring AI Alibaba OpenManus

OpenManus is a workflow engine that can invoke tools during execution. Add the MCP starter and configure a Baidu‑Map MCP server:

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

Inject ToolCallbackProvider into the OpenManus service constructor and add it to the ChatClient builder. A prompt such as “Plan a route from Shanghai to Beijing” produces a step list that first calls the Baidu geocoding tool, then the routing tool, and finally returns distance, duration, and main highway information.

Conclusion

MCP provides a standardized bridge for AI models to interact with external tools. Spring AI Alibaba enables Java developers to publish MCP servers in stdio or SSE mode, consume them from AI applications, resolve integration bugs, and extend complex workflows like OpenManus with third‑party services such as Baidu Map.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMCPTool IntegrationSpring AIServerClaudeClientSSE
Alibaba Middleware
Written by

Alibaba Middleware

Aliware Alibaba Middleware Official Account

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.