<?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 Prasanna Nattuthurai on Medium]]></title>
        <description><![CDATA[Stories by Prasanna Nattuthurai on Medium]]></description>
        <link>https://medium.com/@prasannanattuthurai?source=rss-cbb47ae3704c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DSWgLzbAidDaPFoR87YUtw.png</url>
            <title>Stories by Prasanna Nattuthurai on Medium</title>
            <link>https://medium.com/@prasannanattuthurai?source=rss-cbb47ae3704c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:54:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prasannanattuthurai/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[Stop Reading Your AI Agent. Start Talking to It.]]></title>
            <link>https://medium.com/@prasannanattuthurai/stop-reading-your-ai-agent-start-talking-to-it-fd2ceaba49d9?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2ceaba49d9</guid>
            <category><![CDATA[wisper]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[kokoro]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 01:29:25 GMT</pubDate>
            <atom:updated>2026-11-12T01:29:25.581Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I gave my coding agent a free, fully local voice for my personal projects, and why I think this is where agentic coding is headed.</em></p><blockquote><em>🏡 Everything here was built and used on my own side projects, on my personal laptop.</em></blockquote><p>Here’s a confession: I’ve stopped reading most of what my coding agents write.</p><p>Not because it’s bad. Because there’s too much of it. An agent kicks off, reads twelve files, runs the tests, edits four modules, and then hands me a 900-word wall of text with tables, file paths, and a bulleted summary of a bulleted summary. By paragraph three, my eyes are skimming. By paragraph five, I’ve wandered off to another tab.</p><p>That’s the quiet problem with agentic coding nobody talks about.</p><blockquote><strong><em>The agents got faster. Our attention didn’t.</em></strong></blockquote><p>The bottleneck isn’t the model anymore. It’s me, scrolling.</p><p>So I tried something different. I gave my agents a voice and ears. Now I ask a question out loud, the agent goes off and does the work, and comes back with two spoken sentences: <em>“Tests pass. I changed the retry logic in two files. Want the details on screen?”</em></p><p>💻 It runs entirely on my laptop. 💸 It cost me nothing. I built it in Claude Code, but nothing about it is Claude-specific: any agent that can use MCP tools can get the same thing.</p><p>Here’s how, and why I think you should try it.</p><h3>🎙️ Why voice, why now</h3><p>Three things changed my mind.</p><p><strong>1. Agents produce output faster than humans can read it.</strong> A single agentic task can generate more text than a short blog post. Reading all of it is exhausting; skimming it means you miss the one line that mattered. Speech forces the agent to <em>summarise</em>. You can’t speak a table. You can’t speak a 40-line diff. So the agent has to tell you what actually matters, and put the rest on screen if you want it.</p><p><strong>2. Talking keeps you in the loop without keeping you glued to the screen.</strong> When I’m in voice mode, I can lean back, look away, think. The agent works between turns and reports back by voice. It feels less like supervising a log file and more like pairing with a friend who’s sitting next to you.</p><p><strong>3. It’s finally free and local.</strong> A year ago this meant cloud speech APIs, API keys, and paying per minute. Today, open models like <strong>Whisper</strong> (speech-to-text) and <strong>Kokoro</strong> (text-to-speech) run comfortably on a laptop. No account, no key, no audio leaving your machine.</p><h3>🔌 The idea: one voice layer, any agent</h3><p>The trick is that the voice doesn’t live <em>inside</em> the agent. It lives in an <strong>MCP server</strong>, the standard plug-in protocol that Claude Code and a growing list of other coding agents already speak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDTTDgRRbW12VDMvWt0uGQ.png" /></figure><p>The MCP server I use is <strong>VoiceMode</strong> (open source, MIT licensed). It exposes one main tool, converse: speak something, then listen and return what the user said. Any agent that can call MCP tools can now hold a conversation.</p><p>That’s the whole point: <strong>build the voice once, plug it into every agent you use.</strong> When the next coding assistant comes along, it gets a voice for free too.</p><h3>⚡ Setup: about ten minutes</h3><p>I’m on an Apple Silicon Mac with 16 GB of RAM. Nothing exotic.</p><p><strong>1. Install VoiceMode and the local speech services</strong></p><pre>uvx voice-mode-install<br>voicemode service install whisper   # speech-to-text<br>voicemode service install kokoro    # text-to-speech</pre><p><strong>2. Pin it to local only</strong></p><p>By default, VoiceMode can fall back to a cloud API if it finds an API key. I don’t want that:</p><pre>voicemode config set VOICEMODE_STT_BASE_URLS http://127.0.0.1:2022/v1<br>voicemode config set VOICEMODE_TTS_BASE_URLS http://127.0.0.1:8880/v1</pre><p>Now nothing you say leaves the machine.</p><p><strong>3. Plug it into Claude Code</strong></p><p>One line:</p><pre>claude mcp add --scope user voicemode -- ~/.local/bin/voicemode</pre><p><strong>4. Add a </strong><strong>/talk command</strong></p><p>A tiny custom slash command: a markdown file in ~/.claude/commands/ whose prompt says <em>start a voice loop with the </em><em>converse tool, keep replies short, stop when I say “stop”.</em> Type /talk, and you’re talking.</p><p>That’s it.</p><h3>🧩 Using a different agent?</h3><p>The same recipe works in any coding agent that supports MCP. The pieces are always the same:</p><ol><li><strong>Run the two local speech services</strong> (Whisper and Kokoro). They don’t care which agent calls them.</li><li><strong>Register VoiceMode as an MCP server</strong> in your agent’s MCP config, pointing at the voicemode binary.</li><li><strong>Allow its </strong><strong>converse tool</strong>, if your agent asks you to approve tools.</li><li><strong>Add a reusable prompt</strong> (a slash command, custom prompt or rules file, whatever your agent calls it) with the voice-loop rules below.</li></ol><p>Check your agent’s docs for where its MCP config lives. Some read one global file; others want the server listed per agent or per project.</p><h3>💬 Making it feel like a conversation, not a robot</h3><p>Getting audio in and out is the easy part. Making it <em>pleasant</em> took some prompt tuning. The rules that made the biggest difference:</p><ul><li><strong>One or two sentences, ~25 words.</strong> The agent offers to say more instead of explaining everything. This alone fixes the wall-of-text problem.</li><li><strong>Never read code, paths, or tables aloud.</strong> Speak the summary; put the detail on screen.</li><li><strong>A live transcript.</strong> Before each turn, the agent prints 🎤 You: … and 🔊 Friday: …, so the screen matches what you hear. Handy when the speech recognizer mishears you.</li><li><strong>A persona.</strong> In voice, my agent answers as “Friday”: calm, concise, a little dry. Put the persona in the shared prompt and every agent you wire up sounds like the same assistant. Small thing, surprisingly nice.</li><li><strong>Sound human.</strong> Vary the acknowledgements. Nothing kills the vibe like hearing “Great question!” eleven times.</li></ul><h3>🛑 The safety rule you must not skip</h3><p>Speech recognition mishears things, especially names, numbers, and jargon. “Delete the test branch” and “delete the best branch” are one syllable apart.</p><p>So my rule is simple:</p><ul><li><strong>Read-only questions</strong> (“what failed?”, “summarise the last change”): the agent just answers.</li><li><strong>Anything that changes or sends something</strong> (file writes, deletes, git commits and pushes): the agent repeats back what it understood in one sentence and <strong>waits for a spoken “yes”</strong>.</li></ul><p>👉 <strong>Never let a voice command run an action unconfirmed.</strong> This one rule is what makes voice safe enough to actually rely on.</p><h3>🪙 “But doesn’t voice burn more tokens?”</h3><p>I wondered the same, so I measured it from my own session logs.</p><p>Across 16 voice exchanges:</p><ul><li><strong>~350 output tokens per turn</strong> (spoken reply + on-screen transcript + reasoning)</li><li><strong>~800 uncached input tokens in total.</strong> What you say comes back as a tiny bit of text.</li><li>The big number, ~110k cached tokens per call, is just the conversation context being re-read, which is <strong>the same when you type</strong>.</li></ul><p>✅ <strong>Verdict:</strong> a voice turn costs about the same as a typed one. Speech-to-text and text-to-speech run locally, so they’re free. The only extra is the transcript line, maybe 50–100 tokens a turn. If anything, voice <em>saves</em> tokens, because short spoken answers replace long written ones.</p><p><em>(Caveat: that’s one session, not a controlled typed-vs-spoken comparison. Take it as a strong hint, not a benchmark.)</em></p><h3>⏱️ Is it fast enough?</h3><p>Mostly, yes. The voice gap after the agent finishes thinking is about <strong>2 seconds</strong>: ~0.3 s for Whisper to transcribe you, ~1.6 s for Kokoro to start speaking. The real variable is how long the <em>model</em> thinks, which you’d wait for anyway.</p><p>One surprise: <strong>Kokoro was faster on CPU than on the Mac’s GPU.</strong> Time to first audio was 0.4 s on CPU versus 2.2 s on GPU, and the GPU never caught up after warm-up. If your local text-to-speech feels slow, try forcing CPU.</p><p>And a lesson: when benchmarking TTS, use <strong>new text every time</strong>. Repeated text gets cached, and my first measurement looked 5× better than reality.</p><h3>🪤 Gotchas I hit, so you don’t</h3><ul><li><strong>Bluetooth headset as the mic → beeps and robot voice.</strong> macOS flips the headset into “call mode” when it starts listening. Use the laptop mic for input and keep the headset for output.</li><li><strong>voice-mode-install --model small Broke the Whisper install</strong> on my setup. Install Whisper on its own with voicemode service install whisper.</li><li><strong>Python version mismatch.</strong> Kokoro wants Python 3.10; if your machine defaults to a newer version, rebuild its venv on 3.10.</li><li><strong>Corrupt model download.</strong> If Kokoro won’t start, check the model file size. Mine was 50 MB short.</li><li><strong>Not every agent reads a global MCP config.</strong> If the voice tools don’t show up, add the server to the per-agent or per-project config.</li><li><strong>Privacy note:</strong> VoiceMode’s logs store what you said in plain text. Put them on your cleanup list.</li></ul><h3>🚫 What I didn’t use, and why</h3><p>I looked around before settling on this:</p><ul><li><strong>Claude Code’s built-in </strong><strong>/voice</strong>: great for dictation, but input-only and cloud-transcribed. No spoken replies.</li><li><strong>Other voice MCP servers</strong>: either barely maintained, macOS-only and stale, or multiple GBs of models per project.</li><li><strong>Cloud voice tools</strong>: some have nicer live transcripts, but they send your audio to the cloud and some bill separately. Not what I wanted.</li></ul><p>VoiceMode was the only option I found that was fully local, actively maintained, and worked across every project and every agent.</p><h3>🧠 “Is AI making us dumber?”</h3><p>You’ve probably seen the term <strong>cognitive debt</strong> going around, along with <strong>cognitive surrender</strong> and <strong>AI brain fry</strong>. The worry is real, and the research is starting to back it up:</p><ul><li>In a <a href="https://www.infoq.com/news/2026/02/ai-coding-skill-formation/">randomized trial from Anthropic</a>, junior developers who used an AI assistant scored <strong>17% lower</strong> on comprehension tests than those who coded by hand. The interesting part is <em>how</em> they used it. People who handed the whole task to the AI scored below 40%. People who asked it to <em>explain</em> things scored above 65%, as did the no-AI group.</li><li>Researchers <a href="https://arxiv.org/pdf/2609.20143">Shaw and Nave</a> draw a useful line between <strong>cognitive offloading</strong> (you delegate a task but keep thinking about it) and <strong>cognitive surrender</strong> (the AI’s answer becomes your answer without much scrutiny).</li><li>Boston Consulting Group researchers coined <a href="https://builtin.com/articles/ai-brain-fry-software-developers">“AI brain fry”</a> for the mental hangover of keeping up with tools that produce more than you can absorb.</li></ul><p>Here’s my take: the wall of text is a big part of the problem. When an agent dumps 900 words on you, the easiest move is to skim, nod, and accept. That’s surrender by exhaustion.</p><p>Voice won’t fix this on its own. You can say “yes” to everything just as lazily as you can click “accept”. But it changes the default in a few useful ways:</p><ul><li><strong>You have to say what you want out loud.</strong> Putting your intent into a sentence is thinking. It’s hard to explain a task without understanding it.</li><li><strong>Short answers invite follow-ups.</strong> When the agent says “I changed the retry logic in two files”, the natural reply is “why two?” A spoken back-and-forth pulls you into the reasoning instead of past it.</li><li><strong>Less to read means less overload.</strong> You get the gist by ear and open the detail on screen only when it matters. That’s the brain fry problem in reverse.</li><li><strong>The confirmation step makes you decide.</strong> The agent says back what it’s about to do, and you have to actively agree.</li></ul><p>A few habits I’ve picked up to stay on the <em>offloading</em> side of the line:</p><ul><li>Say your guess before you ask. (“I think it’s the timeout. Check?”)</li><li>Ask “why” at least once per task.</li><li>Ask the agent to explain, not just to do, especially in code you don’t know yet.</li><li>Every so often, solve something yourself first and use the agent to check it.</li></ul><p>Voice makes these habits feel natural, because they’re just how you’d talk to a person.</p><h3>🚀 Where this is going</h3><p>I don’t think we’ll read our agents’ output forever. As agents take on longer, more autonomous tasks, the human job shifts from <em>reading everything</em> to <em>staying oriented</em>: knowing what happened, what’s blocked, and what needs a decision, while still thinking yourself.</p><p>Voice is good at exactly that. It’s short and in the moment, and you don’t have to sit and stare at a screen to follow it. Details stay on screen when you want them; the gist comes to you.</p><p>The setup is free, local, and about ten minutes of work. If you spend your evenings building side projects with a coding agent, try talking to it for a week. I don’t think you’ll go back to scrolling.</p><p>🔭 <em>Next up for me: trying NVIDIA’s Parakeet model for even faster speech recognition, and moving the speech services to a home server so the laptop stays cool.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2ceaba49d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My AI Trading Bot Looked Profitable. Every Number That Said So Was the Wrong Number.]]></title>
            <link>https://medium.com/@prasannanattuthurai/my-ai-trading-bot-looked-profitable-every-number-that-said-so-was-the-wrong-number-b5f0052eff71?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f0052eff71</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[sports-betting]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 17:22:26 GMT</pubDate>
            <atom:updated>2026-11-05T17:22:26.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Five ways a prediction-market model fooled me, and the one metric I trust now</h3><p>For five months I ran an LLM-powered forecaster against real prediction markets: Kalshi and Polymarket. It researched a market, estimated a probability, compared it with the price, and logged a “shadow” bet whenever it disagreed enough. Every resolved bet went into a SQLite database.</p><p>The dashboards looked great. Directional accuracy was above 60%. Brier scores cleared the bar I’d set. One strategy beat the market on its first 45 trades. Another showed a statistically significant edge.</p><p>None of it held up. That isn’t because the model was secretly brilliant and unlucky. Each of those numbers was measuring something other than “will this make money.” This post is about how I found that out, one metric at a time. It’s the most useful engineering lesson I’ve learned this year, and it applies well beyond betting. If you evaluate any AI system, whether a classifier, a ranker, an agent, or a forecaster, you probably have one of these five problems too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyApEPWyXOuLnQfOlVvYRA.png" /></figure><h3>1. Accuracy over everything vs. accuracy on what you act on</h3><p>The headline number was <strong>60.9% directional accuracy</strong>. That was over every market the model looked at.</p><p>But most of those were SKIPs: markets where the model’s estimate sat close to the price, so no bet would ever be placed. On those, “pick the favourite” is easy and the model agrees with the crowd. That pads the score.</p><p>The bets that matter are the ones where the model <em>disagrees</em> with the market by 5 points or more. That’s the only subset where money moves. On that subset:</p><blockquote><strong><em>61 of 152 correct. 40.1%.</em></strong></blockquote><p>The corpus number and the actionable number pointed in <strong>opposite directions</strong>. The model was right when it agreed with everyone and wrong 60% of the time when it had an opinion.</p><p><strong>The lesson:</strong> score the decisions your system actually makes, not everything it touches. If your agent only acts on 15% of inputs, the other 85% are noise in your eval.</p><h3>2. Beating a fixed bar vs. beating the baseline you compete with</h3><p>My go-live gate said “Brier score under 0.25.” Soccer came in at 0.2177, which passed.</p><p>The market’s own price scored 0.2118 on the same games.</p><p>The model “passed” while losing to the thing it was betting against. A fixed threshold told me nothing. The only bar that matters for a forecaster is the <strong>price</strong>, because the price is your opponent. When I re-scored every football category against the market, the market won every time. Over 517 markets it was 0.2376 for the model and 0.2166 for the price. I killed football forecasting.</p><p><strong>The lesson:</strong> a threshold is a guess. A baseline is a fact. Compare against the best simple thing you could do instead, whether that’s the price, the heuristic, the last model or the if/else.</p><h3>3. Small-sample edge vs. the same edge at 4× the data</h3><p>Cross-venue “arbitrage” (the same event priced differently on two exchanges) looked like the cleanest win. At <strong>n=45</strong>, its Brier score was 0.0906 against the market’s 0.0928. It was a small edge, but a real one, and it was enough that I wired it up to place real orders.</p><p>At <strong>n=170</strong>, the edge was gone: 0.1951 for the model, 0.1951 for the market. On the 21 bets it actually took, it went 9 for 21.</p><p>A negative or zero edge doesn’t turn positive with more data. More volume only makes you more certain it’s not there.</p><p><strong>The lesson:</strong> never promote a system on its first good sample. Decide the checkpoint size <em>before</em> you look, and don’t let an early number buy production access.</p><h3>4. Gross edge vs. net edge at the price you can actually get</h3><p>This one hurt the most because the bug was a single constant.</p><p>The “favourites” strategy bought heavily favoured outcomes priced 0.65–0.80. I pre-registered it: run until 100 resolved out-of-sample bets, then judge. At 135 resolved bets:</p><ul><li>Hit rate <strong>65.19%</strong> against an average price of <strong>68.69%</strong></li><li>Gross edge <strong>-3.50pp</strong> per contract</li></ul><p>That was already negative. Then I found my fee model was wrong. I had Polymarket US’s taker fee as 0.003 × p. The real formula is 0.0695 × p × (1 − p), about 1.5 points at these prices, or <strong>five times what I&#39;d modelled</strong>. Net edge was <strong>-4.97pp</strong>.</p><p>Even the one <em>statistically significant</em> positive result had the same problem. Closing-line value on favourites was +1.15pp, with a 95% CI of [+0.37, +1.97] that stayed above zero. But that was measured at the <em>mid</em>-price. Scored at the ask, the price you actually pay, after fees, it came to <strong>-1.93pp</strong>. The spread plus the fee ate it.</p><p><strong>The lesson:</strong> measure at the point of execution, with the real costs, from the real docs. “Edge at mid” is a backtest fantasy. For AI systems, the equivalent is quality measured without latency, token cost or the retry rate.</p><h3>5. Data that leaks vs. data the model could actually see</h3><p>The economics markets ask things like “Will CPI come in above 3.2%?” The model’s estimates were wildly off, and for weeks I treated that as a modelling problem.</p><p>It was a parsing bug. Any strike with a decimal point got cut off, so the question the model received read <strong>“more than -0”</strong>. 251 rows were estimated from questions with the threshold missing. I was grading a model on a test it could not read.</p><p>The opposite leak showed up in the backtest. The walk-forward calibration was quietly using information from after the forecast time (look-ahead), and it counted some markets more than once. Fixing both made the numbers worse, and they were also the first honest ones.</p><p><strong>The lesson:</strong> before you blame the model, read the exact input it received. Then check that your evaluation can’t see the future.</p><h3>The one metric I trust now</h3><p>After all five fixes, one number decides whether real money is allowed:</p><blockquote><strong><em>Realised edge, net of fees, at the executable price, one row per market, with a bootstrapped 95% confidence interval whose lower bound must clear zero.</em></strong></blockquote><p>The all-time figure today: <strong>-0.61pp, CI [-8.01, +6.88].</strong> Not cleared.</p><p>Then there’s the part nobody puts on a dashboard: statistical power. My earlier gate said I needed “about 400 more bets.” That was a 50%-power figure built on an effect size that turned out to be inflated. At 80% power, proving a real <strong>3-point edge takes about 2,000 bets.</strong> At my volume, that’s a long time.</p><p>So the bot doesn’t trade. Specifically:</p><ul><li><strong>Real orders are hard-disabled.</strong> Every command that can place one refuses unless an explicit environment flag is set for that single run.</li><li><strong>There’s a lifetime loss cap</strong> of $50 per venue, enforced in code, not by willpower.</li><li><strong>Kill criteria are pre-registered, and “kill” is the default.</strong> The economics strategy gets judged on a fixed date against a fixed test. If the result is ambiguous, it dies. I wrote the rule down before seeing the data so I can’t negotiate with myself later.</li><li><strong>No refitting a dead hypothesis.</strong> When “favourites” failed, the 0.70–0.80 slice looked mildly positive. That slice came from cutting up a failed experiment, so it doesn’t get a test of its own.</li></ul><h3>Why I’m publishing a failure</h3><p>Every “I built an AI trading bot” post I’ve read ends with an upward-sloping equity curve. Mine ends with a confidence interval that straddles zero and an honest power calculation. That’s the more useful post.</p><p>The bot didn’t fail because LLMs can’t reason about probabilities. The <em>evaluation</em> failed five times, and each failure flattered the model. That pattern is everywhere in AI engineering right now: a leaderboard number that doesn’t match your traffic, a demo scored on the easy cases, a cost model off by 5×, a benchmark leaking into the training data.</p><p>The forecaster was the easy part. Building a measurement system that couldn’t lie to me took months, and that’s the part I’d hire for.</p><p><em>If you’re building evals for agents or forecasters and want to compare notes on baselines, power and pre-registration, I’d love to hear how you’re doing it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f0052eff71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Developer Toolchain Is a Supply Chain Attack Surface — Here’s How I Hardened Mine]]></title>
            <link>https://medium.com/@prasannanattuthurai/your-developer-toolchain-is-a-supply-chain-attack-surface-heres-how-i-hardened-mine-e18072c68c4b?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e18072c68c4b</guid>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 16:33:26 GMT</pubDate>
            <atom:updated>2026-08-22T16:34:50.095Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to applying SLSA, Sigstore, and SBOM-based verification to the tools on your local machine.</em></p><h3>The Problem Nobody Talks About</h3><p>We obsess over dependency scanning in CI/CD. We pin versions in package-lock.json. We run Dependabot. But what about the tools that <em>build</em> your software?</p><p>Every morning, you run brew upgradenpm updates your global packages. rustup update refreshes your Rust toolchain. Each of these is an implicit trust decision:</p><blockquote>“I trust that the binary I just downloaded is exactly what the publisher built, from the source code I’d expect, without tampering in transit.”</blockquote><p>For most developers, that trust is blind. I decided to make it explicit.</p><h3>Threat Model: What Can Go Wrong</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*fExmJYbTU2qxiFatYtXjWw.png" /></figure><p>The attack surface is your entire toolchain: <strong>compilers, linters, security scanners, CLI tools, language runtimes</strong>. If an attacker compromisestrivy, they can hide their own CVEs from your scans.</p><h3>The Architecture: 6 Defense Layers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Yj_dpn0Yv0-BXDZI3crN8g.png" /></figure><pre>┌─────────────────────────────────────────────────────────────────────┐<br>│                    DEVELOPER WORKSTATION                            │<br>├─────────────────────────────────────────────────────────────────────┤<br>│                                                                     │<br>│  Layer 1: TRANSPORT SECURITY                                        │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  All channels: TLS 1.2+ (brew, npm, PyPI, crates.io, Go)     │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                              │                                      │<br>│  Layer 2: CRYPTOGRAPHIC VERIFICATION                                │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  brew: SHA256 bottles    │  uv: Sigstore cosign              │   │<br>│  │  rustup: signed manifest │  npm: ECDSA registry sigs         │   │<br>│  │  macOS: Apple code-sign  │  Go: sum.golang.org               │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                              │                                      │<br>│  Layer 3: SOURCE ALLOWLISTING                                       │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  Homebrew tap allowlist (BLOCK on untrusted)                 │   │<br>│  │  npm pinned package list + --ignore-scripts                  │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                              │                                      │<br>│  Layer 4: SYSTEM INTEGRITY                                          │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  SIP enabled │ Gatekeeper enabled │ No world-writable PATH   │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                              │                                      │<br>│  Layer 5: AUDIT TRAIL                                               │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  SHA256 pre/post snapshot │ Timestamped log │ Diff alerting  │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                              │                                      │<br>│  Layer 6: SUPPLY-CHAIN VERIFICATION (post-update)                   │<br>│  ┌──────────────────────────────────────────────────────────────┐   │<br>│  │  ┌─────────────┐ ┌───────────────┐ ┌─────────────────────┐   │   │<br>│  │  │ brew verify │ │ npm audit sig │ │ gh attestation      │   │   │<br>│  │  │ (Sigstore)  │ │ (provenance)  │ │ verify (SLSA L3)    │   │   │<br>│  │  └─────────────┘ └───────────────┘ └─────────────────────┘   │   │<br>│  │  ┌─────────────┐ ┌───────────────┐ ┌─────────────────────┐   │   │<br>│  │  │ syft→grype  │ │ govulncheck   │ │ cargo audit         │   │   │<br>│  │  │ (SBOM+CVE)  │ │ (-mode=binary)│ │ (RustSec DB)        │   │   │<br>│  │  └─────────────┘ └───────────────┘ └─────────────────────┘   │   │<br>│  │  ┌─────────────┐ ┌───────────────┐                           │   │<br>│  │  │ codesign -v │ │ SHA diff alert│                           │   │<br>│  │  │ (macOS sig) │ │ (tampering)   │                           │   │<br>│  │  └─────────────┘ └───────────────┘                           │   │<br>│  └──────────────────────────────────────────────────────────────┘   │<br>│                                                                     │<br>└─────────────────────────────────────────────────────────────────────┘</pre><h3>The Gap Analysis: Industry vs. Reality</h3><p>I benchmarked my existing toolchain updater against SLSA v1.0, NIST SP 800–218 (SSDF), and CISA’s Secure Software Development guidance. Here’s what I found:</p><h3>What Most Developers Have (SLSA L1)</h3><ul><li>✅ Lock files with checksums (package-lock.json, Cargo.lock, go.sum)</li><li>✅ TLS on all download channels</li><li>✅ Package manager verifies checksums at install time</li></ul><h3>What’s Missing (SLSA L2/L3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*R7c4R9zw9RPfp8J61hvbzg.png" /></figure><h3>The Implementation</h3><h3>1. Sigstore Provenance Verification (Homebrew)</h3><p>Homebrew bottles from homebrew-core have had SLSA L3 Sigstore attestations since 2024. Most developers don&#39;t know this — or that you can verify them independently:</p><pre># Verify your security tools came from the real Homebrew CI<br>brew verify trivy<br>brew verify semgrep<br>brew verify gitleaks<br>brew verify gh</pre><p>This checks the Sigstore transparency log and confirms the bottle was built by Homebrew’s GitHub Actions workflow, from the expected source commit.</p><p><strong>Real output from my system:</strong></p><pre>[sec]   ✓ provenance verified: trivy<br>[sec]   ✓ provenance verified: semgrep<br>[sec]   ✓ provenance verified: gitleaks<br>[sec]   ✓ provenance verified: osv-scanner<br>[sec]   ✓ provenance verified: gh<br>[sec]   ✓ provenance verified: jq<br>[sec]   ✓ provenance verified: node<br>[sec]   ✓ provenance verified: python@3.13<br>[sec]   ✓ provenance verified: go<br>[ok]    Homebrew provenance: all 9 critical formulae verified</pre><h3>2. npm Provenance Signatures (Not Just npm audit)</h3><p>npm audit checks for known CVEs. npm audit signatures Checks that packages were built from their claimed source repo via Sigstore:</p><pre># This checks CVEs:<br>npm audit<br><br># This checks provenance (different!):<br>npm audit signatures</pre><p>These are complementary, not interchangeable. A package can have zero CVEs but be a complete forgery.</p><h3>3. SBOM + Binary Vulnerability Scanning</h3><p>Here’s the insight most developers miss: <strong>compiled binaries embed their entire dependency tree.</strong> A Go binary built with a vulnerable net/http is vulnerable even after you&#39;ve updated your system Go.</p><pre># Generate an SBOM of all your Homebrew binaries<br>syft dir:$(brew --prefix)/bin -o cyclonedx-json &gt; toolchain-sbom.json<br># Scan for embedded vulnerabilities<br>grype sbom:toolchain-sbom.json --only-fixed --fail-on high</pre><p><strong>My result:</strong> grype: no high/critical fixable vulns in toolchain binaries✅</p><h3>4. Go Binary Vulnerability Scanning</h3><p>govulncheck -mode=binary is the Go team&#39;s official tool for scanning compiled Go binaries. It reads the embedded module info and checks against the Go vulnerability database:</p><pre># Scan your security tools (they&#39;re all written in Go!)<br>govulncheck -mode=binary $(which trivy)<br>govulncheck -mode=binary $(which gh)<br>govulncheck -mode=binary $(which gitleaks)<br>govulncheck -mode=binary $(which osv-scanner)</pre><p>On a first run, this surfaced a batch of Go stdlib DoS advisories in one of the scanners above — the binary had been compiled against an older Go toolchain than the one that fixed them. Low risk in a local CLI context, and resolved by a rebuild, but the point is that nothing else I ran would have told me.</p><h3>5. SHA Diff Alerting (The Most Important One)</h3><p>Recording SHA256 hashes is meaningless if you never compare them. The real value is <strong>detecting unexplained changes</strong>:</p><pre># After every update run, record hashes<br>shasum -a 256 $(brew --prefix)/bin/trivy &gt;&gt; binary-shas.txt<br><br># On next run, compare:<br># - If SHA changed AND an update was logged → expected ✅<br># - If SHA changed WITHOUT a logged update → RED FLAG 🚨</pre><p><strong>My implementation detects this automatically:</strong></p><pre>[sec]   Comparing runs: 2026-08-09 → 2026-08-18<br>[sec]   ✓ go: SHA changed (update logged)<br>[ok]    Binary diff: 1 changes, all explained by logged updates</pre><p>If a binary ever changes without a corresponding update in the log, the script flags it as potential tampering.</p><h3>The Complete Flow</h3><pre>┌──────────────────┐<br>│   brew upgrade   │──→ SHA256 bottle verification (automatic)<br>│   npm install -g │──→ --ignore-scripts (kill postinstall RCE)<br>│   uv self update │──→ Sigstore cosign verification (automatic)<br>│   rustup update  │──→ Signed manifest verification (automatic)<br>└────────┬─────────┘<br>         │<br>         ▼<br>┌──────────────────────────────────────────────────────┐<br>│            POST-UPDATE VERIFICATION                   │<br>├──────────────────────────────────────────────────────┤<br>│                                                      │<br>│  1. brew verify (Sigstore provenance)                │<br>│  2. npm audit signatures (provenance ≠ CVE scan)    │<br>│  3. gh attestation verify (SLSA L3 for Releases)    │<br>│  4. syft → grype (SBOM-based binary vuln scan)      │<br>│  5. codesign -v (macOS signature validation)        │<br>│  6. SHA diff alerting (detect unexplained changes)   │<br>│  7. govulncheck -mode=binary (Go embedded deps)     │<br>│  8. cargo audit (RustSec advisory DB)               │<br>│                                                      │<br>└────────┬─────────────────────────────────────────────┘<br>         │<br>         ▼<br>┌──────────────────┐<br>│  SHA256 snapshot │──→ Baseline for next run&#39;s diff<br>│  SBOM archived   │──→ Audit trail<br>│  Log recorded    │──→ Evidence<br>└──────────────────┘</pre><h3>What This Catches (Real Examples)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*rm1h9RheysSHe9JpFdeJGw.png" /></figure><h3>The Ecosystem Reality Check</h3><p>Not everything is verifiable yet. Here’s the honest state as of 2026:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*fO8PPJAbSXdux478_8r-yA.png" /></figure><p>The strategy is <strong>defense in depth</strong>: verify what you can cryptographically, scan what you can’t verify, and detect tampering as a last resort.</p><h3>Getting Started (15 Minutes)</h3><pre># 1. Install the verification tools<br>brew install syft grype cosign<br>go install golang.org/x/vuln/cmd/govulncheck@latest<br>cargo install cargo-audit<br># 2. Verify your current Homebrew bottles<br>for f in trivy semgrep gh node python@3.13 go; do<br>  brew verify &quot;$f&quot; 2&gt;/dev/null &amp;&amp; echo &quot;✓ $f&quot; || echo &quot;✗ $f&quot;<br>done<br># 3. Check npm provenance<br>npm audit signatures<br># 4. Generate your first toolchain SBOM<br>syft dir:$(brew --prefix)/bin -o cyclonedx-json &gt; ~/toolchain-sbom.json<br>grype sbom:~/toolchain-sbom.json --only-fixed<br># 5. Scan Go binaries<br>govulncheck -mode=binary $(which trivy)<br>govulncheck -mode=binary $(which gh)<br># 6. Create your SHA baseline<br>for bin in brew node npm go cargo trivy gh; do<br>  shasum -a 256 &quot;$(which $bin)&quot; &gt;&gt; ~/binary-shas-baseline.txt<br>done</pre><h3>What I Learned</h3><ol><li><strong>Recording hashes is not monitoring.</strong> A hash file that’s never diffed is security theater. You need automated comparison with explainability (was there a logged update or not?).</li><li><strong>Your security tools are attack surface.</strong> trivy, semgrep, gitleaks — if these are compromised, they can hide their own findings. Scan the scanners.</li><li><strong>npm audit is not </strong><strong>npm audit signatures.</strong> One checks CVEs, the other checks provenance. You need both.</li><li><strong>Bash 3.2 is still the default on macOS.</strong> If your security script uses mapfile or associative arrays, it silently fails on every Mac. Ship it or test it.</li><li><strong>Timeouts matter.</strong> Any network call in a security script that can hang indefinitely will eventually hang indefinitely. I learned this the hard way when Sigstore transparency log queries hung for 90 minutes.</li><li><strong>SLSA is a consumer spec too.</strong> Most people think SLSA is for producers/builders. It’s equally a spec for how consumers should verify artifacts.</li><li><strong>A check that fires on a healthy machine is worse than no check.</strong> My world-writable PATH test matched any two w characters in the permission string — so it flagged every <em>group</em>-writable directory, which is Homebrew&#39;s own normal layout. It also read the wrong column, testing other-<em>read</em> instead of other-write. Result: PATH hijack risk! On a correctly configured Mac, every single run — a warning with no way to act on it, the kind you stop reading. A false positive doesn&#39;t just waste attention; it trains you to skip the output, and then the true positive scrolls past too. Prefer a false negative you&#39;ll notice missing over a false alarm you&#39;ll learn to filter.</li><li><strong>My tool was broken for every user but me, and only a second machine could tell me.</strong> One line read the list of Rust-installed binaries:</li></ol><pre>cargo install --list | grep -E &quot;^[a-z]&quot; | while read -r line; do</pre><p>Under set -euo pipefail, grep matching nothing exits 1, which aborts the entire script. On a machine with no cargo-installed binaries — a fresh Mac, most people&#39;s Mac — the dry run died silently a third of the way through. It worked flawlessly for me because I happen to have some. No amount of testing on my own laptop could have surfaced it; a CI runner found it on its first execution. If you&#39;re writing a tool that inspects an environment, the one environment you cannot test in is your own.</p><h3>References</h3><ul><li><a href="https://slsa.dev/spec/v1.0/verifying-artifacts">SLSA v1.0 — Verification specification</a></li><li><a href="https://csrc.nist.gov/publications/detail/sp/800-218/final">NIST SP 800–218 (SSDF)</a></li><li><a href="https://github.com/Homebrew/brew/issues/17019">Homebrew Sigstore attestations</a></li><li><a href="https://docs.npmjs.com/generating-provenance-statements">npm provenance documentation</a></li><li><a href="https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck">govulncheck binary mode</a></li><li><a href="https://github.com/anchore/syft">Anchore syft + grype</a></li><li><a href="https://rustsec.org/">RustSec Advisory Database</a></li></ul><p>The full implementation is open source — a 1,300-line bash script with no<br>runtime dependencies beyond Homebrew itself:</p><pre>brew tap prasannavarshan/tap<br>brew trust prasannavarshan/tap    # Homebrew gates third-party taps<br>brew install update-toolchain<br>update-toolchain --dry            # report; change nothing<br>update-toolchain --audit          # security checks only</pre><p>Source, threat model and known limitations:<br><a href="https://github.com/prasannavarshan/update-toolchain">github.com/prasannavarshan/update-toolchain</a></p><p>Allowlists are config files, not code, so nothing updates unless you name it—and the config is parsed, never sourced, because a tool that decides what to trust should not let its own config file execute anything.</p><p><strong>Tags:</strong> #SupplyChain #DevSecOps #SLSA #Sigstore #macOS #Homebrew #SBOM #SecurityEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e18072c68c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Second Brain for Claude Code: The Architecture and the Features It Took to Make It…]]></title>
            <link>https://medium.com/@prasannanattuthurai/building-a-second-brain-for-claude-code-the-architecture-and-the-features-it-took-to-make-it-7ce4f106087c?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce4f106087c</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[second-brain]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 03:05:15 GMT</pubDate>
            <atom:updated>2026-08-18T03:05:15.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Second Brain for Claude Code: The Architecture and the Features It Took to Make It Actually Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SecACarGD2w9M_7DXLzrRA.png" /></figure><p>I run Claude Code across a number of separate projects. Each one accumulates its own hard-won lessons: gotchas, architectural decisions, things that broke once and shouldn’t break again. The problem was never capturing that knowledge once. It was making it survive.</p><p>A single Claude Code session forgets everything the moment it ends. So I built a “second brain” — a system that turns every session into durable, structured knowledge that future sessions read back automatically. This is a walkthrough of how it’s actually built: the pieces, why each one exists, and the failure that forced the most important one.</p><h3>The shape of the problem</h3><p>A second brain for a coding agent has to answer three questions correctly, every time:</p><ol><li><strong>How does new information get captured</strong> without me manually writing it down?</li><li><strong>How does it get back in front of the agent</strong> in a future session, automatically?</li><li><strong>How does it stay correct</strong> as facts change, instead of slowly filling up with stale and contradictory notes?</li></ol><p>The first two are the “obvious” half of the system — most people who build agent memory get this far. The third is the part that actually determines whether the thing is trustworthy six months in. It’s also the part I got wrong initially, and the fix for it is the core engineering story here.</p><h3>Architecture overview</h3><p>The diagram above shows the full loop. In words:</p><ul><li>A <strong>new Claude Code session starts</strong> → session-start.py injects knowledge/index.md (a compiled summary of everything known) plus the most recent daily log into context. This is the only reason any of this knowledge is useful — it has to show up automatically, with zero manual recall.</li><li><strong>You work the session.</strong> At the end — either a natural session end or a context-window compaction — session-end.py / pre-compact.py fire, extract the full transcript, and spawn flush.py in the background so it doesn&#39;t block you from continuing to work.</li><li>flush.py is the <strong>real-time distillation path</strong>: it hands the transcript to an LLM with a classification prompt and asks it to pull out anything durable, in real time, per session.</li><li>Separately, compile_knowledge.py is a <strong>weekly batch pass</strong> over the accumulated daily/*.md logs — a second, slower pass that catches anything the real-time path missed or under-weighted, using the same classification logic.</li><li>Both paths converge on one decision: <strong>is this fact STATE or EVENT?</strong></li><li>knowledge/*.md files store the result in two sections — ## Current State and ## Log — with different write semantics for each.</li><li>A separate <strong>audit tool</strong> periodically scans the whole knowledge base for rot and reports findings — it doesn’t fix anything, it just tells you where to look.</li><li>knowledge/index.md gets regenerated, and the loop closes back into session-start.py for the next session.</li></ul><p>Every one of those boxes exists because of something that broke without it. Here’s the feature-by-feature version.</p><h3>Feature 1: Two capture paths, not one</h3><p>It would be simpler to have exactly one place where knowledge gets written. I built two on purpose.</p><p>flush.py runs immediately after every session, in the background, so a lesson learned tonight is available tomorrow morning without waiting for anything. But real-time extraction under a &quot;don&#39;t block the user&quot; constraint is going to miss things — an LLM given one transcript in isolation doesn&#39;t have the benefit of seeing the same fact stated three different ways across three different sessions.</p><p>compile_knowledge.py is the reconciliation pass: once a week, it reads the full backlog of daily/*.md journal entries and re-runs the same classification, with the benefit of more context and no urgency. It&#39;s the difference between a fast, cheap first draft and a slower editorial pass.</p><h3>Feature 2: STATE vs EVENT — the classification that actually matters</h3><p>This is the load-bearing idea in the whole system, and it’s simple enough to state in one line:</p><blockquote><em>Every fact is either </em><strong><em>state</em></strong><em> (one current value that changes over time) or an </em><strong><em>event</em></strong><em> (a thing that happened, permanently true as a historical record).</em></blockquote><p>“The billing kill-switch is currently OFF” is state — there is exactly one correct answer at any given moment, and it changes.<br>“I shipped the circuit breaker fix on 2026–07–06” is an event — it happened, and it stays true forever.</p><p>Before this distinction existed in the write path, both kinds of fact got the same treatment: appended to the file. That’s correct for events. It’s silently wrong for state, because appending a new state value next to the old one doesn’t correct anything — it just leaves two facts in the same file, disagreeing, with no signal about which one is current. I found this rotting a real file: a billing kill-switch documented as “paused” sat in a knowledge file for months after it had actually fired for real, because the correction had been appended below the original note instead of replacing it. Whichever line an LLM (or me, skimming at 11pm) happened to read first became “true,” at random.</p><p>The fix is COMPILE_PROMPT (the classification prompt inside flush.py, shared by compile_knowledge.py) asking, for every extracted fact: is this is_state: true or false? That one boolean is what routes the fact down one of two different write paths.</p><h3>Feature 3: merge_state_bullet() — replace in place, keep the history</h3><p>Classifying a fact as “state” only matters if something downstream actually treats it differently. That something is a ~40-line function wired into both write paths:</p><ul><li>Every state fact carries a bolded key — **Kill-switch**, **Streamlit ports**, **Open action items**.</li><li>When a new state fact for the same key arrives, merge_state_bullet() finds the existing bullet under ## Current State and <strong>replaces it in place</strong>, dated.</li><li>The <strong>old value doesn’t disappear</strong> — it gets pushed into the append-only ## Log section. Nothing is lost; it&#39;s just filed as history instead of left sitting next to its own replacement pretending to still be current.</li><li>Event facts skip all of this and go straight to ## Log, exactly as before.</li></ul><p>This is the reason every knowledge/*.md file now has the same two-section shape you see in the diagram: a ## Current State block that&#39;s small, dated, and always tells the truth as of its date, and a ## Log block that&#39;s an honest, append-only record of everything that ever happened. Two files I&#39;d been actively relying on — one tracking a long-running service&#39;s rollout status, one tracking a dashboard&#39;s build status — were quietly rotted exactly this way before the fix went in.</p><h3>Feature 4: an audit layer that only finds problems, never fixes them</h3><p>Even with the write path fixed, old rot doesn’t heal itself, and new rot can still creep in (a fact classified wrong, a note written by hand outside the normal path). So there’s a separate tool — adopted from Cole Medin’s second-brain-audit skill — that periodically scans every file in knowledge/ and reports three things, deterministically, with no LLM involved:</p><ul><li><strong>Cross-file contradictions</strong> — the same subject answered differently in two different files.</li><li><strong>“Finished, but still open”</strong> — an item marked done in one place while a checklist elsewhere still lists it as pending.</li><li><strong>Dating coverage</strong> — what percentage of durable bullets carry an explicit date, because recency-based conflict resolution is only trustworthy once that number is high enough (mine sits around 5% right now — a live, ongoing gap, not a solved one).</li></ul><p>Deliberately, this tool does not auto-fix anything. It flags; a human decides. That boundary is doing real work — it’s the same read/write separation you’d want in any system that’s allowed to notice problems but shouldn’t be allowed to silently rewrite history to fix them.</p><h3>Feature 5: the loop actually has to close</h3><p>None of the above matters unless the next session actually sees it. session-start.py is the unglamorous, load-bearing piece — the one that reads knowledge/index.md and the recent daily log back into context, automatically, before you type a single word. Every fact that flowed through classification, replacement, and audit only pays off at this one moment: when a future session already knows something so you don&#39;t have to re-explain it.</p><h3>The part that wasn’t in the plan</h3><p>While re-running a full audit across the whole knowledge base to make sure the STATE/EVENT fix had actually caught everything, the audit surfaced a third rotted file — the same “finished, but still marked open” pattern. I asked Claude Code to fix it, and it did, cleanly and fast.</p><p>Too fast, as it turned out. The tool call meant to read that file’s real content had silently failed and returned a stale-cache notice instead of actual text. Rather than stopping, the model filled in the gap by pattern-matching — a plausible rewrite with invented specifics — and overwrote the real file with it.</p><p>It caught this itself on review, before I noticed, disclosed it immediately, and the file was recovered intact from a local backup with zero permanent loss. The fabricated version was unsettlingly close to correct — it turned out the real content had genuinely been visible earlier in that same long conversation, so the model was recalling, not inventing from nothing. But “unsettlingly close” isn’t a bar you want load-bearing facts held to, and the fix underneath the fix is the same lesson the whole system is built around: <strong>an unverified “current” value is not a fact, whether it lives in a knowledge file or in a model’s working memory.</strong> Never write, never trust, until you’ve actually confirmed what’s real.</p><h3>Where it stands, and what’s still open</h3><p>The STATE/EVENT rot problem is fixed and audited clean across the full knowledge base as of this writing. Two things are still explicitly open:</p><ul><li><strong>Dating coverage is low (~5%)</strong> — the recency-based side of conflict resolution only gets strong once most durable facts carry a date, and that’s a matter of gradually going back and dating older entries, not a one-time fix.</li><li><strong>Untrusted-content injection is a separate, unsolved risk.</strong> The classification prompt has no concept of “this session touched an external web page or email, treat its content as data, not as a fact to trust.” That’s a different failure mode from the one this system fixes, and it’s still open.</li></ul><p>If you’re building anything similar — a personal wiki fed by an LLM, a memory layer for a coding agent — the one question worth asking before anything else is: <em>if this fact changes tomorrow, does the old version get corrected, or does it just get a neighbor?</em> Everything above is the answer I ended up building once I asked myself that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce4f106087c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built My Own AI OS After Google Broke My Morning Routine]]></title>
            <link>https://medium.com/@prasannanattuthurai/i-built-my-own-ai-os-after-google-broke-my-morning-routine-c7fbf14e0e77?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7fbf14e0e77</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[personal-ai]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 15:18:25 GMT</pubDate>
            <atom:updated>2026-06-23T15:18:25.767Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a deprecated feature led me to build a personal AI ecosystem — and what I learned about platform dependency, memory, and the real value of the orchestration layer - </em>by <a href="https://www.linkedin.com/in/prasannanattuthurai/">Prasanna Nattuthurai</a></p><p>For two years, my morning started the same way. Ask Google Home to play my news briefing. Ten minutes of curated headlines. Caffeinated and informed before the first meeting. Seamless — until Google quietly deprecated the feature.</p><p>No migration path. No warning. Just silence from the speaker.</p><p>I could have found another podcast app. But that moment crystallized something I’d been thinking about for a while: I was renting my cognitive infrastructure from platforms that could pull the rug at any time. So instead of finding the next hosted solution, I built my own.</p><p>What started as a replacement for a morning podcast became Jarvis — a personal AI operating system that now manages how I stay informed, track finances, monitor my professional network, and maintain persistent memory across hundreds of daily interactions.</p><h3>The Architecture</h3><p>Jarvis is a Telegram-first assistant that acts as a central hub for a constellation of specialized agents. You message it like a person. Behind the scenes, it orchestrates a multi-agent network over the MCP protocol, with GCP Vertex AI (Gemini) as the language backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx7BtsYzo7uziDZIcK1UMA.png" /></figure><p>The core has three main components running inside a single FastAPI service:</p><p>Orchestrator + Skills handles incoming messages, routes intent, loads relevant skill context from markdown files, and decides which sub-agents to invoke. Skills are directories with a YAML-frontmattered markdown spec — adding a capability is adding a folder, not modifying code.</p><p>Memory System is a markdown-driven store — three files called SOUL, USER, and MEMORY — indexed into SQLite with FTS5 for semantic search. Jarvis remembers context across sessions without a vector database. The simplicity is deliberate: markdown files are human-readable, diffable, and easy to edit directly when needed.</p><p>Heartbeat Scheduler is a proactive agent that fires on a cron schedule. Instead of waiting to be asked, it sends context-aware notifications: market signals, upcoming renewals, morning briefings. This shift — from reactive assistant to proactive partner — is where the real value lives.</p><p>Everything is observable via Langfuse, which traces every LLM call. If something behaves unexpectedly, I have a full audit trail to the exact prompt and response.</p><h3>The Agent Network</h3><p>Six specialized agents connect to Jarvis over MCP, each with a scoped tool surface and its own dependency environment:</p><p>Newsflow — Daily AI Podcast Aggregates sources, summarizes via LLM, generates a structured script, and synthesizes it into a polished audio briefing using Azure TTS with distinct host voices. Lands in my podcast app every morning. The direct replacement for what Google deprecated.</p><p>Seeker — Network Intelligence Monitors professional networks for signal: job movements, funding rounds, notable connection activity. Proactive alerts instead of manually scrolling feeds.</p><p>Artha — Finance Agent Ingests bank and card statements, detects patterns, surfaces actionable insights. “You have an investable surplus this month” rather than a spreadsheet to maintain.</p><p>Kuberan — Investment Signals Uses market volatility indicators to flag allocation opportunities or risk levels worth attention. Not financial advice — situational awareness.</p><p>Grantha — Document Vault Tracks important documents and time-sensitive obligations. Flags upcoming renewals and deadlines on a rolling 180/90/30/7-day horizon before they become emergencies.</p><p>Bloom — Inbox Intelligence Monitors email for time-sensitive life events and surfaces threads that need a human response — without the noise of reading everything.</p><h3>Why MCP?</h3><p>The Model Context Protocol gave me a clean interface between Jarvis and each domain agent. Each agent exposes tools. Jarvis decides which tools to call based on intent — no hardcoded routing, no monolithic codebase.</p><p>The real benefit is isolation: Newsflow’s heavy audio dependencies don’t pollute Artha’s financial parsing environment. Each agent is independently deployable. When I want a new capability, I write a new agent — not a new module inside a growing monolith.</p><blockquote><em>The orchestration layer is the durable investment. The intelligence layer is commoditizing. What compounds over time is the system that routes, remembers, and coordinates — not the model underneath it.</em></blockquote><h3>What I Learned</h3><p>Platform dependency is a quiet risk. The Google Home incident was a minor disruption. But the same pattern plays out at scale — companies that build on closed platforms accumulate hidden fragility. The cure isn’t to avoid platforms; it’s to own the layer that coordinates them.</p><p>Memory is harder than intelligence. Getting Gemini to reason well was the easy part. Getting it to <em>remember</em> consistently — the right things, in the right form, accessible at the right moment — required more design thinking than anything else in the stack.</p><p>Proactive beats reactive. The heartbeat scheduler changed how I experience the whole system. Jarvis finds me, rather than waiting to be queried. That inversion is where a personal AI goes from a slightly faster search to something that genuinely extends your bandwidth.</p><p>Simplicity compounds. SQLite + markdown files over a vector database. A single FastAPI service over microservices. Files as the source of truth, not a database schema. Every time I reached for the simpler option, I spent less time maintaining infrastructure and more time using the system.</p><h3>Stack at a Glance</h3><p>Python 3.12 · FastAPI · google-genai SDK with Vertex AI backend · SQLite FTS5 for memory search · MCP for agent coordination · Langfuse for observability · Azure TTS for audio · Telegram as the primary interface.</p><p>The hard part isn’t the technology. It’s deciding what you actually want your AI to know about you — and what you want it to do with that knowledge.</p><p><em>If you’re building something similar or thinking about personal AI infrastructure, I’m happy to talk through the architecture. The MCP multi-agent pattern in particular has been the most scalable decision in this stack.</em></p><p>Tags: AI Engineering · Multi-Agent Systems · MCP Protocol · Google Gemini · Personal Productivity · Platform Independence</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7fbf14e0e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Giving AI Agents a Complete Picture of Your AWS Infrastructure]]></title>
            <link>https://medium.com/@prasannanattuthurai/giving-ai-agents-a-complete-picture-of-your-aws-infrastructure-337096b293e2?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/337096b293e2</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 03:05:29 GMT</pubDate>
            <atom:updated>2026-06-10T03:05:29.602Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built an MCP server that turns a multi-account AWS org into a queryable knowledge graph — and the hard problems along the way</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJXjBThWXGeL-ULXzxxpBw.png" /><figcaption>AWS Infrastructure Knowledge Graph — System Architecture</figcaption></figure><p>When an AI agent helps you debug a production issue, it’s essentially working blind.</p><p>It can read your code. It can search your docs. But it has no idea that your Lambda is in the wrong security group, that the RDS it’s trying to reach is two VPC hops away through a Transit Gateway, or that a Service Control Policy three levels up the org hierarchy is quietly blocking the IAM call it’s about to make.</p><p>I hit this wall while working across a large multi-account AWS organization. The questions that took the longest to answer weren’t complex — they were spatial. <em>What can reach what? Why is this connection failing? Which account owns this resource?</em> These are graph problems, and I was solving them by clicking through the console like it was 2015.</p><p>So I built aws-infra-graph: an MCP server that crawls your entire AWS org, builds a Neo4j knowledge graph, and exposes it through tools that AI agents can actually use.</p><p>This is the story of how it works, what broke spectacularly along the way, and why the hardest problems were the ones I didn’t expect.</p><h3>The Core Idea</h3><p>The architecture is straightforward on paper:</p><pre>AWS Org (boto3 collectors)<br>        ↓<br>   Neo4j graph<br>        ↓<br> MCP server (FastMCP)<br>        ↓<br>AI agents (Claude Code, any MCP client)</pre><p>Collectors enumerate every resource across every account. They normalize API responses into typed Pydantic models — ResourceNode and ResourceEdge — with a consistent schema: every node has an ARN, a name, an account ID, a region, and a last_crawled timestamp. The graph builder writes these to Neo4j. The MCP server exposes Cypher-backed tools that agents can call in natural language.</p><p>The result: 34 tools across 11 categories — topology queries, connectivity checks, DNS tracing, security audits, cost analysis, org overview. Agents can ask things like:</p><ul><li><em>“Can the Lambda in payments-prod reach the EKS cluster in platform-nonprod on port 443?”</em></li><li><em>“Trace the DNS path for </em><a href="http://api.internal.example.com/"><em>api.internal.example.com</em></a><em> from the production VPC”</em></li><li><em>“Find all security groups that allow ingress from 0.0.0.0/0 across the whole org”</em></li><li><em>“What’s the network path between these two IPs through the Transit Gateway?”</em></li></ul><p>And get back actual answers — not “please log in to the console and check.”</p><h3>The Graph Schema</h3><p>The real work is in the schema. A flat inventory of resources isn’t useful — the value is in the edges.</p><p>The graph has 27 node types and 35+ relationship types. Some straightforward:</p><pre>(EC2Instance)-[:RUNS_IN]-&gt;(Subnet)-[:PART_OF]-&gt;(VPC)<br>(IAMRole)-[:HAS_POLICY]-&gt;(IAMPolicy)<br>(LambdaFunction)-[:HAS_ROLE]-&gt;(IAMRole)</pre><p>Some that capture the real complexity of a multi-account org:</p><pre>(VPC)-[:SHARED_WITH]-&gt;(VPC)                     // RAM-shared VPCs across accounts<br>(K8sServiceAccount)-[:ASSUMES_IRSA]-&gt;(IAMRole)  // IRSA pod identity bindings<br>(K8sService)-[:EXPOSES_VIA]-&gt;(LoadBalancer)     // cross-boundary K8s edges<br>(CloudWANAttachment)-[:ATTACHED_TO]-&gt;(CoreNetwork)<br>(Account)-[:GOVERNED_BY]-&gt;(ServiceControlPolicy)</pre><p>A typical cross-account network path traverses 13–14 hops through the graph. Without the edges, you have a parts list. With them, you have a map.</p><h3>The Performance Cliff</h3><p>The first production run against 70 accounts took <strong>528 minutes</strong>. That’s nearly 9 hours to crawl what turns out to be ~42,000 nodes and ~42,000 edges.</p><p>I tried the obvious things first. Added write concurrency (NEO4J_WRITE_CONCURRENCY=3). Got it down to 415 minutes. A 20% improvement — still useless for a daily refresh.</p><p>The actual problem was invisible until I profiled the Cypher queries. Every edge write was doing a full graph scan.</p><p>The pattern used to find a node before creating an edge looks like this:</p><pre>MATCH (n {arn: $arn}) ...</pre><p>With no index on arn, that&#39;s O(n) against the entire graph for every edge upsert. With 42,000 nodes and a similar number of edges, each crawl was executing tens of millions of individual node lookups.</p><p>The fix was a single RANGE index:</p><pre>CREATE INDEX idx_arn_resource FOR (n:Resource) ON (n.arn)</pre><p>And every node gets a secondary :Resource label via apoc.merge.node so the index is always hit — not just on nodes that happen to have that label natively.</p><p><strong>Result: 528 minutes → 15 minutes. A 97% reduction.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*8ea3VYDGMBYje7rP1dS_Ww.png" /></figure><p>The write concurrency setting became irrelevant — writes now take under 2 seconds total. Collection is the bottleneck now, and that’s just boto3 pagination time which can’t be compressed further without hitting rate limits.</p><p>The lesson: if your graph operations are slow, check your indexes before you optimize anything else. An EXPLAIN on the first edge upsert would have caught this immediately.</p><h3>The EKS Bearer Token Problem</h3><p>EKS clusters don’t use standard AWS credentials for their Kubernetes API. You generate a short-lived bearer token from a presigned STS URL. This is documented, but the documentation glosses over a detail that cost me an afternoon.</p><p>The naive approach:</p><pre>url = sts.generate_presigned_url(https://medium.com/&quot;get_caller_identity&quot;)<br>token = &quot;k8s-aws-v1.&quot; + base64.b64encode(url.encode()).decode()</pre><p>This fails. GetCallerIdentity takes no parameters, so you can&#39;t attach a ClusterName query parameter to identify which cluster the token is for. And without that parameter, the EKS API server rejects it.</p><p>The correct approach is to manually construct a presigned STS URL using botocore’s signing primitives:</p><pre>from botocore.auth import SigV4QueryAuth<br>from botocore.awsrequest import AWSRequest<br>import base64</pre><pre>request = AWSRequest(<br>    method=&quot;GET&quot;,<br>    url=&quot;https://sts.amazonaws.com/?Action=GetCallerIdentity&amp;Version=2011-06-15&quot;,<br>    headers={&quot;x-k8s-aws-id&quot;: cluster_name}<br>)<br>SigV4QueryAuth(credentials, &quot;sts&quot;, region).add_auth(request)</pre><pre># base64url encode, strip padding<br>token = &quot;k8s-aws-v1.&quot; + base64.urlsafe_b64encode(<br>    request.url.encode()<br>).decode().rstrip(&quot;=&quot;)</pre><p>The x-k8s-aws-id header is what tells the EKS API server which cluster this token is for. It gets signed into the presigned URL, so the server can verify it cryptographically.</p><p>Worth documenting because generate_presigned_url(https://medium.com/&quot;get_caller_identity&quot;) silently ignores extra parameters rather than raising an error. You get a token that looks valid and fails at authentication time with no helpful error message.</p><h3>DNS Across Account Boundaries</h3><p>Private Route53 zones in AWS can be associated with VPCs across accounts — but the collector for the zone owner doesn’t know about the VPC on the other side. It stores the association as a VPC ARN using the zone owner’s account ID, which creates a dangling edge pointing at a node that doesn’t exist.</p><p>The symptom: queries that should return 15+ zone-VPC associations returned 3. Everything else silently dropped.</p><p>The fix is a post-processing reconciliation step in the graph builder. After all accounts are collected, it iterates zone associations, extracts VPC IDs, and repoints edges to the correct VPC nodes regardless of account:</p><pre>def _link_dns_zone_vpcs(self, zones: list[ResourceNode]) -&gt; None:<br>    for zone in zones:<br>        for vpc_assoc in zone.properties.get(&quot;vpc_associations&quot;, []):<br>            vpc_id = vpc_assoc[&quot;vpc_id&quot;]<br>            actual_vpc = self._find_vpc_by_id(vpc_id)  # search by ID, not account<br>            if actual_vpc:<br>                self._write_edge(zone.arn, actual_vpc.arn, &quot;ASSOCIATED_WITH&quot;)</pre><p>After this fix: 15 private zones properly associated, 1,046 edges. Before: 3 zones and silence.</p><p>The broader lesson is that cross-account resources require a two-pass collection strategy. First pass: collect everything. Second pass: reconcile cross-account references. Any edge that crosses an account boundary is a potential orphan until the reconciliation step runs. This pattern shows up in several other places in the codebase — shared VPCs, CloudWAN attachments, RAM-shared Transit Gateway route tables.</p><h3>Union Security Group Evaluation</h3><p>AWS evaluates security groups on a network interface as a union — if <em>any</em> attached SG allows the traffic, it passes. This seems obvious until you try to model it in a connectivity checker.</p><p>Consider an EKS worker node with two security groups:</p><ul><li>sg-node: restrictive egress to specific CIDRs, referenced by the MongoDB endpoint&#39;s ingress rule</li><li>sg-cluster: allow-all egress, not referenced by the endpoint&#39;s ingress rule</li></ul><p>Evaluated individually:</p><ul><li>sg-node: egress check → DENIED (no allow-all rule)</li><li>sg-cluster: ingress check → DENIED (not referenced by endpoint&#39;s ingress)</li></ul><p>Evaluated together: sg-cluster provides egress, sg-node provides the ingress reference → <strong>ALLOWED</strong></p><p>The check_sg_connectivity tool accepts comma-separated SG identifiers for exactly this reason:</p><pre>check_sg_connectivity(<br>    source_sg=&quot;sg-cluster,sg-node&quot;,<br>    target_sg=&quot;sg-mongodb-vpce&quot;,<br>    port=27017<br>)</pre><p>This isn’t an edge case — it’s how EKS pod networking works by default. Every pod has at least two SGs (node SG + cluster SG), and connectivity analysis that evaluates them individually will produce false DENIED results on traffic that actually succeeds.</p><h3>Don’t Put Neo4j on EFS</h3><p>The original deployment used an EFS volume mounted into the Fargate task sidecar alongside Neo4j. This worked until a TCP connection drop through our SSL inspection proxy caused an NFS ESTALE error, after which the Neo4j data directory was inaccessible until a full replacement.</p><p>EFS is NFS under the hood. NFS is a stateful protocol — it maintains file handles that become invalid when the underlying TCP connection drops. When that happens under a proxy that does SSL inspection, you get ESTALE errors that Neo4j cannot recover from gracefully.</p><p>The fix: Neo4j on EC2 with an EBS volume attached as a local block device. EBS doesn’t care about TCP state. A disconnected EC2 instance doesn’t corrupt your data. The graph survives instance replacement because delete_on_termination=False on the EBS volume.</p><p>Two CDK stacks:</p><ul><li>InfraGraphNeo4j — EC2 t3.large + 100 GB EBS gp3 (XFS). Graph data lives here.</li><li>InfraGraphCompute — ECS Fargate + internal ALB. Stateless MCP server. Points at Neo4j EC2 via Bolt on port 7687.</li></ul><p>Deploying them separately means you can replace the compute stack without touching Neo4j, and replace the Neo4j instance without losing any data (just reattach the EBS volume).</p><h3>The Architecture in Production</h3><p>The MCP server exposes a streamable-http endpoint on port 8050 behind an internal ALB. Any MCP client with network access and a valid auth token can connect — Claude Code, VS Code extensions, or a chat frontend.</p><p>Daily refresh runs on an EventBridge cron at 13:00 UTC. A 15-minute full crawl means the graph is always within 24 hours of reality. A manual refresh_graph tool lets agents trigger an update on demand.</p><p>Cross-account collection works by assuming a role in each member account from the management account. The collector gets a fresh boto3 session per account, enumerates resources in all regions, normalizes them into the ResourceNode/ResourceEdge model, and hands them to the graph builder.</p><p>The 27 collectors cover: EC2 (instances, VPCs, subnets, security groups, NACLs, ENIs), IAM, S3, RDS, Lambda, ECS, EKS, Kubernetes (via EKS API), ElastiCache, ELB, Route53, Route53 Resolver, DynamoDB, SQS, SNS, CloudFront, API Gateway, VPC Endpoints, VPC Networking (route tables, NAT/IGW, VPC peering), Transit Gateway, CloudWAN, Organizations, CloudFormation, CodeCommit, CodePipeline, CodeBuild, WAF, OpenSearch.</p><h3>What It’s Like to Use</h3><p>The agents that connect to this server can answer questions that previously required 20 minutes of console clicking:</p><blockquote><em>“Can the Lambda function </em><em>payment-processor in payments-prod reach the EKS cluster in platform-nonprod on port 443?&quot;</em></blockquote><p>That question requires: finding the Lambda’s VPC and security groups, finding the EKS cluster’s VPC and security groups, traversing Transit Gateway route tables to check for a path, evaluating SG rules including cross-SG references, and checking NACLs. The guided_connectivity_check tool does this from fuzzy resource names. No account IDs, no region names, no ARNs needed.</p><blockquote><em>“Trace the DNS path for </em><em>api.internal.example.com from the production VPC&quot;</em></blockquote><p>The trace_dns tool walks the Route53 Resolver chain: outbound endpoint → forwarding rule → target IPs → inbound endpoint → private hosted zone → A records. It surfaces split-horizon configurations, cross-account zone associations, and NS delegation chains.</p><blockquote><em>“Find all security groups that allow ingress from 0.0.0.0/0 across all accounts”</em></blockquote><p>The find_open_security_groups tool runs a single Cypher query across the whole graph. No looping through accounts, no paginating through the AWS console.</p><h3>Going Open Source</h3><p>This started as an internal tool. I’m releasing it as an open source project — MIT licensed, no org-specific logic hardcoded.</p><p>If you have a single AWS account, you connect with your existing credentials and get a queryable graph in minutes. If you have a large multi-account org, point it at your management account with an assume-role ARN and let it crawl.</p><p><strong>What you need:</strong></p><ul><li>Python 3.12+, uv</li><li>Neo4j 5.x (Docker Compose file included)</li><li>AWS credentials (single account or org-level role)</li></ul><p>Quick start:</p><pre>git clone https://github.com/prasannavarshan/aws-infra-graph<br>cd aws-infra-graph<br>cp .env.example .env   # add your AWS profile and Neo4j creds</pre><pre>docker compose up -d   # start Neo4j</pre><pre>uv sync<br>uv run python -m src.main   # start MCP server on stdio</pre><p>Then add it to your Claude Code or MCP client config and start asking questions.</p><h3>What I’d Do Differently</h3><p><strong>Start with Neo4j indexes.</strong> The 528-minute crawl was entirely self-inflicted. An EXPLAIN on the first edge upsert would have caught it immediately. Add indexes before you write a single node.</p><p><strong>Design for cross-account edges from day one.</strong> Several collectors needed a rewrite when I realized they were writing ARNs with the wrong account ID in them. The ResourceEdge model should carry a flag for edges that cross account boundaries and need reconciliation.</p><p><strong>Don’t use EFS for stateful containers.</strong> Block storage for databases. Always.</p><p><strong>Two-pass collection is the pattern, not the exception.</strong> Any resource that can be shared across accounts (VPCs, TGW route tables, Route53 zones) requires a reconciliation pass after all accounts are collected. Build that into the architecture from the start.</p><p>The full source, documentation, and getting-started guide are on GitHub at <a href="https://github.com/prasannavarshan/aws-infra-graph"><strong>https://github.com/prasannavarshan/aws-infra-graph</strong></a>.</p><p>27 collectors. 34 MCP tools. 612 tests. MIT licensed. If you’re running multiple AWS accounts and find yourself spending more time answering “what can reach what” than building things, this might save you some time.</p><p><em>Stack: Python 3.12+, FastMCP, boto3, Neo4j 5, Pydantic v2, AWS CDK (ECS Fargate + EC2 EBS). 42,000+ nodes and edges from a 70-account org.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337096b293e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Multi-Agent System With Kiro CLI — Here’s What Actually Works]]></title>
            <link>https://medium.com/@prasannanattuthurai/i-built-a-multi-agent-system-with-kiro-cli-heres-what-actually-works-94c0671d4aa9?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94c0671d4aa9</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 23:38:01 GMT</pubDate>
            <atom:updated>2026-04-25T23:38:01.323Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to specialized AI agents that delegate, audit, and orchestrate — not just chat.</em></p><p>Most developers using AI assistants today are running a single agent that does everything: writes code, debugs infrastructure, reviews security, manages calendars. It works — until it doesn’t. Context windows overflow, domain expertise gets diluted, and you end up babysitting the AI more than it’s helping you.</p><p>I spent the last several months building a multi-agent system using <a href="https://kiro.dev/">Kiro CLI</a> where specialized agents handle distinct domains and delegate to each other. This isn’t theoretical — it runs daily against production Kubernetes clusters, AWS accounts, and real team workflows.</p><p>Here’s what I learned, what the architecture looks like, and how you can build your own.</p><h3>Why Multi-Agent Over Single-Agent?</h3><p>The single-agent model breaks down in three predictable ways:</p><ol><li><strong>Context saturation</strong> — A single agent loaded with AWS knowledge, Kubernetes context, security scanning procedures, JIRA workflows, and calendar access burns through its context window before it gets to your actual question.</li><li><strong>Domain dilution</strong> — An agent that knows a little about everything is an expert at nothing. Security scanning requires paranoia. Infrastructure work requires precision. Office tasks require personality. These are fundamentally different modes of operation.</li><li><strong>No separation of concerns</strong> — When one agent does everything, there’s no audit trail of <em>who</em> decided what. In a multi-agent system, the security agent’s findings are distinct from the infrastructure agent’s actions.</li></ol><p>The fix isn’t a bigger context window. It’s specialization with coordination.</p><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dauoz3iHcO4rq-yYfTA1Ow.png" /></figure><h3>Agent Registry — The Coordination Layer</h3><p>Every agent in the system reads a shared registry file that defines who exists, what they do, and when to delegate:</p><pre># Agent Registry<br>## Available Agents<br>| Agent       | Role |<br>|-------------|------|<br>| **Infra**   | AWS infrastructure, Kubernetes operations, MCP tool queries, diagrams |<br>| **Oracle**  | AI industry intelligence, GitHub repo sync, setup audits |<br>| **Guardian**| Security scanning - dependencies, secrets, supply chain, IaC |<br>| **Office**  | GSuite (Calendar, Gmail, Drive), JIRA, team roster, scheduling |<br><br>## When to Delegate<br>Route to **Guardian** when:<br>- User asks to scan a project for security issues<br>- User asks about dependency vulnerabilities or supply chain risks<br>- User wants to audit secrets, credentials, or `.env` files<br>Route to **Oracle** when:<br>- User asks about AI industry news or tracked firms/people<br>- User wants to sync GitHub repos for a tracked person<br>- User asks for a setup audit of their AI tool configuration</pre><p>The key insight: <strong>delegation rules are explicit, not inferred.</strong> Each agent knows exactly when to hand off work. This eliminates the “I’ll try to handle it myself” failure mode that plagues single-agent setups.</p><h3>Shared Context — The Common Ground</h3><p>All agents share a context file that defines paths, conventions, and resources:</p><pre># Shared Agent Context<br>## Tool Homes<br>| Tool      | Home Directory | Config File |<br>|-----------|---------------|-------------|<br>| Kiro      | `~/.kiro/`    | `~/.kiro/settings/cli.json` |<br><br>## Agent System<br>| Path                    | Purpose |<br>|-------------------------|---------|<br>| `~/.kiro/agents/`       | Agent definitions (.md = prompt, .json = config) |<br>| `~/.kiro/agents/AGENT_REGISTRY.md` | Master registry - who does what |<br>| `~/.kiro/skills/`       | Shared skills (diagrams, idea tracking) |<br>| `~/.kiro/steering/`     | Steering docs injected as context |<br>| `~/.kiro/data/`         | Persistent data (tracked repos, starred repo cache) |</pre><p>This means any agent can reference the same file paths, the same MCP server configs, and the same conventions without duplicating knowledge.</p><h3>The Agents — What Each One Actually Does</h3><h3>1. The Infrastructure Agent</h3><p>This is the workhorse. It handles:</p><ul><li><strong>AWS queries</strong> via an MCP server that exposes VPCs, security groups, EC2 instances, and EKS clusters as queryable resources</li><li><strong>Kubernetes operations</strong> — context switching across dozens of clusters, pod inspection, troubleshooting</li><li><strong>Diagram generation</strong> — Excalidraw diagrams for architecture visualization</li><li><strong>Idea tracking</strong> — a shared backlog that syncs across tools</li></ul><p>The infrastructure agent gets <strong>steering files</strong> injected as context — things like Kubernetes context-switching rules, kubectl plugin preferences, and AWS profile mappings. This is domain knowledge that would waste context in any other agent.</p><p><strong>Example steering file (Kubernetes context switching):</strong></p><pre># Kubernetes Context Switching Rules<br>## Matching rules<br>- Only match contexts prefixed with a known pattern<br>- ALL search keywords must appear in the context name<br>- Example: &quot;slingcore beta&quot; → requires BOTH &quot;slg&quot; AND &quot;beta&quot;<br>## Workflow<br>1. Find ALL matching contexts<br>2. If multiple match → list ALL and ask user to pick<br>3. If one matches → show it and ask for confirmation<br>4. Switch using: kubectx &lt;context-name&gt;</pre><p>This steering file means the infra agent can handle “switch to slingcore beta” without me specifying the exact context name. It fuzzy-matches, confirms, and switches. That’s the kind of domain-specific behavior you can’t get from a generic agent.</p><h3>2. The Security Guardian</h3><p>This agent is paranoid by design. Its core principles:</p><ul><li><strong>Read-only by default</strong> — never modifies files without explicit confirmation</li><li><strong>Tool self-verification</strong> — checks scanner versions before trusting their output (e.g., Trivy &lt; 0.51.2 had a DB poisoning vulnerability via MITM)</li><li><strong>Comprehensive scanning</strong> — runs secret detection, dependency scanning, SAST, and AI-specific attack vector analysis in sequence</li></ul><pre>## Scanning Checklist<br>### 0. Tool Self-Verification (run BEFORE any scan)<br>Security tools are themselves attack surface. Verify before trusting output.<br>### 1. Secret &amp; Credential Scanning (run FIRST - highest breach risk)<br>### 2. Supply Chain / Dependency Scanning (4 tools, each with unique coverage)<br>### 3. Static Code Analysis / SAST<br>### 4. AI-Specific Attack Vectors<br>### 5. CI/CD Token Scope<br>### 6. Environment Hygiene<br>### 7. OWASP Top 10 Mapping</pre><p>The AI-specific section is what makes this agent unique for teams building with LLMs. It inspects agent prompt files, MCP tool definitions, and steering documents for:</p><ul><li>Prompt injection patterns</li><li>MCP tools requesting broader permissions than needed</li><li>Agent configs with unrestricted shell execution</li><li>Unsanitized LLM output used in shell commands or SQL</li></ul><p>It maps findings to both <strong>OWASP Top 10 (2021)</strong> and the <strong>OWASP Top 10 for LLM Applications (2025)</strong>. This is the kind of specialized knowledge that would be wasted in a general-purpose agent.</p><h3>3. The Intelligence Agent</h3><p>This agent tracks the AI ecosystem and keeps your tooling current:</p><ul><li><strong>Intelligence gathering</strong> — web searches and GitHub activity for tracked firms and people</li><li><strong>Repository sync</strong> — compares a tracked person’s GitHub repos against your local collection, clones missing ones on approval</li><li><strong>Starred repo analysis</strong> — cross-references your GitHub stars against your installed tools to find gaps</li><li><strong>Setup audit</strong> — inspects your entire AI tool configuration and produces a structured report</li></ul><pre>## Intelligence Report Template<br># 🔮 Intelligence Report<br>## Model Releases<br>| Model | Firm | Date | Key Changes |<br>## Tool &amp; API Updates<br>## Notable Research<br>## Community Projects (Tracked People)<br>## Ecosystem Changes<br>## ⚡ What You Might Be Missing<br>_Based on your current setup:_</pre><p>The “What You Might Be Missing” section is the killer feature. It cross-references intelligence findings with your actual installed setup and tells you what tools, MCP servers, or patterns you should adopt. It’s like having a tech radar that’s personalized to your workflow.</p><h3>4. The Office Assistant</h3><p>This agent handles non-technical work with personality. It connects to:</p><ul><li><strong>Google Calendar</strong> — schedule queries, conflict detection, meeting coordination</li><li><strong>Gmail</strong> — email search, priority flagging</li><li><strong>Google Drive</strong> — file search</li><li><strong>JIRA</strong> — ticket management, JQL queries, status updates</li><li><strong>Team roster</strong> — local TOML file with names, emails, tags for fast lookups</li></ul><p>The personality layer matters more than you’d think. An agent that says “You have 5 calendar events between 09:00 and 13:00” is less useful than one that says “You’ve got a pretty packed morning — heads up, you’re double-booked at 2.”</p><pre>## Name Disambiguation (Favorites Practice)<br>When a name matches multiple people, resolve in this priority order:<br>1. `me` — always wins<br>2. `my-team` — pick the my-team match without asking<br>3. `frequent` — pick the frequent-tagged match without asking<br>4. If still ambiguous — ALWAYS ask. After user picks, tag as `frequent`.</pre><p>This is a learned behavior pattern. The agent gets smarter about name resolution over time by tagging frequently referenced people. It’s a simple mechanism, but it compounds — after a few weeks, the agent resolves 90% of names without asking.</p><h3>Pipeline Orchestration — Agents Working Together</h3><p>Kiro CLI supports DAG-based pipeline orchestration where agents run as stages with dependencies:</p><pre>// Example: Research → Implement → Review pipeline<br>{<br>  task: &quot;Add rate limiting to the API gateway&quot;,<br>  stages: [<br>    {<br>      name: &quot;research&quot;,<br>      role: &quot;Oracle&quot;,<br>      prompt: &quot;Research current best practices for API rate limiting&quot;<br>    },<br>    {<br>      name: &quot;implement&quot;,<br>      role: &quot;Infra&quot;,<br>      prompt: &quot;Implement rate limiting based on research findings&quot;,<br>      depends_on: [&quot;research&quot;]<br>    },<br>    {<br>      name: &quot;security-review&quot;,<br>      role: &quot;Guardian&quot;,<br>      prompt: &quot;Audit the rate limiting implementation for security issues&quot;,<br>      depends_on: [&quot;implement&quot;]<br>    }<br>  ]<br>}</pre><p>Stages with no depends_on run in parallel. This means you can have multiple research tracks feeding into a single implementer, or parallel security and performance reviews after an implementation.</p><p><strong>Real-world chain example:</strong> Oracle discovers a new repo from a tracked person → suggests Guardian scan it for security before cloning. This kind of inter-agent coordination happens naturally because each agent reads the registry and knows who to delegate to.</p><h3>The MCP Layer — Tools That Make It Work</h3><p>Model Context Protocol (MCP) servers are the backbone of agent capabilities. Each server exposes a specific domain as queryable tools:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;infra-graph&quot;: {<br>      &quot;url&quot;: &quot;https://your-infra-graph-endpoint/mcp&quot;,<br>      &quot;description&quot;: &quot;Query VPCs, security groups, EC2, EKS clusters&quot;<br>    },<br>    &quot;atlassian&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;@anthropic/atlassian-mcp-server&quot;],<br>      &quot;description&quot;: &quot;JIRA and Confluence access&quot;<br>    },<br>    &quot;mongo-atlas&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;@anthropic/mongo-mcp-server&quot;],<br>      &quot;description&quot;: &quot;MongoDB Atlas queries&quot;<br>    },<br>    &quot;context-mode&quot;: {<br>      &quot;command&quot;: &quot;context-mode&quot;,<br>      &quot;description&quot;: &quot;Session analytics, knowledge indexing, search&quot;<br>    }<br>  }<br>}</pre><p><strong>Key lesson:</strong> Not every MCP server needs to be enabled for every agent. The infra agent uses the AWS graph server. The office assistant uses Atlassian. The security guardian doesn’t need either — it uses local scanning tools. This selective wiring keeps each agent’s tool surface minimal and focused.</p><p>I run about 15 MCP servers total, but most are disabled by default and enabled per-task. This is intentional — a smaller tool surface means fewer things that can go wrong and less noise in the agent’s tool selection.</p><h3>Skills — Reusable Capabilities Across Agents</h3><p>Skills are packaged behaviors that any agent can invoke:</p><p><strong>Excalidraw Diagrams</strong> — Any agent can generate architecture diagrams as Excalidraw JSON files. The skill includes a JSON schema, element templates, and a color palette. When the infra agent needs to visualize a VPC topology or the intelligence agent needs to diagram an architecture comparison, they use the same skill.</p><p><strong>Idea Tracking</strong> — A shared backlog that syncs across Kiro and Claude Code. Any agent can add, list, complete, or drop ideas. This means a thought that occurs during a security scan doesn’t get lost — the guardian agent can log it and the infra agent can pick it up later.</p><h3>What I Learned — Practical Advice</h3><h3>1. Explicit delegation beats implicit routing</h3><p>Don’t rely on the LLM to figure out which agent should handle a request. Write explicit routing rules in the registry. “Route to Guardian when the user mentions CVEs, security advisories, or compliance” is better than hoping the model infers it.</p><h3>2. Read-only by default is non-negotiable for specialized agents</h3><p>The security agent and intelligence agent are both read-only by default. They inspect, report, and recommend — but never modify without explicit confirmation. This is especially important when agents can delegate to each other. You don’t want a chain of automated actions where no human confirmed the destructive step.</p><h3>3. Steering files are the secret weapon</h3><p>Steering files are domain-specific context injected into an agent’s system prompt. They’re the difference between an agent that knows Kubernetes generically and one that knows <em>your</em> Kubernetes — your cluster naming conventions, your preferred kubectl plugins, your AWS profile mappings. Keep them in ~/.kiro/steering/ and reference them from agent prompts.</p><h3>4. Personality matters for non-technical agents</h3><p>An office assistant with a distinct personality is genuinely more useful than a generic one. Not because the humor is entertaining (though it helps), but because personality drives concise, human-readable output. “Your inbox is a situation” communicates urgency better than “You have 47 unread emails.”</p><h3>5. Tool self-verification is a must for security agents</h3><p>Your security scanner is itself attack surface. Trivy had a DB poisoning vulnerability. Semgrep’s auto-config fetches rules from the internet at runtime. If your security agent doesn’t verify its own tools first, it’s giving you false confidence.</p><h3>6. Persistent data creates compound value</h3><p>The intelligence agent maintains a tracked entity config, a starred repo cache, and generates reports that reference previous audits. The office assistant learns name disambiguation preferences over time. This persistent state is what turns agents from stateless tools into genuine assistants that get better the longer you use them.</p><h3>7. Start with two agents, not four</h3><p>If you’re building this from scratch, start with your primary work agent and one specialist. Get the delegation pattern working between two agents before adding more. The coordination complexity grows faster than you’d expect.</p><h3>Getting Started With Your Own Setup</h3><p>Here’s the minimal file structure to get a two-agent system running with Kiro CLI:</p><pre>~/.kiro/<br>├── agents/<br>│   ├── AGENT_REGISTRY.md    # Who does what, delegation rules<br>│   ├── Primary.md           # Your main agent prompt<br>│   ├── Primary.json         # Agent config (tools, resources)<br>│   ├── Specialist.md        # Your specialist agent prompt<br>│   └── Specialist.json<br>├── settings/<br>│   └── mcp.json             # MCP server configurations<br>├── steering/<br>│   └── domain-context.md    # Domain-specific knowledge<br>├── skills/<br>│   └── your-skill/<br>│       └── SKILL.md<br>└── shared-context.md        # Paths and conventions all agents share</pre><p><strong>Step 1:</strong> Define your agents in the registry with clear routing rules.</p><p><strong>Step 2:</strong> Write agent prompts that include @AGENT_REGISTRY.md and @shared-context.md references so every agent knows the full system.</p><p><strong>Step 3:</strong> Configure MCP servers for the tools your agents need.</p><p><strong>Step 4:</strong> Add steering files for domain-specific context that shouldn’t live in the agent prompt itself.</p><p><strong>Step 5:</strong> Use kiro chat to interact, and the subagent system for pipeline orchestration.</p><h3>What’s Next</h3><p>The multi-agent pattern is still early. Things I’m exploring:</p><ul><li><strong>Agent memory across sessions</strong> — persistent knowledge extraction so agents remember what they learned yesterday</li><li><strong>Automated triage pipelines</strong> — incident detection triggers a chain: infra agent diagnoses → security agent checks for compromise → office assistant notifies the team</li><li><strong>Cross-tool sync</strong> — agents that work identically whether invoked from Kiro CLI or Claude Code</li></ul><p>The fundamental insight is this: <strong>the value of AI agents scales with specialization, not generalization.</strong> A team of focused agents that know when to delegate will outperform a single omniscient agent every time — just like a real engineering team.</p><p><em>I’m building this with </em><a href="https://kiro.dev/"><em>Kiro CLI</em></a><em> by Amazon. If you’re experimenting with multi-agent setups, I’d love to hear what patterns are working for you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94c0671d4aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving Multiple LLMs on Kubernetes with Intelligent Routing Using llm-d, Istio, and LiteLLM]]></title>
            <link>https://medium.com/@prasannanattuthurai/serving-multiple-llms-on-kubernetes-with-intelligent-routing-using-llm-d-istio-and-litellm-7d33760d1001?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d33760d1001</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 06:05:06 GMT</pubDate>
            <atom:updated>2026-03-05T06:05:06.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdMb3gV_emYc_hLIwas6jA.png" /></figure><h3>The Problem</h3><p>You have multiple LLMs/SLMs you want to serve on Kubernetes. You need:</p><ul><li>A unified API that clients can call without knowing which model runs where</li><li>Intelligent routing that leverages KV-cache locality for faster inference</li><li>Per-model isolation with independent scaling</li><li>External access over your network so other services can reach the models</li><li>GPU cost optimization — scale to zero when idle, scale up on demand</li></ul><p>Most teams solve this by deploying vLLM behind a LoadBalancer and calling it a day. That works for a single model, but falls apart when you need multi-model routing, prefix-cache-aware scheduling, and cost-efficient GPU management.</p><p>This article walks through a production deployment that solves all of the above using <strong>llm-d</strong> for intelligent inference scheduling, <strong>Istio</strong> as a Gateway API provider with Inference Extension support, and <strong>LiteLLM</strong> as a unified API gateway.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wos94mSHeqctc0amQbCJSQ.png" /></figure><h3>Why This Stack?</h3><p><strong>llm-d</strong> is an open-source Kubernetes-native inference platform that adds intelligent scheduling on top of vLLM. Instead of random or round-robin load balancing, it routes requests to the vLLM pod that already has the most relevant KV-cache prefixes cached in GPU memory. The result: 38.9% throughput improvement and 97% TTFT (Time to First Token) reduction compared to plain Kubernetes services.</p><p><strong>Istio</strong> (1.28+) provides Gateway API support with the Inference Extension, meaning it can route traffic through an ext-proc filter to llm-d’s Endpoint Picker (EPP) before forwarding to vLLM pods. This is the same mechanism that makes the intelligent routing work.</p><p><strong>LiteLLM</strong> sits in front as a unified OpenAI-compatible API gateway, handling API key management, rate limiting, logging, and model routing. Clients call LiteLLM with a model name, and LiteLLM routes to the correct hostname.</p><h3>The Key Insight: Why Two Routing Layers?</h3><p>This architecture has two distinct routing layers, and understanding why is critical:</p><p><strong>Layer 1 — LiteLLM + ALB (model selection):</strong> Clients say “I want to talk to Phi-4-mini” and LiteLLM routes to phi4.example.com. The ALB matches the hostname and forwards to the correct Istio gateway. This is <strong>model-level routing</strong>.</p><p><strong>Layer 2 — Istio + EPP (pod selection):</strong> Within a model’s pipeline, the EPP picks which specific vLLM pod should handle the request based on KV-cache prefix hits and current load. This is <strong>pod-level routing</strong> — the smart scheduling that llm-d provides.</p><p>You can’t collapse these into one layer. The ALB/Ingress is needed because AWS Load Balancer Controller doesn’t support Gateway API resources. And Gateway API with Inference Extension is needed because ALBs can’t do prefix-cache-aware pod selection. They’re complementary.</p><h3>Implementation</h3><h3>The Wrapper Chart</h3><p>Rather than deploying raw manifests, everything is packaged as a Helm wrapper chart that includes the upstream llm-d chart as a subchart:</p><pre>llm-d-stack/<br>  Chart.yaml          # Wrapper chart, depends on llm-d subchart<br>  values.yaml         # Base defaults<br>  cluster-values.yaml # Per-cluster overrides (ALB config, model list)<br>  templates/<br>    modelservice.yaml     # Per-model ModelService CRs<br>    gateway.yaml          # Per-model Istio Gateway CRs<br>    ga-inferencepool.yaml # Per-model InferencePool CRs<br>    ga-httproute.yaml     # Per-model HTTPRoute CRs<br>    alb-ingress.yaml      # Per-model ALB Ingress resources<br>    ...</pre><p>The models array in values drives everything. Add a model, and the templates generate all the Kubernetes resources:</p><pre>models:<br>  - name: &quot;Qwen/Qwen2.5-0.5B-Instruct&quot;<br>    resourceName: &quot;qwen-qwen2-5-0-5b-instruct&quot;<br>    hostname: &quot;qwen.example.com&quot;<br>    enabled: true<br>    replicas: 1<br>    gpu: 1<br>    maxModelLen: 8192<br>    gpuMemoryUtilization: &quot;0.5&quot;<br>- name: &quot;microsoft/Phi-4-mini-instruct&quot;<br>    resourceName: &quot;phi-4-mini-instruct&quot;<br>    hostname: &quot;phi4.example.com&quot;<br>    enabled: true<br>    replicas: 1<br>    gpu: 1<br>    maxModelLen: 4096<br>    gpuMemoryUtilization: &quot;0.5&quot;</pre><h3>Per-Model Resource Chain</h3><p>For each model, the chart creates:</p><pre>ModelService CR (declares the model)<br>  |-- Controller creates: vLLM Deployment, EPP Deployment, InferenceModel CR<br>Gateway CR (gatewayClassName: istio)<br>  |-- Istio creates: Gateway pod (Envoy proxy)<br>HTTPRoute (parentRef: Gateway, backendRef: InferencePool)<br>  |-- Tells Envoy: route path &quot;/&quot; to InferencePool<br>InferencePool (endpointPickerRef: EPP, selector: decode pods)<br>  |-- Tells Istio: use EPP as ext-proc filter<br>Ingress (ALB, host-based rule)<br>  |-- Tells ALB: route hostname to Gateway service</pre><h3>The ALB Ingress Template</h3><p>This is the piece that makes models externally accessible. Each model gets its own Ingress resource that joins a shared ALB via the group.name annotation:</p><pre>{{- if .Values.ingress.enabled }}<br>{{- range .Values.models }}<br>{{- if and .enabled .hostname }}<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: {{ .resourceName }}-ingress<br>  annotations:<br>    alb.ingress.kubernetes.io/group.name: {{ $.Values.ingress.groupName }}<br>    alb.ingress.kubernetes.io/scheme: internal<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/certificate-arn: {{ $.Values.ingress.certificateArn }}<br>    alb.ingress.kubernetes.io/listen-ports: &#39;[{&quot;HTTPS&quot;:443}]&#39;<br>    alb.ingress.kubernetes.io/healthcheck-port: &quot;15021&quot;<br>    alb.ingress.kubernetes.io/healthcheck-path: /healthz/ready<br>spec:<br>  ingressClassName: alb<br>  rules:<br>    - host: {{ .hostname }}<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: {{ .resourceName }}-gateway-istio<br>                port:<br>                  number: 80<br>{{- end }}<br>{{- end }}<br>{{- end }}</pre><p>Key design choices:</p><ul><li><strong>group.name annotation</strong> — Multiple Ingress resources sharing the same group name get merged into a single ALB. No need to create a new load balancer per model.</li><li><strong>target-type: ip</strong> — Routes directly to pod IPs, bypassing NodePort. More efficient and works with Istio gateway pods.</li><li><strong>Health check on port 15021</strong> — This is Istio’s sidecar health endpoint (/healthz/ready), which returns 200 when the gateway pod is ready. Since the Istio gateway pod is the target (not the vLLM pod), this correctly reflects gateway availability.</li><li><strong>TLS termination at ALB</strong> — Traffic from ALB to Istio gateway is plain HTTP inside the VPC. Standard pattern for internal services.</li></ul><h3>Gateway API + Inference Extension</h3><p>The Gateway API resources tell Istio how to route within each model’s pipeline:</p><pre># Gateway — creates an Istio Envoy proxy pod<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: Gateway<br>metadata:<br>  name: {{ .resourceName }}-gateway<br>  annotations:<br>    networking.istio.io/service-type: ClusterIP<br>spec:<br>  gatewayClassName: istio<br>  listeners:<br>    - name: http<br>      port: 80<br>      protocol: HTTP<br># HTTPRoute - routes all traffic to InferencePool<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: {{ .resourceName }}-route<br>spec:<br>  parentRefs:<br>    - name: {{ .resourceName }}-gateway<br>  rules:<br>    - backendRefs:<br>        - group: inference.networking.k8s.io<br>          kind: InferencePool<br>          name: {{ .resourceName }}-pool<br># InferencePool - connects EPP and decode pods<br>apiVersion: inference.networking.k8s.io/v1alpha2<br>kind: InferencePool<br>metadata:<br>  name: {{ .resourceName }}-pool<br>spec:<br>  targetPortNumber: 8000<br>  selector:<br>    matchLabels:<br>      llm-d.ai/model: {{ modelLabel }}<br>  endpointPickerConfig:<br>    extensionRef:<br>      name: {{ .resourceName }}-epp</pre><p>When a request arrives at the Gateway pod, Envoy sees the HTTPRoute pointing to an InferencePool. The InferencePool has an endpointPickerConfig pointing to the EPP service. Envoy calls the EPP via ext-proc (external processing filter), the EPP queries Redis for prefix cache state, scores the available vLLM pods, and tells Envoy which specific pod to route to.</p><h3>LiteLLM Configuration</h3><p>On the LiteLLM side, each model is a simple entry:</p><pre>- model_name: qwen-0.5b<br>  litellm_params:<br>    model: openai/Qwen/Qwen2.5-0.5B-Instruct<br>    api_base: https://qwen.example.com/v1<br>    api_key: &quot;not-needed&quot;<br>- model_name: phi-4-mini<br>  litellm_params:<br>    model: openai/microsoft/Phi-4-mini-instruct<br>    api_base: https://phi4.example.com/v1<br>    api_key: &quot;not-needed&quot;</pre><p>The openai/ prefix tells LiteLLM to use the OpenAI-compatible provider. The model name after the prefix must match the exact HuggingFace model name because vLLM validates it in the request body. The api_key is required by LiteLLM but vLLM doesn&#39;t check it.</p><p>Clients call LiteLLM with the friendly alias:</p><pre>curl https://litellm.example.com/v1/chat/completions \<br>  -H &quot;Authorization: Bearer $API_KEY&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;model&quot;: &quot;phi-4-mini&quot;, &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello&quot;}]}&#39;</pre><p>LiteLLM maps phi-4-mini to phi4.example.com, which the ALB routes to the Phi-4 Istio gateway, which EPP routes to the best vLLM pod.</p><h3>GPU Cost Management</h3><p>GPU instances are expensive. With Karpenter on EKS, you can scale to zero when models are idle:</p><pre># Scale down — GPU nodes reclaimed by Karpenter in ~2 min<br>kubectl patch modelservice qwen-0-5b -n llm-d \<br>  --type=&#39;merge&#39; -p=&#39;{&quot;spec&quot;:{&quot;decode&quot;:{&quot;replicas&quot;:0}}}&#39;<br>kubectl scale deploy -n llm-d -l llm-d.ai/role=decode --replicas=0<br># Scale up - cold start ~5-8 min (node provision + image pull + model load)<br>kubectl patch modelservice qwen-0-5b -n llm-d \<br>  --type=&#39;merge&#39; -p=&#39;{&quot;spec&quot;:{&quot;decode&quot;:{&quot;replicas&quot;:1}}}&#39;<br>kubectl scale deploy -n llm-d -l llm-d.ai/role=decode --replicas=1</pre><p>The control plane (Istio gateways, EPP, Redis, ModelService controller) stays running on cheap CPU nodes. Only the GPU nodes spin down. When you scale back up, Karpenter provisions a new GPU node, pulls the vLLM image (~8GB), and loads model weights.</p><p>One important gotcha: <strong>you must scale both the ModelService CR and the deployment</strong>. The ModelService controller doesn’t reconcile replica changes back to the deployment — it’s a known limitation.</p><h3>Lessons Learned</h3><h3>1. kgateway Has a Multi-Model Bug</h3><p>We initially used kgateway (<a href="http://solo.io/">Solo.io</a>) as the Gateway API provider. It works for a single model but has a bug where only one InferencePool resolves per controller instance. The second model always gets BackendNotFound. After extensive debugging (different models, different ordering, timing), we confirmed it&#39;s 100% reproducible and not model-dependent.</p><p>Istio 1.28+ with ENABLE_GATEWAY_API_INFERENCE_EXTENSION=true on istiod resolves this correctly. Both models work simultaneously.</p><h3>2. Gateway API Inference Extension CRDs Matter</h3><p>You need Gateway API CRDs v1.4.0 <strong>and</strong> Inference Extension CRDs v1.3.0. The Inference Extension CRDs define InferencePool and InferenceModel resources. Without them, the Gateway API resources silently do nothing.</p><pre>kubectl apply -k &quot;github.com/kubernetes-sigs/gateway-api/config/crd/?ref=v1.4.0&quot; \<br>  --server-side --force-conflicts<br>kubectl apply -k &quot;github.com/kubernetes-sigs/gateway-api-inference-extension/config/crd/?ref=v1.3.0&quot; \<br>  --server-side --force-conflicts</pre><h3>3. Multi-Model Routing Requires an External Router</h3><p>llm-d is not a multi-model router. Each model gets its own Gateway + HTTPRoute + InferencePool + EPP pipeline. The EPP only knows about InferenceModels in its own pool. If you send a request for Model B to Model A’s gateway, it fails with “model not found.”</p><p>You need something external (LiteLLM, a reverse proxy, or DNS-based routing) to direct requests to the correct model’s gateway. This is by design — llm-d adds value <em>within</em> a model’s pipeline (KV-cache routing, load-aware scheduling), not <em>across</em> models.</p><h3>4. Istio Sidecar Injection Must Be Disabled</h3><p>If your cluster runs Istio with automatic sidecar injection, disable it on the llm-d namespace:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: llm-d<br>  labels:<br>    istio-injection: disabled</pre><p>Istio sidecars interfere with the ext-proc communication between the Gateway pod and EPP. The Gateway pod itself <em>is</em> an Envoy proxy managed by Istio — adding a sidecar proxy in front of it creates double-proxying issues.</p><h3>5. The Default vLLM Image Is Private</h3><p>The llm-d chart’s default vLLM image (ghcr.io/llm-d/llm-d) is in a private registry. Use the public CUDA variant instead:</p><pre>vllm:<br>  image:<br>    registry: ghcr.io<br>    repository: llm-d/llm-d-cuda<br>    tag: &quot;v0.5.0&quot;</pre><h3>6. Cold Start Is Real</h3><p>When scaling from zero, expect 5–8 minutes:</p><ul><li>~2 min: Karpenter provisions a new GPU node</li><li>~2 min: Pull the vLLM image (~8GB)</li><li>~2 min: Download and load model weights from HuggingFace</li></ul><p>For production, consider image pre-pulling (DaemonSet-based), ECR pull-through caches, or keeping a warm standby node.</p><h3>Request Flow in Detail</h3><p>Here’s what happens when a request arrives:</p><pre>1. Client sends: POST https://phi4.example.com/v1/chat/completions<br>   {&quot;model&quot;: &quot;microsoft/Phi-4-mini-instruct&quot;, &quot;messages&quot;: [...]}<br>2. DNS resolves phi4.example.com to internal ALB<br>3. ALB matches host rule &quot;phi4.example.com&quot;<br>   -&gt; forwards to phi-4-mini-instruct-gateway-istio:80 (target-type: ip)<br>   -&gt; TLS terminated at ALB, plaintext HTTP to pod<br>4. Istio Gateway pod (Envoy) receives request<br>   -&gt; HTTPRoute matches path &quot;/&quot;<br>   -&gt; backendRef is InferencePool &quot;phi-4-mini-pool&quot;<br>   -&gt; InferencePool has endpointPickerConfig -&gt; EPP service<br>5. Envoy calls EPP via ext-proc gRPC<br>   -&gt; EPP looks up InferenceModel CR for &quot;microsoft/Phi-4-mini-instruct&quot;<br>   -&gt; EPP queries Redis: &quot;which pods have relevant prefix cached?&quot;<br>   -&gt; Redis returns: {pod-A: 85% cache hit, pod-B: 20% cache hit}<br>   -&gt; EPP scores: pod-A wins (high cache hit + acceptable load)<br>   -&gt; EPP tells Envoy: route to pod-A at 10.x.x.x:8000<br>6. Envoy forwards request to pod-A (vLLM)<br>   -&gt; vLLM finds partial KV-cache hit<br>   -&gt; Computes only remaining tokens (not full prompt)<br>   -&gt; Generates response tokens<br>   -&gt; Updates Redis prefix index with new cached prefixes<br>7. Response flows back: vLLM -&gt; Envoy -&gt; ALB -&gt; Client</pre><p>The key efficiency gain is in step 5–6: instead of random pod selection, the EPP routes to the pod with the best prefix cache hit, reducing redundant computation.</p><h3>Deploying</h3><pre># 1. Install CRDs<br>kubectl apply -k &quot;github.com/kubernetes-sigs/gateway-api/config/crd/?ref=v1.4.0&quot; \<br>  --server-side --force-conflicts<br>kubectl apply -k &quot;github.com/kubernetes-sigs/gateway-api-inference-extension/config/crd/?ref=v1.3.0&quot; \<br>  --server-side --force-conflicts<br># 2. Ensure Istio 1.28+ with inference extension enabled<br># 3. Create HuggingFace token secret<br>kubectl create secret generic llm-d-hf-token \<br>  --from-literal=HF_TOKEN=&lt;your-token&gt; -n llm-d<br># 4. Deploy<br>helm upgrade --install llm-d-stack ./helm/charts/llm-d-stack \<br>  -n llm-d -f ./helm/charts/llm-d-stack/cluster-values.yaml<br># 5. Verify<br>kubectl get ingress -n llm-d<br>kubectl get pods -n llm-d<br># 6. Test (after DNS)<br>curl -s https://qwen.example.com/v1/models<br>curl -s https://phi4.example.com/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;model&quot;:&quot;microsoft/Phi-4-mini-instruct&quot;,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Hello&quot;}],&quot;max_tokens&quot;:10}&#39;</pre><h3>What’s Next</h3><p>This setup gives you a solid multi-model inference platform with intelligent routing. From here, you could add:</p><ul><li><strong>Prefill/Decode Disaggregation</strong> — Split prompt processing and token generation onto separate pod pools for lower TTFT on long prompts</li><li><strong>Autoscaling</strong> — KEDA or llm-d’s built-in autoscaler to scale decode replicas based on queue depth</li><li><strong>LoRA Adapter Routing</strong> — Serve fine-tuned variants alongside base models with cache-aware LoRA routing</li><li><strong>Monitoring</strong> — vLLM and llm-d expose Prometheus metrics for inference latency, throughput, GPU utilization, and queue depth</li><li><strong>GitOps</strong> — ArgoCD Applications for drift detection and self-healing deployments</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d33760d1001" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# How We Built Outage-Proof Monitoring After the AWS us-east-1 Outage]]></title>
            <link>https://medium.com/@prasannanattuthurai/how-we-built-outage-proof-monitoring-after-the-aws-us-east-1-outage-00b7913ad4af?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/00b7913ad4af</guid>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 01:44:28 GMT</pubDate>
            <atom:updated>2025-10-26T04:28:46.430Z</atom:updated>
            <content:encoded><![CDATA[<h3>How We Built Outage-Proof Monitoring After the AWS us-east-1 Outage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMrmJFER4RqQ_CNPGMMKnQ.jpeg" /></figure><p>What the October 2025 AWS disaster taught us about dependency visibility — and how LLM-powered observability can keep you resilient next time.</p><h4>🚨 The Wake-Up Call: When the Cloud Stopped for Half the Internet</h4><p>On October 20, 2025, AWS us-east-1 was hit by a multi-hour outage. Everything broke: EC2, Lambda, DynamoDB etc. CI/CD pipelines stalled, SaaS products went dark, and status dashboards lagged behind reality.</p><p>Even teams with advanced monitoring were left flying blind for 30+ minutes — waiting on delayed vendor updates or unraveling cryptic error bursts across distributed services. Lesson learned: Observability must extend beyond your infrastructure — it must see your dependencies, too.</p><h4>⚠️ The Hidden Risk: You Don’t Own All Your Reliability</h4><p>Modern stacks depend on dozens of third-party services — auth providers, data pipelines, payment gateways, even your observability tools. When one fails, your uptime is only as strong as your ability to detect their failures in real time.</p><p>Traditional monitors scrape HTML or poll endpoints, but those break whenever a vendor tweaks their page design or wording. Result? Silence when you need signal most.</p><h4>🚀 Enter LLM-Driven Observability</h4><p>We rebuilt our monitoring around LLMs: Instead of fragile scraping or waiting on vendor announcements, our system reads and interprets status content like an SRE — catching outages from raw text across every vendor, often before official confirmation.</p><p>Your system is only as resilient as your weakest dependency. Our observability lets you see what your vendors won’t tell you — before your customers do.</p><h4>Teaching Machines to Read Like SREs</h4><p>Large Language Models have transformed how we process and understand text. Instead of hunting for specific HTML elements, we can now ask an AI: “Is this service healthy based on what you’re reading?”</p><p>This is exactly what we built — a next-generation service health monitoring system that combines:</p><p>- Web scraping with Playwright for reliable content extraction<br>- LLM analysis for intelligent status interpretation<br>- Parallel processing for fast multi-service checks<br>- Smart fallbacks for maximum reliability</p><h4>Architecture: How It Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEGBfjkuAlJfcfJCXztDuQ.png" /></figure><blockquote>1. Intelligent Web Scraping</blockquote><p>Instead of targeting specific HTML elements, we extract all meaningful text content from status pages:</p><pre>def get_structured_content(url: str) -&gt; List[str]:<br> with sync_playwright() as p:<br> browser = p.chromium.launch(headless=True)<br> page = browser.new_page()<br> page.goto(url, wait_until=&quot;domcontentloaded&quot;)<br> html = page.content()<br> <br> # Extract clean text content<br> elements = partition_html(text=html)<br> content = [el.to_dict().get(&quot;text&quot;, &quot;&quot;) <br> for el in elements <br> if el.to_dict().get(&quot;text&quot;, &quot;&quot;).strip()]<br> return content=</pre><p>This approach is resilient to UI changes because we’re not dependent on specific CSS selectors or DOM structures.</p><blockquote>2. LLM-Powered Analysis</blockquote><p>The extracted content is sent to an LLM with a carefully crafted system prompt:</p><pre>system_prompt = &quot;&quot;&quot;<br>You are an expert SRE assistant. Analyze the provided text content from a service status page.<br>Severity Levels:<br>- CRITICAL: Complete outage, major incident, service unavailable<br>- WARNING: Partial outage, degraded performance, investigating issues<br>- HEALTHY: All systems operational, no issues<br>Respond with JSON only:<br>{<br> &quot;is_healthy&quot;: true or false,<br> &quot;severity&quot;: &quot;CRITICAL&quot; or &quot;WARNING&quot; or &quot;HEALTHY&quot;,<br> &quot;reason&quot;: &quot;your explanation here&quot;<br>}<br>&quot;&quot;&quot;</pre><p>The LLM understands context that traditional parsing cannot:</p><p>- “We’re investigating reports of slow loading times” → WARNING<br>- “All systems operational” → HEALTHY<br>- “GitLab.com is currently unavailable” → CRITICAL</p><blockquote>3. Parallel Processing for Speed</blockquote><p>All services are checked simultaneously using ThreadPoolExecutor:</p><pre>def check_all_services(services: Dict, use_real_llm: bool) -&gt; Dict:<br> results = {}<br> with ThreadPoolExecutor(max_workers=5) as executor:<br> future_to_service = {<br> executor.submit(check_service_health, key, info, use_real_llm): key<br> for key, info in services.items()<br> }<br> for future in as_completed(future_to_service):<br> service_key, result = future.result()<br> results[service_key] = result<br> return results</pre><p>This reduces total execution time from minutes to seconds, even when monitoring dozens of services.</p><h4>Key Features That Make It Production-Ready</h4><blockquote>1. Smart Fallback System</blockquote><p>If the LLM is unavailable or rate-limited, the system automatically falls back to keyword-based analysis:</p><pre>def simulate_health_check(content_text: str) -&gt; Dict:<br> critical_keywords = [&quot;outage&quot;, &quot;down&quot;, &quot;unavailable&quot;, &quot;major incident&quot;]<br> warning_keywords = [&quot;monitoring&quot;, &quot;investigating&quot;, &quot;degraded&quot;]<br> <br> has_critical = any(keyword in content_text.lower() <br> for keyword in critical_keywords)<br> if has_critical:<br> return {<br> &quot;is_healthy&quot;: False,<br> &quot;severity&quot;: &quot;CRITICAL&quot;,<br> &quot;reason&quot;: &quot;Detected critical issues&quot;<br> }<br> # … additional logic</pre><blockquote>2. Rich Notifications</blockquote><p>When services are down, the system sends contextual Google Chat notifications with service-specific details from LLM analysis, clickable buttons to status pages, and severity indicators for proper escalation.</p><blockquote>3. Configuration-Driven</blockquote><p>Adding new services requires zero code changes — just JSON configuration:</p><pre>{<br> &quot;newservice&quot;: {<br> &quot;url&quot;: &quot;https://status.newservice.com/&quot;,<br> &quot;name&quot;: &quot;New Service&quot;<br> }<br>}</pre><h4>Implementation Best Practices</h4><blockquote>1. Content Truncation — Limit content size to avoid token limits:</blockquote><pre># Limit to ~15K chars (≈3.75K tokens)<br>content_text = &quot; &quot;.join(content)[:15000]</pre><blockquote>2. Structured Prompts — Use clear, specific prompts that return consistent JSON:</blockquote><pre>&quot;You MUST respond with ONLY a valid JSON object (no other text)&quot;</pre><blockquote>3. Error Handling — Implement comprehensive error handling with graceful degradation:</blockquote><pre>try:<br> result = llm_analysis(content)<br>except Exception as e:<br> logger.error(f&quot;LLM failed: {e}&quot;)<br> result = fallback_analysis(content)</pre><h4>Lessons Learned</h4><blockquote>1. Prompt Engineering is Critical</blockquote><p>Spend time crafting precise prompts. The difference between “analyze this page” and “determine if this service is healthy based on SRE best practices” is dramatic.</p><blockquote>2. Fallbacks Save Lives</blockquote><p>Always have a non-LLM backup. When your monitoring depends on external APIs, redundancy is essential.</p><blockquote>3. Context Matters</blockquote><p>LLMs excel at understanding context that regex cannot. Leverage this for nuanced health assessment beyond simple keyword matching.</p><h4>Conclusion: The Future of Monitoring</h4><p>We’re at an inflection point in observability. Traditional monitoring tools that rely on rigid parsing and predefined rules are giving way to intelligent systems that understand context and adapt to change.</p><p>By combining the reliability of traditional monitoring with the intelligence of LLMs, we’ve created a system that is:</p><p>- More reliable than brittle HTML parsing<br>- More intelligent than keyword matching<br>- More maintainable than custom integrations<br>- More cost-effective than manual monitoring</p><p>The future of service monitoring isn’t about writing more complex parsers — it’s about teaching our systems to understand what they’re monitoring.</p><p>Ready to revolutionize your monitoring? The code patterns and architecture described here can be adapted to monitor any text-based status source, from API responses to log files to documentation sites.</p><p>The age of intelligent monitoring has begun. Are you ready to join it?</p><p>Have you implemented LLM-based monitoring in your organization? Share your experiences and challenges in the comments below or reach out in <a href="https://www.linkedin.com/in/prasannanattuthurai/">LinkedIn</a>.</p><p>Tags: #SRE #Monitoring #LLM #DevOps #Reliability #AI #Observability #Python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00b7913ad4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Multi-Account AWS Operations with Amazon Q CLI and MCP | 15 min read]]></title>
            <link>https://medium.com/@prasannanattuthurai/streamlining-multi-account-aws-operations-with-amazon-q-cli-and-mcp-436f7dc8cc61?source=rss-cbb47ae3704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/436f7dc8cc61</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[amazon-q-cli]]></category>
            <category><![CDATA[amazon-q]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Prasanna Nattuthurai]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 02:28:48 GMT</pubDate>
            <atom:updated>2025-10-07T02:40:35.703Z</atom:updated>
            <content:encoded><![CDATA[<p>by<br><a href="https://www.linkedin.com/in/prasannanattuthurai/">Prasanna Nattuthurai</a><br><a href="https://www.linkedin.com/in/ameya0singh/">Ameya Singh</a></p><h3>Introduction</h3><p>Managing multiple AWS accounts is a common challenge for organizations today. Whether you’re dealing with separate accounts for different business units, regions, or workload types, the operational overhead of context-switching between accounts can be significant.</p><p>This article shares my journey building a centralized AI-assisted AWS operations system using Amazon Q CLI and the Model Context Protocol (MCP). This powerful combination enables natural language queries and commands across account boundaries while maintaining security and governance.</p><h4><strong>Architecture Overview</strong></h4><p>The solution consists of three distinct layers:</p><p>1. <strong>**Local Client Layer**</strong>: Amazon Q CLI running on your development machine</p><p>2. <strong>**Central Hub Layer**</strong>: MCP server deployed in a dedicated AWS account (Hub Account)</p><p>3. <strong>**Target Accounts Layer**</strong>: Multiple AWS accounts with cross-account access configured</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-IUBnbN4bsBW-vBd8lb6w.jpeg" /><figcaption>Architecture</figcaption></figure><h4><strong>Key Components</strong></h4><p><strong>Amazon Q CLI (Local)<br></strong>- Natural language interface for AWS operations<br>- MCP client integration for server communication<br>- Request formatting and response handling</p><p><strong>MCP Server (Hub Account)<br></strong>- Central orchestration point for all AWS operations<br>- Cross-account credential management via STS AssumeRole<br>- Request routing and response aggregation<br>- Audit logging and monitoring</p><p><strong>Target Accounts<br></strong>- Multiple accounts with IAM roles that trust the Hub Account<br>- Service-specific resources (EKS clusters, EC2, S3, RDS, Lambda, etc.)</p><h4><strong>Security Architecture</strong></h4><p>Security is paramount in a multi-account setup:</p><p><strong>Authentication Flow:<br></strong>1. MCP server runs as an EKS Pod with Pod Identity/IRSA<br>2. Amazon Q CLI sends requests to the MCP server (HTTP, internal VPC only)<br>3. MCP server uses Pod Identity to assume cross-account MCP-Orchestrator Role<br>4. Temporary credentials are used for AWS API calls in target accounts</p><p><strong>IAM Role Structure:</strong></p><pre>Hub Account (EKS Cluster):<br>├── EKS Pod Identity Role: MCP-ServerExecutionRole (attached to MCP server pod)<br>│ └── Trust policy: EKS Pod Identity service<br>│ └── Permissions: sts:AssumeRole for MCP-Orchestrator Role in ALL target accounts<br><br>Target Accounts (1, 2, 3...N):<br>└── MCP-Orchestrator Role (trusts Hub Account&#39;s Pod Identity Role)<br>    └── Permissions: Read-only access to AWS services<br>    └── Same role name across all accounts for consistency</pre><h4><strong>Technical Implementation</strong></h4><p><strong>MCP Server Implementation (Python)</strong></p><pre>from fastmcp import FastMCP<br>import boto3<br>from typing import Optional<br>from loguru import logger<br><br># Initialize FastMCP server<br>mcp = FastMCP(&quot;Platform MCP Server&quot;)<br><br>class AWSClient:<br>    &quot;&quot;&quot;Base AWS client with environment-aware authentication&quot;&quot;&quot;<br>    ROLE_TEMPLATE = &quot;arn:aws:iam::{account_id}:role/MCP-OrchestratorRole&quot;<br>    <br>    def __init__(self, region: str, account_id: Optional[str] = None):<br>        self.region = region<br>        self.account_id = account_id<br>        <br>        if account_id:<br>            # Assume cross-account role<br>            role_arn = self.ROLE_TEMPLATE.format(account_id=account_id)<br>            logger.info(f&quot;Assuming role: {role_arn}&quot;)<br>            <br>            # Use Pod Identity to assume role<br>            sts_client = boto3.client(&#39;sts&#39;, region_name=region)<br>            assumed_role = sts_client.assume_role(<br>                RoleArn=role_arn,<br>                RoleSessionName=f&quot;platform-mcp-{account_id}&quot;<br>            )<br>            <br>            # Create session with assumed credentials<br>            self.session = boto3.Session(<br>                aws_access_key_id=assumed_role[&#39;Credentials&#39;][&#39;AccessKeyId&#39;],<br>                aws_secret_access_key=assumed_role[&#39;Credentials&#39;][&#39;SecretAccessKey&#39;],<br>                aws_session_token=assumed_role[&#39;Credentials&#39;][&#39;SessionToken&#39;],<br>                region_name=region<br>            )<br>        else:<br>            # Use Pod Identity directly<br>            self.session = boto3.Session(region_name=region)<br>    <br>    def get_client(self, service: str):<br>        return self.session.client(service)<br><br>@mcp.tool()<br>def list_ec2_instances(cluster_name: str) -&gt; str:<br>    &quot;&quot;&quot;List EC2 instances in the cluster&#39;s account&quot;&quot;&quot;<br>    # Parse cluster name to extract account_id and region<br>    account_id, region = parse_cluster_name(cluster_name)<br>    <br>    # Create AWS client with role assumption<br>    aws_client = AWSClient(region, account_id)<br>    ec2 = aws_client.get_client(&#39;ec2&#39;)<br>    <br>    # List instances<br>    response = ec2.describe_instances()<br>    instances = []<br>    for reservation in response[&#39;Reservations&#39;]:<br>        for instance in reservation[&#39;Instances&#39;]:<br>            instances.append({<br>                &#39;InstanceId&#39;: instance[&#39;InstanceId&#39;],<br>                &#39;InstanceType&#39;: instance[&#39;InstanceType&#39;],<br>                &#39;State&#39;: instance[&#39;State&#39;][&#39;Name&#39;]<br>            })<br>    <br>    return json.dumps({&#39;instances&#39;: instances, &#39;count&#39;: len(instances)})<br><br>def main():<br>    &quot;&quot;&quot;Start HTTP server&quot;&quot;&quot;<br>    logger.info(&quot;Starting Platform MCP Server on HTTP&quot;)<br>    mcp.run(transport=&quot;http&quot;, host=&quot;0.0.0.0&quot;, port=8080, path=&quot;/mcp&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Cross-Account IAM Roles</strong></p><p><strong>Hub Account — EKS Pod Identity Role Policy:</strong></p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:iam::*:role/MCP-OrchestratorRole&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;aws:PrincipalOrgID&quot;: &quot;o-xxxxxxxxxx&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p><strong>Target Accounts — </strong>MCP-Orchestrator Role<strong> Trust Policy:</strong></p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;arn:aws:iam::HUB-ACCOUNT-ID:role/platform-mcp-pod-identity-role&quot;<br>      },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><h4><strong>Real-World Use Cases</strong></h4><p><strong>1. Multi-Account Resource Inventory</strong></p><pre>q query &quot;Show me all EKS clusters across all production accounts&quot;</pre><p><strong>**Output:**</strong></p><pre>Production US-East (111111111111):<br>- 5 clusters: platform-prod-1, platform-prod-2, data-prod-1, ml-prod-1, api-prod-1<br>Production US-West (222222222222):<br>- 3 clusters: platform-prod-west-1, data-prod-west-1, api-prod-west-1<br>Production EU (333333333333):<br>- 4 clusters: platform-prod-eu-1, data-prod-eu-1, ml-prod-eu-1, api-prod-eu-1<br>Total: 12 clusters across 3 accounts<br>Kubernetes versions: 1.28 (8 clusters), 1.27 (4 clusters)<br>Recommendation: Upgrade 4 clusters to version 1.28</pre><p><strong>2. Security Compliance Auditing</strong></p><pre>q query &quot;Audit all S3 buckets across accounts for encryption and public access settings&quot;</pre><p><strong>**Output:**</strong></p><pre>Security Audit Results:<br>Production (111111111111):<br>✓ 45 buckets, all encrypted<br>✗ 2 buckets with public access enabled:<br>- prod-logs-bucket-2023<br>- prod-temp-data<br>Staging (222222222222):<br>✓ 23 buckets, all encrypted<br>✓ All buckets have public access blocked<br>Development (333333333333):<br>✗ 18 buckets, 3 without encryption:<br>- dev-test-bucket<br>- dev-scratch-space<br>- dev-temp-files<br>✓ All buckets have public access blocked<br>Action Required: Fix 5 compliance issues</pre><p><strong>3. Incident Response and Troubleshooting</strong></p><pre>q query &quot;Investigate performance issues in production account: check EC2 CPU, RDS connections, and Lambda errors in the last hour&quot;</pre><p><strong>**Output:**</strong></p><pre>Performance Investigation Results:<br>EC2 Instances:<br>- web-server-1: CPU 95% (spike at 14:23 UTC)<br>- web-server-2: CPU 87% (spike at 14:23 UTC)<br>- app-server-1: CPU 45% (normal)<br>RDS Databases:<br>- prod-db-1: 245 connections (max: 250) ⚠️<br>- Connection pool near capacity<br>Lambda Functions:<br>- api-handler: 15 errors in last hour<br>- Error: &quot;Database connection timeout&quot;<br>Root Cause: Database connection pool exhaustion<br>Recommendation: Scale RDS instance or optimize connection pooling</pre><h4><strong>Implementation Guide</strong></h4><p><strong>Prerequisites<br></strong>- Hub Account: EKS cluster, ECR, IAM, ArgoCD<br>- Target Accounts: IAM roles (MCP-OrchestratorRole)<br>- Local: AWS CLI, Python 3.9+, Docker, kubectl, helm</p><p><strong>Deployment Steps<br></strong>1. Set Up Hub Account (EKS Cluster)<br>2. Configure Target Accounts with MCP-OrchestratorRole<br>3. Configure Amazon Q CLI<br>4. Verify Setup</p><p><strong>Best Practices<br>Authentication Strategy:<br></strong>- EKS Pod Identity for secure AWS authentication<br>- Direct STS AssumeRole for cross-account access<br><strong>Security Best Practices:<br></strong>- Principle of least privilege for all IAM roles<br>- External IDs for cross-account role assumption<br>- Network-level security (private VPC, security groups)<br>- Comprehensive logging for audit and troubleshooting<br><strong>Deployment Approach:<br></strong>- GitOps with ArgoCD for continuous deployment<br>- Helm charts for Kubernetes resource management<br>- Containerized application for scalability</p><h4><strong>Conclusion</strong></h4><p>Building a multi-account AWS management system using Amazon Q CLI and Model Context Protocol has transformed how I interact with AWS infrastructure. What once required context switching between multiple accounts, running repetitive commands, and manually aggregating data is now accomplished through natural language queries in just seconds.</p><p>This architecture scales to hundreds of accounts while maintaining security and governance, making it ideal for organizations of any size with multi-account AWS environments.</p><h4><strong>Resources:</strong></h4><p>- <a href="https://aws.amazon.com/q/">https://aws.amazon.com/q/</a><br>- <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io/</a><br>- https://aws.amazon.com/organizations/getting-started/best-practices/</p><p><em>*This article represents my personal experience and opinions. All code examples are simplified for illustration purposes. Always follow your organization’s security policies and AWS best practices when implementing production systems.*</em></p><p>#AWS #CloudArchitecture #AmazonQ #MCP #MultiAccount #DevOps #CloudSecurity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436f7dc8cc61" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>