<?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 Aashana Shanu on Medium]]></title>
        <description><![CDATA[Stories by Aashana Shanu on Medium]]></description>
        <link>https://medium.com/@aashanashanu?source=rss-deeaa8041728------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KThQIrkAEC2O5YSz</url>
            <title>Stories by Aashana Shanu on Medium</title>
            <link>https://medium.com/@aashanashanu?source=rss-deeaa8041728------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:46:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aashanashanu/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[Configuring GitHub Copilot for Spring Boot: An Agent-Based Framework with Skills, Instructions, and…]]></title>
            <link>https://medium.com/@aashanashanu/configuring-github-copilot-for-spring-boot-an-agent-based-framework-with-skills-instructions-and-c90dd2e93def?source=rss-deeaa8041728------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90dd2e93def</guid>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aashana Shanu]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 21:57:53 GMT</pubDate>
            <atom:updated>2026-07-01T21:57:53.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuring GitHub Copilot for Spring Boot: An Agent-Based Framework with Skills, Instructions, and Guardrails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3kyRoYe5yNdy8rkGfcmMA.png" /></figure><p>Inside an enterprise-grade Copilot customization framework for Spring Boot WebFlux: a single orchestrator, nine specialist agents, eighteen implementation playbooks, and a guardrail system that blocks bad code before it’s ever written.</p><p>Every team that’s adopted GitHub Copilot has lived through the same six months.</p><p>Week one feels like magic — boilerplate appears before you finish typing the method name. By week three, the magic has a catch: Copilot writes code that <em>works</em>, but doesn’t look like your code. It returns an Optional&lt;Order&gt; from a reactive service. It throws a plain RuntimeException instead of your ResourceNotFoundException. It calls .block() inside a WebFlux controller because, technically, that compiles. None of it is wrong, exactly. It&#39;s just not yours.</p><p>So you fix it in code review. Every time. The AI never remembers what you told it last week, because it was never actually told — it just guessed, reasonably, from a training set that has never seen your team’s conventions.</p><p>That’s the real problem with AI coding agents right now: they’re capable, but they’re context-free. They don’t know your team rejected MongoDB for Couchbase eighteen months ago. They don’t know every error response needs a traceId field. They don&#39;t know .block() is a firing offense in your reactive codebase. So instead of hoping Copilot would eventually figure it out, I built it a brain.</p><p><strong>In numbers:</strong> 1 orchestrator + 9 specialist agents · 18 implementation skills · 7 instruction sets · 7 ready-made prompts · 12 automated guardrails · 1 shared source of truth. Here’s how all of it fits together, and how to actually use it.</p><blockquote><em>🔗 </em><strong><em>Full source, ready to drop into your own repo:</em></strong><em> </em><a href="https://github.com/aashanashanu/spring-webflux-agent-customization"><em>github.com/aashanashanu/spring-webflux-agent-customization</em></a></blockquote><h3>The Big Idea: Stop Writing Prompts, Start Writing an Org Chart</h3><p>The insight that makes this framework work isn’t really about AI. It’s about organizational design.</p><p>A real engineering team doesn’t run on one giant document that tries to say everything at once. It runs on a tech lead who routes work, senior engineers who each own a domain, a wiki nobody has to be reminded to check, and a CI pipeline that rejects a bad pull request before a human has to say “actually, we don’t do that here.” This framework rebuilds exactly that structure for an AI coding agent, as five distinct, versioned pieces living in a .github/ folder:</p><ul><li><strong>Agents</strong> — the people. They decide <em>what</em> needs to happen and <em>who</em> should do it.</li><li><strong>Skills</strong> — the playbooks. The actual templates and patterns each specialist reaches for.</li><li><strong>Instructions</strong> — the handbook. Standards that apply automatically the moment you touch the right kind of file.</li><li><strong>Hooks</strong> — the CI pipeline. Automated checks that run before and after every change — and can block it outright.</li><li><strong>The MCP context contract</strong> — the shared brain. One JSON file that every other layer quietly defers to.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mz9vUF_8EoreuJkdGhZzKA.png" /></figure><p><em>The whole framework in one picture — one entry point, nine specialists, two supporting layers, guardrails flanking both sides, and a single source of truth underneath all of it.</em></p><p>Here’s what’s actually inside each layer, and what it lets you do.</p><h3>The Orchestrator: One Door In, No Matter the Job</h3><p>Every request — “add a feature,” “fix this bug,” “build me an AI agent” — goes through exactly one front door: the <strong>Orchestrator agent</strong>. Its only job is traffic control. It:</p><ol><li>Classifies what you’re actually asking for: a greenfield build, an enhancement to an existing app, a bug fix, a refactor, an architecture review, or a brand-new AI agent.</li><li>Decides whether you’re building a traditional service or an AI-agent-based application, because those need different downstream specialists.</li><li>For existing applications, refuses to generate a single line of code before running an architecture review first — more on why that’s one of my favorite details in this whole system in a minute.</li><li>Routes the request through a staged pipeline of specialists, in a fixed, sensible order.</li><li>Aggregates everything into one final report.</li></ol><p>That last point matters more than it sounds like it should. Every orchestrator run is contractually required to hand back four things: what it detected about your project, which agents and skills it ran and in what order, what artifacts it created or changed, and a validation summary of what’s tested versus what still needs human eyes. It’s a pull request description, generated automatically, every single time — so you’re never reverse-engineering what the AI actually did after the fact.</p><h3>Nine Specialists, and a Rule That Keeps Them Honest</h3><p>Below the Orchestrator sit nine specialist agents, each scoped to exactly one domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzW8KpHRwwGgAUtW7WbHwQ.png" /></figure><p>Here’s the rule that keeps this maintainable instead of becoming a mess: <strong>agents are explicitly forbidden from holding any code, templates, or standards.</strong> Every single agent file states some version of “no implementation templates in this file.” An agent only ever decides <em>what</em> needs to happen and <em>who</em> should own it — never <em>how</em>.</p><p>That sounds like a small constraint. It’s actually the whole reason this framework can scale. If “how to build a reactive repository” lived inside the Persistence agent’s own instructions, you’d have to hunt through nine different files every time your Couchbase config changed. Instead, every agent points to the exact same place for implementation knowledge — which brings us to the playbooks themselves.</p><h3>18 Skills: The Playbooks Behind the Personas</h3><p>If agents are <em>who</em>, skills are <em>how</em>. Each of the eighteen skills is a focused, self-contained guide: when to use it, what inputs it needs, a real code template, best practices — and, in a detail most prompt libraries skip entirely, explicit <strong>validation criteria</strong> the agent checks its own output against before calling the work done.</p><p>Together they cover a genuinely wide surface:</p><ul><li><strong>Build:</strong> create-api, create-service, create-repository, create-webclient</li><li><strong>Eventing:</strong> create-event-handler, create-kafka-consumer, create-kafka-producer, create-sqs-consumer, create-eventbridge-integration</li><li><strong>AI-native:</strong> create-ai-agent, create-mcp-tool</li><li><strong>Security and testing:</strong> secure-endpoint, write-unit-tests, write-integration-tests</li><li><strong>Maintenance:</strong> refactor-feature, fix-bug, review-architecture</li><li><strong>The conductor:</strong> webflux-feature-workflow, which stitches all of the above into end-to-end flows for greenfield builds, existing-app changes, event-driven features, and AI-agent integrations</li></ul><p>None of it is vague hand-waving. Here’s the actual controller skeleton baked into create-api:</p><pre>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>@Validated<br>public class OrderController {<br>    private final OrderService service;<br><br>    public OrderController(OrderService service) {<br>        this.service = service;<br>    }<br><br>    @PostMapping<br>    public Mono&lt;ResponseEntity&lt;OrderResponse&gt;&gt; create(@Valid @RequestBody OrderCreateRequest request) {<br>        return service.create(request)<br>            .map(response -&gt; ResponseEntity.status(HttpStatus.CREATED).body(response));<br>    }<br>}</pre><p>And the validation criteria attached to it aren’t suggestions — they’re a checklist: every controller method returns Mono or Flux, no blocking calls anywhere, request DTOs carry validation annotations, route naming follows project convention. The skill doesn&#39;t just show the agent what good code looks like. It tells the agent how to grade its own homework.</p><h3>Instructions: The Handbook Nobody Has to Remember to Open</h3><p>Skills tell an agent how to build <em>one thing</em> when invoked. Instructions are different — they’re standards that switch on automatically the instant you touch a matching file, whether or not anyone explicitly asked for them. Each instruction file carries an applyTo glob pattern, so security-hardening.instructions.md quietly activates the moment you&#39;re editing *SecurityConfig*.java or application.yml, and exception-handling.instructions.md does the same for anything under **/exception/**.</p><p>That routing trick is neat on its own, but the standards underneath are where this gets genuinely impressive. A few favorites:</p><p><strong>Every error response, from every endpoint, uses one exact shape:</strong></p><pre>public record ApiErrorResponse(<br>    Instant timestamp, String path, int status,<br>    String error, String code, String message, String traceId<br>) {}</pre><p>backed by a 14-row table mapping every exception type Spring throws to an HTTP status and an application error code — ResourceNotFoundException → 404 / RESOURCE_NOT_FOUND, BusinessRuleException → 422 / BUSINESS_RULE_VIOLATION, all the way down to a safe, generic fallback so a stack trace never accidentally ships to a client.</p><p><strong>Logging has opinions, too:</strong> size-and-time-based rotation (50MB files, 30-day history, a 2GB total cap), JSON structured logs outside local and test profiles, and a standing rule to mask nine categories of sensitive fields — password, token, apiKey, creditCard, and ssn among them — in any logged payload, automatically, no exceptions.</p><p><strong>Security defaults to “no”:</strong> every route is authenticated() unless explicitly and individually marked permitAll() — and every permitAll() has to carry a comment explaining <em>why</em> it&#39;s public. CSRF gets disabled for the stateless API, but only with a mandatory comment justifying it. The full security header set — X-Frame-Options, HSTS, Referrer-Policy, and friends — ships on every response, automatically.</p><p><strong>And underneath all of it, the baseline conventions a senior engineer would nod along to without thinking twice:</strong> constructor injection only, records for immutable DTOs, thin controllers with the real logic in the service layer, and a test-naming format that turns the test itself into documentation — should_&lt;outcome&gt;_when_&lt;condition&gt;.</p><p><strong>The one rule that shows up almost everywhere:</strong> no .block(), .blockFirst(), or .blockLast(). Anywhere. Ever. Which would just be a nicely written rule if the framework stopped there. It doesn&#39;t.</p><h3>Hooks: Guardrails With an Actual “No”</h3><p>This is the part that takes the framework from “nice documentation” to something with teeth. Most prompt-engineering setups stop at instructions — write the rules down and hope the model follows them. This one backs the rules with twelve automated checks, split across two files, that fire <em>during</em> code generation, not after the fact.</p><p><strong>Five pre-tool guardrails</strong> run before a file gets written, and several of them can flat-out block the action:</p><ul><li>No persistence code generates until SQL vs. NoSQL is explicitly confirmed.</li><li>Cassandra and Redis are rejected outright — Couchbase and MongoDB are the only supported NoSQL engines, full stop.</li><li>Any .block(), .blockFirst(), .blockLast(), or Thread.sleep() inside a controller, service, handler, or filter gets stopped cold.</li><li>Hardcoded secrets in application.yml never make it to disk.</li><li>New controllers can’t appear until the global exception handler already exists.</li></ul><p><strong>Seven post-tool quality gates</strong> run right after a file is written, checking the work like an automated reviewer leaning over your shoulder: confirming new exception classes are mapped in the global handler, scanning new logging filters for unmasked sensitive fields, verifying every Service and Controller method returns Mono or Flux and never void or Optional, checking new request DTOs carry validation annotations, confirming the security config covers any new controller&#39;s routes, and reminding you, every time, to actually run the Testcontainers suite.</p><p>The split between the two files maps almost exactly onto a real team’s safety net: pre-tool guardrails are the senior engineer glancing over your shoulder before you commit; post-tool quality gates are the CI pipeline checking the diff right after. Most teams have one of these. This framework gives the AI agent both.</p><h3>The MCP Context Contract: The One File Everything Else Quietly Cites</h3><p>Here’s a question that breaks most prompt-engineering setups the moment a project scales past one person: what happens when the “rules” live scattered across nine agent files, eighteen skill files, and seven instruction documents — and they slowly drift out of sync with each other?</p><p>This framework’s answer is a single structured file: context-contract.json. It pins down the actual ground truth of the project — Java 21, Spring Boot 3.3.x, Gradle, which Actuator endpoints are exposed, where Swagger lives — alongside the same exception-to-status mapping table from the instructions, now machine-readable, the exact Testcontainers images to use for SQL and NoSQL, the seven mandatory test cases every feature needs, and a closing policy block of plain boolean flags:</p><pre>&quot;no_blocking_in_reactive_path&quot;: true,<br>&quot;require_spring_security_hardening&quot;: true,<br>&quot;reject_nosql_alternatives&quot;: [&quot;cassandra&quot;, &quot;redis&quot;, &quot;dynamodb&quot;, &quot;elasticsearch&quot;]</pre><p>Every other layer — agents, skills, instructions, hooks — is really just a <em>view</em> onto this one contract. Change the contract, and you’re not chasing nine files to keep them consistent. You’ve changed the project’s source of truth, and everything downstream inherits the update automatically.</p><h3>AI Agents Don’t Get a Free Pass Here (And That’s the Smart Part)</h3><p>Most teams I’ve watched treat “add an AI feature” as its own special, vibes-based category — no security review, no real test plan, just whatever the prototype happened to do. This framework refuses that distinction outright. Building an AI agent runs through the <em>exact same</em> governed pipeline as building a REST endpoint: architecture review, then the AI-Agent specialist, then integration, then security, then observability, then testing. An agent’s tool definitions get the same least-privilege scrutiny as a database credential would. A new MCP tool needs a bounded schema, an explicit error contract, and a defined security scope before the create-mcp-tool skill considers the job done.</p><p>If you’ve spent any time around multi-agent system design, the framework’s own shape will look familiar: one Orchestrator that never touches implementation, fanning work out to narrowly-scoped specialist Workers, each of which reports back to a single aggregation point. That’s not a coincidence — it’s the <strong>Orchestrator-Workers pattern</strong>, the same one you’ll find sketched out in most serious agentic AI architecture diagrams. Except here it isn’t a diagram in a slide deck. It’s pinning down Spring Security headers and Testcontainers images for a living.</p><h3>Watching It Work: A Payments API on a Tuesday Afternoon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqypP-Yr65Mon_DqpBgXuA.png" /></figure><p><em>Every stage hands its output to the next, and the Orchestrator aggregates all of it into one final report.</em></p><p>Theory is nice. Here’s what actually happens when you ask for something real: <em>“Use the Orchestrator to add a new payments API to my existing order service.”</em></p><ol><li><strong>Architecture review runs first — no exceptions.</strong> Because this is an existing application, the Orchestrator won’t generate anything until review-architecture finishes scanning the codebase: architecture style (layered? hexagonal? event-driven? DDD?), package conventions, the existing error-handling shape, the security model already in place, the testing patterns already in use. It comes back with an explicit do-not-break list.</li><li><strong>API Designer</strong> builds the controller and DTOs in the style the review just detected — not a generic template, <em>your</em> template.</li><li><strong>Persistence</strong> adds the repository in whichever database the project already runs on. (The pre-tool guardrail makes sure nobody quietly tries to slip in Redis here.)</li><li><strong>Integration</strong> wires up the WebClient call to the actual payment gateway, with a timeout and a bounded retry policy, because the create-webclient skill doesn&#39;t treat that as optional.</li><li><strong>Security Hardening</strong> adds the new route to SecurityWebFilterChain, deny-by-default, and a post-tool quality gate immediately checks that the routes are actually covered.</li><li><strong>Observability</strong> wires in tracing and metrics for the new endpoint.</li><li><strong>Testcontainers Test</strong> writes the unit and integration tests — happy path, validation, not-found, conflict, both auth failure modes — against a real database container, not a mock.</li><li><strong>The Orchestrator aggregates everything</strong> into one final report: what got built, what was assumed, what’s tested, what still needs a human judgment call.</li></ol><p>Eight steps. One request. Zero “wait, why is there a .block() here&quot; moments waiting in code review.</p><h3>How to Actually Use This</h3><p>You don’t need to assemble any of this yourself — that’s the entire point. Quick-start version:</p><ol><li><strong>Drop the </strong><strong>.github/ folder into your Spring Boot WebFlux repository.</strong> Agents, skills, instructions, hooks, and the MCP contract travel together as one unit.</li><li><strong>Start from one of the seven ready-made prompts</strong> instead of writing a request from scratch: add-feature, create-api, create-ai-agent, create-event-handler, fix-bug, refactor-feature, or review-architecture. Each one is a short, structured template — what input to give, what orchestration request to make — so you&#39;re never staring at a blank prompt box.</li><li><strong>For an existing codebase, just ask — the framework handles the rest.</strong> You never have to remember to say “please check our conventions first.” It’s mandatory, every time, for every existing-app request.</li><li><strong>For a brand-new service, tell the Orchestrator your architecture style</strong> — Layered, Hexagonal, Event-Driven, or Domain-Driven Design — or let the Architecture agent recommend one based on what you’re building.</li></ol><p>The integration surface is broad enough to cover most real backend work: REST and WebClient, Kafka, SQS, EventBridge, OpenSearch/Elasticsearch, the AWS SDK, Bedrock, and MCP servers. The testing surface is just as complete — unit tests, integration tests, Testcontainers, contract testing, performance testing — and every feature ships with a mandatory matrix of happy path, validation error, not-found, conflict, and both auth failure modes, every time, without you having to ask for it.</p><h3>Why This Matters Past One Spring Boot Repo</h3><p>Strip away the Java specifics and what’s left is a genuinely portable idea: <strong>don’t prompt your AI coding agent — govern it.</strong> Separate the decision-making from the implementation knowledge from the standards from the enforcement, write each one down exactly once, and let an orchestrator stitch them together fresh on every request. This particular framework happens to be wearing a Spring WebFlux costume, but the architecture underneath — one router, scoped specialists, a shared knowledge base, automated guardrails, a single source of truth — would sit just as comfortably around a Django app, a Go microservice, or a frontend design system.</p><p>The honest pitch isn’t “this makes Copilot smarter.” It’s narrower than that, and more useful: it makes Copilot <em>consistent</em>. And consistency, multiplied across every pull request your team ships this year, is worth a lot more than one clever autocomplete.</p><h3>Get the Code</h3><p>The full framework — every agent, skill, instruction set, hook, and the MCP context contract — is open on GitHub:</p><p><strong>🔗 </strong><a href="https://github.com/aashanashanu/spring-webflux-agent-customization"><strong>github.com/aashanashanu/spring-webflux-agent-customization</strong></a></p><p>Clone it, drop the .github/ folder into your own Spring Boot WebFlux repo, and point Copilot at the Orchestrator. If you end up building something like this for your own stack, I&#39;d genuinely love to hear what your guardrails end up catching — feel free to open an issue or a PR.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90dd2e93def" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Design Patterns, Explained Simply]]></title>
            <link>https://medium.com/@aashanashanu/agent-design-patterns-explained-simply-21bc2644d7da?source=rss-deeaa8041728------2</link>
            <guid isPermaLink="false">https://medium.com/p/21bc2644d7da</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Aashana Shanu]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 03:41:08 GMT</pubDate>
            <atom:updated>2026-06-24T03:41:08.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>A visual field guide to how AI agents actually make decisions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-_A5A65Y_edXVYzZXO7iA.png" /></figure><p>If you’ve used an AI coding assistant, a customer support bot, or a research tool that “looks things up” before answering, you’ve used an <strong>agent</strong>. But “agent” is a vague word. Under the hood, there isn’t just one way to build one — there are several recurring <em>patterns</em>, each suited to a different kind of problem.</p><p>This post walks through the most common ones, in plain language, with a diagram for each. No PhD required.</p><h3>What even is an “agent”?</h3><p>Think of a plain LLM (large language model) as a really well-read intern who’s never left the building. It can write, summarize, and reason brilliantly — but it has no inbox, no calendar, no internet, and no memory of yesterday. It only knows what you type into the chat box right now.</p><p>An <strong>agent</strong> is what you get when you give that intern a phone, a notebook, and the authority to act: it can now look things up, run code, call an API, write down what it learns, and decide what to do next <em>on its own</em>, in a loop, until the job is done.</p><p>That loop — <strong>perceive something, reason about it, take an action, observe the result, repeat</strong> — is the heartbeat behind every pattern in this post. The patterns below are really just different ways of organizing that loop for different kinds of work.</p><h3>The basic building block: the augmented LLM</h3><p>Before the patterns, there’s one core unit they’re all made of: an LLM that’s been hooked up to a few extra capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vydlJeC6WDFLKNRr9y44EA.png" /></figure><ul><li><strong>Memory/Retrieval</strong> — so it can pull in facts it wasn’t trained on, or remember earlier in the conversation.</li><li><strong>Tools/APIs</strong> — so it can check the weather, query a database, or send an email.</li><li><strong>Code execution</strong> — so it can do math properly, or test something instead of guessing.</li><li><strong>User/task input</strong> — the actual question or job it’s been given.</li></ul><p>Every pattern below is just a different arrangement of this one Lego brick. Once you see that, the rest gets a lot less mysterious.</p><p>A quick but important distinction: a <strong>workflow</strong> runs these steps in a fixed order that <em>you</em> coded in advance — predictable, easy to debug, great for tasks you understand well. An <strong>agent</strong> decides its own steps as it goes — more flexible, but less predictable. Most of the patterns below sit somewhere on that spectrum, and picking the right one is often about picking the right amount of freedom to hand over.</p><h3>Pattern 1: ReAct (Reason + Act)</h3><p>This is the simplest and most common agent loop. The model reasons about what to do, takes one action (usually a tool call), looks at what came back, and reasons again — until it decides it has enough to answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nh7HioDgy_zO4JQ4kkxJ6A.png" /></figure><p><strong>Plain-language version:</strong> imagine asking a friend a question they don’t know off the top of their head. They don’t just guess — they say “let me check,” look something up, glance at the result, maybe check one more thing, and <em>then</em> answer you. That little “check, glance, check again” rhythm is ReAct.</p><p><strong>Good for:</strong> open-ended questions where you don’t know in advance how many steps it’ll take — research questions, troubleshooting, “find me the answer” type tasks.</p><p><strong>Watch out for:</strong> it can wander. Without a step limit or a clear stopping rule, a ReAct agent can loop longer (and cost more) than you’d expect.</p><h3>Pattern 2: Plan-and-Execute</h3><p>Instead of figuring out one step at a time, the model first writes out the <em>whole plan</em>, then works through it step by step. If something goes wrong partway through, it can revise the plan rather than starting over.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZcRQtKH2uXcIZQmMyNrRQ.png" /></figure><p><strong>Plain-language version:</strong> this is the difference between wandering through a grocery store picking things up as you spot them (ReAct) versus writing a shopping list before you leave the house, then working down it aisle by aisle. If the store’s out of something, you adjust the list — you don’t throw the whole trip out.</p><p><strong>Good for:</strong> multi-step tasks where the steps are fairly predictable up front — generating a report, executing a structured workflow, multi-stage data processing.</p><p><strong>Watch out for:</strong> plans made too early can be wrong. If step 2 depends heavily on what step 1 actually returns, a rigid plan can break — which is why the “replan” arrow back to the planner matters.</p><h3>Pattern 3: Reflection</h3><p>Here, one part of the system generates a draft, and another part (sometimes the same model, prompted differently) critiques it. The draft gets revised based on that feedback, and the cycle repeats until the critic is satisfied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJPL36JRBX1-Q9XwCDRUDA.png" /></figure><p><strong>Plain-language version:</strong> it’s a writer handing a draft to an editor, getting notes back, rewriting, and repeating — instead of publishing the very first thing they typed.</p><p><strong>Good for:</strong> writing, code generation, anything where “good on the first try” is unlikely but “good after a couple of revisions” is realistic.</p><p><strong>Watch out for:</strong> the critique has to be genuinely useful, or the loop just spins without improving anything. Vague feedback like “make it better” doesn’t help much more than no feedback at all.</p><h3>Pattern 4: Evaluator-Optimizer</h3><p>This is Reflection’s stricter sibling. Instead of an open-ended critique, the output is scored against explicit, defined criteria — and only passes once it clears the bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iuMKv3rUki2ol7KbFtKKg.png" /></figure><p><strong>Plain-language version:</strong> Reflection is an editor giving notes. Evaluator-Optimizer is more like a checklist-driven quality inspector: “Does it meet requirement A? Requirement B? Pass or fail.” No pass, no ship.</p><p><strong>Good for:</strong> anything with measurable success criteria — code that needs to pass tests, translations checked against a rubric, content that has to satisfy compliance rules.</p><p><strong>Watch out for:</strong> the whole pattern is only as good as the criteria you define. A poorly designed rubric can approve bad output or reject good output just as easily as no rubric at all.</p><h3>Pattern 5: Routing</h3><p>A first step looks at the incoming request and classifies it, then hands it off to whichever specialized agent is built to handle that type of request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEFw21jne8eW1ceDGkiDAQ.png" /></figure><p><strong>Plain-language version:</strong> this is exactly what happens when you call a company’s support line and a recorded voice asks “for billing, press 1; for technical support, press 2.” The router isn’t trying to solve your problem — it’s just making sure the right specialist picks up the phone.</p><p><strong>Good for:</strong> systems that handle several distinct categories of request, where each category is genuinely better served by a differently prompted (or differently built) agent.</p><p><strong>Watch out for:</strong> the router itself can misclassify, especially on requests that straddle two categories. It’s often worth having a fallback “general” handler for anything ambiguous.</p><h3>Pattern 6: Parallelization</h3><p>The same task (or slight variations of it) gets sent to several LLM calls at the same time, and the results are merged or voted on at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg35Y5ZYOYHeL94PVK3AIQ.png" /></figure><p><strong>Plain-language version:</strong> instead of asking one judge to score a competition, you ask three judges independently and average — or take the majority verdict. You trade some extra cost for more reliable, less idiosyncratic results.</p><p><strong>Good for:</strong> tasks where independent attempts genuinely improve quality or confidence — content moderation, code review checks, “run it three ways and pick the best/most common answer.”</p><p><strong>Watch out for:</strong> it’s more expensive (you’re paying for multiple calls), and it only helps if the calls are meaningfully independent. Three calls that all make the exact same mistake won’t catch anything.</p><h3>Pattern 7: Orchestrator-Workers</h3><p>A manager-style agent breaks a task into different <em>subtasks</em> — not copies of the same task, but genuinely different pieces — hands each one to a worker built or prompted for that piece, and then combines everything into a final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtGuUK_IaoUOieEyKsKb8g.png" /></figure><p><strong>Plain-language version:</strong> this is a head chef on a busy night. They don’t cook every dish themselves, and they’re not just forwarding the whole ticket to one cook (that’s Routing). They split the order — appetizer to one station, main to another, dessert to a third — then plate it all together as one meal.</p><p><strong>Good for:</strong> complex tasks that naturally break into different <em>kinds</em> of work — building a feature (research the API, write the code, write the tests), or producing a report (gather data, draft sections, fact-check).</p><p><strong>Watch out for:</strong> this is the most complex pattern here, with the most moving parts and the most ways for things to go subtly wrong. It usually isn’t where you should start — reach for it once a simpler pattern has demonstrably hit its limits.</p><h3>A few more worth knowing</h3><p>These don’t need their own diagrams — they’re really small additions to the patterns above:</p><ul><li><strong>Multi-agent debate</strong> — two or more agents argue different sides of a question before a final decision is made. A specialized cousin of Orchestrator-Workers, used mainly for high-stakes or judgment-heavy decisions.</li><li><strong>Memory-augmented agents</strong> — any of the above, given a persistent memory store so they remember things across sessions, not just within one conversation.</li><li><strong>Human-in-the-loop</strong> — a checkpoint where the agent pauses and waits for a person to approve before continuing. Common in any pattern where the next action is risky, costly, or hard to undo.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*mtf1YRS6-MlqnWPzisZr2g.png" /></figure><h3>The simplest advice in this whole post</h3><p>Start simpler than you think you need to. A single well-prompted LLM call solves more problems than people expect. Reach for ReAct when you need tools. Reach for Plan-and-Execute when the steps are foreseeable. Save Orchestrator-Workers and multi-agent setups for when you’ve actually hit the ceiling of something simpler — not because they’re impressive, but because every extra moving part is something that can break, cost more, and take longer to debug.</p><p>The patterns aren’t a ladder you have to climb. They’re a toolbox. The skill is picking the smallest tool that does the job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21bc2644d7da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Serverless Visual Search Engine Using S3 as a Vector Database — And It Cost Almost…]]></title>
            <link>https://medium.com/@aashanashanu/i-built-a-serverless-visual-search-engine-using-s3-as-a-vector-database-and-it-cost-almost-0a1887816076?source=rss-deeaa8041728------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a1887816076</guid>
            <category><![CDATA[amazon-s3-vectors]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Aashana Shanu]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 04:18:20 GMT</pubDate>
            <atom:updated>2026-04-27T04:20:49.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a Serverless Visual Search Engine Using S3 as a Vector Database — And It Cost Almost Nothing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH93Le9kjIQ7vvjh08N3tw.png" /></figure><h3>How an S3 Vector Database Replaced OpenSearch in a Production-Grade AI Shopping App</h3><p>When I set out to build an AI-powered visual shopping assistant, the first architecture diagram I sketched had the usual suspects: a React frontend, AWS Lambda for compute, Amazon Bedrock for multimodal embeddings — and Amazon OpenSearch Service as the vector database.</p><p>Then I looked at the pricing.</p><p>OpenSearch Service runs roughly <strong>$100–200/month</strong> for even the smallest production-grade cluster. For a hobby project or an early-stage product with modest catalog sizes, that’s a hard pill to swallow. So I asked a different question: <strong>do I actually need a dedicated vector database?</strong></p><p>The answer, for sub-100k products, turned out to be <strong>no</strong>. Here’s how I turned plain Amazon S3 into a fully functional <strong>S3 vector database</strong> — and what I learned along the way.</p><h3>The Problem: Visual Search at Low Cost</h3><p>The system works like this:</p><ol><li>A user uploads a photo of a product they like (say, a leather tote bag).</li><li>Amazon Bedrock’s <strong>Amazon Nova Multimodal Embeddings</strong> model converts that photo into a <strong>1024-dimensional float vector</strong>.</li><li>That vector is compared against every product in the catalog using the <strong>S3 vector database</strong>.</li><li>Results are filtered by price, color, and category, then explanations are generated by <strong>Amazon Nova Lite</strong>.</li></ol><p><strong>Step 3 is the vector search problem.</strong> This is where most people reach for Pinecone, Weaviate, Qdrant, or OpenSearch. All excellent choices — but all carry a standing cost whether or not a single query is made.</p><h3>The Solution: An S3 Vector Database Using S3VectorStore</h3><p>The core insight is simple: <strong>a vector search over a few thousand products is just a for-loop with some math.</strong> No special hardware. No index structures. No cluster to maintain.</p><p>By storing vector embeddings as structured JSON in S3 and implementing k-NN search client-side, you get a fully operational <strong>S3 vector database</strong> at a fraction of the cost of any managed vector store.</p><p>Here’s the class that powers the entire search pipeline:</p><pre>class S3VectorStore:<br> &quot;&quot;&quot;<br> S3-backed vector database for product embeddings.<br> Ultra-low cost alternative to OpenSearch for cost-optimized deployments.<br> &quot;&quot;&quot;<br>def __init__(self, bucket_name: str, region: str = &quot;us-east-1&quot;):<br> self.s3 = boto3.client(&#39;s3&#39;, region_name=region)<br> self.bucket_name = bucket_name<br> self.embeddings_cache = None<br> self.products_cache = None</pre><p>The <strong>S3 vector database</strong> maintains two JSON documents:</p><p><strong>embeddings/product_embeddings.json</strong><br>Stores { product_id: [float, float, …] } — the raw vector index for every product.</p><p><strong>catalog/products.json</strong><br>Stores [ { product_id, name, price, color, … } ] — the product metadata used to return results.</p><p><strong>That’s the entire persistence layer.</strong></p><h3>Loading and Caching the S3 Vector Index</h3><p>Both files are loaded lazily and cached in memory within a single Lambda invocation:</p><pre>def load_embeddings(self) -&gt; Dict[str, List[float]]:<br>    if not self.embeddings_cache:<br>        response = self.s3.get_object(<br>            Bucket=self.bucket_name,<br>            Key=&#39;embeddings/product_embeddings.json&#39;<br>        )<br>        self.embeddings_cache = json.loads(response[&#39;Body&#39;].read())<br>    return self.embeddings_cache</pre><p>Because a Lambda execution container is reused across warm invocations, this <strong>single S3 </strong><strong>GetObject call</strong> — the S3 vector database&#39;s &quot;index load&quot; — may serve hundreds of requests before the container is recycled. <strong>The cost of loading the index amortizes down to nearly zero.</strong></p><h3>Vector Search: Cosine Similarity From Scratch</h3><p>The similarity metric is <strong>cosine similarity</strong> — the standard choice for embedding-based retrieval in any vector database:</p><p><strong>similarity(A, B) = (A · B) / (‖A‖ · ‖B‖)</strong></p><p>Implemented in <strong>pure Python with zero NumPy dependency</strong> (critical for lean Lambda deployment packages):</p><pre>def _vector_norm(self, vector: List[float]) -&gt; float:<br>    return math.sqrt(sum(x * x for x in vector))<br><br>def _dot_product(self, vec1: List[float], vec2: List[float]) -&gt; float:<br>    return sum(a * b for a, b in zip(vec1, vec2))<br><br>def search_similar(self, query_embedding, top_k=10):<br>    embeddings = self.load_embeddings()  # Load S3 vector index<br>    query_norm = self._vector_norm(query_embedding)<br>    similarities = []<br><br>    for product_id, embedding in embeddings.items():<br>        embedding_norm = self._vector_norm(embedding)<br>        if embedding_norm &gt; 0:<br>            similarity = self._dot_product(query_embedding, embedding) / (query_norm * embedding_norm)<br>            similarity = max(-1.0, min(1.0, similarity))  # clamp for float safety<br>            similarities.append((product_id, similarity))<br><br>    similarities.sort(key=lambda x: x[1], reverse=True)<br>    return similarities[:top_k]</pre><p>The result is a ranked list of (product_id, score) tuples — <strong>the same output you’d expect from Pinecone or any other vector database, served entirely by S3.</strong></p><h3>Seeding the S3 Vector Database</h3><p>When products are added, a DataSeeder Lambda reads from sample_catalog.json, preprocesses each product image, generates an embedding via Bedrock, and writes it into the S3 vector database:</p><pre>self.vector_store = S3VectorStore(<br>    bucket_name=self.product_images_bucket,<br>    region=self.region<br>)<br><br># For each product:<br>embedding = bedrock_client.generate_multimodal_embedding(image_bytes)<br>vector_store.add_embedding(product_id, embedding, product_data)</pre><p>Every write also creates a <strong>timestamped backup automatically</strong>:</p><pre>timestamp = datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)<br>self.s3.put_object(<br>    Bucket=self.bucket_name,<br>    Key=f&#39;embeddings/backup/product_embeddings_{timestamp}.json&#39;,<br>    Body=json.dumps(embeddings, indent=2),<br>)</pre><p><strong>Backups in the S3 vector database are essentially free.</strong> A managed vector database would charge for every write operation or index rebuild.</p><h3>Image Quality Guardrails</h3><p>Before any embedding is written to the S3 vector database, images go through two preprocessing steps:</p><p><strong>1. Auto-orient and resize</strong> — EXIF-aware rotation is applied and the image is downscaled to a max side of 1024px for consistent embedding quality.</p><p><strong>2. Blur detection</strong> — An edge-variance algorithm flags blurry photos <em>before</em> the Bedrock call is made, saving latency and API cost:</p><pre>blur_threshold = float(os.environ.get(&#39;IMAGE_BLUR_THRESHOLD&#39;, &#39;6300.0&#39;))<br>if is_blurry(image_bytes, threshold=blur_threshold):<br>    return {<br>        &#39;error&#39;: &#39;image_blur&#39;,<br>        &#39;message&#39;: &#39;Please upload a clearer photo.&#39;,<br>        &#39;suggestions&#39;: [<br>            &#39;Retake the photo ensuring focus&#39;,<br>            &#39;Crop the image to the product area&#39;,<br>            &#39;Upload a higher-resolution image&#39;<br>        ]<br>    }</pre><p><strong>No Bedrock call is made on a blurry image.</strong> No money is spent on a query that would return noisy results from the S3 vector database.</p><h3>The Full Search Pipeline</h3><p>A single POST /search flows through the S3 vector database like this:</p><pre>User Photo (base64)<br>    → Image validation + blur check<br>    → preprocess_image_bytes()  — auto-orient, resize to 1024px<br>    → Bedrock Nova: generate 1024-dim multimodal embedding<br>    → S3 Vector Database: cosine k-NN search across all products<br>    → Post-retrieval filter: color / category / price<br>    → Bedrock Nova Lite: generate AI explanation per product<br>    → JSON response → React frontend</pre><p><strong>All of this runs in a single Lambda</strong> with sub-second warm latency for a catalog of a few hundred products.</p><h3>Cost: S3 Vector Database vs OpenSearch</h3><p>Here’s the honest monthly breakdown:</p><p><strong>S3 Vector Database — 10K products (~10 MB storage)</strong><br>Cost: less than $0.01/month</p><p><strong>S3 GET calls — index loads and warm misses</strong><br>Cost: less than $0.01/month</p><p><strong>Bedrock Nova Embeddings — per search query</strong><br>Cost: ~$0.006 per query</p><p><strong>Lambda — 128 MB memory, ~3s average duration</strong><br>Cost: ~$0.20 per 1,000 requests</p><p><strong>OpenSearch Vector Database — smallest production node</strong><br>Cost: ~$120/month standing, whether you use it or not</p><p><strong>The S3 vector database is orders of magnitude cheaper.</strong> For a catalog under 100K products, this approach is not just workable — it’s optimal.</p><h3>When to Graduate Beyond an S3 Vector Database</h3><p>The S3 vector database pattern isn’t for everyone. Switch to a purpose-built vector database when:</p><ul><li><strong>Your catalog exceeds ~100K products.</strong> Loading a full embedding index in memory on every cold start becomes untenable. ANN indexing via HNSW (Pinecone, Weaviate, OpenSearch) becomes critical.</li><li><strong>You need real-time index updates.</strong> The S3 vector database rewrites the entire embeddings file on every add_embedding call — fine for batch seeding, painful for high-frequency updates.</li><li><strong>You need filtered vector search at index time.</strong> Post-retrieval filtering in Python works at small scale; purpose-built vector databases filter inside the index.</li><li><strong>Multi-tenancy or RBAC matters.</strong> S3 JSON files have no concept of row-level permissions.</li></ul><h3>Conclusion</h3><p>Building this project reinforced something I keep relearning: <strong>choose the simplest architecture that honestly meets your requirements.</strong></p><p>An <strong>S3 vector database</strong> — embeddings stored as JSON, similarity search implemented in pure Python — is not a toy. It’s a legitimate production choice for small-to-medium catalogs when serverless cost and operational simplicity are the dominant constraints.</p><p>The S3VectorStore class is <strong>fewer than 200 lines of Python</strong>, has <strong>zero external dependencies</strong> beyond boto3, and runs identically in a Lambda, a local environment, or a unit test.</p><p>When the catalog grows and the S3 vector database’s in-memory model no longer fits the budget, migrating is a <strong>one-file swap</strong>. Until then, S3 is doing just fine as a vector database.</p><p><em>The full project — including the React frontend, CloudFormation IaC, and Lambda implementations — is open source. Check the repository for the complete s3_vector_store.py, image preprocessing utilities, and deployment scripts.</em></p><p><a href="https://github.com/aashanashanu/ai-visual-shopping">GitHub - aashanashanu/ai-visual-shopping</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a1887816076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Used AWS Lambda as an MCP Server — Here’s What I Learned Building an AI Agent That Recovers…]]></title>
            <link>https://medium.com/@aashanashanu/i-used-aws-lambda-as-an-mcp-server-heres-what-i-learned-building-an-ai-agent-that-recovers-f88feb688bf5?source=rss-deeaa8041728------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88feb688bf5</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[ecomerce]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Aashana Shanu]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 06:03:21 GMT</pubDate>
            <atom:updated>2026-04-11T02:02:32.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Used AWS Lambda as an MCP Server — Here’s What I Learned Building an AI Agent That Recovers Abandoned Carts</h3><p><strong>TL;DR:</strong> I built an AI agent that autonomously recovers abandoned e-commerce carts. The brain runs on Elastic’s AI Agent, but the hands — the tools that actually <em>do things</em> — run on AWS Lambda behind the Model Context Protocol (MCP). This post is about that decision, the trade-offs, and everything I wish I’d known before I started.</p><h3>The Problem I Was Solving</h3><p>Every year, <strong>$4.6 trillion</strong> worth of e-commerce carts are abandoned. Most recovery systems blast a generic “Hey, you forgot something!” email 24 hours later. By then, the customer has already bought from a competitor or lost interest.</p><p>I wanted to build something smarter — an AI agent that:</p><ol><li><strong>Detects</strong> abandoned carts in real time</li><li><strong>Diagnoses</strong> <em>why</em> each cart was abandoned (payment failure? slow page? just browsing?)</li><li><strong>Decides</strong> the optimal recovery action per customer</li><li><strong>Executes</strong> that action autonomously</li></ol><p>The agent’s brain lives in Elasticsearch (workflow + AI agent). But the agent needs <em>hands</em> — it needs to read a decision matrix, send emails, and log recovery actions. That’s where MCP and Lambda come in.</p><blockquote><em>🔗 </em><strong><em>Full project:</em></strong><em> </em><a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent"><em>GitHub — AI Abandoned Cart Recovery Agent</em></a></blockquote><h3>What Is MCP, and Why Does It Matter?</h3><p>The <strong>Model Context Protocol (MCP)</strong> is an open standard (created by Anthropic) that gives AI models a uniform way to call external tools. Think of it as a USB-C port for AI — one standard interface, any tool can plug in.</p><p>An MCP server exposes tools via two methods:</p><pre>// &quot;What tools do you have?&quot;<br>POST /mcp  { &quot;method&quot;: &quot;tools/list&quot; }</pre><pre>// &quot;Use this specific tool&quot;<br>POST /mcp  { &quot;method&quot;: &quot;tools/call&quot;, &quot;params&quot;: { &quot;name&quot;: &quot;decision_engine&quot;, &quot;arguments&quot;: {...} } }</pre><p>The AI agent doesn’t need to know <em>how</em> the tool works. It just knows the tool’s name, its input schema, and that it can call it. The MCP server handles the rest.</p><h3>The Architecture: Three Lambdas, One MCP Endpoint</h3><p>Here’s what I built:</p><pre>Elastic AI Agent<br>    │<br>    │  HTTPS (tools/list, tools/call)<br>    ▼<br>API Gateway (POST /mcp)<br>    │<br>    ▼<br>┌─────────────────────────────────┐<br>│  Lambda 1: MCP Server (Router)  │<br>│                                 │<br>│  tools/list → return schemas    │<br>│  tools/call → dispatch to:      │<br>│  ├─ &quot;decision_engine&quot; ─────────►│──► Lambda 2<br>│  └─ &quot;recovery_action&quot; ─────────►│──► Lambda 3<br>└─────────────────────────────────┘<br>         │                │<br>         ▼                ▼<br>┌──────────────┐  ┌──────────────────┐<br>│ Lambda 2:    │  │ Lambda 3:        │<br>│ Decision     │  │ Recovery         │<br>│ Engine       │  │ Action           │<br>│              │  │                  │<br>│ → Read S3   │  │ → Send SES email │<br>│   decision  │  │ → Publish to     │<br>│   matrix    │  │   EventBridge    │<br>│ → Return    │  │ → Log recovery   │<br>│   action    │  │   history        │<br>└──────────────┘  └──────────────────┘</pre><p><strong>Three Lambdas. One API Gateway route. Two tools. Zero servers to manage.</strong></p><p>I chose to split the MCP server from the tool implementations. The MCP Server Lambda is the single entry point — it handles the MCP protocol (tools/list, tools/call) and dispatches to the appropriate tool Lambda via invocation.</p><p>The AI agent calls decision_engine first with the diagnosis payload. It gets back a recommended action (e.g., &quot;offer 15% discount&quot; or &quot;send payment retry link&quot;). Then it calls recovery_action to execute it — send the email and log the result back into the system.</p><h3>Why Three Lambdas Instead of One?</h3><p>This was a deliberate choice. Here’s why:</p><p><strong>Separation of concerns</strong> — The MCP server owns protocol handling. Each tool Lambda owns its business logic. They deploy, scale, and fail independently.</p><p><strong>Independent IAM roles</strong> — The Decision Engine Lambda only needs s3:GetObject. The Recovery Action Lambda needs ses:SendEmail + events:PutEvents. The MCP Server Lambda needs lambda:InvokeFunction. Least-privilege per function.</p><p><strong>Independent scaling</strong> — If recovery emails spike (e.g., Black Friday), only the Recovery Action Lambda scales. The Decision Engine stays at baseline.</p><p><strong>Independent timeouts</strong> — S3 reads complete in ~50ms. SES sends can take 2–3 seconds. Different timeout configs per function.</p><p><strong>Easier debugging</strong> — Each Lambda has its own CloudWatch log group. When something fails, you know exactly which function and which tool.</p><p><strong>The trade-off?</strong> — Three cold starts instead of one on a fully cold pipeline. In practice, the MCP Server Lambda is always the first to warm (called every 5 minutes by the workflow), and it warms the tool Lambdas by invoking them. The second tool call in each cycle is always warm.</p><h3>Why Lambda? The Decision Process</h3><p>I evaluated three options:</p><p><strong>Option A: Always-on container (ECS/Fargate)</strong></p><ul><li>✅ No cold starts</li><li>✅ Can run SSE/WebSocket transports</li><li>❌ $35–70/month for a service that runs ≤288 times/day</li><li>❌ Overkill — each tool call takes &lt;2 seconds</li><li>❌ Need to manage health checks, scaling, deployments</li></ul><p><strong>Option B: EC2 instance</strong></p><ul><li>❌ Just… no. Not in 2026.</li></ul><p><strong>Option C: AWS Lambda (chosen ✅)</strong></p><ul><li>✅ Pay per invocation (~$0.02/month for my workload)</li><li>✅ Zero ops — no patching, no scaling config, no health checks</li><li>✅ Scales to 1000 concurrent automatically</li><li>✅ Native integration with S3, SES, EventBridge via SDK</li><li>✅ SAM template = entire infra in one file</li><li>❌ Cold starts (500ms–1.5s first call)</li><li>❌ Stateless — can’t hold connections open</li><li>❌ 15-minute max timeout</li></ul><p>For a scheduled workflow that runs every 5 minutes and processes ≤100 carts per run, Lambda was the obvious choice.</p><h3>The Implementation</h3><h3>The MCP Server Lambda (Router)</h3><p>This Lambda is the protocol layer. It understands MCP, but it doesn’t understand business logic.</p><pre>TOOLS = {<br>    &quot;decision_engine&quot;: {<br>        &quot;description&quot;: &quot;Determines optimal recovery action based on diagnosis&quot;,<br>        &quot;lambda_name&quot;: &quot;DecisionEngineFunction&quot;,<br>        &quot;inputSchema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;root_cause&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [<br>                    &quot;payment_failure&quot;, &quot;high_cart_value&quot;,<br>                    &quot;shipping_issue&quot;, &quot;browsing_abandonment&quot;<br>                ]},<br>                &quot;customer_segment&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                &quot;cart_value&quot;: {&quot;type&quot;: &quot;number&quot;},<br>                &quot;currency&quot;: {&quot;type&quot;: &quot;string&quot;}<br>            },<br>            &quot;required&quot;: [&quot;root_cause&quot;, &quot;customer_segment&quot;, &quot;cart_value&quot;]<br>        }<br>    },<br>    &quot;recovery_action&quot;: {<br>        &quot;description&quot;: &quot;Executes recovery: sends email, logs to EventBridge&quot;,<br>        &quot;lambda_name&quot;: &quot;RecoveryActionFunction&quot;,<br>        &quot;inputSchema&quot;: { ... }<br>    }<br>}</pre><pre>def lambda_handler(event, context):<br>    body = json.loads(event[&quot;body&quot;])</pre><pre>    if body[&quot;method&quot;] == &quot;tools/list&quot;:<br>        return format_tool_list(TOOLS)</pre><pre>    if body[&quot;method&quot;] == &quot;tools/call&quot;:<br>        tool = TOOLS[body[&quot;params&quot;][&quot;name&quot;]]<br>        # Invoke the tool Lambda<br>        response = lambda_client.invoke(<br>            FunctionName=tool[&quot;lambda_name&quot;],<br>            Payload=json.dumps(body[&quot;params&quot;][&quot;arguments&quot;])<br>        )<br>        result = json.loads(response[&quot;Payload&quot;].read())<br>        return format_tool_response(result)</pre><h3>The Decision Engine Tool</h3><p>This tool doesn’t use AI. It’s deliberately deterministic.</p><pre>def lambda_handler(event, context):<br>    # Load decision matrix from S3 (cached in Lambda memory after first call)<br>    matrix = load_decision_matrix()</pre><pre>    root_cause = event[&quot;root_cause&quot;]<br>    segment = event[&quot;customer_segment&quot;]<br>    cart_value = event[&quot;cart_value&quot;]</pre><pre>    # Look up the right action for this segment + root cause<br>    segment_rules = matrix.get(segment, matrix[&quot;default&quot;])<br>    action = segment_rules.get(root_cause, segment_rules[&quot;default&quot;])</pre><pre>    # Check cart value threshold<br>    if action.get(&quot;cart_value_threshold&quot;) and cart_value &lt; action[&quot;cart_value_threshold&quot;]:<br>        action = segment_rules[&quot;default&quot;]</pre><pre>    return {<br>        &quot;recommended_action&quot;: action[&quot;action_type&quot;],<br>        &quot;discount&quot;: action.get(&quot;discount&quot;, None),<br>        &quot;free_shipping&quot;: action.get(&quot;free_shipping&quot;, False),<br>        &quot;message&quot;: action[&quot;message&quot;],<br>        &quot;priority&quot;: action[&quot;priority&quot;]<br>    }</pre><p>Why not let the AI decide the recovery action? Because <strong>AI should diagnose, not prescribe</strong>. The business owns the recovery strategy. A product manager should be able to update the S3 JSON file and change every recovery action without touching code or retraining a model.</p><p>Here’s what the decision matrix looks like in practice:</p><p><strong>VIP Customers:</strong></p><ul><li>Payment failure → Payment retry link</li><li>High cart value (≥$500) → 15% discount</li><li>Shipping issue → Free shipping</li><li>Browsing abandonment → Free shipping</li></ul><p><strong>Standard Customers:</strong></p><ul><li>Payment failure → Payment retry link</li><li>High cart value (≥$300) → 10% discount</li><li>Shipping issue → Free shipping</li><li>Browsing abandonment → Reminder email</li></ul><p><strong>High Fraud Risk:</strong></p><ul><li>Payment failure → <strong>Blocked</strong> (no action)</li><li>Shipping issue → Reminder only (no incentives)</li><li>Browsing abandonment → Reminder only (no incentives)</li></ul><p><strong>Default (unknown segment):</strong></p><ul><li>Payment failure → Payment retry</li><li>Everything else → Generic reminder</li></ul><p>Notice: high_fraud_risk customers are <strong>never</strong> offered discounts or free shipping. This is a business rule, not an AI decision. It lives in a JSON file on S3, not in a prompt.</p><h3>The Recovery Action Tool</h3><p>This tool has side effects — it sends emails and logs events.</p><pre>def lambda_handler(event, context):<br>    # Send personalized recovery email via SES<br>    ses_response = ses_client.send_email(<br>        Source=&quot;recovery@store.com&quot;,<br>        Destination={&quot;ToAddresses&quot;: [event[&quot;customer_email&quot;]]},<br>        Message={<br>            &quot;Subject&quot;: {&quot;Data&quot;: event[&quot;subject&quot;]},<br>            &quot;Body&quot;: {&quot;Html&quot;: {&quot;Data&quot;: event[&quot;email_body&quot;]}}<br>        }<br>    )</pre><pre>    # Publish recovery event back to EventBridge<br>    # This closes the feedback loop<br>    eventbridge_client.put_events(Entries=[{<br>        &quot;Source&quot;: &quot;mcp.recovery&quot;,<br>        &quot;DetailType&quot;: &quot;recovery_history&quot;,<br>        &quot;Detail&quot;: json.dumps({<br>            &quot;cart_id&quot;: event[&quot;cart_id&quot;],<br>            &quot;action_taken&quot;: event[&quot;action&quot;],<br>            &quot;channel&quot;: &quot;email&quot;,<br>            &quot;sent_at&quot;: datetime.utcnow().isoformat(),<br>            &quot;message_id&quot;: ses_response[&quot;MessageId&quot;]<br>        })<br>    }])</pre><pre>    return {&quot;status&quot;: &quot;sent&quot;, &quot;message_id&quot;: ses_response[&quot;MessageId&quot;]}</pre><p>The key insight: <strong>publishing back to EventBridge closes the feedback loop</strong>. The recovery event gets indexed into Elasticsearch, so the next workflow run knows this cart was already contacted and won’t send duplicate emails.</p><h3>The Challenges (and How I Solved Them)</h3><h3>Challenge 1: Cold Starts in a Three-Lambda Chain</h3><p>With three Lambdas in sequence, a fully cold pipeline hits three cold starts. Worst case: ~3–4 seconds of added latency.</p><p><strong>In practice, it’s not that bad.</strong> The MCP Server Lambda is called every 5 minutes by the workflow, so it stays warm most of the time. When it invokes the tool Lambdas, the first call (decision_engine) may be cold (~800ms), but the second call (recovery_action) is usually warm because Lambda pre-warms instances in the same account.</p><p><strong>My solution for production:</strong></p><pre># Provisioned concurrency on the MCP Server only<br>MCPServerFunction:<br>  Properties:<br>    Architectures:<br>      - arm64  # 20% faster cold starts<br>    AutoPublishAlias: live<br>    ProvisionedConcurrencyConfig:<br>      ProvisionedConcurrentExecutions: 1  # ~$2.78/month</pre><p><strong>My solution for demo:</strong> Accept it. A 3-second cold start in a cart recovery pipeline that runs every 5 minutes is irrelevant to the business outcome.</p><h3>Challenge 2: MCP Protocol Over HTTP (Not SSE)</h3><p>The MCP spec supports multiple transports: stdio, SSE, and Streamable HTTP. Lambda naturally supports <strong>request-response HTTP</strong> — but not persistent SSE connections.</p><p>This matters because some MCP clients expect SSE for streaming tool results. Elastic’s AI Agent connector, however, uses simple HTTP POST, which maps perfectly to Lambda’s invocation model.</p><p><strong>Takeaway:</strong> Before choosing Lambda, verify your MCP client supports HTTP transport. If it needs SSE or stdio, Lambda isn’t the right choice without workarounds.</p><h3>Challenge 3: Lambda-to-Lambda Invocation Permissions</h3><p>With three Lambdas, IAM gets more complex. The MCP Server Lambda needs lambda:InvokeFunction on both tool Lambdas. Each tool Lambda needs its own specific permissions.</p><pre># MCP Server role<br>- Effect: Allow<br>  Action: lambda:InvokeFunction<br>  Resource:<br>    - !GetAtt DecisionEngineFunction.Arn<br>    - !GetAtt RecoveryActionFunction.Arn</pre><pre># Decision Engine role — minimal<br>- Effect: Allow<br>  Action: s3:GetObject<br>  Resource: !Sub &quot;arn:aws:s3:::${DecisionMatrixBucket}/*&quot;</pre><pre># Recovery Action role — more permissions<br>- Effect: Allow<br>  Action:<br>    - ses:SendEmail<br>    - events:PutEvents<br>  Resource: &quot;*&quot;</pre><p>Getting this right took iteration. The principle: <strong>each Lambda gets only the permissions it needs, nothing more.</strong></p><h3>Challenge 4: Idempotency for Recovery Actions</h3><p>What if the workflow retries a failed step? What if Lambda processes the same cart twice due to a race condition?</p><p>The recovery_action tool sends emails — a non-idempotent side effect. Sending a duplicate &quot;Here&#39;s 15% off&quot; email is annoying. Sending it 100 times is a lawsuit.</p><p><strong>Solution:</strong> Deterministic idempotency keys based on cart ID + action + date.</p><pre>def lambda_handler(event, context):<br>    idempotency_key = f&quot;{event[&#39;cart_id&#39;]}:{event[&#39;action&#39;]}:{today()}&quot;</pre><pre>    # Check if we already processed this<br>    if already_sent(idempotency_key):<br>        return {&quot;status&quot;: &quot;already_sent&quot;, &quot;skipped&quot;: True}</pre><pre>    # ... send email and log event</pre><h3>Challenge 5: Error Semantics — HTTP Errors vs Tool Errors</h3><p>This tripped me up. In MCP, there are two types of errors:</p><ol><li><strong>Infrastructure errors</strong> — Lambda crashed, timeout, out of memory → return HTTP 500</li><li><strong>Tool errors</strong> — invalid input, business rule violation, SES rejected the email → return HTTP 200 with isError: true</li></ol><pre># ✅ Correct: tool-level error returned by MCP Server<br>{<br>    &quot;statusCode&quot;: 200,<br>    &quot;body&quot;: {<br>        &quot;isError&quot;: true,<br>        &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Customer email is on suppression list&quot;}]<br>    }<br>}</pre><p>The AI agent needs to know the difference. If a tool returns isError: true, the agent can try a different approach. If it gets an HTTP 500, it should retry or escalate.</p><h3>Challenge 6: Decision Matrix Edge Cases</h3><p>What happens when the root cause + segment combination doesn’t exist in the matrix? What about a new segment the business adds next month?</p><p><strong>Solution:</strong> Cascading fallbacks.</p><pre>Exact match (segment + root_cause)<br>    → Segment default<br>        → Global default<br>            → &quot;reminder&quot; (hardcoded safe fallback)</pre><p>Every path through the decision matrix ends at a valid action. No null responses, no crashes, no silent failures.</p><h3>The Honest Pros and Cons</h3><h3>✅ Pros</h3><p><strong>Near-zero cost</strong> — My workload: 288 invocations/day × 3 Lambdas × ~500ms = $0.03/month.</p><p><strong>Zero ops</strong> — No servers, no containers, no Kubernetes, no health checks.</p><p><strong>Native AWS integration</strong> — S3, SES, EventBridge — just import boto3 and go.</p><p><strong>Instant scaling</strong> — If 1,000 carts abandon simultaneously, Lambda handles it.</p><p><strong>Infrastructure as code</strong> — Entire MCP server + both tools defined in one template.yaml.</p><p><strong>Security model</strong> — IAM roles per function, API Gateway auth, no open ports, no SSH.</p><p><strong>Deployment speed</strong> — sam build &amp;&amp; sam deploy — done in 60 seconds for all three functions.</p><p><strong>Independent failure domains</strong> — If the Recovery Action Lambda crashes, Decision Engine still works. The agent gets a diagnosis even if it can’t send the email.</p><h3>❌ Cons</h3><p><strong>Cold starts compound</strong> — Three Lambdas = up to three cold starts on a fully cold pipeline.</p><p><strong>No persistent connections</strong> — Can’t do SSE or WebSocket natively.</p><p><strong>15-minute timeout</strong> — Not suitable for long-running tool operations.</p><p><strong>Stateless</strong> — Can’t share context between tool Lambdas without external store.</p><p><strong>Vendor lock-in</strong> — Tightly coupled to AWS (boto3, SAM, IAM).</p><p><strong>Debugging friction</strong> — Three CloudWatch log groups to search instead of one stdout.</p><p><strong>Invocation overhead</strong> — Lambda-to-Lambda invoke adds ~20–50ms per hop.</p><p><strong>Package size limits</strong> — 250 MB unzipped — fine for Python, tight for heavy ML libs.</p><h3>⚖️ Trade-offs I Accepted</h3><p><strong>Cold starts vs separation of concerns</strong> — Three cold starts is worse than one. But independent IAM roles, independent scaling, and independent failure domains are worth it for a production system.</p><p><strong>Vendor lock-in vs speed</strong> — Wasn’t building for multi-cloud. AWS services (S3, SES, EventBridge, Lambda) saved weeks of development.</p><p><strong>Invocation overhead vs modularity</strong> — 40ms per Lambda-to-Lambda hop is invisible in a 5-minute recovery pipeline. Clean boundaries are worth more than 40ms.</p><h3>Key Takeaways</h3><h3>1. Lambda Is Perfect for MCP — If Your Transport Is HTTP</h3><p>MCP over HTTP maps 1:1 to Lambda’s invocation model. Request in, response out. If your AI agent talks HTTP, Lambda is the cheapest, simplest MCP server you can build.</p><h3>2. Split the Router from the Tools</h3><p>The MCP Server Lambda should only handle protocol — tools/list and tools/call routing. It should not contain business logic. This makes it trivial to add a third or fourth tool: add a new Lambda, register it in the router, deploy.</p><h3>3. Separate Decision from Action</h3><p>My best architectural decision was making decision_engine (read-only, deterministic, S3) a separate tool Lambda from recovery_action (side effects, SES + EventBridge). They have completely different failure modes, retry strategies, permissions, and ownership models.</p><h3>4. The AI Should Diagnose, Not Prescribe</h3><p>The decision matrix lives in S3, not in the AI model. Business rules change weekly. Model retraining takes days. An S3 file update takes seconds. The AI tells you <em>why</em> the cart was abandoned. The business rules tell you <em>what to do about it</em>.</p><h3>5. Feedback Loops Are Non-Negotiable</h3><p>Publishing recovery_history back to EventBridge means the system learns from itself. The next workflow run knows what was already tried. Without this, you get duplicate emails, wasted discounts, and angry customers.</p><h3>6. MCP Error Semantics Matter</h3><p>Return isError: true in the MCP response body for tool-level errors. Reserve HTTP 5xx for infrastructure failures. The AI agent handles these differently, and conflating them causes unpredictable retry behavior.</p><h3>Lessons Learned</h3><p><strong>Lambda-to-Lambda invocation needs careful IAM</strong> — The MCP server needs lambda:InvokeFunction on specific function ARNs. Wildcards work but violate least-privilege. Take the time to set up precise resource-level permissions.</p><p><strong>Decision matrix edge cases will bite you</strong> — The first time a new customer segment appeared that wasn’t in the matrix, the Decision Engine returned null. Always build cascading fallbacks: exact match → segment default → global default → hardcoded safe action.</p><p><strong>SES sandbox is a pain during development</strong> — You can only send to verified email addresses until you request production access. Start the verification process early or use SNS as a placeholder during dev.</p><p><strong>Cold-start chains are multiplicative, not additive</strong> — Three sequential cold starts don’t just add latency — they add unpredictability. The first call might take 1.2s, the next 0.8s, the next 1.5s. Budget for the worst case in your workflow timeout.</p><p><strong>Liquid templating in Elastic workflows is powerful but poorly documented</strong> — Passing complex objects (customer profiles, diagnosis payloads) through Liquid templates requires careful escaping. Test with real data early.</p><p><strong>Deterministic IDs prevent duplicate recovery actions</strong> — Using cart_id + action + date as an idempotency key means the same cart will never get the same recovery email twice in one day, even if the workflow retries.</p><p><strong>Always separate read tools from write tools</strong> — The decision engine <em>reads</em> a matrix. The recovery action <em>writes</em> emails and events. Keeping these separate means you can test, debug, and permission them independently.</p><h3>What I’d Do Differently</h3><p><strong>Add a caching layer</strong> — DynamoDB or ElastiCache for the decision matrix instead of reading S3 on every cold start. S3 GetObject is fast (~50ms), but a cache would make it ~5ms.</p><p><strong>Implement circuit breakers</strong> — If SES is down, stop calling recovery_action and queue carts for later instead of failing repeatedly.</p><p><strong>Add tool versioning</strong> — MCP doesn’t have built-in versioning. I’d add version prefixes to tool names (v1_decision_engine) for backwards compatibility when schemas change.</p><p><strong>Build a local MCP test harness</strong> — Something that simulates tools/list + tools/call locally without deploying to AWS. SAM local gets close but doesn&#39;t test the Lambda-to-Lambda invocation chain.</p><p><strong>Add provisioned concurrency from day one</strong> — Even for a demo, consistent latency makes the system feel production-grade. $2.78/month is worth it.</p><h3>The Numbers</h3><p>MetricValueLambda functions3 (MCP Server + 2 tools)Lambda invocations/day~864 (288 runs × 3 functions)Average tool latency (warm)120msAverage tool latency (cold)980msMonthly Lambda cost$0.03Monthly API Gateway cost$0.01Monthly S3 cost$0.001Time to deploy all 3 functions58 secondsLines of code (all Lambdas)~400Lines of infrastructure (SAM)~120</p><h3>Try It Yourself</h3><p>The entire project is open source:</p><p>🔗 <strong>GitHub:</strong> <a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent">AI Abandoned Cart Recovery Agent</a></p><p>🔗 <strong>Architecture Docs:</strong> <a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent/blob/main/docs/architecture_diagram.md">docs/architecture_diagram.md</a></p><p>🔗 <strong>MCP Server Code:</strong> <a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent/tree/main/mcp_server">mcp_server/</a></p><p>🔗 <strong>Decision Matrix:</strong> <a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent/blob/main/docs/decision_matrix.md">docs/decision_matrix.md</a></p><p>🔗 <strong>SAM Template:</strong> <a href="https://github.com/aashanashanu/ai-abandoned-cart-recovery-agent/blob/main/aws/stack.yml">aws/stack.yml</a></p><h3>Final Thought</h3><p>MCP is going to be as important to AI agents as REST APIs were to web applications. The question isn’t <em>whether</em> your AI will call external tools — it’s <em>how</em>.</p><p>Lambda gives you a way to build those tools with minimal cost, zero ops, and a deployment experience that takes under a minute. It’s not perfect for every use case (streaming, long-running tasks, stateful tools), but for the 80% of MCP tools that are “receive input, do something, return result” — it’s hard to beat.</p><p>The AI handles the thinking. Lambda handles the doing. MCP is the contract between them.</p><p>Three Lambdas. Two tools. One protocol. Zero servers.</p><p><em>If this was useful, follow me for more on AI agents, serverless architecture, and the tools that connect them.</em></p><p><em>Tags: #MCP #AWS #Lambda #AIAgents #Serverless #Elasticsearch #AbandonedCart #ModelContextProtocol</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88feb688bf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>