<?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 Dheeraj Pai on Medium]]></title>
        <description><![CDATA[Stories by Dheeraj Pai on Medium]]></description>
        <link>https://medium.com/@pai.dev?source=rss-e1cc04a21c65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jE9dHyt6ejBmTtkaQpfmdA.jpeg</url>
            <title>Stories by Dheeraj Pai on Medium</title>
            <link>https://medium.com/@pai.dev?source=rss-e1cc04a21c65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:14:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pai.dev/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[I went through every line of code of OpenClaw so you don’t have to.]]></title>
            <link>https://medium.com/@pai.dev/i-went-through-every-line-of-code-of-openclaw-so-you-dont-have-to-bec04bfe3be0?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec04bfe3be0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[openclaw]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 09:07:29 GMT</pubDate>
            <atom:updated>2026-02-09T09:07:29.603Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR: OpenClaw has a lot of flaws, but some fundamental changes it has brought are here to stay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twfKYL4q-cz0UTW3RkZNLw.png" /><figcaption>Image from repo. Not AI Generated.</figcaption></figure><p>OpenClaw was released and went really wild. But a lot of things have changed, a lot of new things. There are some naysayers. It has divided the internet into two:</p><ol><li>The big followers of OpenClaw who believe this is going to be the Next Big Thing</li><li>People who say it’s nothing new and it has added no new value to the entire system</li></ol><p>There are few things that are very, very clear. I’ve gone through the entire codebase, I’ve gone through what people have been doing, what can be done, verified several claims and did a deep dive into what is actually happening over there. Before this, I’d been into the MCP ecosystem, I’d gone through the MCP hype cycle and also understood what stayed and what didn’t stay. This is all during my LeanMCP work.</p><h3>The whole purpose of OpenClaw</h3><p>First of all, a lot of people I see on the internet, Twitter, and LinkedIn claiming it is not secure for enterprise and you should not install the enterprise version. Including me, I just posted a few days ago not to install OpenClaw on the laptop. Any company would be really terrified if someone lets an AI agent have full access to the computer. Giving an AI agent full access to the computer is notoriously higher privilege than what you should give to any particular app, let alone an AI agent that can run arbitrary scripts using arbitrary skills.</p><p>And I don’t expect it to penetrate the enterprise at all. In fact, it is not designed to do so.</p><p>Its primary design is to enable an individual user to express his creativity and leverage an AI agent to get things done. An individual user has a lot of things they want automated using AI, but their hands are tied because of the restrictions imposed by operating systems and apps in the name of security or proprietary IP rights.</p><p>It is yet to penetrate the enterprise, and I don’t think the open source version will ever be accepted by the enterprise at all. In fact, the entire design is not meant for enterprise. It’s for consumers, for hackers and indie hackers. The whole purpose of it is to show what agents can do if you give them the permissions to do so.</p><p>What I see is people demonstrating what can be done when you give full access and full control of the entire OS to the agent without interference, and allow it to “self-mutate” the code whenever needed based on user requirements — fully natural language scripts for updating itself and fully natural language config.</p><p>OpenClaw showed what Jensen Huang once said. Your natural language English will be the next programming language. English is the way agents take actions. You take actions by your words. You configure the agent with your words. You run the entire workflow with your judgment. It boils down to this: your judgment and your agency are all it takes to get things done.</p><h3>So, is it all great?</h3><p>The successes and miracles of OpenClaw reminds me of a 2,000 years old story.</p><p>Back in Athens during the roman empire, skeptic Diagoras was shown tablets of worshippers who prayed and survived shipwrecks. They claimed and offered it as proof that praying god would saves lives. Diagoras replied: “Where are the pictures of those who prayed and drowned?” The drowned stay silent at the bottom of the sea; only the survivors get to advertise. That missing evidence is survivorship bias.</p><p>The whole point of OpenClaw is to put in people’s hands what agents can actually do. Of course, it’s not all great. There are a lot of bugs, errors, and unreliability. OpenClaw has spectacular asymmetric leverage: for every 1000 workflows don’t work, 5 things work spectacularly well, and those 5 things are the ones that get tweeted and go viral 100x. The virality comes from things that have never been done before being done right now. It doesn’t mean it is reliable for everyday use. In fact, on an average it is a net loss. No-one is making money. Not even the token providers. Even Anthropic and OpenAI run at a loss even at inference.</p><p>People are spending thousands of dollars per day on Claude tokens generating slop that never works, and getting frustrated with security issues being distributed wildly via Claw hubs and other platforms. Though the generation would never stop hitting Dopamine highs, at least for a while.</p><p>Many people don’t even understand the risks and security issues, yet they rush in. The majority don’t know the difference between models or how to execute reliably, let alone understand the code and what the agent is actually doing on their operating system.</p><h3>The key points of OpenClaw</h3><p>I went through the entire source code of OpenClaw and understood what is actually does.</p><p>Honestly, there is no monumental breakthrough. But if you take a step back and look at the whole picture, you’ll realize and understand the efforts that has gone into context engineering.</p><p>The goal was not to create a chatbot that runs at once and stops, the goal was to create an agent that remembers what you said, and works for you eternally, given the LLMs, memory, your OS, the network bandwidth, and your token (and bank) balance, everything being limited.</p><p>They managed context for real long-running tasks with continually increasing context, running a background-processes that continuously indexes and reduces long conversations, routing the queries to the right models for the right token sizes. These are simple things but required massive experimentation and implementation. Given it is just easy to overcomplicate stuffs.</p><p>Most of these things are independently done before, but they removed the context fluff that bogs down LLMs. It’s still not perfect, but good context management and good usage of available data made the difference. Platforms like Open Interpreter, Claude Computer Use, etc. already had similar access but failed due to bad context engineering. OpenClaw delivered what Microsoft Copilot promised.</p><p>Another reason it worked better is simply that underlying LLMs are now much better at reasoning than when open-interpreter came out. LLMs are just way better at picking skills rather than ingesting entire prompt at one shot. Better at intelligently deferring tool calls. And do not make errors even in copying very complex high-entropy text chunks which are essential for any authentication or security related tool usage.</p><h3>The OS is all you need</h3><p>One of the remarkable things OpenClaw did was build everything just on existing OS APIs. No additional protocols, no fancy MCPs, ACPs and other payment protocols etc. For the core functionality of getting things done with AI, you do not need all that extra stuff, and that’s exactly what it proved.</p><p>I’ve been working in open source for the past 7–8 years and coding for past 10 years. I went through OpenClaw’s source code in greatest detail. What blew my mind was how different its paradigm is. The reliance on natural language prompt is a lot. And surprisingly, with the better models like Opus-4.6 it works remarkably well.</p><p>I was surprised when I saw the entire update script was literally a skill.md file which has the instruction to the agent on how to update and restart itself. And can you guess how they make this skill.md file non-tamperable? Yes, it is another Skill.md file which that says “Never overwrite updates folder’s skill.md”.</p><p>I tried added another long skill with a malicious instruction to update the agent from another link and it did change without a question.</p><p>If you are security researcher, I know what you are thinking but spare me over here.</p><p>The point is NOT to teach the vibe-coders about the security and help them write script and better OS permissions levels. BUT to adapt security feature to the new paradigm of programming. When the entire code is technically a written English paragraph what would you actually do to build a secure, trustable system that scales.</p><p>And honestly, this was just ONE example among 1000+ skills. And you cannot directly decide and maintain every single file on how to actually manage these.</p><p>There are several alternative ways to secure these by controlling the distribution of these skills itself: By code-signing(or skill-signing) them using a trusted chain of trust. The simpler the approach is and more it is delegated to the LLM, the more would be the adoption.</p><h3>A blatant fight against fake promises</h3><p>The founder of OpenClaw, Peter, mentioned Openclaw is what Apple Intelligence should actually should have been.</p><p>And honestly, it is what Microsoft co-pilot, Apple Intelligence, and Gemini had promised us. Apple and MSFT had everything in hand to get this done. The distribution, the trust that it would work. But they just broke all the promises by series of disappointing releases.</p><p>And it makes sense. Apple charges premium prices yet ships buggy, lagging software compared to Android or especially Huawei, where you get 10x performance for half the price. OpenClaw completely disregards Apple’s security model. It can access all your messages, mails, apps, photos, browser cookies, and logged-in accounts. It does not promise security — that’s not what it’s designed for. It promises control: if you decide your agent can do something, it must be able to do it.</p><p>And since OpenClaw is open source and distributed outside the App Store, there is no easy way for Apple to prevent users from using it.</p><p>OpenClaw may not be perfect or enterprise-ready but definitely challenging the status quo. Apple, MSFT, Google should ramp up to survive or they would just never be able to capture the agent-application market. The next set of startups cannot be just wrappers as one single mega-wrapper now just does all your job (Though I still predict there will be several OpenClaw for X startups soon).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec04bfe3be0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generalist AI Agents Are Dead. Long live Hyper-Expert Agents]]></title>
            <link>https://medium.com/@pai.dev/generalist-ai-agents-are-dead-long-live-hyper-expert-agents-712909ec3196?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/712909ec3196</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Sat, 10 May 2025 21:18:22 GMT</pubDate>
            <atom:updated>2025-05-10T21:19:26.437Z</atom:updated>
            <content:encoded><![CDATA[<h2>Generalist AI Agents Are Dead. Hyper-Expert Agents Are the Future.</h2><p>Let’s be real — 2024 was the year of the generalist AI agent. Everyone was building some kind of AI assistant that “helps you build things.” Cute demos, lots of hype.</p><p>Cursor took off fast — hit $200M ARR by the end of the year. Windsurf got scooped up for $3 billion. Big numbers. But if you’ve used them, you know the truth — they’re helpful, but only if you already know what you’re doing.</p><p>Cursor is great if you’re a solo hacker or trying to bootstrap an idea. OR you already know what you are doing and just make cursor do some repetitive stuffs. It can scaffold things, help with quick fixes. But take that into a serious engineering org? You’ll hit a wall real quick.</p><p>Let’s talk frontend development for a second. Hobbyists want code that just works. But at scale — in actual companies — things look way different. You’re not just writing buttons. You’re profiling for speed, doing memory audits, checking security (static and dynamic). You’re running unit tests, E2E tests, making sure your app doesn’t break on Safari 14. You’re testing on 10 different devices. You’re tracking Core Web Vitals. You’re updating dependencies, checking for CVEs. This is real work. Cursor doesn’t do that. Windsurf doesn’t either. And that’s exactly why we need a new kind of AI agent.</p><p>This next wave of agents? They’re not assistants. They’re specialists. Hyper-opinionated, domain-obsessed agents that know exactly what needs to be done — and do it right. Not tools you chat with. Not assistants that ask what you want. These are agents that already know what’s expected in your workflow and just go get it done. With standards. With rigor. With memory of your previous mistakes baked in.</p><p>These agents aren’t playing around. They don’t just give you a skeleton of a React component. They’ll flag your bundle size, check your Lighthouse scores, patch up the dependencies, run tests, and ship it through CI/CD. They won’t let you push insecure code. They’re the annoying but brilliant senior engineer who always catches the things you missed — except now, it’s a machine.</p><p>The Market’s Already Moving</p><p>You’re not the only one noticing this. The shift is loud and clear in the numbers. “Vertical AI” is exploding. It was a $5B market in 2024, on track to hit $47B by 2030, maybe more. In just 2024, investors threw in $3.8B into agent startups. But the difference? This time, it’s not for general-purpose copilots. It’s for deeply verticalized, workflow-aware, domain-native agents.</p><p>You want examples? Let’s go.</p><p>•	Harvey is doing this in legal. They’re not just summarizing contracts. They’re writing drafts, flagging compliance issues, doing legal research. They’re in half of the top law firms in the U.S. Just raised $300M at a $3B valuation. Real traction.</p><p>•	Qodo (ex-CodiumAI) is going hard in dev tools — building agents that focus entirely on code quality, testing, and verification. Not “hey write me a Python function,” but “here’s why this test is missing edge cases and will fail in prod.” They got $40M recently.</p><p>•	Hippocratic AI is taking on healthcare. Built a whole agent app store for hospitals — from virtual nurses to billing agents. Raised $141M in a Series B, just nine months after their last round. The total haul? $278M. Healthcare needs this badly.</p><p>•	Salient is automating loan servicing. Their agents handle calls, compliance, insurance updates — they processed over half a billion in loan payments. These aren’t chatbots. These are revenue-generating machines for banks.</p><p>•	Apriora is automating first-round interviews with AI recruiters. They’re not just asking questions. They’re assessing candidates across behavior, speech, and matching them to job specs. No scheduling hell. No wasted recruiter time. It just works.</p><p>•	Sweetspot is helping businesses win government contracts. The agent matches RFPs, writes the damn proposals, makes sure you’re compliant. Small businesses usually don’t even try for these contracts because the paperwork is too dense. Now they can.</p><p>See the pattern? These aren’t tools. These are AI agents that run full workflows end-to-end. They don’t just “assist.” They replace entire job segments and increase the throughput of entire teams.</p><h3>The opportunity</h3><p>While everyone’s chasing the next billion-dollar hyper-expert agent, the real long-term winners might just be the ones building the rails underneath. Think about it — every specialized agent needs to be hosted, fine-tuned, updated, secured, and shipped to end users. That’s not trivial. Hosting platforms for MCPs, model routers, tools that enable agent orchestration, secure sandboxes — these are the backbones. Whoever owns the “AWS of agent infrastructure” is sitting on a goldmine.</p><p>Same goes for custom model hosting and fine-tuning. Every hyper-expert agent eventually needs domain-specific behavior. That means RAG, custom models, embeddings, secure memory layers, usage analytics — and all that needs to be plug-and-play. The platforms that make this easy, fast, and reliable — they’re the ones everyone will build on. And here’s the kicker — the ones that build faster than Big Tech, that ship the missing pieces the hyperscalers aren’t touching yet — agent-aware CI/CD pipelines, context management layers, agent state recovery, policy enforcement — they’ll win by being indispensable before the big players even realize the opportunity.</p><p>Trusted distribution is another piece. Agents don’t live in a vacuum — they need a way to reach users safely and securely. Whether that’s through agent marketplaces, native app wrappers, or verified sandboxes with permissions, someone’s going to build the “App Store” for agents. And if they do it right — with trust, with security, with discoverability — they’ll become the gatekeepers of this entire ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712909ec3196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP 2.0: The Top 5 Missing Components Required to Accelerate Its Adoption]]></title>
            <link>https://medium.com/trmx-ai/mcp-2-0-the-top-5-missing-components-required-to-accelerate-its-adoption-7b1a62e622ca?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1a62e622ca</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[startupş]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 06:35:02 GMT</pubDate>
            <atom:updated>2025-04-16T06:35:02.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2wv3VKgiWCkdua4B7rXVg.png" /></figure><p>MCP has seen rapid adoption within the developer community. However, this accelerated uptake comes with significant challenges — both in sustaining fast growth and doing so without triggering widespread concerns around scalability and security.</p><h3>Understanding today’s MCP ecosystem</h3><p>MCP supports two types of communication: Local (running in a separate process and connected via stdio) and Remote (running on a different machine and connected using SSE or Streamable HTTP). To use a remote server, your client must support remote communication — i.e., you need an MCP client that supports remote connections. Similarly, to use a locally running server, you need a locally running MCP server.</p><p>State of MCP clients now — Most MCP clients today support only locally running MCPs, including Claude Desktop. Cursor is one of the few that uses remote ones via SSE. Another issue is that running remote SSE-based MCP servers is increasingly painful. They are expensive to run and more complicated. It takes time to build them, and you need to run them on a server. Serverless MCPs, on the other hand, are extremely difficult to run.On the other hand the local MCPs run locally on your machine. So, it does not take you to spend a ton of money to host MCPs remotely.</p><p>Read More on why Serverless MCPs are really hard here — <a href="https://pai.dev/why-serverless-mcps-are-especially-hard-6796a09613fe">https://pai.dev/why-serverless-mcps-are-especially-hard-6796a09613fe</a></p><p>So, as a consequence, most of the MCPs used today are local MCPs. They are hosted locally on your machine, and most of them are run using npx. It&#39;s really convenient because hosting your code on npmjs publicly doesn&#39;t cost anything for the MCP server developer or publisher. Most of them are hosted under an npmjs organization and are used via the npx command. Which looks something like this</p><pre>npx -y @modelcontextprotocol/server-memory</pre><p>All looks fine so far — until you look deeper. From a software engineering perspective, when you start thinking in terms of scalability, reliability, security, and privacy, these become key components for widespread adoption that are still limiting the broader adoption of MCPs.</p><h3>1. Security and trust</h3><p>The problem is the registries npx are targetted for developers and not common users who do not understand what is running behind in the code.</p><p>When a user runs an npx server with arguments, they are literally executing someone else&#39;s code on their local machine—granting it permissions to access many resources without even realizing it. It&#39;s like downloading software from the internet and running it without knowing who wrote it or what it actually does.</p><p>Firstly, you do not know who wrote the code you are running. You do not know if it contains malware. Things become even more complex when using npx. npx downloads a package from npmjs and runs it on your local machine. If you run it a second time, it doesn&#39;t download it again but instead uses a cached version. The catch is that between your first and second run, the server might have been tainted—and there’s no straightforward way to verify this. You don’t know if some other software on your system modified it in between. In fact, when you install one server, that server technically has the ability to remove or alter another server.</p><p>A solution for this would be to establish a registry for MCP servers — not just a random collection of MCPs that anyone can upload. There are bunch of them mcp.so, smithery, glama AI and what not. All of them are garbage. What we need is a well organized registry where users can register their identity, sign their MCP servers, and upload them. It should be a registry where MCP clients can request verification of a server’s integrity and authenticity.</p><p>How do enterprises handle this today?</p><ul><li>Today, whenever an end user — especially a non-developer — uses an app, it is properly vetted. For example, every app in the App Store and Android Play Store is signed, and there is a vetting program that checks whether the app requests restricted permissions.</li><li>The App Store has even stricter conditions. Moreover, even if you want to distribute your personal app and share it with your friends, it must be signed with your developer key and submitted for a malware check (notarization). Without this, you cannot simply share your app with random users. This process deters developers from creating and distributing malware</li><li>The problem with npm and PyPI is that they are focused on developers. It is assumed that you have some basic understanding of what the code is doing, what it can access, and how it runs. Even though there are companies that scan these packages for malware and malicious behavior, the restrictions are relatively relaxed.</li><li>Browsers, on the other hand, use keychains to verify whether a website’s SSL certificate is valid. It’s a standard protocol handled by the browser itself, as well as by all request-handling SDKs that support HTTPS, such as curl, requests, fetch, and others.</li></ul><p>To be continued…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1a62e622ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/mcp-2-0-the-top-5-missing-components-required-to-accelerate-its-adoption-7b1a62e622ca">MCP 2.0: The Top 5 Missing Components Required to Accelerate Its Adoption</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP-An attempt to fix the security issue with the MCP servers]]></title>
            <link>https://medium.com/trmx-ai/mcp-an-attempt-to-fix-the-security-issue-with-the-mcp-servers-5b7b00991c56?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b7b00991c56</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-client]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 06:07:05 GMT</pubDate>
            <atom:updated>2025-04-15T06:07:05.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>MCP-armor: An attempt to fix the security issue with the MCP servers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZONkLOEgB2LqrLz9Yy4aQ.png" /></figure><p>Model Context Protocols (MCPs) are powerful. They allow users to connect various tools to their LLMs without building custom integrations from scratch. This makes it easy for developers to build servers that let their users access these tools seamlessly within AI apps like Cursor or Claude — all without needing to understand the underlying LLM or tool invocation mechanics.</p><p>But MCPs today are a security mess. Most MCP servers aren’t remote SSE servers. While connecting a tool to your AI looks seamless, you’re often exposing your system to unknown code written by someone you’ve never heard of — code that’s never been audited. It can have arbitrary access to your computer, potentially download malware the moment you install it, and worst of all, you might not even realize it until it’s too late.</p><p>I looked into this issue and tried to find a resolution. Personally, I want to experiment with many MCP servers, but to be honest, I’m not comfortable using them in their current form.</p><p>There are two main concerns here. First is security. I want the entire system to run inside a sandbox — no access to my local files, with all network calls and syscalls being logged and monitored.</p><p>Second, I don’t want to constantly modify code just to run it in a sandboxed environment. I want to keep changes minimal, ideally just a small tweak in the MCP config.</p><p>Third, the npx command — which many MCP servers rely on — is fairly mature. It downloads the required npm module and caches it in .npm. If the module is already cached, it reuses it; otherwise, it pulls the latest version.</p><p>So, I built <strong>MCP-armor</strong> — a simple, lightweight sandbox to run your MCP servers locally. It combines the best of both Docker and npx: it leverages Docker’s sandboxing capabilities while retaining the caching and speed benefits of npx.</p><p>There might be better solutions out there. In the future, if I plan to use this in production, I’ll probably switch to a more robust sandbox with enhanced logging — possibly using AppArmor or similar tools, or Docker with tighter tracing and controls. But for now, this does the job well.</p><p>The module is open source- <a href="https://github.com/rosaboyle/mcp-armor">https://github.com/rosaboyle/mcp-armor</a></p><p>It’s available on npm: <a href="https://www.npmjs.com/package/mcp-armor-npx">https://www.npmjs.com/package/mcp-armor-npx</a></p><p>Feel free to leave a comment if you have any thoughts or suggestions.</p><p>You can start using it right away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b7b00991c56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/mcp-an-attempt-to-fix-the-security-issue-with-the-mcp-servers-5b7b00991c56">MCP-An attempt to fix the security issue with the MCP servers</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP Playground: An attemt to fix the broken experience for the MCP client developers]]></title>
            <link>https://medium.com/trmx-ai/mcp-playground-an-attemt-to-fix-the-broken-experience-for-the-mcp-client-developers-a50dd2cd999f?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/a50dd2cd999f</guid>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 06:38:30 GMT</pubDate>
            <atom:updated>2025-04-14T06:38:30.711Z</atom:updated>
            <content:encoded><![CDATA[<p>Model Context Protocols (MCPs) cool! They are changing the game of AI Agents. They drastically accelerate tool integration with LLMs by offering a model-agnostic interface. Instead of hardcoding every tool into every model, MCPs let the supporting AI agent to dynamically connect to external data and tools on the fly. More on this in my previous article <a href="https://pai.dev/model-context-protocol-and-why-it-matters-for-ai-agents-88e0e0a7bb73">here</a></p><p><a href="https://pai.dev/model-context-protocol-and-why-it-matters-for-ai-agents-88e0e0a7bb73">Model Context Protocol and why it matters for AI Agents</a></p><p>You might have already come across a 1000s of MCP servers out there and you might have already used some. It’s cool there are bunch of resources out there to build an MCP server</p><ul><li>Tools to create MCP servers from Openapi specs — FastMCP, Glama etc..</li><li>Tools to debug MCP servers — Inspector, Cloudflare inspector.</li><li>Marketplace and registry for MCP servers — A whole bunch of <a href="https://github.com/punkpeye/awesome-mcp-servers">them</a></li></ul><p>As an AI engineer, I don’t just want to build MCP servers — I build AI apps. I’m more interested in MCP clients. I want my users to connect the countless MCP servers available in the market within my app, instead of going to Claude or Cursor.</p><p>I faced several problems when working with MCPs. First, the client-side support is lacking. While you can find long lists of MCP servers in many places-(smithery, cloudflare and what not), which is great for users and server developers, there’s a significant gap for those of us building AI applications.</p><p>The current landscape has three main problems:</p><ul><li>It’s difficult to test, log, and visually analyze if an MCP is working correctly.</li><li>There’s no easy way to test if a specific model will support tool handling properly.</li><li>It’s challenging to evaluate if a model is good at tool calls — especially if you are not using the default MCP support by Claude.</li></ul><h3>An Open platform for addressing these challenges</h3><p>To overcome these pain points, I created MCP Playground — a platform specifically designed to streamline and simplify the use of MCPs for client-side developers.</p><p>You can find it here — <a href="https://github.com/rosaboyle/mcp-playground">https://github.com/rosaboyle/mcp-playground</a></p><p>MCP Playground was designed with several clear objectives to solve the challenges faced by developers working with Model Context Protocol:</p><ol><li>Simplify MCP Client Development — Make MCP client integrations and logging with LLMs super easy for MCP client developers. Remove the friction in connecting LLMs to tool ecosystems.</li><li>Provide Lightweight Testing Environment — Offer a simple Electron app that connects with MCP servers and logs everything that the MCP server does, giving complete visibility into the interactions.</li><li>Enable LLM Integration Testing — Let developers check how responses would look with various LLMs that already have clients implemented. If you’re working on open-source LLMs, you can test with existing implementations before building MCP clients from scratch.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EQEXb245RooH4gdWxWPxA.png" /><figcaption>Connect with multiple MCP servers and check if you have all that you expected— tools, resources, prompts and logs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkeEpsUTUpiCP5ZSNy4aCg.png" /><figcaption>Test with different tools with your custom LLMs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YbVmMRXZb3xPRYsnxtY6Q.png" /><figcaption>Test with different tools with your LLM providers. I have just added Fireworks and Groq as an example.</figcaption></figure><h3>Not everything is solved yet</h3><h4>Todays’ clients are a security mess</h4><p>Local MCP servers today are a security mess. I don’t understand how developers today easily install these using <em>npx</em> or <em>uvx</em>. By default, npx has complete filesystem access to your computer. I don’t understand how people are comfortably using it.</p><p>A simple MCP server has full access to your filesystem (userland) and network; it can make network calls and change or hijack PATHs and environment variables. It can download and load files.</p><p>In fact, it can literally delete the MCP client it is hosted by and replace it with a malicious one. (Do we call this a App-phishing, self-mutation attack or something?, I don’t know yet)</p><h4>Thinking of a solution</h4><p>I am still thinking of a better solution to sandbox the MCP server yet provide the necessary fine grained permissions to them on the local system.</p><h4>Docker with Custom permissions?</h4><p>Docker provides an excellent balance between security and usability for MCP servers with different permission requirements. The key advantage is its ability to apply fine-grained controls per container through capabilities, volume mounts, and network configurations. How badly would it bloat the docker images? With the N number of MCP servers you would be using?</p><h4><strong>Why open source?</strong></h4><p>Open source is essential for MCP Playground because AI engineers need to integrate with their organization’s specific LLM providers. While we’ve included Fireworks and Groq as examples, most enterprises use different or custom models. By open sourcing the project, developers can easily adapt it to work with their preferred LLMs — a simple task compared to building an entire client-server integration framework with logging and connection handling from scratch.</p><h3>Open for Contributions</h3><p>MCP Playground welcomes contributions from the community! Whether you’re interested in adding support for new LLM providers, improving the UI, enhancing security features, or fixing bugs, your help is valuable. Check out <a href="https://github.com/rosaboyle/mcp-playground/blob/main/CONTRIBUTING.md">https://github.com/rosaboyle/mcp-playground/blob/main/CONTRIBUTING.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a50dd2cd999f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/mcp-playground-an-attemt-to-fix-the-broken-experience-for-the-mcp-client-developers-a50dd2cd999f">MCP Playground: An attemt to fix the broken experience for the MCP client developers</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why serverless MCPs are especially hard.]]></title>
            <link>https://medium.com/trmx-ai/why-serverless-mcps-are-especially-hard-6796a09613fe?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/6796a09613fe</guid>
            <category><![CDATA[serverless-mcp]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 05:05:44 GMT</pubDate>
            <atom:updated>2025-04-04T01:03:16.419Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR; Building serverless MCPs are really hard due to their stateful nature of SSE. The current serverless architecture like AWS lambda, vercel functions, cloudflare workers do not support stateful processes, nor SSE, hence not MCP. The recent RFC will change this and make serverless MCPs easily deployable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozkFmToIbLh5oWx7X6T5uw.png" /></figure><h4>MCPs</h4><p>The <strong>Model Context Protocol (MCP)</strong> is a standardized framework that enables AI agents — like Anthropic’s Claude, cursor (and many more) to interact with external tools and services. Think of it as the glue that lets an agent call APIs, fetch data, or invoke functions in the real world. MCP is based on JSON-RPC. It supports both local execution (e.g., calling a subprocess ) and <strong>remote tool invocation</strong> — where the tools are hosted over the network (Using HTTP — SSE protocol). I have explained the nitty-gritties in great detail in my previous article — <a href="https://medium.com/@pai.dev/model-context-protocol-and-why-it-matters-for-ai-agents-88e0e0a7bb73\">Model Context Protocol and why it matters for AI Agents</a>. All you need to know is that MCP has three components — The LLM host, the Client, and the server. The server can be local or remote. The local servers are totally cool and I won’t fo into details over here. The one that I want to discuss today is the remote MCPs.</p><h4>How MCP Remote Uses SSE</h4><p>R<strong>emote MCP communication</strong> uses a combination of HTTP for requests and <strong>Server-Sent Events (SSE)</strong> for streaming server-to-client responses. Here’s how it worked: the client sends a JSON-RPC request via an HTTP POST to the server, and simultaneously keeps an open SSE connection to receive progress updates or final responses. This makes sense for long-running operations where partial results or live feedback are essential — like token-by-token streaming from a large language model (LLM). The SSE connection stayed open throughout the session, acting as a pipeline for the server to push information as events occurred.</p><h4>Why? What’s the issue here?</h4><p>The issue is simple but fundamental: SSE assumes a stateful, <strong>always-on server</strong>, while serverless platforms are designed to be stateless and short-lived. In the traditional setup, keeping an SSE stream open means the server must maintain a dedicated connection for each client, manage that connection’s lifecycle, and have the infrastructure to support persistent communication. But serverless functions — like AWS Lambda, Vercel Functions, or Cloudflare Workers — don’t work that way. They’re spun up per request, execute quickly, and shut down. They can’t “stay alive” just to stream events. Worse, most of them time out or charge for idle time if you try to hold a connection open. This turns a simple stream into an architectural headache, where you’re forced to manage sticky sessions, external state, or retries manually. The SSE model simply doesn’t map to the way serverless is built to work.</p><h4>Options for developers to handle Remote MCPs — Today</h4><p>Developers have had a few options to work around the limitations of SSE in serverless environments, but each comes with significant trade-offs.</p><h4>0. Pay for long-running tasks.</h4><p>The first and most direct option is to keep the existing protocol and run MCP servers as long-lived services(Like EC2 Instances, or EKS services). This means paying for compute resources to keep connections open, even when the CPU is idle. It works — but it’s expensive. Cloud providers like AWS and Google charge by the millisecond or seconds, so a service that maintains thousands of idle SSE streams racks up significant costs. These costs grow with scale and are often unjustifiable for small developers or open-source projects.</p><blockquote>Ironically, the cloud providers — like AWS and Google — are also major investors in Anthropic, the original author of MCP. This has raised concerns among some <a href="https://github.com/modelcontextprotocol/specification/pull/206">developers</a> that the protocol’s original design may have favored long-running infrastructure in a way that aligns with those investors’ business models.</blockquote><h4>1. Build a virtualization layer to handle SSE.</h4><p>A more sophisticated alternative is to build a dedicated component that handles SSE connections like a load balancer. This “SSE virtualization layer” would manage long-lived SSE streams with clients while proxying actual tool calls to short-lived backend functions or services. Essentially, it decouples the persistent connection management from the actual compute tasks. While this works and maintains compatibility with the original protocol, it pushes a significant amount of complexity onto the developer. You now have to manage state, routing, connection retries, and message ordering — manually. It’s not just overhead; it’s infrastructure. For larger teams, especially for cloud providers, this may be feasible. For solo developers or teams aiming to leverage serverless infrastructure to stay lean, this becomes an unnecessary burden. As far as I know, there is no such open source project that does this yet.</p><blockquote>That said, this approach also opens up opportunities — SSE virtualization could become a niche product or platform offering for teams looking to plug that gap.</blockquote><p>2. Change the protocol — support Streamable HTTP.<br>The third option is to acknowledge that the protocol design itself is the root of the problem and fix it directly. That’s exactly what the community did. After months of discussion, feedback, and practical pain points, the MCP maintainers agreed to introduce a new transport format called Streamable HTTP. Instead of requiring a dedicated, long-lived SSE channel, Streamable HTTP allows each HTTP request to optionally return an SSE stream. This keeps the benefits of streaming responses but fits naturally within the stateless request-response model of serverless environments. This change supports backward compatibility, so older clients and servers can continue functioning during the transition. It’s a structural shift in how MCP communicates — but a necessary one to unlock faster developer adoption.</p><h4>The change</h4><p>This change was approved and merged into the MCP specification on March 26, 2025, but it has not yet been implemented in the SDKs yet. As of now, most cloud providers still do not offer serverless MCP hosting out of the box. The reason is simple: running MCP in a serverless context under the old design was expensive and operationally complex. For many developers, it just didn’t make sense to spend over $100/month to keep persistent connections alive for a protocol that wasn’t designed for ephemeral compute.</p><p>However, with the Streamable HTTP update now in motion, it’s only a matter of time before we see the rise of serverless MCP platforms. These could be built directly into cloud provider offerings or emerge from third-party startups or open-source ecosystems. The path has finally been cleared — now it’s just a question of implementation and tooling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6796a09613fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/why-serverless-mcps-are-especially-hard-6796a09613fe">Why serverless MCPs are especially hard.</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol and why it matters for AI Agents]]></title>
            <link>https://medium.com/trmx-ai/model-context-protocol-and-why-it-matters-for-ai-agents-88e0e0a7bb73?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e0e0a7bb73</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 06:13:40 GMT</pubDate>
            <atom:updated>2025-03-29T03:48:56.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*LBzV4F4d18tSyfyW9ighig.jpeg" /></figure><p>TLDR; MCP is an open meta-protocol enabling AI models to dynamically connect with external data and tools without hard-coded integrations. It is model-agnostic, simplifying tool integration across LLMs while expanding the available AI-ready toolset for the LLMs.</p><h3>MCP RFC and Origins</h3><p>The <strong>Model Context Protocol (MCP)</strong> is an open standard proposed by <strong>Anthropic, PBC</strong> (the organization behind the Claude AI assistant) to connect large language models (LLMs) with external data and tools. It was first introduced in late 2024 when Anthropic open-sourced the MCP specification (<a href="https://www.anthropic.com/news/model-context-protocol#:~:text=Today%2C%20we%27re%20open,produce%20better%2C%20more%20relevant%20responses">Introducing the Model Context Protocol</a>).</p><p>Anthropic published an <strong>RFC-style specification</strong> (Protocol Revision 2024–11–05) for MCP as a community open standard. This specification is maintained openly as part of an Anthropic-led project (<a href="https://github.com/modelcontextprotocol#:~:text=About">Model Context Protocol · GitHub</a>). Anthropic’s goal in filing this RFC-like proposal was to create a <em>common protocol</em> for AI context integration, much like how HTTP became the standard for web data or USB became the standard connector for devices. As Anthropic describes, <em>“the Model Context Protocol is an open standard that enables developers to build secure, two-way connections between their data sources and AI-powered tools”</em> . In other words, Anthropic (as the proposing organization) has laid out MCP to be the <strong>“USB-C port” for AI applications</strong>, providing one standardized interface to plug in any data source or service</p><h4>How MCP Differs from Traditional APIs and Tool Calls</h4><p>MCP fundamentally changes how LLMs interact with external systems compared to traditional APIs or bespoke tool-calling mechanisms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdNsdw6UnXx9XXVepubkCw.png" /><figcaption>A typical API call from a LLM will have multiple application specific integrations</figcaption></figure><ul><li><strong>Standardized “Plug-and-Play” Interface:</strong> Traditional tool integrations require custom code or adapters for each API. By contrast, MCP provides a <strong>single, uniform protocol</strong> for any data source or tool. Anthropic analogizes MCP to a universal port: <em>“Think of MCP like a USB-C port for AI applications”</em>, where diverse tools all connect through the same interface. This means developers no longer need to implement one-off integrations for each new service — if a service has an MCP interface, any MCP-enabled AI app can connect to it out-of-the-box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2b5_-h2NqdrsK1esd5ESQ.png" /><figcaption>Standardized protocol for connecting between a MCP supporting LLM and MCP client</figcaption></figure><blockquote>MCP acts as a <strong>meta-protocol</strong> that allows tools to <strong><em>announce their capabilities</em> to the AI system at runtime.</strong></blockquote><ul><li><strong>Meta-Protocol Above APIs:</strong> Unlike a typical REST API or SDK, which defines specific endpoints/functions, MCP acts as a <strong>meta-protocol</strong> that allows tools to <strong><em>announce their capabilities</em> to the AI system at runtime.</strong> In practice, this means an MCP server can describe what actions or data it provides, and an LLM can understand and call those actions dynamically. <em>Traditionally, developers had to hard-code knowledge of an API at design time, but with MCP an LLM can interpret a new tool’s API on the fly at runtime</em>. This dynamic discovery is a key differentiator — AI agents can automatically detect available MCP services and their APIs without the integration being pre-built into the application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQYoTuWCLK5qEEIzeQ1_og.png" /><figcaption>Standardized Auth protocol for LLM to understand the scope of the MCP (applicable for remote MCP only)</figcaption></figure><ul><li><strong>Two-Way and Stateful Connection:</strong> Standard API calls (like REST requests) are typically stateless and one-way (the application calls the service). MCP, on the other hand, establishes a <strong>persistent two-way connection</strong> between the AI app and the external service. This allows for streaming data, real-time updates, and interactive workflows. For example, an MCP server can send progress updates or logging information back to the client as the tool operates, and either side can cancel or modify requests mid-flight — features not available in simple API calls.</li><li><strong>Uniform Context Handling vs. Ad-hoc Tool Use:</strong> In traditional tool-calling (e.g. hard-coded function calls or Python scripts that an agent can execute), each tool might have its own input/output format and no consistent way of injecting results into the model’s context. MCP standardizes how context is provided to LLMs. <em>Applications “provide context to LLMs” in a standardized way with MCP</em>. This means whether the tool is a database query or a web browser control, it returns information through a common protocol (JSON-RPC in MCP) that the model and host app handle uniformly. By removing format mismatches, MCP differs from ad-hoc tool use (such as prompting the model with raw API responses or parsing HTML) — instead, the context data is structured and integrated in a consistent manner.</li><li><strong>Model-Agnostic and Ecosystem-Friendly:</strong> Traditional integrations are often tied to a specific model or platform (for instance, OpenAI’s function-calling is designed for their models, and plugins follow OpenAI’s proprietary schema). MCP is <strong>model-agnostic and open</strong> — any LLM or AI system can implement an MCP client, and any developer or company can create an MCP server for their service without needing permission. This broad compatibility is a departure from closed or vendor-specific tool ecosystems. In effect, MCP aims to be an <em>open standard backed by a major AI company, rather than yet another proprietary API</em></li></ul><h3>The Problem MCP Solves in LLM Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PIhlTC13i3xdGK4AvpcHA.png" /><figcaption>GPT-4.5, the most expensive LLM from OpenAI fails to answer about MCP — without the search capabilities.</figcaption></figure><p>MCP is designed to solve a <strong>critical problem in LLM interaction: the isolation of language models from the vast context and capabilities of external systems.</strong> Current LLMs are often <em>“constrained by their isolation from data — trapped behind information silos and legacy systems”</em> . In practical terms, an AI assistant might be very intelligent linguistically, but if it cannot access your database, files, or tools, it’s operating in a vacuum of knowledge limited to its training data and the user’s prompt.</p><blockquote><strong>Every new system <em>requires its own custom implementation, making truly connected systems difficult to scale. N different LLMs and M different SaaS Apps would require developers to build MxN integrations for them to work together. With a standardized protocol like MCP it would be M+N.</em></strong></blockquote><p>Developers have found that to get relevant, up-to-date answers or to perform useful actions, they must painstakingly feed data into the model or build custom integrations for each data source. <strong>Every new system (e.g. a CRM, a code repository, a calendar) <em>“requires its own custom implementation, making truly connected systems difficult to scale”</em> </strong>. This fragmentation leads to brittle applications — a chat AI in a coding tool might integrate with GitHub via one custom script and with Jira via another, each integration done from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5-YJfIsSudqUq5_vNH8jQ.png" /><figcaption>A Model without context</figcaption></figure><p>The <strong>exact problem MCP addresses is this fragmentation and context limitation</strong>. LLM-based applications struggle with:</p><ul><li><strong>Context Management Across Tools:</strong> Without MCP, there is no easy way for an AI to maintain context when switching between different tools or data sources. For example, if an AI agent first retrieves info from Slack and then needs to use that info to query a database, the context has to be manually carried over or re-embedded. This is cumbersome and error-prone. <em>Today’s AI integrations are siloed; there’s no consistent way for an AI to “remember” and share context across tools</em> — leading to incoherent or less relevant responses when multiple data sources are involved.</li><li><strong>Multiple Custom Integrations:</strong> In the status quo, connecting an LLM to external data typically means using either retrieval-augmented generation (RAG) pipelines or writing specific tool calls. Each approach is one-off. As one analysis noted, AI models <em>struggle with integrating multiple external data platforms, and developers often need “multiple custom integrations”</em> (one for Google Drive, one for Slack, etc.). This duplication of effort is a major pain point in application development.</li><li><strong>Stale or Insufficient Knowledge:</strong> LLMs without external context can only rely on their training data, which may be outdated or incomplete for a user’s query. The problem becomes acute when users expect the AI to have real-time or personalized information (e.g. “What does my schedule look like tomorrow?” or “Has our code build passed all tests?”). Without a standardized way to plug in live data, the model cannot answer such questions accurately.</li></ul><p>MCP tackles these issues head-on. By providing a <em>“universal, open standard for connecting AI systems with data sources”</em>, MCP <strong>replaces fragmented integrations with a single cohesive approach</strong>. The protocol’s design ensures that an AI agent can draw on the <strong>right context at the right time</strong>, improving the relevance and correctness of its outputs. Anthropic explicitly states the aim: <em>help frontier models produce better, more relevant responses by giving them access to the data they need</em>. In short, MCP solves the problem of LLMs being blind and powerless outside their built-in knowledge, by <strong>breaking down the walls between AI and external data/tools</strong> in a scalable, standardized way.</p><h3>How MCP Works: Architecture and Workflow</h3><p>MCP addresses the above problem through a well-defined architecture and interaction pattern. The protocol draws inspiration from the success of standardized interfaces in other domains (notably, the Language Server Protocol in developer toolsto create a plug-in ecosystem for AI. Below, we describe the architecture and how MCP enables an LLM to incorporate external context through a typical workflow.</p><h3>MCP Architecture Overview</h3><p>At a high level, MCP follows a <strong>classic client-server architecture </strong>within the AI application ecosystem. The key components are:</p><ul><li><strong>Host Application (Host):</strong> This is the AI-powered application or environment that initiates the connection. For example, it could be a chat interface like Claude’s desktop app, an AI coding IDE, or any system that uses an LLM and wants to attach external context. The host includes or manages the AI model.</li><li><strong>MCP Client (Connector):</strong> Within the host, an MCP client acts as the bridge to external data. The client is essentially a connector module for a given external service. If the host needs to connect to a Google Drive data source, it would use a Google Drive MCP client. The client knows how to speak the MCP protocol and is responsible for communicating with the external service’s MCP server. Multiple MCP clients can run in one host (one per integration).</li><li><strong>MCP Server:</strong> This is a service (usually external or separate from the host) that provides access to some data source, knowledge base, or tool. Developers can <em>“expose their data through MCP servers”</em> (<a href="https://www.anthropic.com/news/model-context-protocol#:~:text=The%20Model%20Context%20Protocol%20is,that%20connect%20to%20these%20servers">Introducing the Model Context Protocol \ Anthropic</a>). An MCP server implements the protocol on the server side, meaning it understands standardized requests (like “fetch this document” or “execute this operation”) and translates them into actual actions on the underlying system (e.g. retrieve a file, call an API, run a command). There are already servers for many systems — e.g. a Slack MCP server to fetch messages, a database MCP server to run queries, a Puppeteer MCP server to control a web browser</li><li><strong>Communication Channel:</strong> MCP uses <strong>JSON-RPC 2.0</strong> as the message format for communication between clients and servers. The client and server establish a connection (which can be over stdio pipes for local, or via network transport like WebSocket/HTTP for remote). This connection is stateful and supports <strong>capability negotiation</strong> — when the connection starts, the server announces what features it supports (for instance, “I can provide <em>Resources</em> and <em>Tools</em>”) and the client can announce its capabilities (like supporting certain optional features). After handshake, they exchange JSON-formatted messages for requests and responses.</li></ul><p><em>MCP architecture connects an LLM host application to external data/tool servers via a standardized JSON-RPC channel. Here, an LLM agent in the host uses two MCP clients (Integration A and B), each communicating with an MCP server that interfaces to a specific external Data Source. The MCP protocol handles the request/response so the LLM can retrieve information or invoke actions on those external systems seamlessly.</em></p><p>Critically, MCP defines <strong>three categories of capabilities</strong> that servers can provide (and thus clients can use)</p><ul><li><strong>Resources:</strong> These are contextual data sources the client (application) manages and provides to the model. For example, a resource could be a document’s content, a database record, or an API response that the AI might need for context. Resources are typically pulled into the conversation context for the model to reference (read-only data).</li><li><strong>Prompts:</strong> These are templated interactions or preset messages that can be invoked, often under user control. For instance, a “prompt” might be a pre-defined query or an interactive script that the user can trigger (similar to slash commands or menu options in a UI). Prompts standardize how structured user instructions or workflows are injected.</li><li><strong>Tools:</strong> These are actions the model can execute. In MCP, tools represent <strong>functions or operations that the AI (model) can invoke</strong> via the protocol For example, a tool might be “Send an email” or “Update a database entry” or “call an external API”. Tools are <em>model-controlled</em>: the LLM decides when to use a tool as part of its reasoning. This corresponds to what many AI frameworks call “function calling” — MCP formalizes it as part of the protocol.</li></ul><p>Additionally, MCP supports utility features like <strong>progress updates, cancellation signals, and logging</strong> so that long-running tool calls or data fetches can be managed robustly. Security is also considered — for remote servers, OAuth2 is used to handle user authorization to services in a standardized way (e.g. an MCP server for Gmail would use OAuth to ensure the AI agent only accesses data the user permits).</p><p>Overall, the MCP architecture ensures that an AI application can <strong>seamlessly discover and use external capabilities</strong>. It borrows the idea of a shared protocol from the Language Server Protocol (LSP) — just as LSP enabled any code editor to use any language backend through a common protocol, MCP enables any AI agent to use any tool or data source through a common protocol. This architecture is the backbone that makes AI integrations scalable and interoperable.</p><h3>Workflow: How an LLM Uses MCP</h3><p>To illustrate how MCP works in practice, consider a scenario where an AI assistant needs to answer a query using an external knowledge base and then perform an action based on that info. Below is a step-by-step workflow demonstrating MCP in action:</p><ol><li><strong>Initialization — Discovering Services:</strong> When the AI <strong>host application</strong> starts up (or when a new integration is added), it launches the appropriate <strong>MCP client connector</strong> for each configured service. For example, if the app has integrations for a wiki and an email service, it will start the Wiki MCP client and Email MCP client. Each client then connects to the corresponding <strong>MCP server</strong> (which could be running locally or at a remote URL). During this connection, the client and server perform a handshake to exchange capabilities (e.g. the server advertises what resources/tools it offers). The AI agent thus <strong>discovers</strong> what external functions and data are available in its environment (without the developer hard-coding those functions)</li><li><strong>User Query Triggers Context Need:</strong> Suppose the user asks the AI: <em>“Find any recent design documents about feature X and then notify the team that I’ve reviewed them.”</em> This is a complex request requiring external data (design documents) and an action (a notification). The LLM will first process the query and realize it needs outside information — specifically, <em>“design documents about feature X”</em> likely reside in an external repository (say a Confluence wiki or Google Drive).</li><li><strong>Resource Retrieval via MCP:</strong> The LLM, guided by its system prompts and the MCP integration, knows that an external <strong>Resource</strong> is needed (design docs). Through the MCP client, it formulates a JSON-RPC request to the appropriate server (e.g. the Wiki MCP server) to search for or retrieve the relevant documents. For instance, the MCP server might expose a method like searchDocuments(query=&quot;feature X design&quot;). The MCP client sends this request over the JSON-RPC channel. The <strong>MCP server</strong> then executes the search by querying the actual wiki database or API, and returns the content (or a summary) as a response. This data comes back to the LLM (often inserted into the prompt context). Now the model has the needed context about “feature X design documents” to proceed.</li><li><strong>Tool Use (Action Execution):</strong> Next, the user also wanted to <em>“notify the team”</em>. The LLM determines it should send a message to the team — perhaps via an email or a Slack message. MCP provides this through a <strong>Tool</strong>. The AI’s reasoning will produce an intention like: call the “notify_team” tool with appropriate content. The host’s MCP client for the communication service (Email or Slack) receives this intention and invokes the corresponding function on the MCP server (e.g. sendMessage(channel=&quot;team&quot;, content=&quot;...review done...&quot;) via JSON-RPC. The server, in turn, interacts with the Slack or email API to actually send the notification. It then returns a result (success/failure or message ID, etc.) to the client, which the LLM can use to confirm the action.</li><li><strong>Response to User:</strong> After these interactions, the LLM composes a final answer to the user, e.g. <em>“I found the design doc titled ‘Feature X Design Spec’ and have reviewed it. I’ve also notified the team on Slack about the review.”</em> The important thing is that the AI was able to do this in one coherent workflow: it fetched data and took an action using <strong>MCP</strong> without the user having to manually provide the document or trigger the notification themselves. All context gathering and tool usage happened through the standardized protocol behind the scenes.</li><li><strong>Continuous Context &amp; Iteration:</strong> Because MCP connections are persistent, the AI can maintain a working context with those documents and possibly even subscribe to updates. If the user asks a follow-up question about the same documents, the AI can reuse the <em>Resource</em> it retrieved (or quickly refresh it via the same server). If another action is needed, it can again call the <em>Tool</em>. This persistence and reusability contrast with stateless API calls — the AI effectively has an ongoing “session” with each external service through its MCP clients.</li></ol><p>Throughout this process, <strong>MCP handles the heavy lifting</strong> of making disparate systems look uniform to the AI. The model does not have to be explicitly programmed for each API’s peculiarities; instead it interacts with a consistent JSON-RPC schema. The workflow is also secure and controlled — if a user hasn’t granted access to a certain data source, the MCP server for that source simply wouldn’t be connected (or would require auth).</p><p>Architecturally, what MCP achieves is decoupling the <em>LLM’s logic from the specifics of external systems</em>. The AI agent can remain <em>declarative</em> (“I need data X” or “I want to do Y”), and the MCP layer translates that into concrete operations on external systems. This solution elegantly solves the earlier problem: the AI is no longer isolated, yet the integration is done in a <strong>standard, repeatable way</strong> rather than via custom code for each instance.</p><h3>Why Existing Solutions Aren’t Enough</h3><p>Before MCP, developers attempted various methods to grant LLMs external knowledge or abilities — but each has significant limitations that MCP overcomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*UoeijTZt6pyltqX6B7ut-w.jpeg" /><figcaption>Using tools with LLMs is cool… until it becomes unmanagable.</figcaption></figure><ul><li><strong>Ad-hoc Integrations Don’t Scale:</strong> Without MCP, one must write bespoke glue code for every tool an AI uses. This results in <em>“fragmented integrations”</em>, as Anthropic noted, where each data source had a separate connector and no common protocol. Maintaining many custom integrations is brittle and does not scale well. If an API changes or a new tool needs adding, developers have to do more custom work. MCP replaces these with one standard interface, massively reducing the integration effort. As Anthropic explains, <em>“instead of maintaining separate connectors for each data source, developers can now build against a standard protocol”</em>, leading to a more sustainable architecture.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7REpEC3lwZNOy-zESTYTQ.png" /><figcaption>Connecting 5 LLMs with 10 tools would take 50 integrations in the API world while 15 in the MCP world</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gajHdoKX5J0k54skOP-KSA.png" /><figcaption>Total of 15 integrations that would be needed for developers to build MCPs that work with 5 LLMs and 10 tools</figcaption></figure><ul><li><strong>Lack of Context Continuity:</strong> Existing API calling mechanisms lack a way to carry context seamlessly between calls or between different tools. For example, using a retrieval-augmented generation (RAG) approach, you might vector-search documents and stuff the top results into the prompt. But if the user’s next question needs a different tool (say, running a calculation or sending an email), there is no shared session or memory of what was retrieved except whatever text was in the prompt. <strong>MCP solves this by maintaining a persistent link to each context source</strong>, so context can be reused and multiple tools can contribute to one AI session. This ability for AI systems to <em>“maintain context as they move between different tools and datasets”</em> is something prior solutions didn’t offer.</li><li><strong>Existing APIs Are Not AI-Centric:</strong> Traditional APIs weren’t designed to be read and executed by AI agents on the fly; they were meant for programmers. This means they have diverse formats (REST, GraphQL, gRPC, etc.) and often require rigid parameters. AI frameworks like LangChain attempted to wrap some of these for LLMs, and OpenAI’s function calling or plugins provided ways to define tool APIs to the model. However, those approaches are either proprietary or limited in scope. OpenAI plugins, for instance, require writing an OpenAPI spec and hosting a service; they are powerful but only within OpenAI’s ecosystem and use fixed patterns. In contrast, MCP provides a unified, AI-friendly JSON-RPC interface for <em>any kind of tool</em>, and it’s open for anyone to implement. This universality and openness make MCP more flexible. <strong>No existing single API standard covered the breadth of integrations (files, databases, web actions, etc.) in a model-agnostic way</strong> — MCP fills that gap.</li><li><strong>Limited Action Capability in RAG/QA Systems:</strong> Many current-gen LLM applications rely on retrieval (RAG) to bring in data, but stop short of letting the AI <em>act</em> on that data. If an AI retrieves info that suggests an action (e.g., “the server is down”), a human still has to intervene or a separate automation is triggered manually. MCP enables the AI to <em>directly take actions</em> through tools, something earlier approaches couldn’t safely do in a standardized manner. As a Cloudflare tech post noted, <em>MCP lets LLMs go beyond just inference or RAG and actually perform tasks that require access beyond the AI app itself (sending emails, deploying code, etc.)</em>. Without MCP, an AI developer would have had to expose these actions via custom code or rely on the model’s limited code execution abilities — neither approach is robust or secure. MCP formalizes action-taking, which existing API integration methods lacked.</li><li><strong>Fragmented Security &amp; Permissions:</strong> With custom integrations, handling authentication and permissions for each tool is tedious. One tool might use API keys, another OAuth, etc., and the developer must implement each. There was no unified way for an AI agent to request access or for users to grant consent. MCP addresses this by building on standards like OAuth 2.0 for authentication flows in a consistent way for remote connectors. While this is still evolving, the presence of a standard approach in MCP is a step ahead of ad-hoc solutions. In legacy approaches, the patchwork of auth could lead to security oversights. MCP’s design encourages a more uniform and transparent security model for AI tool use.</li></ul><h3>The Future</h3><p>MCP is still in it’s early stage. Several critics have criticized for it’s complexity and have called it redundant compared to the existing OpenAPI specs. I believe it’s going to be evolve and be more flexible than the specs we have now. But a common protocol for connecting tools likely here to stay. What do you think?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e0e0a7bb73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/model-context-protocol-and-why-it-matters-for-ai-agents-88e0e0a7bb73">Model Context Protocol and why it matters for AI Agents</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OS Principles for Multi-Agent Orchestration — Enhancing agent Collaboration, Memory Management…]]></title>
            <link>https://medium.com/trmx-ai/os-principles-for-multi-agent-orchestration-enhancing-agent-collaboration-memory-management-6718b7755f20?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/6718b7755f20</guid>
            <category><![CDATA[startupş]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 16:25:35 GMT</pubDate>
            <atom:updated>2025-03-24T16:25:35.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>OS Principles for Multi-Agent Orchestration — Enhancing agent Collaboration, Memory Management, and Security in AI</h3><p>If you’re in business, you’ve probably been flooded with pitches from AI agent companies. AI agents are everywhere now — they control browsers, run command-line tools via Warp, and manage computers through OpenAI and Claude interfaces. They handle cloud infrastructure with services like Infra.new, optimize terminal operations, and integrate with codebases through tools like Cursor. They’re changing how we build websites, handle customer support, boost sales, run marketing, and develop software.</p><p>Building a specialized AI agent requires several components. Take a stock trading agent that analyzes top performers and executes trades automatically.</p><p>This requires a swarm of agents with specific roles:</p><ul><li>We need privacy protection — agents shouldn’t expose your investment account details or sell data to third parties.</li><li>Public market data is best processed in the cloud, not locally.<br>Only a trusted local LLM should have permission to execute trades — not something running on OpenAI’s servers.</li><li>Transactions above certain thresholds need your approval before execution.</li><li>Time-sensitive analysis (like breaking news impacts) needs fast LLMs like Groq, Cerebras, or Sambanova where milliseconds count.</li><li>Deep fundamental analysis might require powerful models like OpenAI 4.5 or O1-Pro, despite their higher cost ($600/prompt).</li></ul><p>No single LLM can handle this entire workflow effectively.</p><p>Sometimes, time is more important; sometimes, privacy or accuracy matters. Sometimes, having a human in the loop is critical — each case has its specific use scenario.</p><p><strong>Agent memory must be interoperable </strong>— output from one agent should feed directly into another. For collaborative work, agents need shared memory access. If Agent X discovers market insights, Agent Y should immediately access this data. This requires a shared memory system with OS-like locking mechanisms to prevent data corruption.</p><p><strong>Agents should function like team members.</strong> If one agent is evaluating investments and another spots a time-sensitive opportunity, it should interrupt the decision process with critical input.</p><p><strong>Security is non-negotiable. </strong>Individual agents shouldn’t have system-wide access. A central “KERNEL” agent should manage permissions, similar to an OS kernel. Other agents request specific actions through this controller. This architecture should run locally when privacy matters, with human approval for critical operations.</p><p>→&gt; Single LLMs fail because they can’t simultaneously optimize for speed, privacy, and cost. Different tasks need different capabilities, and a coordinated agent swarm delivers better results.</p><h4>OS-Inspired Memory Management</h4><p>Consider the example of the agent system for stock management AI that we discussed above.</p><p>We might have, for example, four different agents:</p><p><strong>Agent 1:</strong> A Groq agent reading news and updating insights continuously.<br><strong>Agent 2:</strong> This agent checks the portfolio and decides the best way to invest at a given point.<br><strong>Agent 3:</strong> A transaction agent that will bid/ask for a share, option, or any asset, and report if it was successful.<br><strong>Agent 4:</strong> A slow “Deep research LLM” that performs fundamental analysis and updates insights to the memory (to be fed to the Groq agent and other decision-making agents as well).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxlwcihwJ2q08glRkxxb7A.png" /></figure><p>Updates from one agent might trigger updates in other agents. You want to avoid issues like race conditions. For example, if two agents read the content, produce output, and then start writing to memory, one might overwrite the other’s data.</p><p>There should be some kind of locking system. Alternatively, if it’s okay to run asynchronously, there should be placeholder memory for Agent 1 to write to when it completes its task.</p><p>Agent Flow Diagram — Shared Memory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9b1iOI7N0jKT7i5KqzPWAA.png" /></figure><p>This is where short-term memory management becomes essential and very useful.</p><p>A simple example implementation would look like this:</p><ol><li>Agent 1 acquires a lock on the shared memory.</li><li>Agent 1 reads the shared memory.</li><li>Creates a placeholder for its result.</li><li>Releases the lock.</li><li>Agent 2 acquires a lock on the shared memory.</li><li>Agent 2 reads the shared memory.</li><li>Recognizes that there is something to be added by Agent 1.</li><li>It decides based on logic whether to wait or continue without it, keeping a placeholder to write down the result.</li><li>Releases the lock.</li></ol><p>This way, Agent 1 and Agent 2 can work together efficiently.</p><p>What happens if there is no lock? Consider an example where there is an overwrite, a dependency, and an alternative where Agent 2 should wait until Agent 1 has completed its job.</p><h4>Long-Term Persistence:</h4><p>Now, we have Agent 4 for deep research. It aims to perform a fundamental analysis of a particular stock, say NVDA. The agent needs to pick up specific information at random. You cannot load all the data about NVIDIA into the prompt and just send it to the LLM. The LLM must be able to select specific data. For instance, if it predicts that GPU hardware parts will be in high demand, it should quickly fetch related information. This retrieval should be fast and accurate. Among a bulk of 1 million articles about 10,000 different stocks, it should identify those relevant to a specific use case.</p><p>We need two things here:</p><ol><li>A retriever that will quickly retrieve memory from the database and get related content efficiently. Load this data into short-term memory for agents currently using it.</li><li>A quick search should be implemented — using RAG (Retrieval-Augmented Generation) and reranker graphs, embedding-based retrieval, multimodal retrievers, summary-based retrievers, and other indexed databases. These tools are essential for efficient data handling.</li></ol><p>Inter-Agent Communication and Shared Memory: Fast data accessibility and shared memory among agents are vital. All data should be accessible to other agents as quickly as possible, ensuring efficient collaboration and decision-making. This shared memory system allows agents to work together seamlessly, much like OS processes using IPC (Inter-Process Communication) to share information efficiently.</p><h4>The Power of Multi-Agent Swarms</h4><p>Multi-agent systems parallel modern OS architecture:</p><p>Coordinated Communication irrespective of how the agents take time to respond: Agents exchange data like OS processes use IPC. Some agents might<br>Resource Sharing: Swarms distribute workloads across specialized agents.<br>Fault Tolerance: Robust agent systems isolate failures and redistribute tasks, preventing single points of failure.<br>OS principles streamline AI development:</p><p>Modular Design: Like OS components, well-designed agents are independently upgradeable, improving maintenance and scaling.<br>Standard Protocols: OS-inspired communication standards ensure agents can exchange data consistently, reducing integration headaches.<br>Effective Debugging: OS monitoring approaches help track distributed agent behavior and quickly identify issues.<br>Securing AI Through OS Concepts<br>OS security translates directly to AI:</p><p>Agent Isolation(process isolation): Like OS sandboxing, agents need strict boundaries and authentication to prevent unauthorized access.<br>Resource Controls: OS security practices like least privilege and secure memory handling protect sensitive data.<br>Regular Updates: Like OS security patches, agent systems need continuous updates to address vulnerabilities.<br>Dynamic Loading: Just as OS loads necessary modules on-demand, modern AI systems can defer loading of non-critical data until it’s needed, ensuring optimal resource allocation.</p><p>Agents like Agent 2, which checks portfolios, and Agent 3, which handles transactions, benefit from dynamic loading by accessing only the data they need at the moment, thus optimizing performance.</p><p>For example, Agent 2 uses dynamic loading to access only the necessary portfolio data at the moment, allowing it to make timely investment decisions without being bogged down by irrelevant information. This ensures that the agent can quickly adapt to market changes and optimize investment strategies.</p><p>Similarly, Agent 3 benefits from dynamic loading by fetching transaction-related data on-demand. This capability allows the agent to respond swiftly to market fluctuations and execute trades efficiently, without the overhead of processing unnecessary data.</p><p>Dynamic loading is a technique commonly used in software engineering where code modules or libraries are loaded into memory at runtime as needed, instead of loading everything upfront. This concept can be effectively leveraged in AI agent architectures.</p><p>Here’s how you could apply dynamic loading to AI agents practically:</p><p>Modular Agent Behaviors: AI agents might handle multiple specialized tasks (e.g., sales, support, analytics, QA). Dynamically load the task-specific models or skills only when the agent encounters a scenario requiring them.</p><p>Dynamic Agent Personalities: Customize agent personalities based on user preferences by dynamically loading personality modules at runtime.</p><p>On-Demand AI Capabilities: AI agents can benefit from modular capabilities like summarization, sentiment analysis, entity extraction, or translation. Dynamically load capability plugins based on the context of user interaction.</p><p>Resource Optimization: Large AI models consume substantial memory. Dynamically load AI models based on current demand and unload them when no longer required, significantly optimizing resource usage.</p><p>Plugin Ecosystem: Create a self-serve platform allowing users to add custom behaviors to their AI agents. Allow users to add plugins that the platform dynamically discovers and loads at runtime.</p><p>The concept of dynamic agent loading and execution is crucial. Every agent does not need to know everything in advance. For example, an AI agent performing stock analysis might need portfolio details only when predicting stock movement. Personal portfolio data is irrelevant to the market but crucial for risk calculation. If a human in the loop needs a graph for decision-making, the main agent doesn’t need to create the graph itself. Instead, it can perform analysis on the main data and rely on subsequent LLMs to update content with internal portfolio data and calculate risk. This is akin to tool calling, where Agent X is dynamically loaded into the output of Agent Y.</p><h4>Advantages</h4><p>Scalability: Dynamic loading enables the scalability of AI systems, allowing for the deployment of thousands of agents if required. For example, in stock market analysis, agents can analyze over 1000 stocks while considering the context of other stocks, demonstrating the system’s ability to scale without explicitly determining the best stock.</p><p>Development Speed: Dynamic loading contributes to faster development by providing a structured way to handle long contexts. It allows for deferring predictions and completions to other LLMs, streamlining the development process and enhancing efficiency.</p><p>Privacy Management: This approach helps manage privacy by ensuring that useful outputs are provided without compromising accuracy. Dynamic loading allows for selective data access, maintaining privacy while delivering precise results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6718b7755f20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmx-ai/os-principles-for-multi-agent-orchestration-enhancing-agent-collaboration-memory-management-6718b7755f20">OS Principles for Multi-Agent Orchestration — Enhancing agent Collaboration, Memory Management…</a> was originally published in <a href="https://medium.com/trmx-ai">TRMX.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about speculative decoding and OpenAI’s new “predicted output” API]]></title>
            <link>https://medium.com/@pai.dev/all-you-need-to-know-about-openais-new-predictive-output-api-1ed06bc4c257?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed06bc4c257</guid>
            <category><![CDATA[speculative-decoding]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 10:17:43 GMT</pubDate>
            <atom:updated>2024-12-09T10:33:10.199Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAI has integrated speculative decoding into GPT-4, referring to it as <a href="https://platform.openai.com/docs/guides/predicted-outputs">“Predicted Output”</a> in its API. This comes two years after the publication of <a href="https://arxiv.org/abs/2211.17192">“Fast Inference from Transformers via Speculative Decoding.”</a> The tpken generation method speeds up inference by processing multiple tokens in parallel based on predicted output sequences. These sequences can come from either explicit user input or a faster auxiliary model. The main model verifies these predictions, accepting matching tokens and discarding those that do not match. This parallel approach reduces latency compared to traditional token-by-token generation.</p><p>Speculative decoding is a method that accelerates language model inference by processing multiple tokens in parallel. Instead of generating tokens sequentially, it uses predicted output sequences (from user input or a faster model) to process several tokens at once. The main model verifies these predictions — matching tokens are kept while mismatches are discarded and regenerated.</p><p>If this sounds a bit confusing the following explanations should make it clearer.</p><p>To understand in detail first let’s rediscover how LLM generates the text output in a traditional setting. Here’s how traditional token generation works in a chat model, using a conversation example:</p><p>Input: “What’s the weather like?”</p><ol><li>Initial Tokenization:</li></ol><pre>&lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt;</pre><p>2. Token-by-Token Generation by LLM (each iteration):</p><pre>T=1: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The<br>T=2: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather<br>T=3: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is<br>T=4: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny<br>T=5: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny today<br>T=6: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny today.<br>T=7: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny today. &lt;EOS&gt;</pre><p>Key Points:</p><ul><li>Each token generation requires full model inference</li><li>Model sees complete context up to current token</li><li>Output probabilities influence next token selection</li><li>Process continues until EOS token</li><li>Time proportional to output length (O(N))</li></ul><p>Next turn would start with:</p><pre>&lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny today. &lt;USER&gt;</pre><p>The sequence diagram for a traditional decoding algorithm would look something as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7Y5lyYBta5w3iaAwRq0-w.png" /><figcaption>Traditional decoding algorithm where one token is predicted at each iteration. Note that the model needs to wait for the tokens from previous iterations to be generated to generate the next token.</figcaption></figure><p>For N tokens it would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0T9uydzFrbSWu-3OUOcSmw.png" /></figure><h3>Speculative decoding</h3><p>But how would speculative decoding work with the same example</p><p>Initial Input:</p><pre>&lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt;</pre><p>User predicted output or a template string:</p><p>Output generation using LLM:</p><p>T=1: Batch Processing</p><pre>T=1: Batch Processing (All processed in Parallell)<br><br>1. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The<br>2. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather<br>3. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is<br>4. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is cloudy<br>5. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is cloudy today<br>6. &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is cloudy today.</pre><pre>Verification:<br>✓ &quot;The&quot; - match<br>✓ &quot;weather&quot; - match<br>✓ &quot;is&quot; - match<br>✗ &quot;cloudy&quot; - model generates &quot;sunny&quot; <br>  (correction done in the sequence and future tokens are regenerated)<br><br>Wasted computations: <br>- &quot;cloudy today&quot;<br>- &quot;cloudy today.&quot;</pre><pre>T=2: Final Processing<br>```<br>New Input: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny<br><br>Batch prediction:<br>- &quot;today&quot;<br>- &quot;.&quot;<br>✓ All match</pre><p>Final output would look like</p><pre>Final: &lt;USER&gt; What&#39;s the weather like? &lt;ASSISTANT&gt; The weather is sunny today. &lt;EOS&gt;</pre><p>The sequence diagram for speculative decoding using LLM would look something like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5h9cGIL5XMgoX_2bZciHg.png" /></figure><p>For N-tokens it would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*texpSpEf9aJeM1eQIBT-Gg.png" /></figure><p>Note that inspite of increased computation due to batched processing the wait time would be significantly reduced since multiple tokens can be generated in paralell.</p><h3>Calculating the wait time</h3><p>Total: 2 steps vs 7 steps in traditional decoding</p><p>This is an example for a small simpler example sentence. Where the number of sequential steps were reduced from 7 to 2. In a real life scenario this could vary anywhere from a factor of 10 to 20.</p><p>Take an example of debugging code using LLM. In majority of the case the generated code would be similar to the existing code but with minor changes in few places. Take for an example of typical syntax correction. The total number of tokens in the codebase would be around 2000–3000 while the number of tokens to be changed are often less than 10. In situations like this speculative decoding would improve the performance of the response time in order of 200x — 300x.</p><h3>When to use speculative decoding a.k.a predicted outputs</h3><h4>Time Complexity Analysis of speculative decoding</h4><p>Traditional Decoding:</p><ul><li>N tokens = O(N) time</li><li>Each token requires one inference</li><li>Computation = O(N)</li></ul><p>Speculative Decoding:</p><ul><li>N tokens, batch size T, m mismatches</li><li>Time complexity = O(N/T + m)</li><li>Computation (Worst case where each of the token needs to be corrected) = O(N*T). Average case = O(N+m*T))</li></ul><p>Example: 100 tokens, batch=10, 5 mismatches</p><ul><li>Traditional: 100 steps</li><li>Speculative: 10 + 5 = 15 steps</li></ul><h4>Trade-offs</h4><p>Pros:</p><ul><li>Faster inference when predictions match</li><li>Significant speedup for predictable sequences</li><li>Same output quality as traditional decoding</li></ul><p>Cons:</p><ul><li>Higher compute cost for parallel processing</li><li>Wasted computation on mismatches</li><li>Additional memory requirements</li></ul><h4>Best Use Cases</h4><p>1. Predictable Outputs<br>- Code editing/formatting<br>- Grammar corrections<br>- Template-based content<br>- Structured data generation</p><p>2. High Token Overlap<br>- Minor text revisions<br>- Style transfers<br>- Debugging sessions<br>- Document formatting</p><p>3. When Speed &gt; Compute Cost<br>- Interactive applications<br>- Real-time systems<br>- User-facing services</p><p>Not Recommended:<br>- Highly creative tasks<br>- Unpredictable outputs<br>- Resource-constrained environments where you cannot run multiple inferences in parallel</p><h3><strong>Industry adoption</strong></h3><p>Speculative decoding has seen varied adoption across AI companies since its 2022 introduction. <a href="https://www.together.ai/blog/sequoia">Together AI </a>and <a href="https://fireworks.ai/blog/cursor">Fireworks AI</a> were early adopters, implementing it for faster inference. <a href="https://fireworks.ai/blog/cursor">Cursor.com</a> integrated it into their code generation platform, while <a href="https://www.sudowrite.com/">Sudowrite</a> uses it for text generation.</p><p>OpenAI recently added it to GPT-4o as <a href="https://platform.openai.com/docs/guides/predicted-outputs">“Predicted output”</a>. The adoption timeline often correlates with companies’ computational resources and their focus on reducing inference latency versus managing computational overhead.</p><h3>Code Examples</h3><p>Example usage of OpenAI predicted outputs API for debugging a large chunk of code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6557327b73603ebc4a171c4b5617329/href">https://medium.com/media/e6557327b73603ebc4a171c4b5617329/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed06bc4c257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a Trillion Parameter model with DeepSpeed and ZeRO]]></title>
            <link>https://medium.com/@pai.dev/training-a-trillion-parameter-model-with-deepspeed-and-zero-8f4c7b6b8e5a?source=rss-e1cc04a21c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4c7b6b8e5a</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dheeraj Pai]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 05:27:46 GMT</pubDate>
            <atom:updated>2024-03-19T05:43:30.712Z</atom:updated>
            <content:encoded><![CDATA[<p>During my tenure as a graduate teaching assistant for the Deep Learning course at Carnegie Mellon University, I instructed students on the utilization of multi-GPU deep learning libraries such as DeepSpeed and Fairscale. These libraries employ various system-level techniques to facilitate the training of multi-billion parameter models in multi-GPU environments. Many students found <a href="https://www.youtube.com/watch?v=FycSknrEVYA">my recitation</a> beneficial. Hence, I have decided to share this knowledge publicly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eK75QvMQFa4ZFcjyjym8og.png" /></figure><p>Large language models have taken the world by storm, marking a “transform”ative era (pun intended, iykyk) in the field of artificial intelligence.</p><p>Models like GPT-4, LLaMA, Falcon and Mistral with their billion+ parameter designs, have set new benchmarks in several NLP tasks and generation, reasoning, powering chatbots, and creative writing.</p><p>These humongous models, ranging in size from tens to hundreds of gigabytes, and in cases like GPT-4, even reaching terabyte scale for it’s 1.8 Trillion parameter model. It’s just not possible to train these models using the traditional techniques in basic pytorch. Even using ModelParallel and DataParallel techniques would not suffice. Much advanced multi-GPU training techniques are necessary.</p><p>In this article, I want to delve into the critical differences between traditional deep learning training techniques and the more advanced multi-GPU settings required for these large language models.</p><p>Firstly, I want to focus on system-level optimizations that enable efficient training of these colossal models. We will specifically explore an implementation of DeepSpeed, a library that will help you easily port your traditional pytorch code to a Multi-GPU setting.</p><p>For each component, we’ll implement what we learn and conduct a comparative analysis in terms of training time, network overhead, and the maximum achievable model size. If you don’t want to read more and try your hands on you can jump to the colab notebook directly.</p><h4>Limitations of Pytorch, Tensorflow and JAX</h4><p>PyTorch has become a go-to framework for deep learning due to its dynamic computation graphs and user-friendly interface. But when its comes to training large models pytorch just falls short due to the memory constraints of the GPU. Let’s break this do</p><p>If we are neural network training with Float64 parameters using the Adam optimizer, each parameter requires 32 bytes of memory: 8 bytes for the parameter itself, 8 bytes for the gradient storage, and 16 bytes for the Adam optimizer’s (8 bytes for the first moment and 8 bytes for the second moment estimates. And yes, it’s the optimizer that takes most of the memory while training).</p><p>So, if you want to train a 7 Billion parameter model like Llama-2 or Mistral you would require a total memory of 7*32 = 224 Gigabytes. Training a 340 Billion Parameter model like Grok would require 10,880 GB of GPU memory. And a trillion parameter model would require 32 Terabytes of GPU Memory. This is considering the batch size of 1. Now, for a batch size of 1024, multiply the above numbers with 1024.</p><p>Even the latest GPU from the NVIDIA Blackwell series which has the highest GPU memory of 192GB would not be able to train this model. The reason is that pytorch is originally designed assuming the entire model is on the same GPU. (DataParallel and ModelParallel have limited capabilities).</p><h3>Enter Deepspeed</h3><p>To address this issue, NVIDIA open-sourced a framework for training models on multiple GPUs alongside the release of the Megatron Model. This framework was subsequently developed into FairScale by Meta and DeepSpeed by Microsoft.</p><p>DeepSpeed, developed by Microsoft, is an open-source deep learning optimization library that specifically addresses the challenges of training large-scale models efficiently.</p><p>What enables DeepSpeed to train a trillion parameter (or more) model is the technique called <a href="https://arxiv.org/pdf/1910.02054.pdf">Zero redundancy optimizer</a> (ZeRO optimizer), which builds upon model parallelism, pipeline parallelism, and data parallelism, alongside memory and bandwidth optimizations. Deepspeed seemlessly integrates with PyTorch. Meaning, if you have a pytorch model you can wrap it inside a deepspeed optimizer and deepspeed will take care of the rest.</p><h3>Zero Redundancy Optimizer</h3><p>ZeRO, short for Zero Redundancy Optimizer, is a memory optimization technique developed by Microsoft as part of the <a href="https://arxiv.org/pdf/1910.02054.pdf">DeepSpeed library</a>. It is designed for training of very large deep learning models that were previously too large to fit into the memory of available GPUs. ZeRO addresses the limitations of traditional data parallelism by optimizing the memory usage across multiple GPUs, allowing for significantly larger models to be trained efficiently (This comes at a cost elsewhere, which we will discuss later).</p><p>Here’s how ZeRO works in detail:</p><p>ZeRO optimizes memory by partitioning the model states across the available devices in a distributed training setup. The model states include weights (parameters), gradients, and optimizer states (such as the moving averages in the Adam optimizer). By partitioning these states, ZeRO reduces the memory footprint on each GPU, which allows for training larger models or using larger batch sizes.</p><p>(Note that for ZeRO is not much useful if you keep the batch size as 1. Which is rarely done during training anyway.)</p><p>ZeRO is implemented in incremental stages of optimizations, with each stage building upon the previous one:</p><h4>ZeRO Stage 1 (Optimizer State Partitioning)</h4><p>In this stage, ZeRO partitions the optimizer states across the GPUs. Each GPU only stores and updates a portion of the optimizer states, which reduces the memory required for these states. For example, in the Adam optimizer, this would include the first and second moment estimates.</p><h4>ZeRO Stage 2 (Gradient Partitioning)</h4><p>Building on Stage 1, ZeRO Stage 2 also partitions the gradients across the GPUs. After the backward pass, the gradients are reduced and partitioned such that each GPU holds only a portion of the gradients. This further reduces the memory required on each GPU.</p><h4>ZeRO Stage 3 (Parameter Partitioning)</h4><p>In the final stage, ZeRO partitions the model parameters themselves across the GPUs. During the forward and backward passes, ZeRO-3 automatically collects and partitions the parameters, ensuring that each GPU only needs to store a fraction of the parameters.</p><h4>ZeRO-Infinity</h4><p>ZeRO-Infinity is an extension of ZeRO that includes an offload engine capable of offloading model states not only to CPU memory but also to NVMe memory, providing even more memory savings and enabling training of models with trillions of parameters.</p><h3>All is fine, but at what cost?</h3><p>Theoretically, using ZeRO-Infinity, we can train a trillion-parameter model on a single GPU. Then, you might ask why anyone would use ZeRO Stage 1, 2, or 3. This is because each stage of optimization incurs costs in terms of network overhead.</p><p>The ZeRO optimization levels, while significantly reducing the memory footprint on each GPU, introduce varying degrees of network communication overhead. This overhead is a consequence of the need to synchronize the partitioned states across the GPUs during training. Here’s how network overhead is affected at each ZeRO optimization level:</p><h4>ZeRO Stage 1 (Optimizer State Partitioning)</h4><p>In ZeRO Stage 1, the optimizer states are partitioned across GPUs. This means that each GPU only updates its portion of the optimizer states. However, during the parameter update phase, the optimizer states need to be synchronized across all GPUs to ensure that each GPU has the complete and updated optimizer states for the next iteration. This synchronization introduces network overhead.</p><p>More often than not <strong>we use the technique of gradient accumulation</strong>, where we run several forward and backward computation before updating the gradients (If you haven’t done this, you can read about it <a href="https://towardsdatascience.com/what-is-gradient-accumulation-in-deep-learning-ec034122cfa">here</a>). Hence, the optimizer states are updated less frequently than gradients. The resulting overhead is relatively moderate.</p><h4>ZeRO Stage 2 (Gradient Partitioning)</h4><p>ZeRO Stage 2 adds gradient partitioning to the optimizer state partitioning. After the backward pass, gradients are reduced across all GPUs to compute the global sum. In this stage, the gradients are also partitioned, so each GPU ends up with only a segment of the gradients. <strong>Remember that for the computation of the gradient of current layer you need the gradients of the layers ahead of the current layers.</strong> This incurs significant network overhead, especially for large models with billions of parameters. The overhead is proportional to the size of the gradients and the number of GPUs involved in the training.</p><h4>ZeRO Stage 3 (Parameter Partitioning)</h4><p>ZeRO Stage 3 introduces parameter partitioning on top of gradient and optimizer state partitioning. In this stage, each GPU holds only a fraction of the model parameters. <strong>During the forward and backward passes, parameters need to be exchanged between GPUs to ensure that each GPU has the necessary parameters for its computations</strong>. This exchange is a significant source of network overhead, as it <strong>requires all-to-all communication.</strong> The overhead is further compounded by the fact that parameters are accessed more frequently than gradients or optimizer states, leading to more frequent communication. (This is why the NVIDIA’s NVLink interconnects sells hot. But we will discuss this later)</p><h4>ZeRO-Infinity and ZeRO-Offload</h4><p>ZeRO-Infinity and ZeRO-Offload extend the capabilities of ZeRO by offloading computations and states to CPU and NVMe memory. While this reduces GPU memory usage, it introduces additional network overhead due to data movement between GPU and CPU/NVMe (Including the parameters). The overhead depends on the bandwidth and latency of the interconnects between the GPU and CPU/NVMe storage.</p><h3>Using Deepspeed</h3><p>There are several example usage of Deepspeed in the official website. But here is a simple example how Deepspeed can be used to wrap around an existing pytorch model. For the sake of simplicity I am using a single layer Neural network. But even if it’s a complex transformer Deepspeed will take care of the resource allocation for</p><pre>import torch<br>import torch.nn as nn<br>import deepspeed<br><br>class GiantLinearModel(nn.Module):<br>    def __init__(self, input_size, output_size):<br>        super(GiantLinearModel, self).__init__()<br>        # Using a Linear layer with 1 trillion parameters for simplicity<br>        self.linear = nn.Linear(input_size, output_size)<br><br>    def forward(self, x):<br>        return self.linear(x)<br><br># Instantiate the model<br>input_size = 1<br>output_size = 1_000_000_000_000  # 1 trillion parameters<br># Reduce the size if your RAM cannot fit this huge model.<br>model = GiantLinearModel(input_size, output_size)<br><br><br>batch_size = 1 # For the sake of simplicity<br>dummy_input = torch.randn(batch_size, input_size) # Dummy Random input<br><br># Configure DeepSpeed - More about this https://www.deepspeed.ai/docs/config-json/<br>deepspeed_config = {<br>    &quot;train_batch_size&quot;: batch_size,<br>    &quot;gradient_accumulation_steps&quot;: 2,<br>    &quot;fp16&quot;: {<br>        &quot;enabled&quot;: True <br>    },  # Uses mixed precision - More about this https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html<br>    &quot;zero_optimization&quot;: {<br>        &quot;stage&quot;: 2,  # Using ZeRO Stage 2 for this example. Just change the stage to <br>        &quot;allgather_partitions&quot;: True,<br>        &quot;allgather_bucket_size&quot;: 2e8,<br>        &quot;reduce_scatter&quot;: True,<br>        &quot;reduce_bucket_size&quot;: 2e8,<br>        &quot;overlap_comm&quot;: True,<br>        &quot;load_from_fp32_weights&quot;: True<br>    },<br>    &quot;optimizer&quot;: {<br>        &quot;type&quot;: &quot;Adam&quot;,<br>        &quot;params&quot;: {<br>            &quot;lr&quot;: 1e-3<br>        }<br>    }<br>}<br><br># Initialize DeepSpeed<br>model_engine, optimizer, _, _ = deepspeed.initialize(args=None,<br>                                                     model=model,<br>                                                     model_parameters=model.parameters(),<br>                                                     config_params=deepspeed_config)<br><br># Train the model<br>for step in range(num_training_steps):<br>    outputs = model_engine(dummy_input)<br>    model_engine.backward(outputs)<br>    model_engine.step()</pre><h3>Reducing the network overhead</h3><p>To best use of the multi-GPU setup and harness the full potential of DeepSpeed for efficient deep learning, minimizing communication overhead is extremely crucial. Typically, GPU communication involves the CPU and RAM, creating inefficiencies and bottlenecks. After all what’s the point of a $400,000 DGX if the GPUs sit idle 95% of the time waiting for data to be transferred?</p><p>To circumvent these challenges, hardware companies, notably Nvidia, have developed advanced GPU-to-GPU data transfer protocols, significantly enhancing direct communication between GPUs.</p><p>NVIDIA’s interconnect technologies like NVLink, NVSwitch, Mellanox InfiniBand, and GPUDirect RDMA are designed to speed up data transfer between GPUs and between GPUs and CPUs, which is important for training large models efficiently using Deepspeed.</p><p>NVLink offers fast GPU-to-GPU connections, outdoing PCIe speeds, which is great for tasks that need lots of GPU communication. NVSwitch lets GPUs in big systems talk directly at high speeds, avoiding bottlenecks. Mellanox InfiniBand provides quick and low-latency networking for computers with many GPUs, helping with tasks like gradient reduction and parameter syncing. GPUDirect RDMA lets network devices directly access GPU memory, skipping the CPU to lower delays and overhead in GPU communication across different nodes.</p><p>The reduced network overhead and waiting times and cutting down on bottlenecks makes sure the GPU is more efficiently used for training and not spending idle time transferring data.</p><h3>Further readings</h3><ul><li><a href="https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/">https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/</a></li><li><a href="https://github.com/microsoft/DeepSpeedExamples">https://github.com/microsoft/DeepSpeedExamples</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/">https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4c7b6b8e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>