aakhalilian/Spring-AI-MCP-Example
If you are the rightful owner of Spring-AI-MCP-Example and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
This document provides a structured overview of a Model Context Protocol (MCP) server implementation using Spring AI, showcasing its architecture, features, and usage.
Spring AI MCP Example
A basic reference implementation demonstrating how to use Model Context Protocol (MCP) with Spring AI. This project showcases a client-server architecture where an MCP server exposes weather and travel tools, and an MCP client consumes these tools through an AI chat interface.
What is MCP?
Model Context Protocol (MCP) is a protocol that enables AI applications to securely access external tools, resources, and data sources. In this example, we demonstrate:
- MCP Server: Exposes weather and travel-related tools that can be called by AI models
- MCP Client: Connects to the server and uses OpenAI to chat with users, automatically leveraging the available tools
Project Structure
spring-ai-mcp/
├── mcp-server/ # MCP server exposing weather tools
│ └── src/main/java/dev/fusionize/
│ ├── Main.java # Spring Boot application entry point
│ ├── Config.java # Tool callback provider configuration
│ ├── Controller.java # Health check endpoint
│ └── WeatherService.java # Weather and travel tools implementation
│
└── mcp-client/ # MCP client with chat interface
└── src/main/java/dev/fusionize/
├── Main.java # Spring Boot application entry point
├── Config.java # MCP client and chat client configuration
├── ChatController.java # REST API for chat interactions
└── ChatService.java # Chat service using MCP tools
Features
MCP Server Tools
The server exposes the following tools:
-
getWeather- Get current weather information for a city- Parameters:
city(String),units(String: "celsius" or "fahrenheit") - Returns: Weather info including temperature, condition, humidity, and recommended items
- Parameters:
-
getTravelTips- Get travel recommendations and tips for a destination- Parameters:
destination(String) - Returns: Best time to visit, must-see places, must-try foods, and travel tips
- Parameters:
-
shouldPackUmbrella- Check if you should pack an umbrella based on weather- Parameters:
city(String) - Returns: Recommendation with reason and weather condition
- Parameters:
-
compareWeather- Compare weather between two cities- Parameters:
city1(String),city2(String) - Returns: Weather comparison with temperature difference
- Parameters:
Prerequisites
- Java 21 or higher
- Gradle (wrapper included)
- OpenAI API Key (for the chat client)
Setup
-
Clone the repository
git clone <repository-url> cd spring-ai-mcp -
Set up OpenAI API Key
Export your OpenAI API key as an environment variable:
export OPENAI_API_KEY=your-api-key-hereOr create a
.envfile (not included in the repository):OPENAI_API_KEY=your-api-key-here
Running the Application
Step 1: Start the MCP Server
The server runs on port 8081 and exposes weather tools via MCP.
cd mcp-server
../gradlew bootRun
Or from the root directory:
./gradlew :mcp-server:bootRun
You should see output indicating the server is running. You can verify it's working by visiting:
- Health check: http://localhost:8081/health
Step 2: Start the MCP Client
In a new terminal, start the client on port 8080:
cd mcp-client
../gradlew bootRun
Or from the root directory:
./gradlew :mcp-client:bootRun
The client will automatically connect to the MCP server and register available tools. You should see output like:
=== MCP Tools Registered ===
- getWeather: Get current weather information for a city
- getTravelTips: Get travel recommendations and tips for a destination
- shouldPackUmbrella: Check if you should pack an umbrella based on weather conditions
- compareWeather: Compare weather between two cities
============================
Testing
1. Check Available Tools
Get a list of all available tools from the MCP server:
curl http://localhost:8080/api/tools
2. Chat with the AI
The AI can now use the weather tools to answer your questions. Try these examples:
Get weather information:
curl "http://localhost:8080/api/chat?message=What's the weather like in Paris?"
Get travel tips:
curl "http://localhost:8080/api/chat?message=Give me travel tips for Tokyo"
Compare weather:
curl "http://localhost:8080/api/chat?message=Compare the weather in London and Dubai"
Umbrella recommendation:
curl "http://localhost:8080/api/chat?message=Should I pack an umbrella for Amsterdam?"
Complex queries:
curl "http://localhost:8080/api/chat?message=I'm planning a trip to Paris next week. What should I know about the weather and what should I pack?"
3. Server Health Check
Check the MCP server status and available tools:
curl http://localhost:8081/health
How It Works
MCP Server Flow
- WeatherService defines methods annotated with
@Toolfrom Spring AI - Config creates a
ToolCallbackProviderthat registers these tools - Spring AI MCP Server automatically exposes these tools via HTTP/SSE endpoint at
/mcp/messages - The server runs on port 8081 and listens for MCP client connections
MCP Client Flow
- Config creates
McpSyncClientinstances that connect to the MCP server via SSE - SyncMcpToolCallbackProvider wraps the MCP clients and makes their tools available to Spring AI
- ChatClient is configured to use these tools automatically
- When a user sends a message, the AI model (OpenAI) can decide to call the appropriate tools
- The client runs on port 8080 and provides a REST API for chat interactions
Communication Flow
User → ChatController → ChatService → ChatClient (OpenAI)
↓
(AI decides to use tools)
↓
SyncMcpToolCallbackProvider
↓
McpSyncClient (SSE)
↓
MCP Server (8081)
↓
WeatherService Tools
Configuration
Server Configuration (mcp-server/src/main/resources/application.yml)
- Port: 8081
- MCP Endpoint:
/mcp/messages(SSE) - Server Type: SYNC
- Capabilities: Tools enabled
Client Configuration (mcp-client/src/main/resources/application.yml)
- Port: 8080
- OpenAI Model: gpt-4o-mini
- MCP Server URL: http://localhost:8081/mcp
- Connection Type: SSE (Server-Sent Events)
Technologies Used
- Spring Boot 3.5.6 - Application framework
- Spring AI 1.0.3 - AI integration framework
- Spring AI MCP - Model Context Protocol support
- OpenAI API - AI model provider
- Java 21 - Programming language
- Gradle - Build tool
Limitations
This is a basic example for educational purposes:
- Weather data is simulated (hardcoded in the service)
- Only supports a limited set of cities
- No authentication or security features
- Single MCP server connection
- Basic error handling
Extending the Example
To extend this example, you could:
- Add more tools - Create new
@Toolannotated methods inWeatherService - Connect to real APIs - Replace simulated data with actual weather APIs
- Add multiple MCP servers - Configure multiple server connections in the client
- Add authentication - Implement security for the MCP endpoints
- Add persistence - Store chat history or user preferences
- Add WebSocket support - Use WebSocket instead of SSE for bidirectional communication
Troubleshooting
Client can't connect to server
- Ensure the server is running on port 8081
- Check that the URL in
application.ymlmatches:http://localhost:8081/mcp - Verify firewall settings
OpenAI API errors
- Ensure
OPENAI_API_KEYenvironment variable is set - Check that your API key is valid and has credits
- Verify network connectivity
Tools not appearing
- Check server logs for tool registration
- Verify
@Toolannotations are present - Ensure
ToolCallbackProviderbean is created correctly
License
This is a reference example project. Feel free to use it as a starting point for your own MCP implementations.
Contributing
This is a basic reference example. Feel free to fork and extend it for your needs!
Note: This example demonstrates the basic concepts of MCP with Spring AI. For production use, consider adding proper error handling, security, logging, and testing.