<?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 Kuldeep Singh on Medium]]></title>
        <description><![CDATA[Stories by Kuldeep Singh on Medium]]></description>
        <link>https://medium.com/@kuldeep.singh.manomano?source=rss-05b1cf5c8436------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x1J6c9o63IMVoSdB</url>
            <title>Stories by Kuldeep Singh on Medium</title>
            <link>https://medium.com/@kuldeep.singh.manomano?source=rss-05b1cf5c8436------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:44:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kuldeep.singh.manomano/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[AI Code Review with CodeRabbit]]></title>
            <link>https://medium.com/manomano-tech/ai-code-review-with-coderabbit-ed6ed610f481?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6ed610f481</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[code-review-tool]]></category>
            <category><![CDATA[ai-code-review]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 12:00:15 GMT</pubDate>
            <atom:updated>2025-09-26T12:00:15.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XVpumqp_YCXo-FVT6HDmg.jpeg" /></figure><h3>Introduction</h3><p>Code reviews are a most important part of software development process. They improve code quality, catch bugs early. But traditional code reviews can be time-consuming, repetitive, and sometimes not effective.</p><p>That’s where <strong>AI-powered code review tools</strong> like <a href="https://www.coderabbit.ai/"><strong>CodeRabbit</strong></a> come in. By combining AI models with workflow automation, CodeRabbit speeds up reviews, reduce human efforts, and keep good quality.</p><p>We do have many other tools available, but this blog is on <strong>CodeRabbit</strong>.</p><p>In this blog, I will walk you through what CodeRabbit is, how it works, its benefits, and how you can integrate it into your development process.</p><h3>What is CodeRabbit?</h3><p>CodeRabbit is an <strong>AI-assisted code review tool</strong> that integrates directly into your GitHub or GitLab. Instead of waiting for a teammate to review your pull request (PR), CodeRabbit provides <strong>instant AI-driven feedback</strong>.</p><p><strong>Features</strong>:</p><ul><li>📌 Automated <strong>pull request reviews</strong></li><li>📌 Comments directly inside your PR, just like a human reviewer</li><li>📌 Configurable rules and customization</li><li>📌 Support for multiple languages and frameworks</li></ul><h3>Why Use AI for Code Reviews?</h3><p>Traditional reviews may have these problems:</p><ul><li><strong>Delays</strong> (waiting for reviewers)</li><li><strong>Repetition</strong> (fixing the same issues over and over)</li><li><strong>Subjectivity</strong> (different reviewers may have different opinions)</li></ul><h3>Getting Started</h3><p>Create an account in <a href="https://www.coderabbit.ai/">Code Rabbit</a></p><ol><li>We need to provide read-only access to our Repository (It supports GitHub, Gitlab, Bitbucket and <a href="https://docs.coderabbit.ai/platforms/overview">others</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiWekR6k_GBSBRsfy4qTow.png" /></figure><p>2. Select the Organization, and we need to install Code Rabbit AI to all our repositories or selected repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*gwLEgEWSS-X5BEwUwF63bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i31Mbfl2_-L1X7mkgiiI9w.png" /></figure><p>3. Code Rabbit Dashboard looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIbePZNTbEEIl5pwqy7JuQ.png" /></figure><h3>Code Rabbit Plugins</h3><p>Currently, <a href="https://www.coderabbit.ai/ide">Code Rabbit</a> plugin is only supported in three IDEs Visual Code, Cursor and Windsurf.</p><h3>How AI Code Review Works</h3><p>Two ways AI Code Reviews can be done, it&#39;s up to how we want CodeRabbit to Review our Code.</p><ul><li>Directly in the repository when we raise Merge request.</li><li>Directly in the IDEs (Visual Code, Cursor or WindSurf).</li></ul><p>I have developed a simple <a href="https://github.com/kuldeepsingh99/ai-code-review">Spring boot App</a> for testing the AI Review, I have used Cursor for this (I have to install few Extension to make the Java Spring boot app works)</p><h4>AI Review in the Merge Request</h4><p>I created an MR request, and we can see how CodeRabbit has done the review and also given the suggestion. MR link <a href="https://github.com/kuldeepsingh99/ai-code-review/pull/1">here</a>.</p><p>This way, we can use AI to make our code better and improve its quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qbWX6wEiJIntvkEx6o8Mg.png" /></figure><h4>AI Review in the IDE directly</h4><p>I have used <a href="https://cursor.com/download">Cursor</a> for testing the AI review</p><p>Install Code Rabbit Extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kJOvVnLHGHdnp1tNhFgtQ.png" /></figure><p>Now, when we do any change in the code, we have options to review Uncommitted, commit and all changes.</p><p>I have done a small change and CodeRabbit reviewed the code and also given suggestion’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7gIIngjasPs8e7U_5YF8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qscUrmPQ4Wv3LKbzgteVDw.png" /></figure><h3>Why Use CodeRabbit</h3><h4>⚙️ CodeRabbit</h4><ul><li>An <strong>AI-powered code review assistant</strong>.</li><li>Works directly in <strong>Pull Requests (PRs)</strong> on GitHub/GitLab and in your <strong>IDE</strong>.</li><li>Focuses on <strong>giving human like feedback</strong>: readability, maintainability, edge cases, and best practices.</li><li>Saves developers’ time by <strong>automating first-level reviews</strong> and catching issues early.</li></ul><h4>⚙️ Sonar (SonarQube / SonarCloud)</h4><ul><li>A <strong>static code analysis tool</strong>.</li><li>Focuses on <strong>code quality and security rules</strong>.</li><li>Works best in CI/CD pipelines, scanning for <strong>bugs, vulnerabilities, and code smells</strong>.</li><li>Great for <strong>coding standards</strong> across a team.</li></ul><h4>⚙️ DeepCode (by Snyk)</h4><ul><li>AI based <strong>code analysis</strong>.</li><li>Focuses strongly on <strong>security issues</strong>.</li><li>Integrates with GitHub/GitLab/Bitbucket.</li><li>Helps catch <strong>security vulnerabilities</strong></li></ul><h4>✅ Why Use CodeRabbit?</h4><ul><li>Understands your PR in detail, not just static rules.</li><li>Gives review comments right where needed, like a teammate.</li><li>Reduces back-and-forth between reviewers and authors.</li><li>Works in IDE, helps before code even reaches PR, so you fix things earlier.</li></ul><h4>👉 Comparison</h4><ul><li><strong>Sonar</strong> = rule-based, automated scanning (quality/security).</li><li><strong>DeepCode</strong> = AI for security-focused scanning.</li><li><strong>CodeRabbit</strong> = AI teammate that reviews like a human and fits into your workflow (PR + IDE)</li></ul><h3>Conclusion</h3><p>AI Code Reviews are quickly becoming a standard for development teams. Instead of getting stuck in repetitive checks, tools like <strong>CodeRabbit</strong> handle the heavy lifting spotting issues, keeping things consistent, and speeding up the whole review cycle.</p><p>AI won’t replace human judgment anytime soon. What it does is developers to spend less time fixing small fixes and more time on the important parts of coding, solving business problems etc.</p><p>Whether your team works on GitHub, GitLab, or even a self-hosted setup, CodeRabbit fits right into your workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6ed610f481" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/ai-code-review-with-coderabbit-ed6ed610f481">AI Code Review with CodeRabbit</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical guide to building Multi-Agents AI Systems with A2A]]></title>
            <link>https://medium.com/manomano-tech/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-f61a4ef7c51a?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61a4ef7c51a</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[spring-ai]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 07:55:10 GMT</pubDate>
            <atom:updated>2025-09-08T07:55:55.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ61axiSUE0q8I6ztZZCYQ.png" /></figure><p>If you have to built multi agent AI systems, this pain might sound familiar. Every new agent doubles the complexity. And without any standard, most of your effort goes into fixing connections instead of writing AI logic.</p><p>In this article we will understand about <a href="https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/">Google A2A</a> protocol followed by an example in Java.</p><h3>📢 Introduction: Why the A2A (Agent-to-Agent) Protocol Matters</h3><h4>1. Agents Are Specialized — Not One-Size-Fits-All</h4><p>Today, AI agents are built for specific jobs:</p><ul><li>one agent might calculate numbers.</li><li>another might summarize text.</li><li>another might look up document.</li><li>and another might handle customer orders.</li></ul><p>Each agent does its job really well, but they don’t always know how to <strong>talk to each other</strong>.</p><ul><li><strong>MCP (Model Context Protocol)</strong> is good when you want to connect one model to a tool or a database.</li><li>But what if you want <strong>multiple agents to work together and share tasks</strong>? That is where <a href="https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/"><strong>A2A</strong></a> comes in.</li></ul><h4>2. A2A Standardizes Agent Communication</h4><p>Google launched <a href="https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/">A2A</a> in April 2025 as an <strong>open protocol</strong> that any AI agent can use.</p><ul><li>It gives agents a <strong>common language</strong> to discover each other, talk, and pass tasks around.</li><li>It’s built on <strong>standard web tech</strong> (HTTP, JSON-RPC, SSE), so developers don’t need to invent custom adapters.</li></ul><h4>3. How A2A Works in Practice</h4><p>A2A has a few simple building blocks that make multi-agent systems easier:</p><ul><li><strong>AgentCard (</strong><strong>agent.json)</strong> → A file that describes what an agent can do, its ID, and its API endpoint.</li><li><strong>Message format</strong> → Standard request and response structures.</li><li><strong>Discovery &amp; Delegation</strong> → Agents can find other agents and hand over tasks when needed.</li></ul><p>So, instead of writing custom code every time, agents just follow the protocol.</p><h4>4. A2A vs MCP</h4><ul><li><strong>MCP</strong> — Good for connecting agents to <strong>tools and data sources</strong>.</li><li><strong>A2A</strong> — Good for making <strong>agents talk to other agents</strong>.</li><li><strong>MCP</strong> — operates at a lower level with explicit instructions for specific functionalities.</li><li><strong>A2A</strong> — functions at a higher level focused on intent and capabilities between agents.</li></ul><h3>🚀 Project</h3><p>In this project, we have built a <strong>multi-agent system</strong> using Google’s <strong>Agent-to-Agent (A2A) protocol</strong>. The goal is to show how different agents can talk to each other, delegate tasks, and returns response back to the user.</p><p>We defined three agents:</p><h4>1. Parent Agent</h4><ul><li>Acts as the <strong>orchestrator</strong>.</li><li>Receives the user’s query (for example: <em>“Get B2C order details with seller info”</em>).</li><li>Uses <strong>A2A AgentCards</strong> to discover available agents and their capabilities.</li><li>Decides which agent should handle the request (order-agent, seller-agent, or both).</li><li>Collects responses, aggregates them, and returns a single, clean answer to the user.</li></ul><h4>2. Order Agent</h4><ul><li>Responsible for <strong>order-related queries</strong> (like B2B or B2C order details, order amounts, or order IDs).</li><li>Returns order data, which may include <strong>seller IDs</strong>.</li><li>Example: <em>“Order ID 2, Type: B2C, Seller ID: 2, Amount: $220.00”</em>.</li></ul><h4>3. Seller Agent</h4><ul><li>Handles <strong>seller information queries</strong> (by seller ID or by seller name).</li><li>If the parent agent sees seller IDs inside order results, it can <strong>automatically call the seller-agent</strong> to fetch more details.</li><li>Example: <em>“Seller ID 2 → Seller Name: Acme Corp, Rating: 4.7/5”</em>.</li></ul><h4>🔗 How It All Works Together</h4><ul><li>If the user only asks about <strong>orders</strong> → Parent routes to <strong>order-agent</strong> only.</li><li>If the user only asks about <strong>sellers</strong> → Parent routes to <strong>seller-agent</strong> only.</li><li>If the user asks for <strong>orders + seller info</strong> → Parent first calls <strong>order-agent</strong>, extracts seller IDs, then calls <strong>seller-agent</strong> with those IDs, and finally merges the results.</li></ul><p>Two Diagrams of the project to explain the Flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ye36zh2kghEtzXJ0GkJjMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*LilWLNA6rT0EEJ4u4opxlA.png" /></figure><h3>🚀 Code Explanation</h3><p>I am going to explain only few important files, code is checked-in to <a href="https://github.com/kuldeepsingh99/google-a2a">GitHub</a>. For this example I have used <a href="https://ollama.com/">ollama</a>, if you want to use any other LLM model, you need to modify the dependency on Gradle file.</p><p><strong>Note</strong> — I have just explain the A2A Flow with just a POC Code, when you are going to implement real like Service, we definitely will use some design pattern to divide the code into layers.</p><h4>Order Agent</h4><p><strong>Tools class</strong> (As we are using MCP, so I have created two Tools)</p><p><strong>Note</strong> — I have not used any database, but in real you can use any Database.</p><pre>@Service<br>public class OrderAgentTools {<br><br>    private final List&lt;Order&gt; orders = List.of(<br>            new Order(&quot;1&quot;, &quot;B2B&quot;, &quot;1&quot;, 100.50),<br>            new Order(&quot;2&quot;, &quot;B2C&quot;, &quot;2&quot;, 50.75),<br>            new Order(&quot;4&quot;, &quot;B2C&quot;, &quot;3&quot;, 130.00)<br>    );<br><br>    @Tool(name = &quot;Get B2B Orders&quot;, description = &quot;Returns all B2B orders&quot;)<br>    public List&lt;Order&gt; getB2BOrders() {<br>        return orders.stream()<br>                .filter(o -&gt; o.type().equalsIgnoreCase(&quot;B2B&quot;))<br>                .toList();<br>    }<br><br>    @Tool(name = &quot;Get B2C Orders&quot;, description = &quot;Returns all B2C orders&quot;)<br>    public List&lt;Order&gt; getB2COrders() {<br>        return orders.stream()<br>                .filter(o -&gt; o.type().equalsIgnoreCase(&quot;B2C&quot;))<br>                .toList();<br>    }<br><br>    public record Order(String id, String type, String sellerId, double amount) {}<br>}</pre><p><strong>Controller</strong> (Here we have two endpoints)</p><p><strong><em>/.well-known/agent.json</em></strong><em> — </em>file that describes what an agent can do, its ID, and its API endpoint.</p><p>/<strong><em>task</em></strong> — this handles the User Prompt/Query</p><pre><br>@RestController<br>public class OrderAgentController {<br><br>    private final ChatClient chatClient;<br><br>    public OrderAgentController(ChatClient chatClient) {<br>        this.chatClient = chatClient;<br>    }<br><br>    @GetMapping(&quot;/.well-known/agent.json&quot;)<br>    public AgentCard getAgentCard() {<br>        return new AgentCard.Builder()<br>                .name(&quot;order-agent&quot;)<br>                .url(https://medium.com/&quot;http://localhost:8081&quot;)<br>                .version(&quot;1.0.0&quot;)<br>                .description(&quot;Provides B2B and B2C order information&quot;)<br>                .capabilities(<br>                        new AgentCapabilities.Builder().streaming(false).build()<br>                )<br>                .defaultInputModes(<br>                        List.of(&quot;text&quot;)<br>                )<br>                .defaultOutputModes(<br>                        List.of(&quot;json&quot;, &quot;text&quot;)<br>                )<br>                .protocolVersion(&quot;1.0&quot;)<br>                .skills(List.of(<br>                        new AgentSkill.Builder()<br>                                .id(&quot;b2b-orders&quot;)<br>                                .name(&quot;B2B Orders&quot;)<br>                                .description(&quot;fetches all B2B orders&quot;)<br>                                .tags(List.of(&quot;b2b&quot;, &quot;orders&quot;, &quot;list&quot;))<br>                                .examples(List.of(&quot;Show me all B2B orders&quot;, &quot;List B2B orders&quot;, &quot;Get B2B orders&quot;, &quot;Fetch B2B orders&quot;, &quot;Display B2B orders&quot;))<br>                                .inputModes(List.of(&quot;text&quot;))<br>                                .outputModes(List.of(&quot;json&quot;, &quot;text&quot;))<br>                                .build()<br><br>                ))<br>                .build();<br>    }<br><br>    @PostMapping(&quot;/task&quot;)<br>    public Message handleTask(@RequestBody Message message) {<br>        // Extract plain text task from the incoming A2A message<br>        String task = extractText(message);<br><br>        // Let Ollama + Spring AI decide which @Tool to call<br>        String result = chatClient.prompt()<br>                .user(task)<br>                .call()<br>                .content();<br><br>        // Wrap result into an A2A-compliant agent message<br>        return A2A.toAgentMessage(result);<br>    }<br><br>    private String extractText(Message message) {<br>        if (message.getParts() == null) return &quot;&quot;;<br>        return message.getParts().stream()<br>                .filter(p -&gt; p instanceof TextPart)<br>                .map(p -&gt; ((TextPart) p).getText())<br>                .collect(Collectors.joining(&quot;\n&quot;));<br>    }<br><br>}</pre><h4>Seller Agent</h4><p><strong>Tools class</strong> (As we are using MCP, so I have created two Tools)</p><p><strong>Note</strong> — I have not used any database, but in real you can use any Database.</p><pre>@Service<br>public class SellerAgentTools {<br><br>    List&lt;Seller&gt; sellers = List.of(<br>            new Seller(&quot;1&quot;, &quot;John&quot;, 4.8),<br>            new Seller(&quot;2&quot;, &quot;Jane&quot;, 4.5),<br>            new Seller(&quot;3&quot;, &quot;Mike&quot;, 4.9),<br>            new Seller(&quot;4&quot;, &quot;Emily&quot;, 4.7)<br>    );<br><br>    @Tool(name = &quot;Get Seller By ID&quot;, description = &quot;Returns seller information by seller ID&quot;)<br>    public Seller getSellerById(@ToolParam(description = &quot;The ID of the seller&quot;) String sellerId) {<br>        return sellers.stream()<br>                .filter(seller -&gt; seller.id().equals(sellerId))<br>                .findFirst()<br>                .orElse(null);<br>    }<br><br>    @Tool(name = &quot;Get Seller By Name&quot;, description = &quot;Returns seller information by seller name&quot;)<br>    public Seller getSellerByName(@ToolParam(description = &quot;The name of the seller&quot;) String sellerName) {<br>        return sellers.stream()<br>                .filter(seller -&gt; seller.name().equalsIgnoreCase(sellerName))<br>                .findFirst()<br>                .orElse(null);<br>    }<br><br>    public record Seller(String id, String name, double rating){}<br>}</pre><p><strong>Controller</strong> (Here we have two end points)</p><p><strong><em>/.well-known/agent.json</em></strong><em> — </em>file that describes what an agent can do, its ID, and its API endpoint.</p><p>/<strong><em>task</em></strong> — this handles the User Prompt/Query</p><pre><br>@RestController<br>public class SellerController {<br><br>    private final ChatClient chatClient;<br><br>    public SellerController(ChatClient chatClient) {<br>        this.chatClient = chatClient;<br>    }<br><br><br>    @GetMapping(&quot;/.well-known/agent.json&quot;)<br>    public AgentCard getAgentCard() {<br>        return new AgentCard.Builder()<br>            .name(&quot;seller-agent&quot;)<br>            .url(https://medium.com/&quot;http://localhost:8082&quot;)<br>            .version(&quot;1.0.0&quot;)<br>            .description(&quot;provides seller information&quot;)<br>            .capabilities(<br>                    new AgentCapabilities.Builder().streaming(false).build()<br>            )<br>            .defaultInputModes(<br>                    List.of(&quot;text&quot;)<br>            )<br>            .defaultOutputModes(<br>                    List.of(&quot;json&quot;, &quot;text&quot;)<br>            )<br>            .protocolVersion(&quot;1.0&quot;)<br>            .skills(List.of(<br>                new AgentSkill.Builder()<br>                        .id(&quot;seller-info&quot;)<br>                        .name(&quot;Seller Info By id&quot;)<br>                        .description(&quot;fetches seller information by id&quot;)<br>                        .tags(List.of(&quot;seller&quot;, &quot;info&quot;, &quot;id&quot;, &quot;SellerInformationAgent&quot;))<br>                        .examples(List.of(&quot;Get seller information by id&quot;, &quot;Fetch seller details using id&quot;, &quot;Show seller info for a given id&quot;))<br>                        .inputModes(List.of(&quot;text&quot;))<br>                        .outputModes(List.of(&quot;json&quot;, &quot;text&quot;))<br>                        .build(),<br>                new AgentSkill.Builder()<br>                        .id(&quot;seller-info-by-name&quot;)<br>                        .name(&quot;Seller Info By Name&quot;)<br>                        .description(&quot;fetches seller information by name&quot;)<br>                        .tags(List.of(&quot;seller&quot;, &quot;info&quot;, &quot;name&quot;))<br>                        .examples(List.of(&quot;Get seller information by name&quot;, &quot;Fetch seller details using name&quot;, &quot;Show seller info for a given name&quot;))<br>                        .inputModes(List.of(&quot;text&quot;))<br>                        .outputModes(List.of(&quot;json&quot;, &quot;text&quot;))<br>                        .build()<br><br>            ))<br>            .build();<br>    }<br><br>    @PostMapping(&quot;/task&quot;)<br>    public Message handleTask(@RequestBody Message message) {<br>        // Extract plain text task from the incoming A2A message<br>        String task = extractText(message);<br><br>        // Let Ollama + Spring AI decide which @Tool to call<br>        String result = chatClient.prompt()<br>                .user(task)<br>                .call()<br>                .content();<br><br>        // Wrap result into an A2A-compliant agent message<br>        return A2A.toAgentMessage(result);<br>    }<br><br>    private String extractText(Message message) {<br>        if (message.getParts() == null) return &quot;&quot;;<br>        return message.getParts().stream()<br>                .filter(p -&gt; p instanceof TextPart)<br>                .map(p -&gt; ((TextPart) p).getText())<br>                .collect(Collectors.joining(&quot;\n&quot;));<br>    }<br>}</pre><h4>Seller Agent (Orchestrator)</h4><p>This is the important file of this example</p><ul><li>PostMapping accept user’s Queries/Prompts.</li><li>Fetches all the configured Agents (Check the <a href="https://github.com/kuldeepsingh99/google-a2a/blob/main/parent/parent/src/main/resources/application.yml">application.yml</a> file).</li><li>Based on the user prompt/query LLM will choose the one Agent or both the agents (Check the <a href="https://github.com/kuldeepsingh99/google-a2a/blob/main/parent/parent/src/main/java/com/kuldeep/tech/parent/controller/ParentController.java#L118"><strong>chooseAgentsViaLLM</strong></a> method).</li><li>Call the agents (One or both the agents) on /task endpoint.</li><li>Aggregate the responses with LLM and return the result to the user.</li></ul><p><strong>Note</strong> — based on your need you may need to modify the flow or System Prompts.</p><pre>@PostMapping(&quot;/task&quot;)<br>    public String handleTask(@RequestBody String userQuery) {<br>        // 1️⃣ Fetch all AgentCards<br>        List&lt;AgentCard&gt; agentCards = agentProperties.getAgents().stream()<br>                .map(cfg -&gt; {<br>                    try {<br>                        return A2A.getAgentCard(cfg.getUrl());<br>                    } catch (Exception e) {<br>                        throw new RuntimeException(&quot;Failed to fetch AgentCard from &quot; + cfg.getUrl(), e);<br>                    }<br>                })<br>                .toList();<br><br>        // 2️⃣ Ask LLM which agent(s) to use<br>        List&lt;String&gt; chosenAgentIds = chooseAgentsViaLLM(userQuery, agentCards);<br><br>        if (chosenAgentIds.isEmpty()) {<br>            return &quot;I&#39;m sorry, I can only assist with order and seller related queries.&quot;;<br>        }<br><br>        List&lt;String&gt; responses = new ArrayList&lt;&gt;();<br><br>        Set&lt;String&gt; alreadyCalledAgents = new HashSet&lt;&gt;();<br><br>        for (String agentId : chosenAgentIds) {<br>            if (alreadyCalledAgents.contains(agentId)) continue; // skip duplicates<br>            alreadyCalledAgents.add(agentId);<br><br>            AgentCard card = agentCards.stream()<br>                    .filter(c -&gt; c.name().equals(agentId)) // match by ID<br>                    .findFirst()<br>                    .orElseThrow(() -&gt; new RuntimeException(&quot;Agent not found: &quot; + agentId));<br><br>            Message response = webClient.post()<br>                    .uri(card.url() + &quot;/task&quot;)<br>                    .bodyValue(A2A.toUserMessage(userQuery, UUID.randomUUID().toString()))<br>                    .retrieve()<br>                    .bodyToMono(Message.class)<br>                    .block();<br><br>            if (response != null &amp;&amp; response.getParts() != null &amp;&amp; !response.getParts().isEmpty()) {<br>                var part = response.getParts().get(0);<br>                if (part instanceof TextPart textPart) {<br>                    String text = textPart.getText();<br>                    responses.add(text);<br><br>                    boolean sellerFlag = chosenAgentIds.stream()<br>                            .anyMatch(id -&gt; id.equals(&quot;seller-agent&quot;));<br><br>                    if (agentId.equals(&quot;order-agent&quot;) &amp;&amp; !alreadyCalledAgents.contains(&quot;seller-agent&quot;)<br>                            &amp;&amp; sellerFlag) {<br>                        List&lt;String&gt; sellerIds = extractSellerIds(text);<br>                        for (String sellerId : sellerIds) {<br>                            String sellerResponse = callSellerAgent(sellerId, agentCards, userQuery);<br>                            responses.add(sellerResponse);<br>                            alreadyCalledAgents.add(&quot;seller-agent&quot;); // mark as called<br>                        }<br>                    }<br>                }<br>            }<br>        }<br><br><br>        // 4️⃣ Aggregate with LLM<br>        String aggregationPrompt = &quot;&quot;&quot;<br>        You are the Parent Agent.<br>        Aggregate the following responses into a clear, concise final answer.<br><br>        User query:<br>        %s<br><br>        Child agent responses:<br>        %s<br><br>        Provide the final answer in natural language, without mentioning agents.<br>        &quot;&quot;&quot;.formatted(userQuery, String.join(&quot;\n&quot;, responses));<br><br>        return chatModel.call(aggregationPrompt);<br>    }<br><br><br>    private List&lt;String&gt; chooseAgentsViaLLM(String userQuery, List&lt;AgentCard&gt; agentCards) {<br>        StringBuilder prompt = new StringBuilder();<br>        prompt.append(&quot;You are a task router.\n\n&quot;);<br>        prompt.append(&quot;User query: &quot;).append(userQuery).append(&quot;\n\n&quot;);<br>        prompt.append(&quot;Available agents:\n&quot;);<br>        for (AgentCard card : agentCards) {<br>            prompt.append(&quot;, Name: &quot;).append(card.name())<br>                    .append(&quot;, Skills: &quot;).append(<br>                            card.skills().stream()<br>                                    .map(skill -&gt; skill.name())<br>                                    .collect(Collectors.joining(&quot;, &quot;))<br>                    ).append(&quot;\n&quot;);<br>        }<br><br>        prompt.append(&quot;&quot;&quot;<br>    <br>                Routing rules:<br>                 1. If the query asks about orders (order details, order id, B2B, B2C, order amount, etc.), select ONLY order-agent.<br>                 2. If the query asks about sellers (seller information, seller id, seller rating, seller name, etc.), select ONLY seller-agent.<br>                 3. IMPORTANT:\s<br>                    - &quot;order id&quot; ALWAYS means the ID of an ORDER → use order-agent.<br>                    - &quot;seller id&quot; ALWAYS means the ID of a SELLER → use seller-agent.<br>                    - If the query only says &quot;id&quot; but also mentions &quot;seller&quot;, treat it as seller id → use seller-agent.<br>                 4. If the query explicitly requires BOTH orders AND sellers, then return both agent IDs.<br>                 5. Never include an agent ID unless it is strictly required.<br>                 6. If the query is unrelated to orders or sellers, return an empty response.<br>                 7. ALWAYS return only the exact agent IDs (order-agent or seller-agent).<br>                 8. NEVER include explanations or extra text.<br>                 9. If no agent is relevant, return an empty response.<br>                 10. Return ONLY the agent names, separated by commas if multiple agents are found.<br>                 11. Do NOT return any labels or explanations.<br>            &quot;&quot;&quot;);<br><br>        String llmResponse = chatModel.call(prompt.toString());<br>        if (llmResponse == null || llmResponse.isBlank()) return Collections.emptyList();<br><br>        return Arrays.stream(llmResponse.split(&quot;,&quot;))<br>                .map(String::trim)<br>                .filter(s -&gt; !s.isEmpty())<br>                .toList();<br>    }<br><br><br>    private List&lt;String&gt; extractSellerIds(String orderResponse) {<br>        List&lt;String&gt; sellerIds = new ArrayList&lt;&gt;();<br><br>        Matcher matcher = Pattern.compile(&quot;Seller ID:\\s*(\\d+)&quot;).matcher(orderResponse);<br>        while (matcher.find()) {<br>            sellerIds.add(matcher.group(1));<br>        }<br><br>        return sellerIds.stream().distinct().toList();<br>    }<br><br><br>    private String callSellerAgent(String sellerId, List&lt;AgentCard&gt; agentCards, String originalUserQuery) {<br>        AgentCard sellerCard = agentCards.stream()<br>                .filter(c -&gt; c.name().equals(&quot;seller-agent&quot;))<br>                .findFirst()<br>                .orElseThrow(() -&gt; new RuntimeException(&quot;Seller agent not found&quot;));<br><br>        String sellerTask = &quot;Returns seller information by seller ID &quot; + sellerId;<br><br>        Message response = webClient.post()<br>                .uri(sellerCard.url() + &quot;/task&quot;)<br>                .bodyValue(A2A.toUserMessage(sellerTask, UUID.randomUUID().toString()))<br>                .retrieve()<br>                .bodyToMono(Message.class)<br>                .block();<br><br>        if (response != null &amp;&amp; response.getParts() != null &amp;&amp; !response.getParts().isEmpty()) {<br>            var part = response.getParts().get(0);<br>            if (part instanceof TextPart textPart) {<br>                return textPart.getText();<br>            }<br>        }<br>        return &quot;&quot;;<br>    }<br>}</pre><h3>🚀 Testing with Prompts</h3><p>Run all the three projects and execute the Parent<strong> /task </strong>endpoint.</p><p><strong><em>Note</em></strong> — If you observe the response on the below screenshot, if we ask only for Order Information, it&#39;s returning only order related response. Similarly, if we ask about seller, the response is only about seller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DeL1wXZLXuQp-TkqtOBFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYGZk36Ziv6XwC4CfosiGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol3npJb_KhjnoFPZzLh6dA.png" /></figure><h3>⚠️ Common Mistakes &amp; How to Avoid Them</h3><p><strong>🚨 Converting Existing Micro services vs. Building New A2A Compliant Agents</strong></p><p><strong>Option 1: Converting Existing Micro services</strong></p><ul><li>You already have stable, domain-specific microservices (<em>order-service</em>, <em>seller-service</em>) with well-defined APIs and you don’t want to rebuild business logic.</li><li><strong>Wrap</strong> your service in an <strong>A2A-compliant agent layer.</strong></li><li>Add an agent.json (AgentCard) describing skills, inputs/outputs, and examples.</li><li>Expose an endpoint like /task that accepts/returns A2A Messages.</li></ul><p>This is the fastest way to join the A2A ecosystem without rewriting your services.</p><p>✅ Pros</p><ul><li><strong>Fast adoption</strong>: Wrap and expose your existing services quickly.</li><li><strong>Low risk</strong>: No need to rewrite stable services.</li><li><strong>Incremental migration</strong>: You can A2A enable services one by one.</li><li><strong>Reuse existing logic</strong>: Keeps your current APIs and business rules intact.</li></ul><p>⛔ Cons</p><ul><li><strong>Extra adapter layer</strong>: You have to maintain code between A2A and your native API.</li><li><strong>Legacy </strong>: If the service design is complicated, it will be difficult.</li></ul><p><strong>Option 2: Building New A2A-Compliant Agents</strong></p><p>When you build new services, or decide to rewrite old ones, it is better to <strong>make them A2A compliant</strong> from the start.</p><ul><li>Instead of exposing only REST endpoints like /orders or /sellers/{id}, the service directly speaks the <strong>A2A Message schema</strong>.</li><li>Define <strong>AgentCards</strong> before you code.</li><li>Keep each agent <strong>focused on one domain </strong>(Orders, Sellers, Payments)</li></ul><p>✅ <strong>Pros</strong></p><ul><li><strong>Clean architecture</strong>: Service is designed for A2A communication.</li><li><strong>Full protocol support</strong>: Easier to use discovery, delegation, streaming, etc.</li><li><strong>Future proof</strong>: Less tech debt since no adapters or translation layer required.</li></ul><p>⛔ <strong>Cons</strong></p><ul><li><strong>Higher upfront cost</strong>: Requires rewriting services.</li><li><strong>Migration pain</strong>: Risky if you try to replace large legacy systems all at once.</li><li><strong>Slower adoption</strong>: You cannot enable A2A everything at once.</li></ul><p>👉 That’s why many teams pick a <strong>hybrid approach</strong>:</p><ul><li>Wrap existing microservices (Option 1) for quick adoption.</li><li>Build new or rewritten services (Option 2) as <strong>native A2A agents</strong> for the long run.</li></ul><p><strong>🚨All in one Agent</strong></p><ul><li><strong>Mistake:</strong> Putting many unrelated jobs into one agent (like mixing orders, sellers, and summaries).</li><li><strong>Conclusion/Fix:</strong> Keep it simple — one agent, one job. If we have order-microservice then in this service we can keep tools related to orders ex. <strong>Search Order by Id</strong>, <strong>Search Order by Amount etc. </strong>We should divide the agents by Entity like Order, Seller, Customer, payments etc.</li></ul><p><strong>🚨Overlapping vocabularies</strong></p><ul><li><strong>Mistake:</strong> Two agents both react to similar words (“id”, “details”, “info”), so routing Issues.</li><li><strong>Conclusion/Fix:</strong> Use <strong>domain-specific terms</strong> in skills &amp; examples (“order_id”, “seller_id”). Here we need handle this at two Levels.</li><li>✅ First selecting the right Agent or Agents based on Prompt. So in this case we should give correct name skills tags example in the agent card, and these terms will be the input for LLM to select the right Agent.</li><li>✅ Second give proper tool name in the Agents. Ex. of good tools names “<strong>return order by id</strong>”, “<strong>returns order by name</strong>” etc. Name and description should be proper so that LLM can fins the right tool.</li><li>✅ Ex. of bad tool name “<strong>Return order by id</strong>”, “<strong>Return order by id and name</strong>” — here LLM might get confuse, but its totally based on the LLM model that we are going to use.</li></ul><p><strong>🚨Difficult to understand agents</strong></p><ul><li><strong>Mistake:</strong> The AgentCard does not explain clearly what the agent does. For example, a skill just says <em>“</em><strong><em>manage orders</em></strong><em>”</em> or <em>“</em><strong><em>get info</em></strong><em>”</em>. That is too generic, nobody knows what inputs it expects or what output it gives.</li><li><strong>Conclusion/Fix:</strong> Be specific and clear. Write AgentCards so that both humans and other agents know exactly what to expect.</li></ul><p>✅ Example of a good AgentCard:</p><ul><li><strong>id:</strong> list-b2c-orders — “Return all B2C orders as JSON.”</li><li><strong>id:</strong> get-seller-by-id — “Input: seller_id. Output: seller record as JSON.”</li></ul><p><strong>🚨 LLM Routing Issues</strong></p><ul><li><strong>Mistake:</strong> The LLM sends the same query to multiple agents, even when only one is needed. Example: A query about <em>“seller by id”</em> gets sent to both <strong>order-agent</strong> and <strong>seller-agent</strong>.</li><li><strong>Fix:</strong> Add <strong>clear rules</strong>:</li><li>✅ In the system prompt, tell the LLM: <em>“Pick only one agent unless the user explicitly asks for both.”</em></li></ul><p><strong>🚨 Letting the LLM parse structured fields</strong></p><ul><li><strong>Mistake:</strong> Asking the LLM to extract IDs or numbers from text. Example: From Seller IDs: 2, 3, the LLM returned 23 instead of 2,3.</li><li><strong>Fix:</strong> Don’t make the LLM do data parsing. Use <strong>regex or JSON parsing</strong> for IDs, dates, and amounts.</li></ul><p>🏆 So these are the few learning or key takeaways which i want to share so that we can design Agents.</p><h3>🚀Conclusion</h3><p>By providing a common language for agent discovery, communication, and delegation, it makes multi-agent systems <strong>modular and future-proof</strong>.</p><p>In our example with a <strong>Parent, Order, </strong>and<strong> Seller Agent</strong>, we saw how A2A allows:</p><ul><li>Seamless task routing based on intent.</li><li>Chaining of agents (order → seller) without custom glue code.</li><li>Clear aggregation of results into one final response for the user.</li></ul><p>This pattern can easily extend to more complex systems — finance, healthcare, logistics, or any domain where multiple AI services need to collaborate.</p><p>🔗 <a href="https://github.com/kuldeepsingh99/google-a2a">GitHub Code Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61a4ef7c51a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-f61a4ef7c51a">A practical guide to building Multi-Agents AI Systems with A2A</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation (RAG) With Spring AI]]></title>
            <link>https://medium.com/manomano-tech/retrieval-augmented-generation-rag-with-spring-ai-89d29d9be9ed?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d29d9be9ed</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 12:15:22 GMT</pubDate>
            <atom:updated>2025-06-20T12:15:22.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ61r3_WDM6F-PqRp3t9RQ.jpeg" /></figure><p>In this blog, we will explore <strong>Retrieval-Augmented Generation</strong> (RAG), understand why it’s needed, and conclude with a hands-on tutorial using two different contexts.</p><p>Using large language models (LLMs) can be tricky because they sometimes don’t know enough about certain topics, make mistakes, or even make things up.</p><p><strong>Retrieval-Augmented Generation</strong> (RAG) helps fix these problems by giving the model extra information from outside sources like <strong>databases or websites.</strong> Here’s how it works, when you ask a question, RAG first looks for helpful documents related to your question. It then adds those documents to your original question and sends everything to the language model. This way, the model can give a better and more accurate answer.</p><p><strong>Retrieval — </strong>Retrieval is the process of retrieving highly contextual data from a given source</p><p><strong>Augmentation — </strong>Augmentation is the process of enriching the input to the LLM with the retrieved contextual databases</p><p><strong>Generation — </strong>Generation is the process of converting retrieved information into a coherent text that will form the final output of the model</p><h4><strong>RAG Architecture</strong></h4><p>This is the typical architecture of RAG</p><p>LLM fetches data from data Store and process the Query and gives the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*vZAZdCy5GSCtcZwEC1y9FQ.jpeg" /></figure><h4><strong>This is how Spring AI works with RAG</strong></h4><ul><li>Spring AI fetched data from any external data source it can any like for ex reading file S3 bucket, API source.</li><li>Spring AI converts the data to documents and store it into Vector Store <strong>(We can choose any type of vector DB, more information </strong><a href="https://docs.spring.io/spring-ai/reference/api/vectordbs.html"><strong>here</strong></a><strong>)</strong></li><li>When user gives a prompt or ask something to LLM, 1st Spring AI fetches similar document from Vector DB and then User Query is Augmented with fetched document along with System Message and prompt is created and sent to LLM</li><li>LLM processes the promt and finally gives the response</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*8LxvvMguvtLurrq-qtIHEw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*c2zmG80vrvuPsLakLznD_g.jpeg" /></figure><h4>Implement RAG With Spring AI and PGVector DB</h4><h4>Prerequisites</h4><ul><li>For this example i am using <a href="https://ollama.com/">ollama</a>, so ollama must be running on your machine</li><li>I am using <a href="https://docs.spring.io/spring-ai/reference/api/vectordbs/pgvector.html">PGVector</a> DB (<a href="https://github.com/pgvector/pgvector">PGvector</a> is an open-source extension for PostgreSQL that enables storing and searching over machine learning-generated embeddings)</li></ul><h3>RAG with Spring AI</h3><p>Code for this tutorial is <a href="https://github.com/kuldeepsingh99/spring-ai-with-rag">here</a></p><p>I have created the project in Java and used Version 21</p><p><strong>Use Case</strong>: Chatbot for a Car Service Company and Car Rental Company</p><p>Since the LLM (ollama in this example) wasn’t trained on this specific data, the chatbot cannot rely solely on the pre-trained model to deliver an accurate answer.</p><h4>👉 Step 1 — Create PGVector DB</h4><p>Run <a href="https://github.com/kuldeepsingh99/spring-ai-with-rag/blob/main/docker-compose.yaml"><strong><em>docker-compose.yml</em></strong> </a>file to create PGVector Database, it will create the necessary extension and create the table</p><p><a href="https://github.com/kuldeepsingh99/spring-ai-with-rag/blob/main/Dockerfile.pgvector">Dockerfile.pgvector</a>, this is required to install the necessary extension.</p><p><strong>Note</strong> — it’s a postgress SQL DB but with pgvector plugin, so we need this file</p><pre># Dockerfile.pgvector<br>FROM postgres:13<br><br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y postgresql-server-dev-13 build-essential git &amp;&amp; \<br>    git clone --depth 1 https://github.com/pgvector/pgvector.git /pgvector &amp;&amp; \<br>    cd /pgvector &amp;&amp; make &amp;&amp; make install &amp;&amp; \<br>    rm -rf /pgvector &amp;&amp; \<br>    apt-get remove --purge -y git build-essential &amp;&amp; \<br>    apt-get autoremove -y &amp;&amp; apt-get clean</pre><pre>CREATE EXTENSION IF NOT EXISTS vector;<br>CREATE EXTENSION IF NOT EXISTS hstore;<br>CREATE EXTENSION IF NOT EXISTS &quot;uuid-ossp&quot;;<br><br>CREATE TABLE IF NOT EXISTS vector_store (<br>    id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,<br>    content text,<br>    metadata json,<br>    embedding vector(3072)<br>    );</pre><h4>👉 Step 2 — Run Ollama locally</h4><p>Download <strong>O</strong><a href="https://ollama.com/"><strong>llama</strong></a> and run any <a href="https://ollama.com/search"><strong>model</strong></a> as per your machine capacity</p><h4>🚀 Files &amp; Dependencies</h4><p>💡<strong><em>build.gradle</em></strong></p><pre>plugins {<br> id &#39;java&#39;<br> id &#39;org.springframework.boot&#39; version &#39;3.5.0&#39;<br> id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.kuldeep&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br> toolchain {<br>  languageVersion = JavaLanguageVersion.of(21)<br> }<br>}<br><br>repositories {<br> mavenCentral()<br>}<br><br>ext {<br> set(&#39;springAiVersion&#39;, &quot;1.0.0&quot;)<br>}<br><br>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br> implementation &#39;org.springframework.ai:spring-ai-starter-model-ollama&#39;<br> implementation &#39;org.springframework.ai:spring-ai-spring-boot-docker-compose&#39;<br> implementation &#39;org.springframework.ai:spring-ai-advisors-vector-store&#39;<br> implementation &#39;org.liquibase:liquibase-core&#39;<br> implementation &#39;org.jsoup:jsoup:1.17.2&#39;<br> implementation &#39;org.springframework.ai:spring-ai-starter-vector-store-pgvector&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br> testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>dependencyManagement {<br> imports {<br>  mavenBom &quot;org.springframework.ai:spring-ai-bom:${springAiVersion}&quot;<br> }<br>}<br><br>tasks.named(&#39;test&#39;) {<br> useJUnitPlatform()<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li><strong><em>“spring-ai-starter-model-ollama”</em></strong><em> </em>to connect ollama LLM</li><li>“<strong><em>spring-ai-advisors-vector-store</em></strong>” and “<strong><em>spring-ai-starter-vector-store-pgvector</em></strong>” this is the dependency that stores documents in PGVector DB</li></ul><p>💡<strong><em>application.yml</em></strong></p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5438/pgvector<br>    username: pguser<br>    password: pgpassword<br><br>  liquibase:<br>    change-log: classpath:db/changelog/changelog-master.xml<br>    enabled: true<br><br>  ai:<br>    ollama:<br>      embedding:<br>        model: llama3.2<br>        options:<br>          model: llama3.2:latest<br>        enabled: true<br>      chat:<br>        model: llama3.2<br>        options:<br>          model: llama3.2:latest<br>  vectorstore:<br>    pgvector:<br>    index-type: HNSW<br>    distance-type: COSINE_DISTANCE<br>    dimensions: 3072<br>    max-document-batch-size: 10000<br><br><br>server:<br>  port: 9191</pre><p>👉 <strong>Explanation</strong></p><ul><li>Normal JPA configuration to connect PG Vector DB</li><li>Spring AI Configuration for Ollama</li><li>PG Vector configuration, more information <a href="https://docs.spring.io/spring-ai/reference/api/vectordbs/pgvector.html">here</a></li></ul><p>💡<strong><em>RagConfig</em></strong></p><pre><br>@Service<br>public class RagConfig {<br><br>    private final Logger logger = LoggerFactory.getLogger(RagConfig.class);<br><br><br>    @Autowired<br>    VectorStore vectorStore;<br><br>    private static final String MARKER_PREFIX = &quot;__MARKER__:&quot;;<br><br>    @PostConstruct<br>    public void loadAllTxtFiles() {<br>        try {<br>            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();<br>            Resource[] resources = resolver.getResources(&quot;classpath:data/*.txt&quot;);<br><br>            for (Resource resource : resources) {<br>                String filename = Objects.requireNonNull(resource.getFilename());<br>                String tag = filename.replace(&quot;.txt&quot;, &quot;&quot;);<br><br>                if (isTagAlreadyLoaded(tag)) {<br>                    logger.info(&quot;[&quot; + tag + &quot;] already loaded. Skipping.&quot;);<br>                    continue;<br>                }<br><br>                // 1. Read file and convert to documents<br>                TextReader textReader = new TextReader(resource);<br>                List&lt;Document&gt; rawDocs = textReader.get();<br><br>                // 2. Split documents into chunks<br>                List&lt;Document&gt; splitDocs = new TokenTextSplitter().apply(rawDocs);<br><br>                // 3. Add metadata tag to each doc<br>                List&lt;Document&gt; taggedDocs = splitDocs.stream()<br>                        .map(doc -&gt; new Document(doc.getText(), Map.of(&quot;source&quot;, tag)))<br>                        .collect(Collectors.toList());<br><br>                // 4. Add a marker doc to identify this file was loaded<br>                taggedDocs.add(new Document(MARKER_PREFIX + tag, Map.of(&quot;source&quot;, tag, &quot;type&quot;, &quot;marker&quot;)));<br><br>                // 5. Save to vector store<br>                vectorStore.add(taggedDocs);<br>                logger.info(&quot;[&quot; + tag + &quot;] Loaded &quot; + taggedDocs.size() + &quot; documents.&quot;);<br>            }<br><br>        } catch (IOException e) {<br>            throw new RuntimeException(&quot;Failed to load data files&quot;, e);<br>        }<br>    }<br><br>    private boolean isTagAlreadyLoaded(String tag) {<br>        try {<br>            List&lt;Document&gt; results = vectorStore.similaritySearch(SearchRequest.builder()<br>                    .query(MARKER_PREFIX + tag)<br>                    .topK(1)<br>                    .build());<br><br>            return results.stream()<br>                    .anyMatch(doc -&gt; doc.getText().equalsIgnoreCase(MARKER_PREFIX + tag));<br>        } catch (Exception e) {<br>            logger.error(&quot;Error checking if tag already loaded [&quot; + tag + &quot;]: &quot; + e.getMessage());<br>            return false;<br>        }<br>    }<br>}</pre><p><strong>Explanation</strong></p><ul><li>This class reads all the <strong>txt</strong> file inside <strong>resources/data</strong> folder and converts it into document and stores it into PGVector DB</li></ul><p><strong>Note</strong>:- <em>this is just an example of how to load the data to Vector DB, as per the requirements you can modify the logic to load the data to vector based during server startup or via any API call.</em></p><p>💡<strong><em>Controller</em></strong></p><pre><br><br>@RestController<br>@RequestMapping(&quot;/chat&quot;)<br>public class ChatCarServiceController {<br><br>    private final OllamaChatModel chatModel;<br>    private final ChatClient chatClient;<br>    private final VectorStore vectorStore;<br><br>    public ChatCarServiceController(OllamaChatModel ollamaChatModel, VectorStore vectorStore, ChatClient.Builder chatClient) {<br>        this.vectorStore = vectorStore;<br>        this.chatModel = ollamaChatModel;<br>        this.chatClient = chatClient.build();<br>    }<br><br>    @GetMapping(&quot;/chat-without-advisor&quot;)<br>    public String chatWithRAG(@RequestParam(&quot;message&quot;) String message) {<br>        String systemMessageString = &quot;&quot;&quot;<br>            You are a helpful assistant who answers questions about the Car Services with Type af Service Offered wit Prices.<br>            <br>            * Identify customer queries related to Wiz Auto Car Service.<br>            * respond queries related to car services and prices.<br>            * Refer to the SERVICE section to provide accurate answers. <br>            * If the answer is found, respond clearly and accurately, quoting the relevant section or clause if necessary. <br>            * If the information is not available in the Car Service Terms &amp; Conditions, respond by directing the customer to send an email to the provided contact for further assistance.<br><br>            SERVICE:<br>            {svc}<br>            &quot;&quot;&quot;;<br><br>        Message userMessage = new UserMessage(message);<br><br>        List&lt;Document&gt; similarDocuments = vectorStore.similaritySearch(message);<br>        String tncString = similarDocuments.stream()<br>                .map(Document::getFormattedContent)<br>                .collect(Collectors.joining(&quot;\n&quot;));<br><br>        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemMessageString);<br>        Message systemMessage = systemPromptTemplate.createMessage(Map.of(&quot;svc&quot;, tncString));<br><br>        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));<br><br>        ChatResponse chatResponse = chatModel.call(prompt);<br>        return &quot;Response: &quot; + chatResponse.getResult().getOutput().getText();<br>    }<br><br>    @GetMapping(&quot;/with-rag-advisor&quot;)<br>    public String chatWithRAGAdvisor(@RequestParam(&quot;message&quot;) String message) {<br>        String systemMessageString = &quot;&quot;&quot;<br>            You are a helpful assistant who answers questions about the Car Services with Type af Service Offered with Prices.<br>            <br>            * Identify customer queries related to Wiz Auto Car Service.<br>            * respond queries related to car services and prices.<br>            * Refer to the Car Service Terms &amp; Conditions to provide accurate answers. <br>            * If the answer is found in the Terms &amp; Conditions, respond clearly and accurately, quoting the relevant section or clause if necessary. <br>            * If the information is not available in the Car Service Terms &amp; Conditions, respond by directing the customer to send an email to the provided contact for further assistance.<br><br>            &quot;&quot;&quot;;<br><br>        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemMessageString);<br><br><br>        ChatResponse chatResponse = ChatClient.builder(chatModel).build()<br>                .prompt(systemPromptTemplate.create())<br>                .advisors(new QuestionAnswerAdvisor(vectorStore))<br>                .user(message)<br>                .call()<br>                .chatResponse();<br><br>        return &quot;Response: &quot; + chatResponse.getResult().getOutput().getText();<br>    }<br>}</pre><p><strong>Explanation</strong></p><ul><li>Here i have explained two ways to search</li><li><strong>Option 1</strong> is with vector Store API. The contextual data is retrieved from the vector store using a similarity search of the user’s question and then, that content is added to the placeholder in the System Message and passed to the LLM.</li><li><strong>Option 2</strong> is with using the Advisor API, more information on advisors <a href="https://docs.spring.io/spring-ai/reference/api/advisors.html">here</a>. Spring AI provides an Advisor API to simplify the RAG implementation. When using the Advisor API, the System Message (Prompt) does not need to be parameterized. The contextual data will automatically get appended to the System Message.</li></ul><p>💡<strong><em>Context files</em></strong></p><p>For this blog, I’ve created two files — one detailing the various services offered by a car service company, and the other focused on a car rental service.</p><p>You can check the files <a href="https://github.com/kuldeepsingh99/spring-ai-with-rag/tree/main/src/main/resources/data">here</a></p><h3>Testing</h3><p><strong><em>Question — I need a car service, what the service type offered, give me details about services with price and also tell me how do i book</em></strong></p><p><strong><em>Response</em></strong></p><pre>Response: We appreciate your interest in using our Car Service with Wiz Auto. Below are the types of services we offer, their prices, and a step-by-step guide on how to book:<br><br>**Services Offered:**<br><br>1. **General Service:** This includes:<br> * Engine Oil Replaced<br> * Oil Filter Replaced<br> * Air Filter Cleaning<br> * Coolant - Top up<br> * Brake Oil - Top up<br> * Battery Water Top up<br> * Wiper Fluid Top Up<br> * Front Brake Pad Service<br> * Rear Brake Shoes Service<br> * Caliper Greasing<br> * AC Cooling Check-Up<br> * Heater/Spark Plugs-Check up<br> * Interior Vacuuming<br> * Water Washing (conditional)<br> * Complete Electrical Check up<br><br>Price: ₹2999<br><br>2. **AC Service:** This includes:<br> * AC Gas Top-up<br> * AC Filter Cleaning<br> * AC Cooling Check<br> * Compressor &amp; Condenser Inspection<br> * Leak Test<br> * Labour Included<br><br>Price: ₹999<br><br>3. **Comprehensive Service:** This includes all the services listed under General Service, plus:<br> * Suspension Lubrication<br> * Fuel Filter Check up<br> * Tyre Rotation<br><br>Price: ₹3599<br><br>4. **Painting:** This includes:<br> * Complete body solid color painting<br> * Primer coat<br> * Base coat<br> * Clear coat<br> * Paint finish with gloss and anti-rust protection<br> * Labour included<br><br>Price: ₹35,999<br><br>5. **Washing:** This includes:<br> * Exterior Hand Wash<br> * Interior Vacuuming<br> * Dashboard Cleaning<br> * Glass Cleaning<br> * Tyre Dressing<br> * Wheel Arch Cleaning<br> * All Labour Included<br><br>Price: ₹499<br><br>**Booking a Service:**<br><br>To book a service with our Car Service, please follow these steps:<br><br>1. Visit our website or contact us via phone or email.<br>2. Select the type of service you require (General Service, AC Service, Comprehensive Service, Painting or Washing).<br>3. Choose the make and model of your vehicle from the provided list.<br>4. Review the pricing for the selected service and vehicle.<br>5. Provide your contact information and preferred date and time for the service.<br>6. Confirm your reservation by making the required payment.<br>7. You will receive a confirmation of your booking via email or phone.<br><br>**Additional Tips:**<br><br>* Please ensure your vehicle is available at the agreed location and time on the day of the service.<br>* If you have any questions about our services, please don&#39;t hesitate to contact us.<br>* We accept cash, credit/debit cards, and online payments.<br><br>I hope this information helps! If you have any further questions or need assistance with booking a service, please feel free to ask.</pre><p><strong><em>Question 2 </em></strong><em>— i want to rent a Car for 6 days how much will be the total cost and tell me what are the options do i have ?</em></p><p><strong><em>Response</em></strong></p><pre>Response: Welcome to ola Auto Car Rental! I&#39;d be happy to help you with your car rental needs.<br><br>You&#39;ve decided to rent a car for 6 days. Based on our pricing, here are the options available to you:<br><br>**Economy Car: ₹1000 per day**<br>Total Cost for 6 days = ₹1000 x 6 = ₹6000<br><br>**Luxury Car: ₹5000 per day**<br>Total Cost for 6 days = ₹5000 x 6 = ₹30,000<br><br>**SUV: ₹3000 per day**<br>Total Cost for 6 days = ₹3000 x 6 = ₹18,000<br><br>Please note that these prices do not include any additional fees or taxes.<br><br>If you&#39;d like to book one of these options, please let me know which type of car you prefer and I&#39;ll guide you through the booking process.</pre><h3>Conclusion</h3><p>Spring AI, particularly the Advisor API, offers a streamlined approach to implementing the RAG (Retrieval-Augmented Generation) technique. The Advisor API supports various customization, and an incubating feature introduces support for the Modular RAG approach. Future releases aim to build on this foundation, enabling deeper integration of RAG capabilities within Spring applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d29d9be9ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/retrieval-augmented-generation-rag-with-spring-ai-89d29d9be9ed">Retrieval Augmented Generation (RAG) With Spring AI</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto generating MCP Servers from OpenAPI Schemas]]></title>
            <link>https://medium.com/manomano-tech/auto-generating-mcp-servers-from-openapi-schemas-240082e4ca43?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/240082e4ca43</guid>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Mon, 26 May 2025 08:20:08 GMT</pubDate>
            <atom:updated>2025-05-26T09:15:18.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgD1vQnYtRRGY_9OL-BzAg.jpeg" /></figure><p>In this blog, I will explain you how to generate an <strong>MCP Server</strong> using an OpenAPI JSON file.</p><p>With the help of <strong>Postman</strong>, we can easily turn this API definition into a working <strong>MCP server</strong> and even test it directly from Postman.</p><p>Once the server is up and running, We will check how you can connect a <strong>Claude desktop client</strong> to the MCP server. This is useful for local testing and integration with tools that support MCP.</p><p>No advanced coding is needed, just some basic setup and configuration.</p><h4>🚀Step 1 — Create a Public Workspace in Postman</h4><figure><img alt="Postman" src="https://cdn-images-1.medium.com/max/700/0*hf7z9czyI_rWvseI.png" /></figure><p><strong>Note</strong> — We need to create a public workspace, this is mandatory else postman won’t be able to generate the MCP Server.</p><h4>🚀Step 2 — Import the Openapi JSON</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aRM8NclXUwBuGbrb.png" /></figure><p>Drag drop the file or copy the JSON Content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wAhWEdeBHhrELWt2.png" /></figure><p>Once the open api json is imported we can see all the API’s.</p><p>Here we imported 4 API’s and these are the api’s</p><ol><li><a href="https://api.automovill.com/core/getAllMake"><strong>/core/getAllMake</strong></a> — this api will return all the Car Make.</li></ol><p><a href="https://api.automovill.com/customer/servicelist/getServiceDetails">2. <strong>customer/servicelist/getServiceDetails</strong></a><strong> — </strong>this api returns the types of Service details.</p><p><a href="https://api.automovill.com/customer/servicelist/getnewestimate?city=1&amp;model=1&amp;fuel=1">3. <strong>customer/servicelist/getnewestimate</strong></a><strong> — </strong>this api returns car estimate by city, car model and fuel type.</p><p><a href="https://api.automovill.com/core/getModel?makeId=11">4. <strong>core/getModel</strong></a><strong> — </strong>this api returns all the car model by car make.</p><h4>🚀Step 3— Generating the MCP Server</h4><p><strong>Step 3.1</strong> — Click on <strong>API Network</strong> -&gt; then on <strong>Build API Tools</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oX_v85r8p44T27Bf.png" /></figure><p><strong>Step 3.2</strong> — Search your workspace, if workspace is available then good (Sometime it take time to sync), else click on <strong>Profile</strong> -&gt; then on <strong>settings</strong>.</p><p>This will open the profile in the Browser.</p><blockquote><strong>Note</strong> — In the postman please note down the <strong>workspace Id</strong>, which you can get it by clicking on the <strong>Info Icon </strong>on the right.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hw8DgapPVM8BQN7u.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wplakJsemZkJvCAB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wAhWEdeBHhrELWt2.png" /></figure><p><strong>Step 3.3</strong> — This is the view of the browser, click again on the <strong>Build AI Tools</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BT_olZLiF0c0ZcQY.png" /></figure><p><strong>Step 3.4 — </strong>Now on the URL, append<strong> workspaceId=&lt;YOUR WORKSPACE ID&gt;</strong> and hit enter, this will open your workspace.</p><p>Next select all the API’s for which you want to create MCP Server and Click on <strong>Add Requests</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*i0Jhjd-WmH0wunqs.png" /></figure><p><strong>Step 3.5 — </strong>You can see all the selected API’s and click on <strong>Generate</strong> Button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Ro23ln1fJychBrGz.png" /></figure><p><strong>Step 3.6 — </strong>this will take 20 Sec to 180Sec to generate the server, download the zip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fMQwdm0F3y10Byxs.png" /></figure><p><strong>Step 3.7 — </strong>extract the zip and open it in VS Code.</p><p>Sample code is here in <a href="https://github.com/kuldeepsingh99/mcp-server-postman">GitHub</a>.</p><p>There are 4 tools generated in this project. It’s a good idea to <strong>double-check the URLs and other details</strong>, especially in the tools folder.</p><p>Postman has added some documentation to explain what each tool does. It’s recommended to <strong>improve this documentation</strong>, because <strong>LLMs use these descriptions to understand which tool to use</strong>.</p><p>The main file that starts the server is mcpServer.js.</p><p><strong>Note:</strong> After the initial project is set up, you can always <strong>add more tools later</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Csno4kCf-HUoy7F6.png" /></figure><h4>🚀Step 4 — Testing the MCP Server</h4><p><strong>Step 4.1</strong> In Postman, click on New and create a new mcp request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_4FnYQW3_Th2hQsW.png" /></figure><p><strong>Step 4.2</strong> — MCP Server Path</p><ol><li><strong>Enter the path to </strong><strong>mcpServer.js</strong> in the following format:</li></ol><pre>node C:\Project\ai\mcp-server\mcpServer.js</pre><p><strong>2. Run the command</strong> to start the server.</p><p>3. Once it’s connected successfully, you will <strong>see a list of 4 tools</strong> available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSe8_l2shy-ZDtikGc-8Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gO5FLDLf7a1lEgUt.png" /></figure><p><strong>Step 4.3</strong> — Running the tool</p><ol><li><strong>Select any tool</strong> from the list.</li><li><strong>Run the tool</strong> to see its API response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*znzvcv3GV0qRiZSk.png" /></figure><h4>🚀Step 5 — Connecting MCP Server with Claude Desktop</h4><p><strong>Step 5.1</strong> — Download <a href="https://claude.ai/">Claude AI </a>and create an account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1k4GhK6QQCK1S0oC.png" /></figure><p><strong>Step 5.2- </strong>Go to <strong>Settings</strong> -&gt; then <strong>Developer</strong> and then click on “<strong>Edit Config</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*15b7k6MTrNgrSGO9.png" /></figure><p><strong>Step 5.3</strong> — Editing the config file.</p><ol><li><strong>Edit the configuration file</strong> and specify:</li></ol><ul><li>The <strong>Node.js installation path</strong></li><li>The <strong>MCP Server path</strong> (e.g., C:\Project\ai\mcp-server\mcpServer.js)</li></ul><p><strong>2. Save the file</strong> after making the changes.</p><p><strong>3. Restart the Claude UI</strong> for the changes to take effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kq0TGBDzyJUfGiqv.png" /></figure><p><strong>Note</strong> — this is the <a href="https://github.com/kuldeepsingh99/mcp-server-postman/blob/main/README.md"><strong>readme</strong></a> that Postman has generated, <em>how to integrate MCP Server with Clause Desktop</em>, it has all the instruction.</p><p><strong>Step 5.4</strong>- After restart, clicking on the small Settings icon, we can see that MCP Server has been detected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Op_bdKzlwpJwZowX.png" /></figure><p><strong>Step 5.5 — </strong>Example Prompts</p><ul><li><strong>Prompt:</strong> <em>“Get me all the Make”</em><br> → This triggers the getMake API, which <strong>fetches all car makes</strong>.</li><li><strong>Prompt:</strong> <em>“Can you estimate the car service?”</em><br> → This calls the customer/servicelist/getnewestimate API.<br> → This API requires <strong>three mandatory parameters</strong>:</li><li>City</li><li>Car Model</li><li>Fuel Type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*dpQ_XwYKiGLkV9Z3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WPotKkflhgwDN0vz.png" /></figure><h3><strong>Conclusion</strong></h3><p>Here i have explained connecting Clause AI with MCP Server, but we also use other MCP Client to connect with MCP Server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240082e4ca43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/auto-generating-mcp-servers-from-openapi-schemas-240082e4ca43">Auto generating MCP Servers from OpenAPI Schemas</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own MCP Server With Spring AI]]></title>
            <link>https://medium.com/manomano-tech/build-your-own-mcp-server-with-spring-ai-7c10e76320bb?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c10e76320bb</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Thu, 15 May 2025 09:09:27 GMT</pubDate>
            <atom:updated>2025-05-15T09:09:27.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r45EsC6czvu6SSEPbCo-_g.jpeg" /></figure><p>In this blog, we’ll explore what <strong>MCP</strong> is, how to connect a <strong>Large Language Model (LLM)</strong> to an <strong>MCP Host</strong>, and how Spring AI integrates with both the MCP Server and the MCL Client.</p><p>We will connect to PostgreSQL DB and with AI Prompts we will be able to fetch data from Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*Ep395NTQRTFNaUzeqz23Qw.png" /></figure><h3>📢 Introduction to MCP Servers</h3><p><strong>Anthropic</strong> <a href="https://www.anthropic.com/news/model-context-protocol">released the Model Context Protocol(MCP)</a> in Nov. 2024.</p><p>At present, <strong>MCP</strong> is fully implemented as <a href="https://github.com/modelcontextprotocol/python-sdk">Python SDK</a> , <a href="https://github.com/modelcontextprotocol/typescript-sdk">TypeScript SDK</a> , <a href="https://github.com/modelcontextprotocol/java-sdk">Java SDK</a> , <a href="https://github.com/modelcontextprotocol/kotlin-sdk">Kotlin SDK</a> and <a href="https://github.com/modelcontextprotocol/csharp-sdk">C# SDK</a></p><p>MCP stands for <strong>Model Context Protocol</strong>. It’s an open standard that allows AI systems, like <strong>large language models</strong>, to connect with external tools, data sources, and services. An <strong>MCP server</strong> acts like a bridge or adapter that gives an AI “agent” access to resources such as databases, APIs, or files through a standard interface.</p><p>This means AI models are no longer limited to their training data — they can get live information or perform tasks by talking to <strong>MCP servers </strong>in a shared language. <strong>MCP</strong> servers help connect AI to the real world, making it possible for AI to safely access up-to-date data and carry out actions on behalf of users.</p><h3>🚀Architecture of MCP</h3><p>MCP follows a client-host-server architecture where each host can run multiple client instances.</p><ul><li>This architecture enables users to integrate AI capabilities across applications while maintaining clear security boundaries and isolating concerns.</li><li>Built on JSON-RPC, <strong>MCP</strong> provides a stateful session protocol focused on context exchange and sampling coordination between clients and servers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*jMpTBUtmsBlYxnrr-A5UUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*nWK89pNNaYglmD19q--AwQ.png" /></figure><p>MCP follows a client-server architecture and it has many key components:</p><ul><li><strong>MCP Host</strong>: its the main application that integrates with an LLM and requires it to connect with external data sources</li><li><strong>MCP Clients</strong>: are components that establish and maintain 1:1 connections with MCP servers</li><li><strong>MCP Servers</strong>: components that integrate with external data sources like database, file system, internet and many more</li><li><strong>Tools</strong>: refer to the executable functions/methods that the MCP servers expose for clients to invoke</li></ul><h3>🚀 Project</h3><p>Create two <a href="https://start.spring.io/">Spring boot Project</a> — <strong>mcp-server</strong> and <strong>mcp-client</strong></p><p>I have created the project in Java and used Java 21</p><h4>👉 Step 1 — Create PostgreSQL DB</h4><p>Run <a href="https://github.com/kuldeepsingh99/mcp-server-with-spring-ai/blob/main/mcp/docker/docker-compose.yaml"><strong><em>docker-compose.yml</em></strong></a> file to create postgreSQL Database</p><p><strong>Note</strong> — You don’t need to create table and insert data manually, once you start the <a href="https://github.com/kuldeepsingh99/mcp-server-with-spring-ai/tree/main/mcp/mcp-server/mcp-server"><strong>mcp-server</strong> </a>liquibase will create table and insert’s data in the table.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  db:<br>    image: postgres:13<br>    container_name: postgres_db-ai<br>    restart: always<br>    environment:<br>      POSTGRES_USER: myuser<br>      POSTGRES_PASSWORD: Auto@123<br>      POSTGRES_DB: mydatabase<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    ports:<br>      - &quot;5432:5432&quot;<br><br>volumes:<br>  postgres_data:</pre><h4>👉 Step 2 — Run Ollama locally</h4><p>Download <strong>O</strong><a href="https://ollama.com/"><strong>llama</strong></a> and run any <a href="https://ollama.com/search"><strong>model</strong></a> as per you machine capacity</p><h4>👉 Step 3— Creating an MCP Server</h4><p>Now that we understand MCP at a basic level, let’s start building the MCP architecture in practice.</p><p>We are building an MCP Server that connects to a <strong>PostgreSQL database</strong>, and an MCP Client that connects to the MCP Server. The MCP Client will also need an AI language model. We can use any LLM, but for this example, we will use <a href="https://ollama.com/">Ollama</a>, which runs locally.</p><p>When a user submits a query, the AI assistant connects to an MCP server, which retrieves the appropriate data source and returns the information without additional processing.</p><p>The <strong>Model Context Protocol (MCP)</strong> represents a significant shift in how AI models interact with real-time data. By eliminating the need for intermediate processes like embeddings and vector databases, MCP offers a more efficient, secure, and scalable solution.</p><p>If the future of AI lies in its ability to adapt and provide accurate, real-time information, then MCP could become the new standard for AI model connectivity.</p><h3>🚀 Files &amp; Dependencies</h3><p>💡<strong><em>build.gradle</em></strong></p><pre>plugins {<br> id &#39;java&#39;<br> id &#39;org.springframework.boot&#39; version &#39;3.4.4&#39;<br> id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.portal&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br> toolchain {<br>  languageVersion = JavaLanguageVersion.of(21)<br> }<br>}<br><br>repositories {<br> mavenCentral()<br>}<br><br>ext {<br> set(&#39;springAiVersion&#39;, &quot;1.0.0-M6&quot;)<br>}<br><br>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;<br> implementation &#39;org.springframework.ai:spring-ai-mcp-server-webflux-spring-boot-starter&#39;<br> runtimeOnly &#39;org.postgresql:postgresql&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br> testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>dependencyManagement {<br> imports {<br>  mavenBom &quot;org.springframework.ai:spring-ai-bom:${springAiVersion}&quot;<br> }<br>}<br><br>tasks.named(&#39;test&#39;) {<br> useJUnitPlatform()<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li><strong><em>“spring-boot-starter-data-jpa”</em></strong><em> </em>to connect Database</li><li>”s<strong><em>pring-ai-mcp-server-webflux-spring-boot-starter”</em></strong> to configure as a mcp server</li><li>I am using the milestone version <strong><em>1.0.0-M6</em></strong>, so may be new version will be released.</li></ul><p>💡<strong><em>application.yml</em></strong></p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/mydatabase<br>    username: myuser<br>    password: Auto@123<br>    driver-class-name: org.postgresql.Driver<br><br>  jpa:<br>    hibernate:<br>      ddl-auto: none<br>    show-sql: true<br>    properties:<br>      hibernate:<br>        format_sql: true<br>        dialect: org.hibernate.dialect.PostgreSQLDialect<br>  liquibase:<br>    change-log: classpath:db/changelog/changelog-master.xml<br><br>  ai:<br>    mcp:<br>      server:<br>        name: account-mcp-server<br>        version: 1.0.0<br>        type: SYNC<br>        stdio:<br>          enabled: false<br>        sse-message-endpoint: /mcp/message<br><br><br>logging.level.org.springframework.ai: DEBUG<br><br>server.port: 8060</pre><p>👉 <strong>Explanation</strong></p><ul><li>Normal JPA configuration to connect DB</li><li>Spring AI Configuration ( Name, Version, Type, Stdio and SSE message Endpoint)</li></ul><p>Spring AI Documentation can be found <a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties"><strong>here</strong></a> for detailed explanation</p><p>💡<strong><em>Entity Class</em></strong></p><pre>@Entity<br>@Table(name = &quot;seller_account&quot;)<br>public class SellerAccount {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    @Column(name = &quot;id&quot;, updatable = false)<br>    private Integer id;<br><br>    @Column(name = &quot;name&quot;)<br>    private String name;<br><br>    @Column(name = &quot;owner&quot;)<br>    private String owner;<br><br>    @Column(name = &quot;is_test&quot;)<br>    private Boolean isTest;<br><br>    @Column(name = &quot;type&quot;)<br>    private String type;<br><br>    @Column(name = &quot;status&quot;)<br>    private Integer status;<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li>Entity class for the Database table</li></ul><p>💡<strong><em>Repository Class</em></strong></p><pre>public interface SellerAccountRepository extends JpaRepository&lt;SellerAccount, Integer&gt; {<br><br>    /**<br>     * Search all seller accounts by name<br>     * @param name Seller Account Name<br>     * @return List of Seller Accounts<br>     */<br>    List&lt;SellerAccount&gt; findByName(String name);<br><br>    /**<br>     * Search all seller accounts by owner<br>     * @param owner Seller account owner<br>     * @return List of Seller Accounts<br>     */<br>    List&lt;SellerAccount&gt; findByOwner(String owner);<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li>I have created two method which search accounts by name and owner, we can create as many methods as per or need.</li></ul><p>💡<strong><em>Tools Class</em></strong></p><pre><br>@Service<br>public class SellerAccountTools {<br>    private final SellerAccountRepository sellerAccountRepository;<br><br>    public SellerAccountTools(SellerAccountRepository sellerAccountRepository) {<br>        this.sellerAccountRepository = sellerAccountRepository;<br>    }<br><br>    /**<br>     * Search all seller accounts by name<br>     * @param name Seller Account Name<br>     * @return List of Seller Accounts<br>     */<br>    @Tool(name = &quot;Search Seller account by name&quot;, description = &quot;Find all Seller Accounts by name&quot;)<br>    public String getAccountByName(<br>            @ToolParam(description = &quot;Seller Account Name&quot;) String name) {<br>        List&lt;SellerAccount&gt; accountList = sellerAccountRepository.findByName(name);<br>        StringBuilder result = new StringBuilder();<br>        for (SellerAccount account : accountList) {<br>            result.append(account.toString()).append(&quot;\n&quot;);<br>        }<br>        return result.toString();<br>    }<br><br>    /**<br>     * Search all seller accounts by owner<br>     * @param name Seller account owner<br>     * @return List of Seller Accounts<br>     */<br>    @Tool(name = &quot;Search all Seller account by owner&quot;, description = &quot;Find all Seller Accounts by owner&quot;)<br>    public String getAccountByOwner(<br>            @ToolParam(description = &quot;Seller Account owner&quot;) String owner) {<br>        List&lt;SellerAccount&gt; accountList = sellerAccountRepository.findByOwner(owner);<br>        StringBuilder result = new StringBuilder();<br>        for (SellerAccount account : accountList) {<br>            result.append(account.toString()).append(&quot;\n&quot;);<br>        }<br>        return result.toString();<br>    }<br>}</pre><p>👉 <strong>Explanation</strong></p><p>Tools allows servers to expose tools that can be invoked by language models. The MCP Server Boot Starter provides:</p><ul><li>Change notification support</li><li>Tools are automatically converted to sync/async specifications based on server type</li><li>Automatic tool specification through Spring beans</li></ul><p><strong>More detailed explanation </strong><a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_tools"><strong>here</strong></a></p><p>For this example i have created two tools which will Search from Account Table <strong>by Name</strong> and 2nd method will search from Seller table <strong>by owner</strong>.</p><p>Based on the Prompt AI LLM will automatically pick the correct method, but we need to write name and description properly.</p><p>💡<strong><em>Main Application file</em></strong></p><pre>@SpringBootApplication<br>public class McpServerApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(McpServerApplication.class, args);<br> }<br><br> @Bean<br> public ToolCallbackProvider tools(SellerAccountTools sellerAccountTools) {<br>  return MethodToolCallbackProvider.builder()<br>    .toolObjects(sellerAccountTools)<br>    .build();<br> }<br>}</pre><p>👉 <strong>Explanation</strong> — this auto-configuration will automatically register the tool callbacks as MCP tools. You can have multiple beans producing ToolCallbacks. The auto-configuration will merge them.</p><h3>🚀 Step 4— Creating MCP Client</h3><p>💡<strong><em>build.gradle</em></strong></p><pre>plugins {<br> id &#39;java&#39;<br> id &#39;org.springframework.boot&#39; version &#39;3.4.4&#39;<br> id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.portal&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br> toolchain {<br>  languageVersion = JavaLanguageVersion.of(21)<br> }<br>}<br><br>def springAiVersion = &quot;1.0.0-M6&quot;<br><br>dependencyManagement {<br> imports {<br>  mavenBom(&quot;org.springframework.ai:spring-ai-bom:$springAiVersion&quot;)<br> }<br>}<br><br>repositories {<br> maven {<br>  name = &quot;Central Portal Snapshots&quot;<br>  url = uri(&quot;https://central.sonatype.com/repository/maven-snapshots/&quot;)<br>  mavenContent {<br>   snapshotsOnly()<br>  }<br> }<br> mavenCentral()<br> maven {<br>  name = &quot;Spring Milestones&quot;<br>  url = uri(&quot;https://repo.spring.io/milestone&quot;)<br> }<br> maven {<br>  name = &quot;Spring Snapshots&quot;<br>  url = uri(&quot;https://repo.spring.io/snapshot&quot;)<br>  mavenContent {<br>   snapshotsOnly()<br>  }<br> }<br>}<br><br>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br> implementation &#39;org.springframework.ai:spring-ai-mcp-client-webflux-spring-boot-starter&#39;<br> implementation &#39;org.springframework.ai:spring-ai-ollama-spring-boot-starter&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br> testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br> useJUnitPlatform()<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li>We use “<strong><em>spring-boot-starter-web”</em></strong> to have a simple web app</li><li><strong><em>“spring-ai-mcp-client-webflux-spring-boot-starter”</em></strong> will provides the necessary pieces for use to build a client”</li><li>“<strong><em>spring-ai-ollama-sping-boot-starter</em></strong>” imports the necessary to allow working with ollama, if you use a different LLM you can change starter</li><li>I am using the milestone version <strong><em>1.0.0-M6</em></strong>, so may be new version will be released.</li></ul><p>💡<strong><em>application.properties</em></strong></p><pre>spring.ai.mcp.client.sse.transport-mode=WEBFLUX<br>spring.ai.mcp.client.sse.connections.account-mcp-server.url=http://localhost:8060<br>spring.ai.mcp.client.type=SYNC<br>spring.ai.mcp.client.request-timeout=30s<br>server.port=8040<br>spring.ai.ollama.chat.options.model=llama3.2:3b<br>spring.ai.ollama.chat.model=llama3.2</pre><p>👉 <strong>Explanation</strong></p><ul><li>Transport mode is WEBFLUX</li><li>MCP Server URL is <a href="http://localhost:8060/">http://localhost:8060</a></li><li>Client type is SYNC</li><li>Ollama model llama3.2:3b</li></ul><p><strong>more explanation here in </strong><a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html#_common_properties"><strong>official Spring boot</strong></a><strong> website</strong></p><p>💡<strong><em>Account Controller</em></strong></p><pre><br>@RestController<br>public class AccountController {<br><br>    private final ChatClient chatClient;<br><br><br>    public AccountController(ChatClient.Builder chat, ToolCallbackProvider toolCallbackProvider) {<br>        this.chatClient = chat.defaultTools(toolCallbackProvider)<br>                .build();<br>    }<br><br><br>    @GetMapping(&quot;/account&quot;)<br>    public String getAccount(@RequestParam(&quot;q&quot;) String name) {<br>        PromptTemplate pt = new PromptTemplate(name);<br>        return this.chatClient.prompt(pt.create())<br>                .call()<br>                .content();<br>    }<br>}</pre><p>👉 <strong>Explanation</strong></p><ul><li>Its a rest controller where i am accepting a prompt and connecting to MCP Server</li></ul><p>more explanation here in <a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-overview.html">official Spring boot</a> website</p><p>💡<strong><em>Main Application File</em></strong></p><pre>@SpringBootApplication(exclude = {<br>  org.springframework.ai.autoconfigure.mcp.client.SseHttpClientTransportAutoConfiguration.class<br>})<br>public class McpClientApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(McpClientApplication.class, args);<br> }<br><br>}</pre><p><strong>Note</strong> — I am using Milestone version and their was a bug due to which i have to exclude <em>SseHttpClientTransportAutoConfiguration</em> class</p><h3>🚀<strong>How to Run and test</strong></h3><p>Make sure postgresql is running and DB Table has the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*l71B8zX2HYFd3pukkO0gMw.png" /></figure><p>Run the MCP server and make sure server is started properly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmKT2QtwTXTfiQ2Qm9r8ew.png" /></figure><p>Run the client application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wYql46jOuSruUSdwtYkhQ.png" /></figure><h3>🚀 Testing the Prompts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bci3D6KfgVN9xF5R7bQdnw.png" /></figure><p><strong>Note</strong> — If you observe the <strong><em>SellerAccountTools</em></strong> class, its returning everything in String and MCP Client is formatting it itself and returning it.</p><p>And in the server you can see the logs that Search Account by name method is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EN19cu6gOOsXMzCP1ec4cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdJyQssHxgUpQyOyAkgtUg.png" /></figure><p><strong>Note</strong> — If we ask it to return in JSON Format, its returning in proper format.</p><h3>🚀Conclusion</h3><p>In this demonstration, we created two tools — <strong>Search by Name</strong> and <strong>Search by Owner</strong> — that enable querying a database using simple prompts. These examples showcase how natural language inputs can be effectively used to fetch relevant data.</p><p>This approach is easily extensible. Based on specific requirements or use cases, similar tools can be developed to interact with various datasets or systems.</p><p>Additionally, exploring existing <a href="https://github.com/modelcontextprotocol/servers?tab=readme-ov-file#-reference-servers"><strong>MCP Server</strong></a><strong> </strong>implementations could provide valuable insights and functionality for enhancing our solution.</p><p>GitHub Code link <a href="https://github.com/kuldeepsingh99/mcp-server-with-spring-ai">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c10e76320bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/build-your-own-mcp-server-with-spring-ai-7c10e76320bb">Build Your Own MCP Server With Spring AI</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot-Keycloak Integration Testing with Testcontainers]]></title>
            <link>https://medium.com/manomano-tech/spring-boot-keycloak-integration-testing-with-testcontainers-321488bdaf67?source=rss-05b1cf5c8436------2</link>
            <guid isPermaLink="false">https://medium.com/p/321488bdaf67</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Kuldeep Singh]]></dc:creator>
            <pubDate>Tue, 13 May 2025 20:54:08 GMT</pubDate>
            <atom:updated>2025-05-16T14:32:52.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZ5TDUNBSIhu3PXrbmksrQ.jpeg" /></figure><p>In this blog, we’ll explore how to write <strong>integration tests</strong> for applications that use Keycloak, and how t<strong>estcontainers</strong> can make this easier.</p><h3>🚀 Integration Testing in Software Development: Why it is Essential ?</h3><p>When you’re developing software, testing plays a critical role in making sure everything works as it should.</p><p>While <strong>unit testing</strong> is great for checking small pieces of your code, <strong>integration testing</strong> takes things a step further by examining how those different parts come together.</p><p>This kind of testing is especially essential when your application interacts with external systems, databases, or services like <strong>Keycloak </strong>that handle authentication.</p><p>Imagine you’re setting up an online store. Your site will need to connect smoothly with a payment gateway, manage your inventory database, and authenticate users with a service like Keycloak. Even if each of these components works perfectly on its own, they have to work together effortlessly. That’s where integration testing comes in — to make sure all the systems communicate correctly and that your app runs just how you’d expect in real life.</p><p><strong>Without integration tests, you’d risk:</strong></p><p>✅ Not detecting issues where modules or services don’t work well together.</p><p>✅ Missing bugs that only appear when multiple parts of the application interact (e.g., user authentication, data fetching).</p><p>✅Being unsure if the application is ready to be deployed to production, even if unit tests pass.</p><h3>Unit Test vs Integration Test: What’s the Difference?</h3><h4>🚀Unit Tests:</h4><ul><li>👉 <strong>Focus:</strong> Unit tests test individual components or units of code (like a function, method, or class).</li><li>👉<strong>Purpose:</strong> The goal is to verify that the smallest unit of code works correctly in isolation, without interacting with external systems like databases, APIs, or external services.</li><li>👉 <strong>Example:</strong> Testing if a function that calculates discounts based on user roles works as expected.</li></ul><h4>🚀Integration Tests:</h4><ul><li>👉 <strong>Focus:</strong> Integration tests focus on verifying how various components or services work together in a system.</li><li>👉 <strong>Purpose:</strong> These tests check the interaction between multiple components and ensure they function as expected when integrated (e.g., verifying if a user can log in via Keycloak and access a resource in your application).</li><li>👉 <strong>Example:</strong> Testing if a login request using Keycloak authentication is successfully handled and grants access to the system.</li></ul><p>😎 <strong>Key Difference:</strong> Unit tests are isolated, while integration tests check real-world scenarios where multiple parts of the application work together.</p><h3>🔔 Different Ways to Generate JWTs for your Integration Tests</h3><p>Whenever you’re testing an application that relies on Keycloak or other OAuth2 providers for authentication, you’ll usually need a valid JWT (JSON Web Token) to mimic user login. Here’s a quick explanation of various methods to generate JWTs for testing purposes, along with their advantages and drawbacks.</p><h4>🚀Getting a Real Token from Keycloak via REST API</h4><ul><li>🤗 <strong>How it work</strong>s: You can programmatically grab a token from Keycloak using its REST API by passing in a username and password.</li><li>✅<strong>Pros</strong>: The token you get is authentic and passes validation through Spring Security.</li><li>❌<strong>Cons</strong>: You need to have a Keycloak server up and running, which makes setup a bit more involved.</li></ul><h4>🚀Manually Creating JWTs Using a Private Key</h4><ul><li>🤗<strong>How it works</strong>: You generate and sign the JWT yourself using a private key, along with claims like user roles.</li><li>✅<strong>Pros</strong>: Quick to do and doesn’t depend on Keycloak. Great for CI/CD pipelines.</li><li>❌<strong>Cons</strong>: It skips testing the actual Keycloak flow. Also, managing private keys requires care.</li></ul><h4>🚀Mock JWT Validation with Spring’s MockMvc</h4><ul><li>🤗<strong>How it works</strong>: For unit or integration tests, you can use Spring’s MockMvc to simulate a JWT with predefined roles and authorities.</li><li>✅<strong>Pros</strong>: Fast to set up and doesn’t need real authentication.</li><li>❌<strong>Cons</strong>: Doesn’t actually test JWT validation, just mimics the behavior. Limited to MockMvc-based tests.</li></ul><h4>🚀Using WireMock to Fake Keycloak’s Token Endpoints</h4><ul><li>🤗<strong>How it works</strong>: use WireMock to simulate the token issuance and JWKS endpoints from Keycloak, creating fake JWTs.</li><li>✅<strong>Pros</strong>: No need to run an actual Keycloak server. You control the JWTs and responses.</li><li>❌<strong>Cons</strong>: Still requires some setup to generate and manage valid-looking tokens, which can get complex.</li></ul><h4>🚀Running a Keycloak Server in Docker with Testcontainers</h4><ul><li>🤗<strong>How it works</strong>: Launch a real Keycloak server inside a Docker container specifically for testing.</li><li>✅<strong>Pros</strong>: Tests the complete authentication flow as it would happen in production — real system, real tokens.</li><li>❌<strong>Cons:</strong> Slower test runs compared to mocks and adds a bit of overhead with Docker configurations.</li></ul><p>This list helps you choose the right approach depending on your testing needs, whether you want speed, realism, or simplicity.</p><h3>🔔 Keycloak Testcontainers</h3><p>The <strong>Keycloak Testcontainer</strong> is a really handy tool for running integration tests that involve Keycloak or other authentication systems in your app. Basically, it’s a specialized Testcontainer that lets you spin up a real <strong>Keycloak</strong> server inside Docker whenever you’re testing.</p><p>This approach makes it easier to perform genuine integration tests, closely reflecting how Keycloak would run in a live environment, but without the hassle of manually setting everything up or tearing it down each time.</p><p>👉 Here are some of the main benefits of using Keycloak Testcontainers</p><ul><li>✅ <strong>Realistic Testing</strong> : Because you’re testing against a real Keycloak server (not just a mock), you’re working with the same setup you’d have in production.</li><li>✅ <strong>Automated Setup</strong> : You don’t have to worry about starting or stopping the server yourself — the Testcontainer handles everything automatically for each test run.</li><li>✅ <strong>Isolation</strong>: Running Keycloak in its own container ensures your tests stay separate from your local environment, leading to more consistent results across different setups.</li><li>✅ <strong>Easy Integration:</strong> It plays nicely with your Spring Boot tests and can be set up to start and stop automatically during the test lifecycle, making it straightforward to include in your workflow.</li></ul><h3>🚀Example Code</h3><p>Code is available here in <a href="https://github.com/kuldeepsingh99/keycloak-testcontainers">GitHub</a>.</p><p>This is just an example to demonstrate how to configure <strong>keycloak testcontainers </strong>and perform integration testing. As per your project structure, these classes can be restructured and customized.</p><p>This repository demonstrates how to perform integration testing in a Spring Boot application that uses Keycloak for authentication, by leveraging <strong>Keycloak Testcontainers</strong>.</p><h4>🚀 Explanation of the code</h4><p>We have one controller where endpoints are secured.</p><pre>@RestController<br>@RequestMapping(&quot;/api/v2&quot;)<br>public class TestController {<br><br><br>    @GetMapping(&quot;/customers&quot;)<br>    public String getCustomers() {<br>        return &quot;Hello Customers&quot;;<br>    }<br><br>    @PreAuthorize(&quot;hasAuthority(&#39;products:read&#39;)&quot;)<br>    @GetMapping(&quot;/products&quot;)<br>    public String getProducts() {<br>        return &quot;Hello Products&quot;;<br>    }<br>}</pre><p>Now to perform integration testing we need a valid JWT Token and keycloak must be running because Spring Security will validate the token with keycloak, we have a issuer url in the JWT Token.</p><h4>🚀Keycloak Test Container Initialization</h4><p>Keycloak testcontainers initialization file <a href="https://github.com/kuldeepsingh99/keycloak-testcontainers/blob/main/src/test/java/com/portal/keycloak/init/KeycloakContainerInitializer.java">KeycloakContainerInitializer.java</a>.</p><pre>public class KeycloakContainerInitializer implements ApplicationContextInitializer&lt;ConfigurableApplicationContext&gt; {<br><br>    private static KeycloakContainer keycloakContainer;<br><br>    @Override<br>    public void initialize(ConfigurableApplicationContext applicationContext) {<br>        try {<br>            Properties properties = loadYamlProperties(&quot;application-test.yml&quot;);<br><br>            String keycloakVersion = properties.getProperty(&quot;application.keycloak.version&quot;);<br>            String keycloakAdminUsername = properties.getProperty(&quot;application.keycloak.admin.username&quot;);<br>            String keycloakAdminPassword = properties.getProperty(&quot;application.keycloak.admin.password&quot;);<br>            String keycloakRealmName = properties.getProperty(&quot;application.keycloak.realm.name&quot;);<br><br>            // Start the Keycloak container<br>            keycloakContainer = new KeycloakContainer(&quot;quay.io/keycloak/keycloak:&quot; + keycloakVersion)<br>                    .withEnv(&quot;KEYCLOAK_ADMIN&quot;, keycloakAdminUsername)<br>                    .withEnv(&quot;KEYCLOAK_ADMIN_PASSWORD&quot;, keycloakAdminPassword)<br>                    .withRealmImportFile(&quot;realm/&quot; + keycloakRealmName + &quot;-realm.json&quot;);<br><br>            keycloakContainer.start();<br><br>            // Dynamically set the properties in Spring&#39;s environment<br>            String issuerUri = keycloakContainer.getAuthServerUrl() + &quot;/realms/&quot; + keycloakRealmName;<br><br>            TestPropertyValues.of(<br>                    &quot;keycloak.server.url=&quot; + keycloakContainer.getAuthServerUrl(),<br>                    &quot;spring.security.oauth2.resourceserver.jwt.issuer-uri=&quot; + issuerUri<br>            ).applyTo(applicationContext.getEnvironment());<br><br>        } catch (IOException e) {<br>            throw new RuntimeException(&quot;Failed to load properties from YAML file&quot;, e);<br>        }<br>    }<br><br>    private Properties loadYamlProperties(String yamlFilePath) throws IOException {<br>        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();<br>        yamlPropertiesFactoryBean.setResources(new ClassPathResource(yamlFilePath));<br>        return yamlPropertiesFactoryBean.getObject();<br>    }<br><br>    public static KeycloakContainer getKeycloakContainer() {<br>        return keycloakContainer;<br>    }<br>}</pre><p><strong>Important things to note in this file</strong></p><ul><li>Keycloak testcontainer is initialized.</li><li>We are reading the configuration from <a href="https://github.com/kuldeepsingh99/keycloak-testcontainers/blob/main/src/test/resources/application-test.yml">application-test.yml</a> file like <strong>keycloak version</strong>, <strong>admin credentials</strong>, <strong>realm name </strong>etc. If we have to upgrade the keycloak version, then we have to only update the yml file, we don’t need to change the code.</li><li>We are setting the <strong>issuer uri</strong> dynamically, this is an important property. Service will use this property to discover authorization server and validate JWT Token.</li><li>We are exposing the <strong>KeycloakContainer</strong> to be used in other classes.</li><li><a href="https://github.com/kuldeepsingh99/keycloak-testcontainers/blob/main/src/test/resources/realm/customer-realm.json"><strong>This file</strong></a> contains Realm and Client<strong> </strong>details, which we import during keycloak initialization.</li></ul><h4>🚀Property file</h4><p>In the application test YAML file, most of the configurations required for Keycloak Testcontainer initialization are already defined, but you can customize and add more properties based on your requirements.</p><pre>application:<br>  keycloak:<br>    version: 25.0.2<br>    admin:<br>      username: admin<br>      password: admin@123<br>    realm:<br>      name: customer<br>      client:<br>        id: &quot;department&quot;<br>        secret: &quot;**********&quot;</pre><p>In my case, I have configured the Keycloak version, admin console credentials, realm, and client name.</p><h4>🚀build.grade file</h4><pre>testImplementation &#39;com.github.dasniko:testcontainers-keycloak:3.7.0&#39;</pre><p>This is an important dependency required for Keycloak Testcontainers.</p><h4>🚀Realm and Client Import JSON</h4><p><a href="https://github.com/kuldeepsingh99/keycloak-testcontainers/blob/main/src/test/resources/realm/customer-realm.json">This file</a> contains realm and client details, which are necessary for your microservice to run integration tests.</p><p>👉 The best way to create this file is by exporting it from the Realm settings in the Keycloak administrative interface. It will include all the necessary clients and roles required for your service to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcsmJRtOkmQ9sipHUVmQFQ.png" /></figure><p>👉 Another option is to set up a Keycloak environment using Docker and manually create the realm and client.</p><pre>docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:25.0.2 start-dev</pre><h4>🚀Keycloak Utility class</h4><p>The <a href="https://github.com/kuldeepsingh99/keycloak-testcontainers/blob/main/src/test/java/com/portal/keycloak/KeycloakTestUtils.java"><strong>KeycloakTestUtils</strong></a> class, where I have created few utility methods like <strong>createAccessToken</strong>, <strong>createUser</strong>, <strong>createGroup</strong>, <strong>createClientRole </strong>and <strong>getClientByName</strong>.</p><p>One more point to note here is that to perform an admin operation we need a <strong>Access Token</strong>, So we are generating the access token from master realm, check keycloakClient method.</p><p>As per your requirement you can create methods and play 💥 with keycloak.</p><pre>/**<br>   * Get access token using client credentials<br>   * @param clientId Client ID<br>   * @param clientSecret Client Secret<br>   * @return Access token<br>   */<br>  public String getAccessToken(String clientId, String clientSecret) {<br><br>      String tokenUrl = KeycloakContainerInitializer.getKeycloakContainer().getAuthServerUrl()<br>              + &quot;/realms/customer/protocol/openid-connect/token&quot;;<br><br>      RestTemplate restTemplate = new RestTemplate();<br>      HttpHeaders headers = new HttpHeaders();<br>      headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);<br><br>      MultiValueMap&lt;String, String&gt; form = new LinkedMultiValueMap&lt;&gt;();<br>      form.add(&quot;client_id&quot;, clientId);<br>      form.add(&quot;client_secret&quot;, clientSecret);<br>      form.add(&quot;grant_type&quot;, &quot;client_credentials&quot;);<br><br>      HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; request = new HttpEntity&lt;&gt;(form, headers);<br>      ResponseEntity&lt;Map&gt; response = restTemplate.postForEntity(tokenUrl, request, Map.class);<br><br>      if (response.getStatusCode().is2xxSuccessful()) {<br>          return (String) response.getBody().get(&quot;access_token&quot;);<br>      } else {<br>          throw new RuntimeException(&quot;Failed to obtain access token: &quot; + response);<br>      }<br>  }<br><br>  /**<br>   * Get Keycloak client instance<br>   * @return Keycloak client instance<br>   */<br>  private Keycloak keycloakClient(){<br>      KeycloakContainer keycloakContainer = KeycloakContainerInitializer.getKeycloakContainer();<br><br>      return Keycloak.getInstance(<br>          keycloakContainer.getAuthServerUrl(),<br>          &quot;master&quot;,<br>          keycloakProperties.getAdmin().getUsername(),<br>          keycloakProperties.getAdmin().getPassword(),<br>          &quot;admin-cli&quot;);<br>  }</pre><h4>🚀Test Class</h4><p>We have only one test where we generate <strong>client-credentials</strong> access token and execute the REST Endpoint with valid access token.</p><pre>@Test<br>void testProtectedEndpoint() {<br><br>    String accessToken = keycloakTestUtils.getAccessToken(<br>            keycloakProperties.getRealm().getClient().getId(),<br>            keycloakProperties.getRealm().getClient().getSecret());<br><br>    HttpHeaders headers = new HttpHeaders();<br>    headers.setBearerAuth(accessToken);<br>    HttpEntity&lt;String&gt; entity = new HttpEntity&lt;&gt;(headers);<br><br>    ResponseEntity&lt;String&gt; response = restTemplate.exchange(&quot;/api/v2/products&quot;, HttpMethod.GET, entity, String.class);<br>    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);<br>    assertThat(response.getBody()).isEqualTo(&quot;Hello Products&quot;);<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321488bdaf67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manomano-tech/spring-boot-keycloak-integration-testing-with-testcontainers-321488bdaf67">Spring Boot-Keycloak Integration Testing with Testcontainers</a> was originally published in <a href="https://medium.com/manomano-tech">ManoMano Tech team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>