<?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 Mangesh on Medium]]></title>
        <description><![CDATA[Stories by Mangesh on Medium]]></description>
        <link>https://medium.com/@manpatil1451?source=rss-93b0382f3fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4SDLzVZT_MUfzOUGI6U15g.jpeg</url>
            <title>Stories by Mangesh on Medium</title>
            <link>https://medium.com/@manpatil1451?source=rss-93b0382f3fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:19:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manpatil1451/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[Elasticsearch Under the Hood: Sharding, Routing, and Read/Write Flow]]></title>
            <link>https://medium.com/@manpatil1451/elasticsearch-under-the-hood-sharding-routing-and-read-write-flow-3ba337b090be?source=rss-93b0382f3fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba337b090be</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[internal]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[searchinternals]]></category>
            <dc:creator><![CDATA[Mangesh]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 19:37:46 GMT</pubDate>
            <atom:updated>2026-08-23T19:37:46.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Many enterprise applications use Elasticsearch for search functionality, and Elasticsearch is one of the mature search applications available online. Recently, I’ve been investigating how to upgrade the Elasticsearch version through a rolling upgrade. I actually tried the complete process on my own, but the steps in the playbook I was supposed to write the code for forced me to understand what I was doing and circled me back to the architecture and some of the concepts of Elasticsearch.</p><p>Coming to the point, like Mongo calls the place where some common-format data is stored as <strong>collections</strong>, relational databases call them <strong>tables, and</strong> Elasticsearch calls them <strong>indexes</strong> [I really don’t know the story here, why]. But what comes to my mind as a backend developer is that indexes are the ones that make queries faster for the database, given that you have to create them based on your common query patterns. It’s just a way of telling a database that I will be searching in this pattern most of the time; try to sort or manage the data in this manner.</p><p>That’s a lot of story. I know we are going off-topic, but let’s move forward: an Elasticsearch index is a logical container for the data. But an app like Amazon starts to store the data in one index, which will definitely fill the instance of Elasticsearch. We can increase the Elasticsearch instance to some limit, but the size of your instance will definitely be the bottleneck here. So Elasticsearch shards your data horizontally. How does it share it? So let’s say Elasticsearch has 3–4 indexes; to distribute the data of each index across the nodes, we need to shard the data. So Elasticsearch maintains <strong>primary shards</strong> and some <strong>replica shards</strong>, and one index can have multiple primary shards.</p><p>Let’s go ahead for one index example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tcw7EKlEq-omVBOiVNVDPg.png" /></figure><p>The shard size should be at most 50 GB and 200M documents. You can read more about this here: <a href="https://www.elastic.co/docs/deploy-manage/production-guidance/optimize-performance/size-shards?utm_source=chatgpt.com">Elastic shard sizing guidance</a>. Whenever you are creating the index, you need to ask how large this index is going to be, and depending on that, decide the number of shards for that index. Because you directly can’t manipulate the number of primary shards for your index once it has been created. Yes, there are ways to do it, but we will come to that later.</p><p>Now, for each index, there are multiple primary shards. You might have the doubt: how is this data placed across the Elasticsearch nodes? Each node, rather than having an entire index, will have some of the shards of different indexes. Each node can have some primary shards and some replica shards. A primary shard and its replicas are not allocated to the same node. We can decide the replica count, meaning how many replicas we want for each shard, and we can change it dynamically as well. The elected master node from the cluster, along with Elasticsearch’s shard allocation mechanism, determines on which node a shard will reside.</p><p>Now coming to how your read/write flow path works with this architecture:</p><ol><li>Read Flow:</li></ol><p>So here are two phases: when you search a record from the Elasticsearch, you either search by the docId or any name or query, right?</p><p>Let&#39;s go by the ID first.</p><p>/search/product_ind_2026_08?id = wefwefwlejn124</p><p>What happens when you pass the ID directly in the query?</p><p>Now you have the product index, but that index has multiple primaries and their replicas. How does Elasticsearch know which shard to search this record in?</p><ol><li>Let’s say you have a cluster of 5 ES nodes; this query can go to any of the coordinating nodes</li><li>Once it goes to one of the nodes, we need to find which shard we need to go to</li><li>This is calculated by the hash(routing_key) % number_of_primary_shards, which gives on which shard our data is located.</li><li>The actual formula for getting the shard value is different; this is just for understanding.</li><li>Now we’ve got the shard where our data is located, but we don’t know on which node that shard is placed, right?</li><li>That’s where the cluster state [shard-node allocation information] is important here, and this is available on every node.</li><li>The coordinating node forwards the request to an appropriate copy of that shard (primary or replica), and that node performs the actual lookup.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*9eVUaYumII8npWhLrAlaJg.png" /></figure><p>Now coming to the regular search query on any indexed fields:</p><p>2./search/products_ind_2026_8?q=paneer</p><p>Now we don’t know the actual ID of the product, so we can’t directly find the shard where this product is located, or there can be multiple products named with &#39;paneer&#39;.</p><p>So in such cases:</p><ol><li>Your query goes to any of the co-ordinating nodes.</li><li>So the coordinating node further does this scatter-gather query from either primary or replica shards of that index, for product index, it might search in p0, r1, or r2 [it searches either primary or replica for each shard, not both of the same shard]</li><li>In all of the shards, the paneer is searched in the Lucene index of that shard, and results are returned back to the coordinating node.</li><li>Then all these results are gathered, reduced, and sent to the end user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVMy6B-6c8UgLGSAk4j7vA.png" /></figure><p>At production every 100 ms is counted, and if you want to avoid this scatter-gather query, one optimization Elasticsearch provides is <strong>custom routing</strong>. The routing value can be a value shared by many records, which can reduce your search space. For the above case, we could use it grocery_type_id as the routing value, which can help keep records of the same grocery type on the same shard. Then, when searching for a particular grocery type, we can provide that routing value and avoid searching all shards.</p><p>So with the custom routing, the above search would be just:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*6K7DLg3clrLDDHK19ylACA.png" /></figure><p>One important thing to remember is that <strong>you cannot change the shard placement of existing documents just by changing the routing configuration</strong>. If the existing index was created without this routing strategy, you need to <strong>reindex the data into a new index using the desired routing value</strong>.</p><p>So, if you’re creating a new Elasticsearch index, think carefully about the routing_value. Think of Elasticsearch&#39;s routing value as its equivalent of a shard key: it determines where a document lives. A good routing strategy can dramatically reduce search fan-out, but once documents are indexed, changing the routing strategy means reindexing them. It&#39;s essentially like the <strong>shard key</strong> of your data, so use it wisely, because if you are known with databases and sharding, you know the problems it can bring into developer/product life 🙂</p><ol><li>Write Flow:</li></ol><p>Assume:</p><p>PUT /products_ind_2026_08/_doc/123<br> {<br> “name”: “Paneer”,<br> “grocery_type_id”: 10<br> }</p><ol><li>The request contains the target index and document ID.</li><li>The request can arrive at any eligible Elasticsearch node, which acts as the <strong>coordinating node</strong> for that request.</li><li>That node now finds the correct shards, by hashing the routing_key, if not given anything, by hashing the _id of the document:hash(routing_key) % number_of_primary_shards similar to what we are doing in the write path.</li><li>The coordinating node forwards the write request to the node hosting that primary shard, and the primary processes the write.</li><li>The primary shard replicates the operation to the replica copies of that shard. The primary is responsible for establishing the operation order and coordinating replication to the replicas.</li><li>Once the required acknowledgements are received, the write is considered successful and the response is returned to the client.</li></ol><p>Happy Searching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba337b090be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Product Recommendation Service (HLD)]]></title>
            <link>https://medium.com/@manpatil1451/product-recommendation-service-hld-0ed2f3abcc95?source=rss-93b0382f3fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ed2f3abcc95</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Mangesh]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 19:22:43 GMT</pubDate>
            <atom:updated>2026-06-28T19:22:43.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>FYI: This is a conversational article, so spend time accordingly. It’s just me talking about my experiences. I will soon share the final version of this article.</h3><p>This is my second attempt at this question while learning about HLD. I attempted this question in my Amazon interviews for SDE-II. I failed in the interviews due to my lack of proficiency at that time in this area. This attempt is to learn it, understand it properly, and be explanatory. This will not be a regular article with an information dump or obvious questions. This is an article where I will question my assumptions or add questions the interviewer asked me in the interview.</p><p>The question was to build the high-level design for the product recommendation system for an e-commerce app. I won’t go ahead and say “don’t draw blocks directly&quot; – you already know to collect the functional requirements and non-functional requirements. I moved forward with requirements gathering (FR/NFR).</p><p>I was very doubtful about which requirement should be called FR vs NFR.</p><p>According to my understanding: FR: What does the system do? How will users interact with your service?</p><p>How should the system work?</p><p>For this example, I asked the question, &#39;How<strong> will this be shown on the UI? [1 FR]</strong>, but I was wrong to focus on this at the start because my first job was to show recommendations to the user; I shouldn’t have cared about how it would be consumed on the UI. Conclusion: We wanted a list of recommended products for a given userId.</p><p>My first question would have been: <strong>should these recommendations be personalised or generic? [2 FR]</strong></p><p>→ I asked this question later, and they said, &#39;We want personalised recommendations for each user.&#39;</p><p>My next question was, &#39;How<strong> should we gather these recommendations?&#39; [3 FR—this was crucial]</strong></p><p>→ For this, I started with: we would consider user purchase history, wishlist items, and search history to recommend products of that category.</p><p>The interviewer asked me, “What else?”</p><p>→ I said we would recommend depending on the days, seasons, and festivals; for example, on rainy days we recommend umbrellas [I took this from quick commerce recommendations]. But this was a generic recommendation example, not a personalised recommendation. So the interviewer asked once again and moved forward.</p><p>The correct functional requirement here would be &#39;We will gather the data for recommendations through user search history, purchase history, wishlist items, items the user has rated, items purchased again and again, user click events, and products the user has seen in full detail views (products of such categories).&#39; Then some generic factors like weather/festivals would come later.</p><p>The intent behind the user click events and product detail views is that when buying a laptop, we might view 100 items, click 10 for a detailed view, and add nothing to the cart [we will miss this activity and recommendation because the user has not added anything to the wishlist or cart].</p><p>For a broader purpose, you can tailor your answer accordingly, but these are different facets of gathering personalised recommendations for the user:</p><p><strong>User Signals</strong></p><ul><li><strong>Purchase Intent:</strong> Purchase, Wishlist, Cart</li><li><strong>Browsing Behaviour:</strong> Search, Click, PDP View, Time Spent</li><li><strong>Explicit Feedback:</strong> Ratings, Reviews</li><li><strong>User Profile:</strong> Brand Preference, Category Preference, Price Preference</li><li><strong>Context:</strong> Weather, Festivals, Season, Location</li></ul><p>I moved ahead with the discussion of non-functional requirements:</p><p>For me, I considered these parameters as the points of discussion for NFR:</p><ol><li>Availability</li><li>Scalability</li><li>Consistency</li><li>Fault tolerance</li></ol><p>I missed one major one: <strong>latency. For a product recommendation service that is part of a page load, if it takes a few seconds, it’s still slow.</strong></p><ol><li><strong>Latency:</strong> should be under 500ms</li><li>SLA Downtime per year: 99% ~3.65 days 99.9% ~8.8 hours 99.99% ~52.6 minutes 99.999% ~5.3 minutes <strong>Availability: For</strong> this, we had a discussion about what the availability SLA should be. I told them 99.999%, but I wasn’t able to justify it when asked why. Ideally, a recommendation service doesn’t block a user activity at all (like purchasing an item, etc.). But when you are at 100M DAU, downtime of the service for a day can bring down the purchase rate/spending and directly affect revenue. So ideally, it would be 99.99%, which is around a max of ~1 hour of downtime in a year.</li><li><strong>Scalability:</strong> I was told there are 100M daily active users. The later discussion was on how many actions users perform (i.e., how many times they call the recommendation service). → Some users might call it more (e.g., 20 times), and some might be 5–8 times; on average, assume 10 requests per day per user to the recommendation service. Which makes 1 billion requests/day. The next discussion was on what the TPS/RPS would be: Generally it will be 1B/(number of seconds in a day) ~ 12k RPS Okay, I discussed this, but what I missed was peak RPS: Nobody uses e-commerce the same at 3 AM and 11 AM. <a href="https://am.so/">So</a> peak RPS [the time where this service will be heavily used]: consider it as 10x of the regular RPS, that is around 100k RPS.These are assumptions to be aware of so our system can handle this level of scalability. This will be used for designing our architecture.</li><li><strong>Consistency:</strong> Our recommendations are not time-critical, so it’s okay if we get updated recommendations after some time. So this can be an eventually consistent system.</li></ol><p>Summarised requirements:</p><ol><li>We want a personalised recommendation service.</li><li>This service will return the list of products to the user. [GET]/api/recommendations?userId={userId} returns List&lt;ProductInfo&gt;</li><li>The personalised recommendations for the user will be based on certain intents: I&#39;m considering user purchase history, wishlist, search history, click events, product detail views, and wherever possible their respective categories.</li><li>This system is at 100M DAU, RPS: 12k, and peak RPS: 100k.</li><li>The latency of the request should be &lt; 500ms.</li><li>This will be an eventually consistent service.</li></ol><p>We are done with requirements gathering. Now let’s build the system based on the requirements and assumptions as discussed above.</p><p>For me, this is the user flow that comes to mind. I’m bad at drawing components, so bear with me for some time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*wBbpowaQ1iZ7ah1i" /></figure><p>So this is not the exact diagram I drew there, but with each component explained.</p><p>Basically, the user will be coming through the client of our e-commerce app, so our caller is the client. To handle 100M DAU and 100k RPS, this is definitely not a single node; we need multiple nodes of our server, and therefore we need a load balancer to scale them horizontally. Another thing is an API gateway: the user can’t directly come through the recommendation service. The API gateway takes care of authentication/authorisation.</p><p>Now through the API gateway, the call comes to the recommendation service. For 100k peak RPS and to maintain &lt; 500 ms, we don’t want to query the database every time, so a caching layer is needed. Why Redis? Because of its multi-region deployment support, global cache across regions, and key-value storage.</p><p>Client: E-commerce app UI, which calls our APIs</p><p>Load Balancer: to handle 100M DAU and 100k RPS, we need multiple nodes, and the LB helps in scaling those nodes horizontally</p><p>API Gateway: Authorization, request validation, authentication, rate limiting</p><p>Recommendation Service: This service will look for the cached recommendations; if not available, it will get the recommendations from the database; if not available, it will generate the recommendations with the help of a recommendation engine and send back trending products. The engine will generate recommendation events, which will store recommendations in the recommendation store.</p><p>Redis: Because it’s an in-memory key-value store with low latency that provides sub-millisecond reads to serve requests with &lt; 500ms latency, and our use case will be read-heavy (reads &gt; writes).</p><p>Recommendation Store: We will go for a NoSQL (Cassandra or DynamoDB) database because we have no direct complex relations with other tables, and joins are not required to get the recommendation list. The recommendation data depends on the user’s search history, order history, purchase history, wishlist history, click events history, etc. But while reading the data, we will just fetch from the recommendation store to serve recommendations.</p><p>The above is the read path. The other path would be the write path: How do we insert into the recommendation store?</p><p>Kafka: For updating the recommendation store with order history, click events, purchases, wishlist items added, etc., we will fire events from the respective service(s). These events will be consumed and used to update the Recommendation Store as required and will also invalidate the cache entry so that new recommendations are created in the Recommendation Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qI9aDhXIEkDnlBDX" /></figure><p>I know I’ve avoided fault tolerance, but now that we have a complete idea about our system, we can talk about fault tolerance and how we can make it more efficient.</p><p>Component Impact Recovery/Fallback Single Instance Failure No impact LB redirects requests to another instance Cache Failure: Less impact; works but with higher latency Maintain multiple replicas of Redis so that if one fails, we can fall back to another replica. Until then, latency will be higher, as we will depend on the DB DB Failure [for some reason not able to get the new recommendation list] Users will not be able to see new recommendations; they will get data from the cache, and if not available, they will not get recommendations. This won’t happen if we have multiple replica sets Maintain multiple replica sets [1 primary to write + n secondaries to read]. This helps us fall back to another replica set in that region if required. If the entire DB becomes unavailable, we will serve what’s in the cache Recommendation Engine Failure [not able to generate new recommendations due to error] Users will get stale recommendations Users will get stale recommendations, but if needed we can keep multiple instances of the recommendation engine to avoid an SPF Kafka Stops Users will not get fresh recommendations Continue serving previous recommendations</p><p>Logging and Monitoring:</p><p>The question was particularly: How would the logging and monitoring infrastructure look?</p><p>→ Ideal answer: For logging infrastructure, every component of the design will generate application logs (Recommendation Service, Kafka events, Recommendation Engine, etc.). These logs will be shipped to a central collector rather than being kept locally and then shown to developers via a system like OpenSearch.</p><ol><li>Our API P95 latency for successful requests will show the current latency of our recommendation API.</li><li>We will have a proper dashboard of failing requests by status code.</li></ol><p>For monitoring infrastructure: We will monitor the latency of requests, request rate, error rate, cache hit/miss, consumer lag, etc. The recommendation service will expose these metrics. A monitoring agent like Datadog or Prometheus periodically collects these metrics and stores them in a centralised monitoring backend. We build dashboards to continuously monitor the health of the system and configure alerts for conditions such as increasing latency, low cache hit ratio, high Kafka lag, or failed recommendation generation jobs. Additionally, each Recommendation Service instance exposes a health endpoint so the load balancer can automatically remove unhealthy instances from rotation.</p><p>Business-based monitoring: This can be a list of items users clicked from the recommendation list or items added to the cart that were suggested in the recommendations. These metrics will help us understand whether the recommendation engine and service are benefiting us and will give an idea of what data sources to change to improve. This can be stored as total conversion rate, etc.</p><p>If any performance or development-related problem occurs, monitoring will help identify the problem, and logs will help in getting the root cause.</p><p>Metrics → Detect a problem ↓ Logs → Explain the problem ↓ Traces → Pinpoint exactly where in the request path the problem occurred</p><p>My answer was completely about the tools and not about the architecture [they also asked me how I would debug any ambiguity in production]. The above explains that answer.</p><p>As an improvement, I mentioned sharding. From the above answer, you can also add ML algorithms and go deeper into the recommendation engine (e.g., score-based recommendation lists) if time permits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lmDd2u1CnGKJJy_3" /></figure><p>In the above diagram I missed adding if-else: if cache miss, then go to db; if db miss, then return trending products but fire getRecommendations event, but here’s a more correct AI-generated version.</p><p>Let me know feedback comments. Follow for such content; started documenting the journey. More such articles to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ed2f3abcc95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an MCP Server in Java with Spring]]></title>
            <link>https://medium.com/@manpatil1451/how-to-build-an-mcp-server-in-java-with-spring-857eef9ce102?source=rss-93b0382f3fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/857eef9ce102</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mangesh]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 18:01:51 GMT</pubDate>
            <atom:updated>2026-03-17T18:04:21.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build an MCP Server in Java with Spring.</h3><p>Build an MCP server in Spring WebMVC with Jetty, exposing annotated tools, auto-registration, schema generation, and servlet-based execution.</p><p>Free-access link: <a href="https://medium.com/@manpatil1451/how-to-build-an-mcp-server-in-java-with-spring-857eef9ce102?source=friends_link&amp;sk=d5af674e1c8dd555a9ac844dec3a3f83">https://medium.com/@manpatil1451/how-to-build-an-mcp-server-in-java-with-spring-857eef9ce102?source=friends_link&amp;sk=d5af674e1c8dd555a9ac844dec3a3f83</a></p><p>The Model Context Protocol (MCP) is quickly becoming the standard for connecting applications to LLM agents. Most MCP examples are written in <strong>Python or Node.js</strong>, but many production systems still run on <strong>Java and Spring WebMVC</strong>. There is almost <strong>no documentation on how to run an MCP server inside a Spring application</strong>, especially when deployed on <strong>Jetty or traditional servlet containers</strong>.</p><p>In this article we will build a <strong>Spring-based MCP server from scratch</strong>.</p><h3>Introduction</h3><p>The <strong>Model Context Protocol (MCP)</strong> is quickly becoming a standard way for applications to expose <strong>tools to AI agents</strong>.</p><p>Using MCP, an LLM agent can call server-side functions like:</p><ul><li>querying databases</li><li>fetching documents</li><li>running workflows</li><li>retrieving business data</li></ul><p>Most MCP examples today are written in:</p><ul><li><strong>Python</strong></li><li><strong>Node.js</strong></li></ul><p>However, many real-world backend systems still run on <strong>Java and Spring</strong>, often deployed using <strong>Jetty or Tomcat with Spring WebMVC</strong>.</p><p>Surprisingly, there is <strong>almost no documentation explaining how to run an MCP server inside a Spring application</strong>.</p><p>In this article we will build a <strong>fully working MCP server using Spring WebMVC and Jetty</strong>, where Spring beans can be exposed as MCP tools.</p><p>By the end, you will understand how to:</p><ul><li>expose Spring services as MCP tools</li><li>generate JSON schemas for tools</li><li>register tools automatically</li><li>integrate MCP into a servlet-based application</li><li>execute Spring bean methods via MCP requests</li></ul><p>The complete source code is available here:</p><p><strong>GitHub Repository:</strong></p><p><a href="https://github.com/Mangesh1511/spring-jetty-mcp-server">https://github.com/Mangesh1511/spring-jetty-mcp-server</a></p><h3>What is the Model Context Protocol (MCP)?</h3><p>The <strong>Model Context Protocol</strong> allows AI agents to interact with external systems using a standard interface.</p><p>Instead of hardcoding APIs, an agent can dynamically discover tools provided by a server.</p><p>Typical flow:</p><pre>AI Agent<br>   │<br>   ▼<br>MCP Request<br>   │<br>   ▼<br>Server Tool<br>   │<br>   ▼<br>Tool Response</pre><p>For example, an agent might send a request like:</p><pre>{<br>  &quot;name&quot;:&quot;add&quot;,<br>  &quot;arguments&quot;: {<br>    &quot;a&quot;:5,<br>    &quot;b&quot;:3<br>  }<br>}</pre><p>The MCP server executes the tool and returns:</p><pre>{<br>  &quot;content&quot;: [<br>    { &quot;type&quot;:&quot;text&quot;, &quot;text&quot;:&quot;8&quot; }<br>  ]<br>}</pre><h3>Why Java + Spring MCP Integration Matters</h3><p>Many enterprise systems run on <strong>Spring-based architectures</strong>, often deployed with servlet containers like <strong>Jetty</strong> or <strong>Tomcat</strong>.</p><p>Typical enterprise architecture:</p><pre>Jetty Server<br>      │<br>      ▼<br>Spring WebMVC<br>      │<br>      ▼<br>Business Services<br>      │<br>      ▼<br>   Database</pre><p>Without MCP integration, exposing these services to LLM agents requires building <strong>custom adapters</strong>.</p><p>Instead, we can create a <strong>Spring MCP bridge</strong> that allows developers to simply annotate Spring methods.</p><p>Example:</p><pre>@Component<br>public class MathTools {<br>  @McpTool(name=&quot;add&quot;, description=&quot;Adds two numbers&quot;)<br>  public int add(inta, intb) {<br>      return a + b;<br>   }<br>}</pre><p>The framework automatically exposes this method as an MCP tool.</p><h3>Architecture Overview</h3><p>Let’s look at the architecture of the system.</p><pre>                 ┌──────────────────┐<br>                 │   AI Agent       │<br>                 └─────────┬────────┘<br>                           │<br>                     MCP Request<br>                           │<br>                           ▼<br>                ┌──────────────────┐<br>                │  Jetty Server    │<br>                └─────────┬────────┘<br>                          │<br>                          ▼<br>             ┌────────────────────────┐<br>             │  MCP Delegating Servlet│<br>             └─────────┬──────────────┘<br>                       │<br>                       ▼<br>         ┌─────────────────────────────┐<br>         │ MCP HTTP Transport Provider │<br>         └─────────┬───────────────────┘<br>                   │<br>                   ▼<br>            ┌─────────────────┐<br>            │ MCP Sync Server │<br>            └────────┬────────┘<br>                     │<br>                     ▼<br>           ┌───────────────────────┐<br>           │ Spring MCP Bridge     │<br>           └────────┬──────────────┘<br>                    │<br>                    ▼<br>           ┌───────────────────────┐<br>           │ Spring Tool Beans     │<br>           └───────────────────────┘</pre><h3>Project Structure</h3><p>The project is structured as follows:</p><pre>src/main/java<br>│<br>├── annotations<br>│    ├── McpTool<br>│    └── McpToolParam<br>│<br>├── registry<br>│    ├── ToolRegistrar<br>│    ├── ToolMetadata<br>│    └── ToolParamMetadata<br>│<br>├── servlet<br>│    └── McpDelegatingServlet<br>│<br>├── schema<br>│    └── ParameterSchemaGenerator<br>│<br>├── config<br>│    └── McpServerConfiguration<br>│<br>└── tools<br>     └── ExampleTool</pre><p>Each module handles a specific responsibility.</p><h3>Defining MCP Tools with Annotations</h3><p>To expose Spring methods as MCP tools, we define a custom annotation.</p><pre>@Retention(RetentionPolicy.RUNTIME)<br>@Target(ElementType.METHOD)<br>public @interface McpTool {<br>String name();<br>String description();<br>}</pre><p>We also define a parameter annotation:</p><pre>@Target(ElementType.PARAMETER)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface McpToolParam {<br>String name();<br>String description();<br>boolean required() default true;<br>}</pre><p>Example tool:</p><pre>package com.spring.mcp.tools;<br>import org.springframework.stereotype.Component;<br>import com.spring.mcp.annotations.McpTool;<br>import com.spring.mcp.annotations.McpToolParam;<br>import com.spring.mcp.registry.McpTools;<br><br>@Component<br>public class MathTools implements McpTools{<br>    @McpTool(name = &quot;add&quot;, description = &quot;Adds two integers together.&quot;)<br>    public String add(@McpToolParam(name = &quot;a&quot;, description = &quot;The first integer to add.&quot;, required =  true) Integer a,<br>                   @McpToolParam(name = &quot;b&quot;, description = &quot;The second integer to add.&quot;, required = true) Integer b) {<br>if (a == 0 || b == 0 || a == null || b == null) {<br>                        throw new IllegalArgumentException(&quot;Both parameters must be non-null and non-zero., We do some serious business here.&quot;);<br>                    }<br>                    int result = a + b;<br>        return (&quot;result is: &quot;+result);<br>    }<br>}</pre><h3>Discovering Tools using Spring</h3><p>Spring automatically scans beans.</p><p>We use it ApplicationContext to locate beans that implement the tool interface.</p><pre>Map&lt;String,McpTools&gt;beans=<br>context.getBeansOfType(McpTools.class);</pre><p>Each bean is inspected using reflection.</p><pre>for(Methodmethod :<br>AopUtils.getTargetClass(bean).getDeclaredMethods()) {<br>if(method.isAnnotationPresent(McpTool.class)) {<br>// register tool<br>    }<br>}</pre><p>We use it <strong>AopUtils.getTargetClass()</strong> because Spring often wraps beans with <strong>CGLIB proxies</strong>.</p><p>Without this, annotations may not be detected correctly.</p><h3>Tool Metadata Model</h3><p>Each discovered tool is represented by metadata.</p><pre>public class ToolMetadata {<br><br>  private final String name;<br>  private final String description;<br>  private final Object bean;<br>  private final method;<br>  private final List&lt;ToolParamMetadata&gt; parameters;<br><br>}</pre><p>Parameter metadata:</p><pre>public class ToolParamMetadata {<br><br>  private final String name;<br>  private final String description;<br>  private final boolean required;<br>  private final Class&lt;?&gt; type;<br><br>}</pre><p>These models allow the framework to:</p><ul><li>generate schemas</li><li>invoke methods</li><li>map arguments</li></ul><h3>Generating JSON Schema for MCP</h3><p>MCP requires tools to define input schemas.</p><p>Example schema:</p><pre>{<br> &quot;type&quot;:&quot;object&quot;,<br> &quot;properties&quot;:{<br>   &quot;a&quot;:{&quot;type&quot;:&quot;integer&quot;},<br>   &quot;b&quot;:{&quot;type&quot;:&quot;integer&quot;}<br> },<br> &quot;required&quot;:[&quot;a&quot;,&quot;b&quot;]<br>}</pre><p>Our bridge converts Java parameters to schema automatically.</p><pre>Map&lt;String,Object&gt;properties=newHashMap&lt;&gt;();<br>List&lt;String&gt;required=newArrayList&lt;&gt;();</pre><p>Each parameter is mapped to a JSON type:</p><p>Java Type JSON Schema String string int integer double number boolean boolean</p><h3>Registering Tools with the MCP Server</h3><p>Once tools are discovered, they are registered with the MCP SDK.</p><pre>McpServerFeatures.SyncToolSpecificationspec=<br>McpServerFeatures.SyncToolSpecification.builder()<br>.tool(mcpTool)<br>.callHandler((exchange,request) -&gt;<br>handleToolCall(tool,request))<br>.build();</pre><p>Then added to the server:</p><pre>server.addTool(spec);</pre><h3>Executing Tool Calls</h3><p>When an MCP client invokes a tool, the framework executes the corresponding Spring method.</p><pre>ObjectrawValue=args.get(param.getName());<br>Objectconverted=mapper.convertValue(rawValue,param.getType());</pre><p>Then invokes the method:</p><pre>returnmethod.invoke(tool.getBean(),parameters.toArray());</pre><p>The result is returned to the MCP client.</p><h3>Integrating MCP with Jetty</h3><p>Because this application runs inside a <strong>Servlet container</strong>, we create a delegating servlet.</p><pre>POST /mcp</pre><p>The servlet forwards requests to the MCP transport provider.</p><pre>transportProvider.service(request,response);</pre><p>Initialisation retrieves the Spring context.</p><pre>WebApplicationContextcontext=<br>WebApplicationContextUtils.getWebApplicationContext(<br>getServletContext());</pre><p>This allows the servlet to access Spring beans.</p><h3>Example MCP Request</h3><p>Example tool invocation:</p><pre>{<br> &quot;method&quot;:&quot;tools/call&quot;,<br> &quot;params&quot;:{<br>   &quot;name&quot;:&quot;add&quot;,<br>   &quot;arguments&quot;:{<br>     &quot;a&quot;:4,<br>     &quot;b&quot;:6<br>   }<br> }<br>}</pre><p>Response:</p><pre>{<br> &quot;content&quot;:[<br>   {&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:&quot;10&quot;}<br> ]<br>}</pre><h3>Running the Server</h3><p>After deploying the application to Jetty:</p><pre>http://localhost:8080/mcp&gt;</pre><p>The endpoint will accept MCP tool requests.</p><h3>Future Improvements</h3><p>Possible enhancements include:</p><ul><li>asynchronous tool execution</li><li>streaming responses</li><li>security and authentication</li><li>Spring Boot auto-configuration</li><li>improved schema generation</li></ul><h3>Conclusion</h3><p>In this article we built a <strong>Model Context Protocol server inside a Spring WebMVC application</strong>.</p><p>We explored how to:</p><ul><li>discover Spring tools automatically</li><li>generate MCP schemas</li><li>execute tools using reflection</li><li>integrate MCP into a servlet container</li><li>expose Spring services to LLM agents</li></ul><p>This architecture allows existing Java applications to integrate with <strong>AI agents and LLM workflows</strong> without rewriting services.</p><h3>Source Code</h3><p>Full source code available here:</p><p><em>(</em><a href="https://github.com/Mangesh1511/spring-jetty-mcp-server">https://github.com/Mangesh1511/spring-jetty-mcp-server</a><em>)</em></p><p>If you enjoyed this article, feel free to share it with other Java developers exploring <strong>AI integrations with Spring</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857eef9ce102" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>