This project demonstrates a Spring AI client that uses the Model Context Protocol (MCP) to interact with an MCP Server. Specifically, it shows how to integrate with the Brave Search MCP server, one of the servers available in the official MCP servers repository.
The application uses a ChatClient
configured with McpFunctionCallback
to interact with the Brave Search MCP server via standard input and output (stdio). The client can then ask questions, and the Brave Search server will respond through the MCP protocol, providing search results as if it were a tool.
- Java 17 or higher
- Docker
- OpenAI API Key - set as environment variable
OPENAI_API_KEY
- Brave API Key - set as environment variable
BRAVE_API_KEY
-
Clone the repository:
git clone https://github.com/apappascs/spring-ai-examples.git cd spring-ai-examples/model-context-protocol/spring-ai-mcp-client
-
Set environment variables:
export OPENAI_API_KEY=<your-openai-api-key> export BRAVE_API_KEY=<your-brave-api-key>
-
Build and run the application (using Gradle):
./gradlew bootRun
This will start the Spring Boot application. It will run a predefined question that is logged in the console, demonstrating the interaction with the Brave Search MCP server via MCP.
- The application initializes an
McpSyncClient
configured to useStdioClientTransport
. This client communicates with a Docker container running the Brave Search MCP server via standard input/output. - The
dockerClient
bean is responsible for starting and managing the Docker container that runs the Brave Search MCP server. The server exposes its capabilities (in this case, search functionality) through the MCP protocol. - The
predefinedQuestions
bean is aCommandLineRunner
that sends a predefined question to theChatClient
. - The
ChatClient
is configured to support the Model Context Protocol by passing itMcpFunctionCallback
s via its builder. These callbacks allow theChatClient
to discover and use the tools exposed by the MCP server. - When the
ChatClient
determines that the Brave Search tool should be used, it invokes the correspondingMcpFunctionCallback
. This callback sends the tool execution request to the Brave Search MCP server via theMcpSyncClient
, and the server returns the search results.
- Spring AI: A framework for building AI-powered applications.
- Spring AI MCP: An experimental project that provides a Java and Spring Framework integration for the Model Context Protocol.
- Brave Search: A privacy-focused search engine with a developer API.
- Spring Boot: A framework for building stand-alone, production-grade Spring applications.
- Gradle: A build automation tool.
- Docker: A platform for developing, shipping, and running applications in containers.
Contributions are welcome! Please feel free to submit pull requests or open issues to improve the project.