<?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 Mukundan Kidambi on Medium]]></title>
        <description><![CDATA[Stories by Mukundan Kidambi on Medium]]></description>
        <link>https://medium.com/@mukundkidambi?source=rss-b07cbd95699b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1N6qBwkO4s21X3OH.</url>
            <title>Stories by Mukundan Kidambi on Medium</title>
            <link>https://medium.com/@mukundkidambi?source=rss-b07cbd95699b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:42:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mukundkidambi/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[Multi-turn evals with memory snapshots]]></title>
            <link>https://medium.com/@mukundkidambi/multi-turn-evals-with-memory-snapshots-304cfc14da0b?source=rss-b07cbd95699b------2</link>
            <guid isPermaLink="false">https://medium.com/p/304cfc14da0b</guid>
            <category><![CDATA[ai-agent-testing]]></category>
            <category><![CDATA[agentic-harness]]></category>
            <dc:creator><![CDATA[Mukundan Kidambi]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 16:38:42 GMT</pubDate>
            <atom:updated>2026-11-14T16:38:42.420Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Beyond GraphQL: MCP Server Architecture for Agent Workflows, Part 5</em></p><p>In Part 4 I described the eval harness behind our MCP tools: a question bank, A/B scoring against a baseline on every model, and a CI gate. That harness asks one question and scores one answer. It built most of the application.</p><p>It doesn’t cover conversations, and conversations are where users spend most of their time.</p><h3>Refinement workflows</h3><p>Take a trip-planning agent as the example. A user starts with a draft itinerary and refines it over several turns:</p><ol><li>Plan 10 days in Portugal in May for two of us.</li><li>Keep the whole trip under $3,000.</li><li>No overnight flights.</li><li>Swap Porto for a beach week in the Algarve and compare.</li><li>Go with the Algarve version. Add a day trip to Sintra.</li></ol><p>The user states the budget and the flight rule once and never repeats them. By turn five the agent still has to respect both. A single-turn eval can’t check that.</p><h3>Replaying full sessions</h3><p>The first option is to replay whole sessions end to end and judge the final result. We tried it. It’s slow and expensive, and the results are noisy. Model output varies a little from run to run, and over five turns those differences add up. When a replay fails, you can’t tell whether the cause was a memory bug or a different sample three turns back, or which turn it happened on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA4tB3DxtAg6DIMFw2-NiA.png" /><figcaption>Figure 1. A full replay fails at the end, with no way to tell which turn caused it.</figcaption></figure><p>Testing each turn from a saved state avoids both problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8k7PBJqsHXh47u5tR-Y6w.png" /><figcaption>Figure 2. Each test starts from a known state, so a failure points to its turn.</figcaption></figure><p>The agent is built on LangGraph, calls our MCP tools, and keeps its memory in <a href="https://github.com/masterkidan">langgraph-beads-memory</a>, a library that stores agent memory as a typed fact graph on Postgres. Every turn writes memory markers that record what changed, and the beads graph holds everything the agent knows up to that point.</p><p>Because the memory is explicit, each turn can be tested on its own:</p><ol><li><strong>Capture.</strong> Take a live user session, along with its memory markers.</li><li><strong>Snapshot.</strong> Save the memory state as it stood after turn N.</li><li><strong>Rehydrate.</strong> Load that state into a fresh agent with no conversation history.</li><li><strong>Ask.</strong> Send the user’s message from turn N+1 and capture the output.</li><li><strong>Judge.</strong> Compare the output with the expected result for that turn.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl4dfMRzV-bY0qDxiUYQFQ.png" /><figcaption>Figure 3. The five steps for each test.</figcaption></figure><p>In the example, a snapshot after turn 4 holds these facts:</p><ul><li>goal: 10 days in Portugal in May, two travelers</li><li>constraint: total under $3,000</li><li>constraint: no overnight flights</li><li>alternative: Algarve beach week instead of Porto, proposed</li><li>plan versions v1 to v4</li></ul><p>The fresh agent gets turn 5, “Go with the Algarve version. Add a day trip to Sintra,” and nothing else.</p><pre>agent   = build_agent(tools=mcp_tools)      # new process<br>memory  = load_snapshot(&quot;session-0412&quot;, turn=4)<br>history = []                                 # no transcript carried over<br>agent.attach(memory)<br>result  = agent.run(&quot;Go with the Algarve version. Add a day trip to Sintra.&quot;)</pre><p>An important point to note here, we are not reloading or saving the whole context here, its purely whatever our memory layer ended up saving. This also means its important to not over-save things and save only the right/important facts, see how its measured here: <a href="https://github.com/masterkidan/langgraph-beads-memory">https://github.com/masterkidan/langgraph-beads-memory</a></p><h3>Scoring</h3><p>An adversarial LLM judge scores each turn. It runs on a different model from the agent, so the agent’s model never grades its own output.</p><p>The judge doesn’t grade wording. It checks the itinerary the agent produced against the expected outcome at that turn. For turn 5 that means: the Algarve week is in, Sintra is added, the total is under $3,000, and there are no overnight flights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEMY0_gYcZPnVebEKkO7Hw.png" /><figcaption>Figure 4. The judge compares what the agent built with what the user wanted.</figcaption></figure><h3>Test cases from production</h3><p>The test cases come from live conversations. We sample production sessions and look for turns where the agent drifted from what the user asked for: a constraint dropped, a choice reversed, a follow-up answered as if it were the first question.</p><p>Each miss becomes a test. The memory state from the turn before the miss is the snapshot, the user’s next message is the prompt, and the result the user was steering toward is the expected outcome. The question bank grows from what people actually ask, and from where the agent actually went wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9q0Luh8tGyfzSS4SNXJQyg.png" /><figcaption>Figure 5. Turning a live miss into a test case.</figcaption></figure><h4><strong>A bug it found</strong></h4><p>The agent doesn’t go straight from request to answer. It first writes the solution as an intermediate typed plan, then compiles that plan into the final itinerary. This is part of a phase-decomposition approach to agent planning that I’m building separately.</p><p>Between turns, that plan wasn’t being saved. Memory held only the latest output. Each new turn rebuilt the plan from the bookings and the new message. The bookings don’t record the budget or the flight rule, so those constraints dropped out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0szgh0-XRMDZ9GuseDIvw.png" /><figcaption>Figure 6. Before the fix. The numbers are made up for this example.</figcaption></figure><p>End-to-end replay only showed that the final plan got worse. Snapshot tests showed which turn lost which constraint.</p><p>The fix was to store the intermediate plan in memory as a fact, and to store every version of it, not only the latest one. A fresh agent now continues from the last plan version instead of rebuilding it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXN_X8_ydDkvSYq-29Y8gw.png" /><figcaption>Figure 7. After the fix.</figcaption></figure><h3>Summary</h3><p>Most of the multi-turn failures we found were memory problems. Because the memory layer is explicit, we can test it one turn at a time. Load a known state, send the next message, and compare the result with the expected outcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=304cfc14da0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building MCP Servers for Agents]]></title>
            <link>https://medium.com/@mukundkidambi/test-driven-development-for-mcp-servers-a2101a059cd4?source=rss-b07cbd95699b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2101a059cd4</guid>
            <dc:creator><![CDATA[Mukundan Kidambi]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 22:12:35 GMT</pubDate>
            <atom:updated>2026-08-17T23:01:23.072Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 in a series. </em><a href="https://medium.com/@mukundkidambi/optimizing-token-usage-in-mcp-servers-with-graphql-a-70-80-token-reduction-strategy-d4a620fdc690"><em>Part 1</em></a><em>: N tools → 2 GraphQL tools. </em><a href="https://medium.com/@mukundkidambi/beyond-graphql-what-actually-reduces-token-spend-in-mcp-servers-9aa3350e8d4d"><em>Part 3</em></a><em>: schema → catalog search, ~150k to ~25k tokens per task. Every decision in the series came out of the process described here.</em></p><p>We launched our MCP server on Claude and ChatGPT. Soon after, the requests started: can we get this in Copilot, in Azure AI workspaces, against our own custom models. Each surface brings its own model, and we’d already seen GPT and Claude succeed at different rates on the same tools — the same description would send one to the right tool and the other to the wrong one.</p><p>That raised the question this post is about: how do we know we’re delivering a good experience on every surface we support? What keeps those users around?</p><p>The development model we settled on is closer to test-driven development than API development. A question bank with ground truth is the test suite. An agent harness is the test runner. Every tool change runs against it, on every model we support, and a regression blocks the merge.</p><h3>The loop</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GogukTNvikIKrKzsiu9y7Q.png" /></figure><p>Three flows converge on the question bank. The development loop: a tool change runs through the harness, gets scored A/B against the baseline on every model, and either ships or goes back for another pass. The production loop: real user questions feed back into the bank, so the suite tests what people actually ask rather than what we imagined. And external inputs — support escalations, new use cases, model updates, analytics — land in the bank the same way a bug report becomes a regression test.</p><h3>Metrics to observe</h3><p><strong>Tool selection</strong> — did the model call the right tools. The most direct read on a description. This is how we caught schema fragments causing hedging: the model pulled extra fragments to avoid missing fields, rational behavior, invisible in manual testing.</p><p><strong>Token’s spent</strong> — Capture the token counts of the tool calls/responses and the overall agent itself. Most SDKs like pydantic offer token counts, and for tool calls we simply used <a href="https://github.com/anthropics/anthropic-tokenizer-typescript">https://github.com/anthropics/anthropic-tokenizer-typescript</a> to estimate the count based on the JSON returned.</p><p><strong>Answer correctness </strong>— DeepEval and Ragas with a configurable judge and a containment rubric: every required fact, number, or entity must appear.</p><p><strong>Grounding </strong>— is the answer from tool results, or fabricated.</p><p><strong>Cost and latency </strong>— tokens, dollars, wall-clock, calls-per-task. Part 3’s catalog design sometimes needed more tool calls than GraphQL, which reads as a regression until you see total tokens still dropped, because the model wasn’t spending turns comprehending schema. With cost in a separate report from accuracy, we’d have killed a net win.</p><p>Several scorers because a change can lift one dimension while quietly dropping another. When aggregates don’t explain a slow or expensive question, we open the individual trace in Langtrace — every call, every step, every payload.</p><h3>Tying it all together</h3><p>It drives the real server over real transport (PydanticAI, MCP-native). A target is a (server, model) pair; same question bank, swap whatever you&#39;re comparing.</p><p><strong>No system prompt — </strong>We did this deliberately as we wanted to see the best accuracy we can achieve simply by using <a href="https://modelcontextprotocol.io/specification/draft/schema#discoverresult-instructions">MCP instructions</a>. As customers wanted to use this in their own environments, this allowed us to generate common instructions that worked across all platforms/centralize it.</p><p><strong>Real auth — </strong>The harness walks the full OAuth PKCE flow — Dynamic Client Registration, authorize, callback, exchange — so the agent runs under a real user token and results come back entitlement-filtered, like production.</p><p><strong>CI Gate</strong>: one command, headless, non-zero exit on a net regression. The web surface exists to explain why a number moved; the CLI exists so it can’t move the wrong way unnoticed.</p><h3>Case Studies</h3><p>Lets look at an example run where we were doing some experiments and started seeing improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*uu753TxyNNFTuSxD3at_Sg.png" /></figure><p>Fig 1 — Candidate vs. baseline, 205 questions, both models. Cost and latency in the same table as accuracy. The one regression (Q-051) is surfaced, not averaged away.</p><p>BM25 over vectors: We initially tried to use semantic search on our data dictionary catalog to help identify relevant datapoints, made sense early on. However we quickly noticed that there were scnearios where the LLM would routinely pick the wrong datapoints: in finance, entity names sit one token apart — same prefix, shared qualifier, one word different — and cosine similarity treats them as interchangeable. This lead us down the path to the above experiment to run BM25. After swapping our algorithm, we saw the following improvements: <br>Pass rate up 3.1 points, cost down 78%, tokens down 79%, latency down 51%. One regression: Q-051, where search ranked the wrong entity first, this was the piece that showed bm25 was the right track to head down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*KhSb7ZGVmaIo1dU9h4HOaQ.png" /></figure><p>Fig 2 — The same run in CI. One gated regression, non-zero exit, merge blocked until triaged.</p><h3>Some practices to follow/Lessons learnt</h3><ul><li>Agent harness against the real server, model as a swappable string</li><li>No system prompt — test the tool, not your coaching</li><li>Same questions across every model you support</li><li>Scorers for tools, answers, grounding, with cost and latency in the same row</li><li>Trace-level drill-down for the questions the aggregates don’t explain</li><li>The real auth flow, so results are entitlement-filtered</li><li>A question bank with ground truth, so “did it work” is a diff</li><li>A CI gate that exits non-zero on regression</li></ul><p>A lot of these seem obvious in retrospective, my intent with writing this article was to mainly help folks bootstrap their own build outs with some of these learnings.</p><h3>What’s next</h3><p>All of this is the offline loop. Two things not covered here: closing the online loop — feeding production questions and analytics back into the bank continuously — and keeping eval cost under control as the bank grows, by segmenting it so a change only runs against the questions it can affect. Those are the next posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2101a059cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From schema to search: redesigning an MCP server for agent workflows]]></title>
            <link>https://medium.com/@mukundkidambi/beyond-graphql-what-actually-reduces-token-spend-in-mcp-servers-9aa3350e8d4d?source=rss-b07cbd95699b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa3350e8d4d</guid>
            <dc:creator><![CDATA[Mukundan Kidambi]]></dc:creator>
            <pubDate>Fri, 22 May 2026 00:07:04 GMT</pubDate>
            <atom:updated>2026-05-22T22:04:40.607Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 3. <a href="https://medium.com/@mukundkidambi/optimizing-token-usage-in-mcp-servers-with-graphql-a-70-80-token-reduction-strategy-d4a620fdc690">Part 1</a> covered the move from N-tools-per-endpoint to a two-tool GraphQL pattern (get_schema, execute_query). <a href="https://medium.com/@mukundkidambi/user-impersonation-for-microservices-and-mcps-e2c358f2a759">Part 2</a> covered auth and impersonation. This post is what happened when we put that GraphQL design in front of real users.</p><h3>What we were seeing</h3><p>Costs on the agentic workflow were climbing faster than usage. Context windows were filling up, conversations were hitting limits, and the per-task spend wasn’t trending where we wanted. None of it was catastrophic — the system worked — but the slope was wrong.</p><p>So we started looking at traces.</p><p>What came out of that investigation was that the architecture we’d designed was built for assumptions about usage that didn’t match reality. Two of them in particular:</p><ol><li><strong>Sessions would be long.</strong> Schema cost amortizes across many turns.</li><li><strong>Users want exploration.</strong> A rich schema supports drilling.</li></ol><p>Neither held. Most exploration is single-shot — users want a direct answer, not a guided tour. The schema we’d designed to amortize across 30 turns was paying for itself across 2, which meant it wasn’t paying for itself at all. It had become the dominant cost on every call.</p><p>The latency math broke the same way. With short sessions, schema comprehension is wall-clock time the user is waiting on. Cutting it out didn’t just save tokens — it cut TTFT and tail latency materially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ae1Z_KfN1tavH0h3guz_g.png" /></figure><p>Once we made the changes that fell out of this, a representative task went from ~150k tokens to ~25k, wall-clock roughly halved, and accuracy improved on our internal evals. Cost dropped close to an order of magnitude once you count the shorter conversations. The accuracy gain was the surprise. More on how we measured all of this further down.</p><h3>What GraphQL fixed, and what it didn’t</h3><p>GraphQL fixed one thing: over-fetching on the response side. The model could ask for { name email } and get exactly that.</p><p>What it didn’t fix:</p><ol><li><strong>The model has to read schema fragments first, every session.</strong> We already fragmented the schema by domain and only returned fragments relevant to the prompt. It helped less than expected — the model would pull additional fragments to hedge against missing a field. Rational behavior when the cost of missing a datapoint exceeds the cost of fetching more schema.</li><li><strong>GraphQL syntax is non-trivial cognitive load.</strong> Frontier models handle it, but it shows up as latency, retries, and malformed queries.</li><li><strong>The type system carries noise.</strong> Unions, interfaces, directives, deprecation metadata — useful for human developers, mostly noise for an LLM.</li></ol><p>The deeper problem: we were sending a schema when we should have been sending a search interface. Both return a list of fields, but they incentivize the model differently.</p><h3>Reframe: this is a retrieval problem</h3><p>What the model needs at query time is a small set of relevant datapoints with enough metadata to fetch them. Not the type system. Not fields it won’t use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4Ke-djxDdvzcMQhgGpRnA.png" /></figure><p>So we built an inverted index over a flattened catalog of datapoints, auto-generated from the GraphQL schema, queried with in-memory BM25. GraphQL stays in the pipeline; the model never sees it.</p><p>This looks like fragmenting the schema and serving slices on demand, and structurally it is. The difference is incentive. With fragments, the model chooses between categories it doesn’t fully understand, so it hedges by pulling more. With a search over individual datapoints, the model queries in domain language and gets back the matching fields with descriptions. The unit retrieved is already at the field level. There’s nothing to hedge.</p><h3>The catalog</h3><p>Each entry is a single datapoint, namespaced by its source entity. The metadata is whatever the resolver and the model both need — not a generic schema, a domain-shaped one. For our analytics workload:</p><pre>{<br>  &quot;name&quot;: &quot;signups&quot;,<br>  &quot;description&quot;: &quot;Count of new user signups in the period&quot;,<br>  &quot;entity&quot;: &quot;User&quot;,<br>  &quot;resolver&quot;: &quot;users.created_count&quot;,<br>  &quot;dimensions&quot;: [&quot;country&quot;, &quot;plan&quot;, &quot;channel&quot;, &quot;device&quot;, &quot;campaign&quot;, &quot;referrer&quot;],<br>  &quot;default_dimension&quot;: &quot;day&quot;,<br>  &quot;type&quot;: &quot;integer&quot;,<br>  &quot;aggregations&quot;: [&quot;sum&quot;, &quot;avg&quot;, &quot;p95&quot;],<br>  &quot;default_aggregation&quot;: &quot;sum&quot;,<br>  &quot;filters_supported&quot;: [&quot;country&quot;, &quot;plan&quot;, &quot;is_test&quot;],<br>  &quot;examples&quot;: [<br>    &quot;signups by country last week&quot;,<br>    &quot;weekly signups for the last quarter&quot;,<br>    &quot;signups from the Black Friday campaign by day&quot;<br>  ],<br>  &quot;freshness_seconds&quot;: 300,<br>  &quot;cost_tier&quot;: &quot;cheap&quot;,<br>  &quot;sensitive&quot;: false<br>}</pre><p>Notes:</p><ul><li>dimensions and default_dimension are domain-specific. Our data is time-series, so the model needs to know what it can slice by before it asks. If your domain is operational rather than analytical, this field looks different. The point is to shape the metadata to what the model actually has to figure out, not project the schema generically.</li><li>examples pull more weight than anything else, especially when names are generic. Natural-language phrasings the user might actually utter.</li><li>resolver is the resolver&#39;s instruction. The model never thinks about it — it picks by name and description, the catalog server figures out the calls and batches them.</li><li>freshness_seconds points at a cache layer. Model never sees it.</li><li>cost_tier and sensitive are guardrails the model can act on — prefer cheap when several entries answer equally well, avoid sensitive without explicit consent.</li></ul><p>Not in there: primary keys, foreign keys, join hints. Our domain has shallow relationships and the parent grouping handles cross-entity navigation. Deeper relational structure would need different fields, and would also be the point at which you’d question whether the catalog approach fits at all.</p><p>Generation is mechanical: walk the schema, emit one entry per scalar field, copy descriptions from schema comments, enrich examples from traces or by hand, mark sensitivity from a deny-list. Most fields can come from custom directives — they don’t exist in vanilla GraphQL, but the schema is yours to extend.</p><h3>The search tool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5FNeNLOymMjMLpDi1szuQ.png" /></figure><p>One tool: search_datapoints(query: string) -&gt; Datapoint[]. BM25 over names and descriptions, in-memory, no embeddings.</p><p>For our corpus size (low thousands) and query shape (the model asks in domain language — “user signups”, “Q4 conversion”), BM25 is the right tool. Embeddings add latency, infra, and a quality regression on exact-match phrases like field names.</p><p>At 100k+ entries with the same metric named ten different ways across ten systems, embeddings might be the answer. We’re not at that scale. Benchmark on your own data.</p><h3>Why accuracy went up</h3><p>This was the surprise — the goal was cost, not quality. When we cut schema out of context, we expected tokens to drop. We didn’t expect answers to get better. The category breakdown made it clear:</p><ul><li><strong>Attention dilution.</strong> 8–12k tokens of schema spent attention budget on schema comprehension that should have been on the user’s question, especially on ambiguous phrasing. Cutting schema out freed that budget.</li><li><strong>Spurious field selection.</strong> A full schema exposes many similarly-named fields. The model would sometimes pick users.created_count when the user asked for &quot;new signups&quot; and the right field was users.signups_count. Catalog returns only the relevant field. No neighbors to confuse.</li><li><strong>No syntax tax.</strong> Malformed GraphQL caused retry loops. We weren’t tracking these as accuracy regressions before — eventual success masked them — but they cost tokens and latency. No syntax to malform now.</li></ul><p>Attention dilution was the largest contributor. We didn’t ablate it rigorously, but in the categories where schema disambiguation was the bottleneck, accuracy moved most. None got worse.</p><h3>How we measured all of this</h3><p>A note on methodology, since the numbers above only mean something if you trust how they were captured.</p><p>We built an <strong>agent test harness</strong> — a vanilla LLM bound to an MCP server — and used it as the measurement surface. Langfuse and similar tools instrument LLMs and agents, not MCP servers, so the harness sits on the agent side of the wire. That’s where we captured token counts, tool calls, latency, payloads, and answer accuracy.</p><p>The evals settle it. Livesite is trending the same way; numbers aren’t ready to publish, but the direction isn’t in doubt. Every workload moved in the right direction.</p><p>Worth flagging: in some categories the new architecture needed <em>more</em> tool calls than the GraphQL version. On its own that sounds like a regression. It isn’t. Total token cost still dropped, and the model spent far fewer internal reasoning turns chewing on schema, so end-to-end turn counts came out fine. More tool calls against a small focused surface beats fewer calls against a large schema you re-read every time.</p><p>If you’re building an MCP server without this kind of observability, instrument first. You can’t fix what you can’t see, and the costs that matter are rarely the ones you’d guess. A follow-up post will cover the harness itself — what to instrument, how to build a question bank, what to segment by.</p><h3>The other win: columnar payloads</h3><p>The second piece is more boring but mattered the same dollar amount.</p><p>Typical API response: a list of N records, every field name repeated N times. For 100 orders with 10 fields, that’s the same 10 strings 100 times in the JSON. The model pays for all of it.</p><p>We switched to column-oriented:</p><pre>{<br>  &quot;columns&quot;: [&quot;id&quot;, &quot;created_at&quot;, &quot;user_id&quot;, &quot;total&quot;, &quot;country&quot;],<br>  &quot;rows&quot;: [<br>    [1, &quot;2024-...&quot;, 412, 49.99, &quot;US&quot;],<br>    [2, &quot;2024-...&quot;, 873, 89.50, &quot;CA&quot;]<br>  ]<br>}</pre><p>Cheaper, and the model handles it fine — it can ask for “the third column of the second row” or “sum the fourth column” and the reasoning works. ~50% smaller at 100 rows, ~4x at 1000.</p><p>Where it breaks:</p><ul><li><strong>Nested fields:</strong> denormalize into more rows, or fall back to JSON for that field. We do the latter.</li><li><strong>Heterogeneous rows:</strong> columnar assumes a fixed shape. If responses genuinely vary, you pay more than you save.</li><li><strong>Single objects:</strong> overhead with no payoff.</li></ul><h3>Is GraphQL still earning its place?</h3><p>For us, it’s inertia plus a useful intermediate. The pipeline is prompt → search_datapoints → catalog hits → resolver call → GraphQL query → data layer. GraphQL handles field-level access control, batching, and predictable cost. We could replace it with direct SQL or a domain-specific orchestration layer, and we may.</p><p>The generalizable lesson: GraphQL is a fine internal representation, a poor LLM-facing interface. Building from scratch, don’t pick GraphQL for the LLM contract.</p><h3>When this fits</h3><ul><li><strong>Shallow domains.</strong> Deep object graphs the model needs to traverse may genuinely benefit from schema-as-context — there’s signal in the structure.</li><li><strong>Read-heavy.</strong> Mutations don’t compose the same way. The catalog approach is a query-time optimization; for mutations you want a typed action interface.</li><li><strong>Queries that fold into named primitives.</strong> Our domain has thousands of fields but a small number of common combinations. If each query is a bespoke join, the catalog buys you less because pre-naming is doing the work.</li><li><strong>Mid-size catalogs.</strong> BM25 in memory works under ~100k entries. Above that, you want a real search backend.</li></ul><p>The underlying lesson is independent of architecture: every token in context the model isn’t using is overhead. Schema-in-context was a habit from RAG, where context was abundant. In an agent loop with many tool turns it compounds badly. Same for verbose JSON. The discipline that pays is asking, on every tool call, “what’s the smallest thing I can return that still lets the model do its job.”</p><h3>If I were starting over</h3><ol><li><strong>Build the model-facing interface as a search.</strong> Even if your backing store is GraphQL, SQL, or REST. The model doesn’t want a typed schema — it wants a small set of retrievables given a natural-language query. Build the retrieval layer first.</li><li><strong>Default to columnar for collections.</strong> Costs nothing, compounds at every list response.</li><li><strong>Instrument/evals before you build the agent.</strong> We only noticed the accuracy gain because we had per-category evals in place. Without that, we’d have shipped a cheaper system and never known it was also more accurate.</li></ol><p>Descriptions over names, cost tiers, columnar payloads — refinements. The call that matters is interface shape: a search over a catalog, not a schema as context. Everything else follows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa3350e8d4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Impersonation for Microservices and MCPs]]></title>
            <link>https://medium.com/@mukundkidambi/user-impersonation-for-microservices-and-mcps-e2c358f2a759?source=rss-b07cbd95699b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c358f2a759</guid>
            <dc:creator><![CDATA[Mukundan Kidambi]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 13:45:16 GMT</pubDate>
            <atom:updated>2025-11-29T08:37:27.941Z</atom:updated>
            <content:encoded><![CDATA[<p>co-authors: <a href="https://medium.com/u/fa753086d029">Jorge Garcia</a> and <a href="https://medium.com/u/4c1ae049b46b">Zach Arnold</a></p><p>A dual-token pattern for maintaining user context across service boundaries when identity providers are split</p><h3>🛡️ The Impersonation Pattern</h3><p>When building microservices or Model Context Protocol (MCP) servers where user identities live in one IdP (Auth0, Okta) and service identities live in another (Azure AD, AWS IAM), you need a way to maintain user context through the service chain. This dual-token impersonation pattern solves that by using two independent authentication headers:</p><ul><li>Authorization header: M2M token for service-to-service authentication (Azure AD/AWS)</li><li>X-User-Context header: User token for impersonation context (Auth0/Okta)</li></ul><h4>When to Use This Pattern</h4><p>This pattern achieves the same effect as standard approaches when those tools are not available:</p><ul><li>Native on-behalf-of flows: Your IdP doesn’t support OBO flows (e.g., Auth0 lacks native OBO like Azure AD has), or you’re working across different IdPs where OBO doesn’t work</li><li>Token embedding: You can’t or don’t want to embed user claims in service tokens due to token size limits, security policies, or architectural constraints</li><li>Token exchange (RFC 8693): Cross-IdP token exchange is not supported between your providers, or federation setup is not feasible</li></ul><p>If your IdP supports native on-behalf-of flows within a single provider, use that instead. This dual-token pattern is a pragmatic workaround for split identity scenarios.</p><h3>Token Acquisition Flow</h3><h4>Phase 1: User Authentication</h4><pre>User → Auth0: Login credentials<br>Auth0 → User: user_token (JWT)</pre><h4>Phase 2: Client to API Gateway</h4><pre>Client → API Gateway:<br>  Header: Authorization: Bearer user_token<br>  <br>Note: Only user token at this stage</pre><h4>Phase 3: API Gateway Processing</h4><pre>API Gateway validates: user_token → Auth0<br>API Gateway → Azure AD: Client credentials (service principal)<br>Azure AD → API Gateway: m2m_token (JWT)</pre><h4>Phase 4: Service-to-Service Communication</h4><pre>API Gateway → Service A (Dual Token Pattern Starts):<br>  Header: Authorization: Bearer m2m_token<br>  Header: X-User-Context: Bearer user_token</pre><pre>Service A validates both tokens independently:<br>  ✓ m2m_token → Azure AD (S2S auth)<br>  ✓ user_token → Auth0 (user context)</pre><h4>Phase 5: Further Downstream Calls</h4><pre>Service A → Service B:<br>  Service A fetches new m2m_token from Azure AD<br>  Header: Authorization: Bearer new_m2m_token<br>  Header: X-User-Context: Bearer user_token (unchanged)<br>  <br>Service B validates both tokens independently</pre><h3>Multi-Service Request Flow</h3><p>Request Chain:</p><pre>Client → API Gateway → Service A → Service B<br>   │           │            │           │<br>   │ user      │ validates  │ validates │ validates<br>   │ token     │ user token │ both      │ both<br>   │ only      │            │ tokens    │ tokens<br>   │           │ fetches    │           │<br>   │           │ m2m token  │ fetches   │<br>   │           │            │ new m2m   │<br>   │           ▼            ▼           ▼<br>            Azure AD     Azure AD    Azure AD</pre><p>Key Points:</p><ul><li>Client sends ONLY user token to API Gateway</li><li>API Gateway fetches M2M token and validates user token</li><li>Service-to-Service calls use BOTH tokens (dual-token pattern)</li><li>Each service fetches its own M2M token and validates both</li><li>User token passes through unchanged for full audit trail</li></ul><h3>Client Implementation</h3><h3>TypeScript: Fetching and Sending Tokens</h3><pre>// Note: This code uses standard Node.js libraries (fetch, no external dependencies)<br>// For production, you may want to add libraries like axios, jose, etc.</pre><pre>interface DualTokenConfig {<br>  // Auth0 config for user token<br>  auth0Domain: string;<br>  auth0ClientId: string;<br>  auth0ClientSecret: string;<br>  auth0Audience: string;<br>  <br>  // Azure AD config for M2M token<br>  azureTenantId: string;<br>  azureClientId: string;<br>  azureClientSecret: string;<br>  azureScope: string;<br>}</pre><pre>class DualTokenClient {<br>  private config: DualTokenConfig;<br>  private m2mTokenCache: { token: string; expiresAt: number } | null = null;</pre><pre>  constructor(config: DualTokenConfig) {<br>    this.config = config;<br>  }</pre><pre>  /**<br>   * Fetch M2M token from Azure AD (with caching)<br>   */<br>  async getM2MToken(): Promise&lt;string&gt; {<br>    // Check cache<br>    if (this.m2mTokenCache &amp;&amp; Date.now() &lt; this.m2mTokenCache.expiresAt) {<br>      return this.m2mTokenCache.token;<br>    }</pre><pre>    const tokenUrl = `https://login.microsoftonline.com/${this.config.azureTenantId}/oauth2/v2.0/token`;<br>    <br>    const params = new URLSearchParams({<br>      client_id: this.config.azureClientId,<br>      client_secret: this.config.azureClientSecret,<br>      scope: this.config.azureScope,<br>      grant_type: &#39;client_credentials&#39;<br>    });</pre><pre>    const response = await fetch(tokenUrl, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39; },<br>      body: params.toString()<br>    });</pre><pre>    const data = await response.json();<br>    const token = data.access_token;<br>    const expiresIn = data.expires_in;<br>    <br>    // Cache with 5 minute buffer<br>    this.m2mTokenCache = {<br>      token,<br>      expiresAt: Date.now() + (expiresIn - 300) * 1000<br>    };</pre><pre>    return token;<br>  }</pre><pre>  /**<br>   * Exchange user credentials for Auth0 token<br>   */<br>  async getUserToken(username: string, password: string): Promise&lt;string&gt; {<br>    const tokenUrl = `https://${this.config.auth0Domain}/oauth/token`;<br>    <br>    const payload = {<br>      grant_type: &#39;password&#39;,<br>      username,<br>      password,<br>      audience: this.config.auth0Audience,<br>      client_id: this.config.auth0ClientId,<br>      client_secret: this.config.auth0ClientSecret,<br>      scope: &#39;openid profile email&#39;<br>    };</pre><pre>    const response = await fetch(tokenUrl, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      body: JSON.stringify(payload)<br>    });</pre><pre>    const data = await response.json();<br>    return data.access_token;<br>  }</pre><pre>  /**<br>   * Make API request with both tokens<br>   */<br>  async makeRequest(<br>    url: string,<br>    userToken: string,<br>    method: &#39;GET&#39; | &#39;POST&#39; | &#39;PUT&#39; | &#39;DELETE&#39; = &#39;GET&#39;,<br>    data?: any<br>  ): Promise&lt;any&gt; {<br>    const m2mToken = await this.getM2MToken();</pre><pre>    const headers = {<br>      &#39;Authorization&#39;: `Bearer ${m2mToken}`,<br>      &#39;X-User-Context&#39;: `Bearer ${userToken}`,<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    };</pre><pre>    const response = await fetch(url, {<br>      method,<br>      headers,<br>      body: data ? JSON.stringify(data) : undefined<br>    });</pre><pre>    return await response.json();<br>  }<br>}</pre><pre>// Usage Example<br>async function example() {<br>  const client = new DualTokenClient({<br>    auth0Domain: &#39;your-tenant.auth0.com&#39;,<br>    auth0ClientId: &#39;your-auth0-client-id&#39;,<br>    auth0ClientSecret: &#39;your-auth0-client-secret&#39;,<br>    auth0Audience: &#39;https://your-api.com&#39;,<br>    azureTenantId: &#39;your-azure-tenant-id&#39;,<br>    azureClientId: &#39;your-azure-client-id&#39;,<br>    azureClientSecret: &#39;your-azure-client-secret&#39;,<br>    azureScope: &#39;api://your-api/.default&#39;<br>  });</pre><pre>  const userToken = await client.getUserToken(&#39;user@example.com&#39;, &#39;password&#39;);<br>  const result = await client.makeRequest(&#39;https://api.yourservice.com/data&#39;, userToken, &#39;GET&#39;);<br>}</pre><h3>Server-side Validation</h3><h3>TypeScript: Token Validation Middleware</h3><pre>// Note: For production, use libraries like jose, jsonwebtoken, jwks-rsa<br>// This example shows the conceptual flow</pre><pre>class TokenValidator {<br>  private azureJwksCache: Map&lt;string, any&gt; = new Map();<br>  private auth0JwksCache: Map&lt;string, any&gt; = new Map();</pre><pre>  constructor(<br>    private azureTenantId: string,<br>    private azureAudience: string,<br>    private auth0Domain: string,<br>    private auth0Audience: string<br>  ) {}</pre><pre>  private async fetchJWKS(url: string): Promise&lt;any[]&gt; {<br>    const response = await fetch(url);<br>    const data = await response.json();<br>    return data.keys;<br>  }</pre><pre>  private decodeJWT(token: string): { header: any; payload: any } {<br>    const parts = token.split(&#39;.&#39;);<br>    const header = JSON.parse(Buffer.from(parts[0], &#39;base64&#39;).toString());<br>    const payload = JSON.parse(Buffer.from(parts[1], &#39;base64&#39;).toString());<br>    return { header, payload };<br>  }</pre><pre>  private async verifyJWT(<br>    token: string,<br>    expectedAudience: string,<br>    expectedIssuer: string,<br>    isAzure: boolean<br>  ): Promise&lt;any&gt; {<br>    const { header, payload } = this.decodeJWT(token);</pre><pre>    // Verify claims<br>    const now = Math.floor(Date.now() / 1000);</pre><pre>    if (payload.exp &amp;&amp; payload.exp &lt; now) {<br>      throw new Error(&#39;Token expired&#39;);<br>    }</pre><pre>    if (payload.aud !== expectedAudience) {<br>      throw new Error(&#39;Invalid audience&#39;);<br>    }</pre><pre>    if (!payload.iss.startsWith(expectedIssuer)) {<br>      throw new Error(&#39;Invalid issuer&#39;);<br>    }</pre><pre>    return payload;<br>  }</pre><pre>  async validateM2MToken(token: string): Promise&lt;any&gt; {<br>    return this.verifyJWT(<br>      token,<br>      this.azureAudience,<br>      `https://login.microsoftonline.com/${this.azureTenantId}`,<br>      true<br>    );<br>  }</pre><pre>  async validateUserToken(token: string): Promise&lt;any&gt; {<br>    return this.verifyJWT(<br>      token,<br>      this.auth0Audience,<br>      `https://${this.auth0Domain}/`,<br>      false<br>    );<br>  }<br>}</pre><pre>function createDualTokenMiddleware(<br>  azureTenantId: string,<br>  azureAudience: string,<br>  auth0Domain: string,<br>  auth0Audience: string<br>) {<br>  const validator = new TokenValidator(<br>    azureTenantId,<br>    azureAudience,<br>    auth0Domain,<br>    auth0Audience<br>  );</pre><pre>  return async (req: any, res: any, next: any) =&gt; {<br>    const authHeader = req.headers.authorization;<br>    const userHeader = req.headers[&#39;x-user-context&#39;];</pre><pre>    if (!authHeader?.startsWith(&#39;Bearer &#39;)) {<br>      return res.status(401).json({ error: &#39;Missing Authorization header&#39; });<br>    }</pre><pre>    if (!userHeader?.startsWith(&#39;Bearer &#39;)) {<br>      return res.status(401).json({ error: &#39;Missing X-User-Context header&#39; });<br>    }</pre><pre>    const m2mToken = authHeader.substring(7);<br>    const userToken = userHeader.substring(7);</pre><pre>    // Validate both tokens in parallel<br>    const [m2mPayload, userPayload] = await Promise.all([<br>      validator.validateM2MToken(m2mToken),<br>      validator.validateUserToken(userToken)<br>    ]);</pre><pre>    // Attach validated identities to request<br>    req.serviceIdentity = {<br>      clientId: m2mPayload.azp || m2mPayload.appid,<br>      tenantId: m2mPayload.tid,<br>      roles: m2mPayload.roles || []<br>    };</pre><pre>    req.userIdentity = {<br>      userId: userPayload.sub,<br>      email: userPayload.email,<br>      permissions: userPayload.permissions || []<br>    };</pre><pre>    next();<br>  };<br>}</pre><h3>Security Considerations</h3><h3>⚠️ Critical: Both Tokens Must Be Validated</h3><p>Every service in the chain MUST independently validate BOTH tokens. Never trust tokens just because they came from an upstream service.</p><h3>Token Validation Checklist</h3><ul><li>Verify signature using JWKS</li><li>Check token expiration (exp claim)</li><li>Validate audience (aud claim)</li><li>Validate issuer (iss claim)</li><li>Check not-before time (nbf claim) if present</li><li>Verify token hasn’t been revoked (if using revocation lists)</li></ul><h3>Authorization Strategy</h3><p>Use both token contexts for complete authorization:</p><ul><li>M2M Token: “Is this service allowed to call this endpoint?”</li><li>User Token: “What actions can this user perform?”</li><li>Combined: “Can this service perform this action on behalf of this user?”</li></ul><h3>Audit Logging Best Practices</h3><p>Log both identities for complete traceability:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2025-11-18T12:34:56Z&quot;,<br>  &quot;action&quot;: &quot;UPDATE_RESOURCE&quot;,<br>  &quot;resource_id&quot;: &quot;res_12345&quot;,<br>  &quot;service&quot;: {<br>    &quot;client_id&quot;: &quot;srv_api_gateway&quot;,<br>    &quot;tenant_id&quot;: &quot;azure_tenant_123&quot;<br>  },<br>  &quot;user&quot;: {<br>    &quot;user_id&quot;: &quot;auth0|user_456&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;<br>  },<br>  &quot;result&quot;: &quot;SUCCESS&quot;<br>}</pre><h3>Common Pitfalls to Avoid</h3><h3>❌ Skipping Validation on Internal Services</h3><p>Wrong: “This request came from our API gateway, so I don’t need to validate tokens.”</p><p>Right: Every service validates both tokens independently. Zero trust architecture.</p><h3>❌ Caching User Tokens</h3><p>Wrong: Caching user tokens server-side for reuse.</p><p>Right: User tokens should be passed through as-is. Only cache M2M tokens with proper expiry.</p><h3>❌ Using HTTP Instead of HTTPS</h3><p>Wrong: Transmitting tokens over unencrypted connections.</p><p>Right: Always use HTTPS/TLS for all inter-service communication.</p><h3>❌ Ignoring Token Expiration</h3><p>Wrong: Not checking the exp claim or handling expired tokens gracefully.</p><p>Right: Always validate expiration and return clear error messages to clients.</p><h3>❌ Mixing Token Contexts</h3><p>Wrong: Using user permissions for service authorization or vice versa.</p><p>Right: Keep contexts separate. Service permissions for S2S, user permissions for user actions.</p><h3>Why This Pattern Works</h3><h3>Benefits</h3><ul><li>Cross-IdP Compatibility: Works seamlessly when users and services are in different identity providers. No need for complex token exchange or federation.</li><li>Complete Audit Trail: Every operation has both service and user context, enabling comprehensive security monitoring and compliance reporting.</li><li>Separation of Concerns: Service-to-service trust is managed independently from user authorization. Each identity provider handles its own domain.</li><li>Flexible Authorization: Implement authorization logic that considers both contexts: service capabilities AND user permissions.</li></ul><h3>Conclusion</h3><p>The dual-token impersonation pattern is a pragmatic workaround for microservices, MCP servers, and distributed systems where split identity management prevents using standard on-behalf-of flows or token exchange mechanisms. It achieves the same goal — maintaining user context through service chains — when native IdP features aren’t available or don’t work across providers.</p><p>This pattern is particularly valuable for:</p><ul><li>Microservices architectures with mixed identity providers</li><li>MCP servers that need to act on behalf of users across different auth systems</li><li>Multi-tenant systems requiring per-user audit trails</li><li>Legacy systems being modernized incrementally where full IdP consolidation isn’t feasible</li></ul><p>Important: If your architecture uses a single IdP that supports native on-behalf-of flows (like Azure AD’s OBO flow), use that instead. This dual-token pattern is specifically for scenarios where standard approaches aren’t available due to split identity providers or IdP limitations.</p><p>Remember: this pattern works because both tokens are independently validated at every service boundary. Never skip validation, and always log both identities for complete traceability and security compliance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c358f2a759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Token Usage in MCP Servers with GraphQL: A 70–80% Token Reduction Strategy]]></title>
            <link>https://medium.com/@mukundkidambi/optimizing-token-usage-in-mcp-servers-with-graphql-a-70-80-token-reduction-strategy-d4a620fdc690?source=rss-b07cbd95699b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a620fdc690</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Mukundan Kidambi]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 04:58:41 GMT</pubDate>
            <atom:updated>2025-08-27T04:58:41.967Z</atom:updated>
            <content:encoded><![CDATA[<p>The Model Context Protocol (MCP) has revolutionized how AI models interact with external data sources, but as adoption grows, so do the challenges around token efficiency. In this article, I’ll share how we achieved a dramatic 70–80% reduction in token usage by reimagining our MCP server architecture with GraphQL, transforming a token-hungry system into an efficient, scalable solution.</p><h3>The Problem: Token Bloat in Traditional MCP Implementations</h3><p>When we first implemented MCP servers for AI data access, our approach seemed straightforward: wrap our existing API layer and expose each endpoint as an individual MCP tool. This design offered several advantages:</p><ul><li><strong>Authorization handled at the API level</strong>: Existing entitlement and auth mechanisms worked seamlessly</li><li><strong>Familiar patterns</strong>: Developers could leverage existing API knowledge</li><li><strong>Rapid deployment</strong>: Minimal refactoring of existing services</li></ul><p>However, this approach quickly revealed a critical flaw: <strong>token inefficiency</strong>.</p><h3>The Token Usage Crisis</h3><p>Our initial implementation suffered from two primary issues:</p><ol><li><strong>Verbose API responses</strong>: Each tool call returned complete JSON objects, often containing unnecessary nested data and metadata that consumed significant tokens</li><li><strong>Tool proliferation</strong>: Breaking large responses into smaller chunks meant creating numerous individual MCP tools, leading to:</li></ol><ul><li>Complex orchestration across multiple tool calls</li><li>Increased context switching overhead</li><li>Higher total token consumption due to repeated metadata</li></ul><p>Consider this example scenario:</p><pre>// Single API call returning user data<br>{<br>  &quot;user&quot;: {<br>    &quot;id&quot;: &quot;12345&quot;,<br>    &quot;profile&quot;: {<br>      &quot;name&quot;: &quot;John Doe&quot;,<br>      &quot;email&quot;: &quot;john@example.com&quot;,<br>      &quot;preferences&quot;: { /* 50+ fields */ },<br>      &quot;metadata&quot;: { /* extensive tracking data */ }<br>    },<br>    &quot;permissions&quot;: [ /* 20+ permission objects */ ],<br>    &quot;usage_stats&quot;: { /* detailed analytics */ }<br>  }<br>}</pre><p>When the AI model only needed the user’s name and email, we were still consuming tokens for the entire response payload — a classic case of over-fetching leading to token waste.</p><h3>The GraphQL Solution: Two Tools to Rule Them All</h3><p>Our breakthrough came from recognizing that GraphQL’s core strength — precise data fetching — directly addresses MCP’s token efficiency challenge. Instead of exposing dozens of individual API endpoints as MCP tools, we consolidated our entire data layer into just <strong>two powerful tools</strong>:</p><h3>Tool 1: Schema Introspection (get_graphql_schema)</h3><pre>def get_graphql_schema():<br>    &quot;&quot;&quot;Returns the complete GraphQL schema definition&quot;&quot;&quot;<br>    return {<br>        &quot;schema&quot;: schema_definition_string,<br>        &quot;types&quot;: available_types,<br>        &quot;queries&quot;: available_queries,<br>        &quot;mutations&quot;: available_mutations<br>    }</pre><h3>Tool 2: Query Execution (execute_graphql_query)</h3><pre>def execute_graphql_query(query: str, variables: dict = None):<br>    &quot;&quot;&quot;Executes a GraphQL query and returns precisely requested data&quot;&quot;&quot;<br>    result = graphql_executor.execute(query, variables)<br>    return result.data</pre><h3>Implementation Architecture</h3><p>Our GraphQL-powered MCP server architecture looks like this:</p><pre>AI Model<br>    ↓ (MCP Protocol)<br>GraphQL MCP Server<br>    ↓ (GraphQL queries)<br>GraphQL Gateway<br>    ↓ (REST/gRPC calls)<br>Existing API Services</pre><h3>Schema Design Strategy</h3><p>The key insight was treating our GraphQL schema as a <strong>representation layer</strong> for existing APIs rather than a complete reimplementation. Here’s how we mapped our REST endpoints to GraphQL:</p><pre># REST: GET /users/{id}<br># Becomes:<br>type User {<br>  id: ID!<br>  name: String!<br>  email: String!<br>  profile: UserProfile<br>  permissions: [Permission!]!<br>}</pre><pre># REST: GET /orders/{userId}<br># Becomes:<br>type Query {<br>  user(id: ID!): User<br>  userOrders(userId: ID!): [Order!]!<br>}</pre><p>This approach preserved our existing authorization logic while enabling precise data fetching.</p><h3>The Token Efficiency Revolution</h3><h3>Before: Multiple Tool Calls</h3><pre>Tool 1: getUserProfile(userId) → 450 tokens<br>Tool 2: getUserPermissions(userId) → 320 tokens  <br>Tool 3: getUserPreferences(userId) → 280 tokens<br>Total: 1,050 tokens</pre><h3>After: Single GraphQL Query</h3><pre>query GetUserEssentials($userId: ID!) {<br>  user(id: $userId) {<br>    name<br>    email<br>    permissions {<br>      name<br>    }<br>  }<br>}</pre><p><strong>Result: 180 tokens (83% reduction)</strong></p><h3>Implementation Deep Dive</h3><h3>1. Schema Generation from Existing APIs</h3><p>We automated schema generation by introspecting our existing OpenAPI specifications:</p><pre>def generate_graphql_schema_from_openapi(openapi_spec):<br>    &quot;&quot;&quot;Convert OpenAPI definitions to GraphQL schema&quot;&quot;&quot;<br>    schema_builder = GraphQLSchemaBuilder()<br>    <br>    for path, methods in openapi_spec[&#39;paths&#39;].items():<br>        for method, definition in methods.items():<br>            if method == &#39;get&#39;:<br>                # Convert to GraphQL Query<br>                schema_builder.add_query(path, definition)<br>            elif method == &#39;post&#39;:<br>                # Convert to GraphQL Mutation<br>                schema_builder.add_mutation(path, definition)<br>    <br>    return schema_builder.build()</pre><h3>2. Authorization Preservation</h3><p>Critical to our success was maintaining existing authorization patterns:</p><pre>class AuthorizedGraphQLExecutor:<br>    def execute(self, query, variables, context):<br>        # Extract user context from MCP session<br>        user_context = self.extract_user_context(context)<br>        <br>        # Execute with authorization context<br>        return self.graphql_engine.execute(<br>            query, <br>            variables,<br>            context_value={&#39;user&#39;: user_context}<br>        )</pre><h3>Results and Impact</h3><p>Our GraphQL-powered MCP implementation delivered transformative results:</p><h3>Token Usage Metrics</h3><ul><li><strong>Average token reduction</strong>: 70–80%</li><li><strong>Peak query efficiency</strong>: 90% reduction for complex data fetching</li><li><strong>Tool complexity</strong>: Reduced from 40+ tools to 2 core tools</li></ul><h3>Performance Improvements</h3><ul><li><strong>Query response time</strong>: 40% faster due to precise data fetching</li><li><strong>Model context utilization</strong>: Better focus on relevant data</li><li><strong>Development velocity</strong>: Faster feature implementation</li></ul><h3>Scalability Benefits</h3><ul><li><strong>New API integration</strong>: Minutes instead of hours</li><li><strong>Schema evolution</strong>: Automatic updates without MCP tool changes</li><li><strong>Cross-team adoption</strong>: Self-service data access for AI applications</li></ul><h3>The Path to Full Automation</h3><p>While our two-tool GraphQL approach delivered impressive results, we recognized an even greater opportunity: <strong>complete automation of the API-to-MCP pipeline</strong>. In a future article, we’ll dive deep into how we built a fully automated workflow that transforms any Swagger/OpenAPI specification into a production-ready MCP server.</p><p><em>Have you implemented similar optimizations in your MCP servers? I’d love to hear about your experiences and lessons learned. Connect with me on </em><a href="https://linkedin.com/in/yourprofile"><em>LinkedIn</em></a><em> or </em><a href="https://twitter.com/yourhandle"><em>Twitter</em></a><em> to continue the conversation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a620fdc690" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>