<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amir Arsalan Khalilian on Medium]]></title>
        <description><![CDATA[Stories by Amir Arsalan Khalilian on Medium]]></description>
        <link>https://medium.com/@amir.arsalan.khalilian?source=rss-2bc3cc3b29c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Iwmyg6xfQQBcxnZ9</url>
            <title>Stories by Amir Arsalan Khalilian on Medium</title>
            <link>https://medium.com/@amir.arsalan.khalilian?source=rss-2bc3cc3b29c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:15:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amir.arsalan.khalilian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Agentic Services with Spring AI and MCP: A Developer’s Guide]]></title>
            <link>https://medium.com/@amir.arsalan.khalilian/building-agentic-services-with-spring-ai-and-mcp-a-developers-guide-c1d57b8cd3c1?source=rss-2bc3cc3b29c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d57b8cd3c1</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Amir Arsalan Khalilian]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 05:01:42 GMT</pubDate>
            <atom:updated>2025-11-12T05:01:42.694Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why did the AI agent break up with its API? Because it didn’t follow protocols</em> 😄</p><p>If you’re building AI-powered applications, you’ve probably heard about <strong>Model Context Protocol (MCP)</strong> — the protocol that lets AI models securely access external tools and data sources. But here’s the thing: implementing MCP from scratch can feel like trying to explain quantum physics to a chatbot. That’s where <strong>Spring AI</strong> comes in, making it ridiculously easy to build agentic services that actually work.</p><p>In this article, we’ll walk through building a complete MCP implementation using Spring AI. We’ll create a weather service that exposes tools via MCP, and a chat client that consumes those tools through an AI interface. By the end, you’ll have a working example you can extend for your own use cases.</p><blockquote><strong><em>💡 Quick Note</em></strong><em>: If you’re the type who likes to dive straight into code (no judgment here!), the full repository is linked at the end of this article. Feel free to jump ahead and come back for the explanations.</em></blockquote><h3>The Big Picture: What We’re Building</h3><p>Our example consists of two Spring Boot applications:</p><ol><li><strong>MCP Server</strong> — Exposes weather and travel tools that AI models can call</li><li><strong>MCP Client</strong> — Connects to the server and uses OpenAI to chat with users, automatically leveraging the available tools</li></ol><p>The magic happens when a user asks “What’s the weather in Paris?” and the AI automatically decides to call the getWeather tool, gets the data, and responds intelligently. No manual tool orchestration needed!</p><h3>Part 1: Building the MCP Client</h3><p>Let’s start with the client because it’s where the user interaction happens. The client is the “face” of our system — it’s what users interact with.</p><h3>The Application Entry Point</h3><p>Every Spring Boot app needs a main class, and ours is beautifully simple:</p><pre>@SpringBootApplication<br>public class Main {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Main.class, args);<br>    }<br>}</pre><p>Nothing fancy here — just standard Spring Boot. The real magic is in the configuration.</p><h3>The Configuration: Where MCP Meets Spring AI</h3><p>The Config.java file is where the integration happens. This is the heart of our MCP client:</p><pre>@Configuration<br>public class Config {<br>@Bean<br>    public ChatClient chatClient(ChatClient.Builder builder, List&lt;McpSyncClient&gt; mcpClients) {<br>        // Create tool callback provider from MCP clients<br>        SyncMcpToolCallbackProvider toolProvider = new SyncMcpToolCallbackProvider(mcpClients);<br>        // Log available tools<br>        System.out.println(&quot;=== MCP Tools Registered ===&quot;);<br>        Arrays.stream(toolProvider.getToolCallbacks())<br>                .forEach(tool -&gt; System.out.println(&quot;- &quot; + tool.getToolDefinition().name() + &quot;: &quot; + tool.getToolDefinition().description()));<br>        System.out.println(&quot;============================&quot;);<br>        return builder<br>                .defaultToolCallbacks(toolProvider)<br>                .build();<br>    }<br>}</pre><p>Let’s break this down:</p><ol><li>List&lt;McpSyncClient&gt; mcpClients — Spring AI automatically creates MCP clients based on your application.yml configuration. We&#39;ll see that in a moment.</li><li>SyncMcpToolCallbackProvider — This is Spring AI&#39;s way of wrapping MCP clients and making their tools available to the chat client. It&#39;s like a translator between MCP and Spring AI&#39;s tool system.</li><li>defaultToolCallbacks(toolProvider) — This tells the ChatClient to use our MCP tools automatically. When the AI model decides it needs to call a tool, it just works.</li></ol><p>The logging part is optional but helpful — it shows you which tools are available when the app starts.</p><h3>The Application Configuration</h3><p>The application.yml file configures how the client connects to the MCP server:</p><pre>server:<br>  port: 8080<br><br>spring:<br>  application:<br>    name: spring-ai-chat-client<br>  ai:<br>    openai:<br>      api-key: ${OPENAI_API_KEY}<br>      chat:<br>        options:<br>          model: gpt-4o-mini<br>          temperature: 0.7<br>    mcp:<br>      client:<br>        enabled: true<br>        name: weather-chat-client<br>        version: 1.0.0<br>        request-timeout: 30s<br>        type: SYNC<br>        toolcallback:<br>          enabled: true<br>        sse:<br>          connections:<br>            weather-server:<br>              url: http://localhost:8081/mcp</pre><p>Key points:</p><ul><li><strong>OpenAI Configuration</strong> — We’re using gpt-4o-mini (you can use any OpenAI model). The API key comes from an environment variable.</li><li><strong>MCP Client Configuration</strong> — The sse.connections section tells Spring AI where to find the MCP server. It uses Server-Sent Events (SSE) for communication.</li><li>toolcallback.enabled: true — This automatically registers tools from MCP servers with the chat client.</li></ul><h3>The Chat Service: Where AI Meets Tools</h3><p>The ChatService is where the actual AI interaction happens:</p><pre>@Service<br>public class ChatService {<br>    private final ChatClient chatClient;<br>    private final List&lt;McpSyncClient&gt; mcpClients;<br>    public ChatService(ChatClient chatClient, List&lt;McpSyncClient&gt; mcpClients) {<br>        this.chatClient = chatClient;<br>        this.mcpClients = mcpClients;<br>    }<br><br>    public String chat(String userMessage) {<br>        return chatClient.prompt()<br>                .user(userMessage)<br>                .call()<br>                .content();<br>    }<br><br>    public List&lt;String&gt; getAvailableTools() {<br>        return mcpClients.stream()<br>                .flatMap(client -&gt; client.listTools().tools().stream())<br>                .map(tool -&gt; tool.name() + &quot;: &quot; + tool.description())<br>                .collect(Collectors.toList());<br>    }<br>}</pre><p>The chat method is beautifully simple — just three lines! The AI model automatically:</p><ol><li>Understands the user’s message</li><li>Decides if it needs to call any tools</li><li>Calls the tools if needed</li><li>Returns a natural language response</li></ol><p>The getAvailableTools method is useful for debugging — it shows you what tools are available from connected MCP servers.</p><h3>The REST Controller: Exposing the API</h3><p>Finally, we expose a simple REST API:</p><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class ChatController {<br>    private final ChatService chatService;<br><br>    public ChatController(ChatService chatService) {<br>        this.chatService = chatService;<br>    }<br>    <br>    @GetMapping(&quot;/chat&quot;)<br>    public ChatResponse chat(@RequestParam String message) {<br>        try {<br>            String response = chatService.chat(message);<br>            return new ChatResponse(response, true);<br>        } catch (Exception e) {<br>            return new ChatResponse(&quot;Error: &quot; + e.getMessage(), false);<br>        }<br>    }<br>    <br>    @GetMapping(&quot;/tools&quot;)<br>    public ToolsResponse getTools() {<br>        List&lt;String&gt; tools = chatService.getAvailableTools();<br>        return new ToolsResponse(tools, tools.size());<br>    }<br>}</pre><p>That’s it! The client is complete. Users can now:</p><ul><li>Send messages via /api/chat?message=What&#39;s the weather in Paris?</li><li>Check available tools via /api/tools</li></ul><h3>Part 2: Building the MCP Server</h3><p>Now let’s build the server that exposes the tools. This is where you define what your AI agents can actually do.</p><h3>The Application Entry Point</h3><p>Again, standard Spring Boot:</p><pre>@SpringBootApplication<br>public class Main {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Main.class, args);<br>    }<br>}</pre><h3>The Weather Service: Defining Tools</h3><p>This is where the magic happens. The WeatherService defines the actual tools that the AI can use:</p><pre>@Service<br>public class WeatherService {<br>    <br>    @Tool(name = &quot;getWeather&quot;, description = &quot;Get current weather information for a city&quot;)<br>    public WeatherInfo getWeather(String city, String units) {<br>        // Implementation with simulated weather data<br>        // ... (returns WeatherInfo)<br>    }<br>    <br>    @Tool(name = &quot;getTravelTips&quot;, description = &quot;Get travel recommendations and tips for a destination&quot;)<br>    public TravelTips getTravelTips(String destination) {<br>        // Implementation with travel data<br>        // ... (returns TravelTips)<br>    }<br><br>    @Tool(name = &quot;shouldPackUmbrella&quot;, description = &quot;Check if you should pack an umbrella based on weather conditions&quot;)<br>    public UmbrellaRecommendation shouldPackUmbrella(String city) {<br>        // Implementation<br>        // ... (returns UmbrellaRecommendation)<br>    }<br><br>    @Tool(name = &quot;compareWeather&quot;, description = &quot;Compare weather between two cities&quot;)<br>    public WeatherComparison compareWeather(String city1, String city2) {<br>        // Implementation<br>        // ... (returns WeatherComparison)<br>    }<br>}</pre><p>The @Tool annotation is all you need! Spring AI automatically:</p><ul><li>Extracts the method signature</li><li>Creates tool definitions</li><li>Makes them available via MCP</li></ul><p>Each tool method:</p><ul><li>Has a clear name and description (the AI uses these to decide when to call the tool)</li><li>Takes simple parameters (strings, primitives, etc.)</li><li>Returns a record/POJO (Spring AI handles serialization)</li></ul><h3>The Configuration: Registering Tools</h3><p>The Config.java file registers the tools:</p><pre>@Configuration<br>public class Config {<br>    @Bean<br>    public ToolCallbackProvider weatherTools(WeatherService weatherService) {<br>        return MethodToolCallbackProvider.builder()<br>                .toolObjects(weatherService)<br>                .build();<br>    }<br>}</pre><p>This creates a ToolCallbackProvider that Spring AI MCP Server uses to expose the tools. The MethodToolCallbackProvider automatically finds all @Tool annotated methods in the weatherService object.</p><h3>The Application Configuration</h3><p>The application.yml configures the MCP server:</p><pre>server:<br>  port: 8081spring:<br>  application:<br>    name: mcp-weather-server ai:<br>    mcp:<br>      server:<br>        name: weather-server<br>        version: 1.0.0<br>        instructions: &quot;Weather and travel information server providing real-time forecasts and recommendations&quot;<br>        type: SYNC<br>        sse-message-endpoint: /mcp/messages<br>        capabilities:<br>          tool: true<br>          resource: false<br>          prompt: false<br>          completion: false</pre><p>Key points:</p><ul><li>sse-message-endpoint — This is where MCP clients connect (via SSE)</li><li>capabilities.tool: true — We&#39;re only exposing tools (not resources, prompts, or completions)</li><li>type: SYNC — Synchronous operations (Spring AI also supports async)</li></ul><h3>The Health Check (Bonus)</h3><p>A simple health check endpoint is always useful:</p><pre>@RestController<br>public class Controller {<br>    private final ToolCallbackProvider toolCallbackProvider;<br>   @GetMapping(&quot;/health&quot;)<br>    public Map&lt;String, Object&gt; health() {<br>        int toolCount = toolCallbackProvider.getToolCallbacks().length;<br>        List&lt;String&gt; toolNames = Arrays.stream(toolCallbackProvider.getToolCallbacks())<br>                .map(tc -&gt; tc.getToolDefinition().name())<br>                .toList();<br>       return Map.of(<br>                &quot;status&quot;, &quot;UP&quot;,<br>                &quot;service&quot;, &quot;MCP Weather Server&quot;,<br>                &quot;version&quot;, &quot;1.0.0&quot;,<br>                &quot;toolCount&quot;, toolCount,<br>                &quot;availableTools&quot;, toolNames<br>        );<br>    }<br>}</pre><h3>How It All Works Together</h3><p>Here’s the flow when a user asks “What’s the weather in Paris?”:</p><ol><li><strong>User</strong> → Sends request to /api/chat?message=What&#39;s the weather in Paris?</li><li><strong>ChatController</strong> → Calls ChatService.chat()</li><li><strong>ChatService</strong> → Sends message to ChatClient (OpenAI)</li><li><strong>OpenAI</strong> → Analyzes the message, decides it needs weather data, calls getWeather(&quot;Paris&quot;, &quot;celsius&quot;)</li><li><strong>SyncMcpToolCallbackProvider</strong> → Routes the tool call to the MCP client</li><li><strong>McpSyncClient</strong> → Sends tool call via SSE to the MCP server</li><li><strong>MCP Server</strong> → Executes WeatherService.getWeather() and returns result</li><li><strong>OpenAI</strong> → Receives weather data, generates natural language response</li><li><strong>User</strong> → Gets: “The weather in Paris is currently 15°C and rainy. I’d recommend bringing an umbrella.”</li></ol><p>All of this happens automatically! You don’t need to write any tool orchestration code.</p><h3>Key Takeaways</h3><ol><li><strong>Spring AI makes MCP easy</strong> — No need to implement the protocol yourself. Just use annotations and configuration.</li><li><strong>Tools are just methods</strong> — Use @Tool annotation on any method, and Spring AI handles the rest.</li><li><strong>Automatic tool discovery</strong> — The AI model automatically discovers and uses available tools based on their descriptions.</li><li><strong>Type-safe</strong> — Use Java records/POJOs for tool parameters and return types. Spring AI handles serialization.</li><li><strong>Extensible</strong> — Add more tools by adding more @Tool annotated methods. Add more MCP servers by adding more entries in application.yml.</li></ol><h3>What’s Next?</h3><p>This is a basic example, but you can extend it in many ways:</p><ul><li><strong>Connect to real APIs</strong> — Replace simulated weather data with actual weather APIs</li><li><strong>Add more tools</strong> — Create tools for booking, recommendations, data analysis, etc.</li><li><strong>Multiple MCP servers</strong> — Connect to multiple specialized servers</li><li><strong>Add authentication</strong> — Secure your MCP endpoints</li><li><strong>Add persistence</strong> — Store chat history or user preferences</li><li><strong>WebSocket support</strong> — Use WebSocket instead of SSE for bidirectional communication</li></ul><h3>Conclusion</h3><p>Building agentic services with Spring AI and MCP is surprisingly straightforward. The framework handles all the protocol complexity, leaving you to focus on what matters: defining useful tools and creating great user experiences.</p><p>The combination of Spring AI’s simplicity and MCP’s flexibility makes it easy to build AI applications that can actually <em>do</em> things, not just chat about them. And that’s the real power of agentic AI.</p><h3>Repository</h3><p>You can find the complete working example with setup instructions, testing examples, and more details in the repository:</p><p><a href="https://github.com/aakhalilian/Spring-AI-MCP-Example">GitHub - aakhalilian/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.</a></p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d57b8cd3c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>