<?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 Saima Khan on Medium]]></title>
        <description><![CDATA[Stories by Saima Khan on Medium]]></description>
        <link>https://medium.com/@khansaima?source=rss-2b5cea454596------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*usA73bQ-AZkm4KbqroaA1A.png</url>
            <title>Stories by Saima Khan on Medium</title>
            <link>https://medium.com/@khansaima?source=rss-2b5cea454596------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:25:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khansaima/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[When OBO Isn’t an Option: Securing an Enterprise MCP Server with Entra ID and Downstream…]]></title>
            <link>https://medium.com/@khansaima/when-obo-isnt-an-option-securing-an-enterprise-mcp-server-with-entra-id-and-downstream-03c4ada264d0?source=rss-2b5cea454596------2</link>
            <guid isPermaLink="false">https://medium.com/p/03c4ada264d0</guid>
            <dc:creator><![CDATA[Saima Khan]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 08:01:33 GMT</pubDate>
            <atom:updated>2026-10-15T08:24:41.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>When OBO Isn’t an Option: Securing an Enterprise MCP Server with Entra ID and Downstream Credentials</h3><h3>Extending the Entra-secured MCP pattern to enterprise systems that still require their own downstream credentials</h3><p>In my previous work on securing MCP servers, I explored using <strong>Microsoft Entra ID and the OAuth On-Behalf-Of (OBO) flow</strong> to propagate an authenticated user’s identity to downstream APIs.</p><p><a href="https://medium.com/@khansaima/securing-mcp-tools-with-azure-ad-on-behalf-of-obo-29b1ada1e505?sharedUserId=khansaima">Securing MCP Tools with Azure AD On-Behalf-Of (OBO)</a></p><p>That works well when the downstream service participates in the same OAuth identity model.</p><p>But many existing enterprise systems don’t. They may expose perfectly usable REST APIs while still requiring their own username/password, API token, or system-specific credentials.</p><p>I encountered exactly this requirement while building an MCP interface for an enterprise <strong>IP Address Management (IPAM)</strong> platform.</p><p>The requirements were to:</p><ul><li>authenticate MCP users through Microsoft Entra ID;</li><li>provide read/write tool access based on user permissions;</li><li>retain the credentials required by the existing IPAM API;</li><li>attribute tool invocations to authenticated users;</li><li>audit successes, failures, and authorization rejections;</li><li>provide tool-level observability;</li><li>support remote MCP clients including GitHub Copilot and Claude Code.</li></ul><p>The resulting model separates each concern:</p><pre>Entra ID             → MCP user authentication<br>Entra App Roles      → MCP tool authorization<br>IPAM credentials     → Downstream authentication<br>Application Insights → Audit<br>OpenTelemetry/Arize  → Tool observability</pre><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mILU8LHmARFz_jCW6h8_LA.png" /></figure><p>The server is implemented with <strong>FastMCP</strong> and hosted behind <strong>Azure App Service Easy Auth</strong>.</p><p>Easy Auth establishes the authenticated identity before the request reaches the application. FastMCP handles application-level authorization, while downstream IPAM authentication remains independent.</p><p>That separation is central to the design:</p><blockquote>An authenticated MCP user is not automatically an authenticated IPAM user.</blockquote><h3>1. Protecting the MCP Endpoint with Entra ID</h3><p>The first step was protecting the remote MCP endpoint with <strong>Microsoft Entra ID</strong>.</p><p>I registered the MCP API, exposed a delegated access_as_user scope, configured the required access-token version, and protected the hosted endpoint with <strong>Azure App Service Easy Auth</strong>.</p><p>After authentication, App Service makes the principal available through headers such as:</p><pre>X-MS-CLIENT-PRINCIPAL<br>X-MS-CLIENT-PRINCIPAL-ID<br>X-MS-CLIENT-PRINCIPAL-NAME</pre><p>This keeps responsibilities clear:</p><pre>Entra ID / Easy Auth<br>        ↓<br>Authentication<br><br>FastMCP<br>        ↓<br>Application Authorization</pre><p>The complete Entra and Easy Auth configuration is documented in the reference repository rather than repeated here.</p><h3>2. Why OBO Wasn’t the Right Downstream Pattern</h3><p>This is where the implementation differs from the OBO pattern I explored previously.</p><p>The downstream IPAM REST API doesn’t authenticate using an Entra access token. It expects its <strong>own credentials</strong>.</p><p>Instead of trying to force both systems into the same identity model, I kept them separate:</p><pre>MCP Identity<br>    → Microsoft Entra ID<br><br>Downstream Identity<br>    → IPAM credentials<br></pre><p>The MCP client supplies:</p><pre>X-IPAM-Username<br>X-IPAM-Password</pre><p>Middleware retrieves these during tool invocation and places them into the FastMCP invocation context. The downstream SolidServerClient then converts them into the authentication format expected by SOLIDserver.</p><p>One detail mattered here: <strong>IPAM credentials are checked for presence during </strong><strong>tools/call, rather than during MCP initialization or </strong><strong>tools/list. Their validity is determined by SOLIDserver when the downstream request executes.</strong></p><p>This means authentication and tool discovery can complete independently. Downstream credentials become mandatory only when an IPAM operation is actually executed.</p><h3>3. Authentication Is Not Authorization</h3><p>Authenticating users solved only half the problem. I still needed to control <strong>which tools each user could access</strong>.</p><p>I created two Entra App Roles:</p><pre>IPAM.Read<br>IPAM.Write</pre><p>and mapped them to FastMCP tags:</p><pre>ROLE_PERMISSIONS = {  <br>  &quot;IPAM.Read&quot;: {&quot;read&quot;},  <br>  &quot;IPAM.Write&quot;: {&quot;read&quot;, &quot;write&quot;},<br>}</pre><p>Tools classify themselves directly:</p><pre>@mcp.tool(tags={&quot;read&quot;})<br>async def get_sites(...): <br>   ...</pre><pre>@mcp.tool(tags={&quot;write&quot;})<br>async def add_ip_address(...): <br>   ...</pre><p>During tools/list, the middleware filters the tools returned to the user according to those roles.</p><p>But I deliberately didn’t treat discovery as the security boundary.</p><p>A client that already knows a hidden tool’s name could attempt to invoke it directly. The same authorization policy is therefore enforced again during tools/call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ezig3QrKd8gHu1sbZ4Qz6w.png" /></figure><blockquote>Tool discovery is not an authorization boundary.</blockquote><p>The server fails closed: no recognized role means no tool access.</p><h3>4. Adding a Deployment-Level Safety Boundary</h3><p>User authorization answers <strong>who may write</strong>, but I also wanted the deployment itself to be able to prohibit writes.</p><p>That led to:</p><pre>IPAM_READ_ONLY=true</pre><p>When enabled, write tools are removed from discovery and direct write calls are rejected — even for an IPAM.Write user.</p><p>This gives two independent controls:</p><pre>Who may write?<br>    → Entra App Roles<br><br>Can this deployment write?<br>    → IPAM_READ_ONLY</pre><p>The distinction is useful when the same code is deployed into environments with different risk profiles.</p><h3>5. Designing MCP Tools for Agents, Not REST Clients</h3><p>The implementation uses the existing <strong>EfficientIP SOLIDserver REST API</strong> and currently exposes 14 MCP tools across sites, subnets, addresses, address availability, and pools.</p><p>I deliberately avoided returning complete REST responses to the model.</p><p>For example, a site result is reduced to useful fields such as:</p><pre>site_name<br>site_id<br>site_description<br>parent_site_name<br>parent_site_id</pre><p>This gives the MCP layer an additional responsibility:</p><blockquote>Translate an existing enterprise API into a smaller contract designed for an AI agent.</blockquote><p>It reduces unnecessary model context and avoids coupling the agent to every vendor response field.</p><p>Vendor-specific HTTP behavior is isolated in SolidServerClient, while MCP tools remain focused on agent-facing operations.</p><p>For writes, I also retained the vendor’s explicit operation semantics:</p><pre>add_ip_address  → new_only<br>edit_ip_address → edit_only</pre><p>so an add cannot silently become an edit, or vice versa.</p><h3>6. Auditing Who Used Which Tool</h3><p>With Entra authentication in place, tool activity could be attributed to an authenticated identity.</p><p>The audit trail captures information such as:</p><pre>User<br>Entra role<br>IPAM username<br>Tool<br>Outcome<br>Duration</pre><p>and sends structured events to <strong>Azure Application Insights</strong>.</p><p>Equally important is what it does <strong>not</strong> capture:</p><pre>IPAM password<br>OAuth access token<br>Authorization headers<br>Complete request headers<br>Complete tool responses</pre><p>Auditability shouldn’t turn the logging platform into another credential store.</p><h3>7. Audit Outcomes and Tool Observability</h3><p>One subtle issue appeared while testing failures.</p><p>A tool can complete normally from FastMCP’s perspective while the downstream operation has failed:</p><pre>{<br>  &quot;status&quot;: &quot;error&quot;,<br>  &quot;error&quot;: &quot;Invalid downstream credentials&quot;<br>}</pre><p>No Python exception necessarily occurs.</p><p>So this assumption is unsafe:</p><pre>call_next() returned<br>        ↓<br>      success</pre><p>Instead, the middleware inspects:</p><pre>result.structured_content</pre><p>and uses the returned status to classify the operation:</p><pre>success   → downstream operation succeeded<br>failure   → tool ran, but downstream operation failed<br>rejected  → request was blocked before execution</pre><p>That distinction between <strong>MCP protocol success and downstream operation success</strong> is important for meaningful audit data.</p><p>For execution-level visibility, MCP tool calls are also wrapped in OpenTelemetry spans and exported to <strong>Arize</strong>.</p><p>The two systems therefore serve complementary purposes:</p><pre>Application Insights<br>        ↓<br>Audit / Operational Events<br><br>OpenTelemetry + Arize<br>        ↓<br>MCP Tool Traces</pre><p>The detailed telemetry configuration is available in the repository.</p><h3>8. One OAuth Interoperability Lesson</h3><p>I tested the server with both <strong>VS Code/GitHub Copilot</strong> and <strong>Claude Code</strong>.</p><p>This surfaced a useful reminder that MCP clients don’t necessarily construct identical OAuth requests.</p><p>The GitHub Copilot flow worked once OAuth discovery was configured correctly. Claude Code generated an authorization request containing a resource parameter corresponding to the full MCP endpoint:</p><pre>resource=https://&lt;server&gt;/ipam/mcp</pre><p>while requesting the delegated API scope:</p><pre>api://&lt;mcp-api-client-id&gt;/access_as_user</pre><p>Capturing the actual authorization URL made the mismatch visible. Once the Entra configuration recognized the resource requested by the client, authentication completed successfully.</p><p>The takeaway:</p><blockquote>Don’t assume an OAuth configuration that works for one MCP client will automatically work for another.</blockquote><p>When troubleshooting, inspecting:</p><pre>client_id<br>redirect_uri<br>scope<br>resource</pre><p>was much more useful than relying only on the final browser error.</p><p>The exact client configuration and troubleshooting steps are documented in the GitHub implementation.</p><h3>9. Validating the Security Boundaries</h3><p>I wanted the security model enforced by the server rather than dependent on client behavior.</p><p>Two particularly important test cases are:</p><pre>IPAM.Read<br>    + direct write tools/call<br>    = DENIED</pre><p>and:</p><pre>IPAM.Write<br>    + IPAM_READ_ONLY=true<br>    = DENIED</pre><p>The automated suite also covers role extraction, fail-closed behavior, discovery filtering, execution-time authorization, SOLIDserver client behavior, and tool response handling.</p><p>The downstream IPAM boundary is mocked, so CI doesn’t require access to a live SOLIDserver environment.</p><h3>10. Bringing It Back to OBO</h3><p>Putting everything together, the security model looks like this:</p><pre>Microsoft Entra ID<br>        ↓<br>Who is using the MCP server?<br><br>Entra App Roles<br>        ↓<br>Which MCP tools can they use?<br><br>IPAM_READ_ONLY<br>        ↓<br>Can this deployment perform writes?<br><br>IPAM Credentials<br>        ↓<br>Can the request authenticate downstream?<br><br>Application Insights / Arize<br>        ↓<br>What happened during execution?</pre><p>This brings the implementation back to the question from my previous OBO work.</p><p>With OBO:</p><pre>User<br>  ↓<br>Entra ID<br>  ↓<br>MCP Server<br>  ↓<br>Delegated User Token<br>  ↓<br>OAuth-aware Downstream API</pre><p>Here, the constraint is different:</p><pre>User<br>  ↓<br>Entra ID<br>  ↓<br>Secure MCP Server<br>  ↓<br>Separate Downstream Credentials<br>  ↓<br>Existing Enterprise API</pre><p>Neither pattern replaces the other.</p><blockquote>If the downstream API supports delegated OAuth, OBO is a natural way to propagate user identity. If it doesn’t, keep the identity domains explicit and secure the MCP boundary independently.</blockquote><p>The underlying system doesn’t need to become OAuth-aware or MCP-aware for the MCP layer to provide modern authentication, authorization, auditing, and observability.</p><p>And this pattern isn’t specific to IPAM. It applies to other established enterprise APIs that retain their own authentication mechanisms.</p><h3>Reference Implementation</h3><p>I’ve published the reference implementation on GitHub: <a href="https://github.com/sakhan-rio/enterprise-ipam-mcp">enterprise-mcp-ipam</a></p><p>It contains the FastMCP server, SOLIDserver integration, Entra authorization, deployment-level read-only protection, audit and observability implementation, automated tests, architecture documentation, and client setup guides.</p><p>The repository carries the reproducible setup and implementation details that I’ve intentionally kept out of this article.</p><h3>Closing Thoughts</h3><p>Building the IPAM tools was the straightforward part. The more important decisions were around the boundaries:</p><p><strong>Who is calling the MCP server? What can they do? Can this deployment make changes? How does the existing downstream system authenticate? And can the resulting activity be reliably attributed and observed?</strong></p><p>Keeping those concerns independent allowed an existing credential-based enterprise API to participate in MCP workflows without requiring changes to its underlying authentication model.</p><blockquote>Modernizing access to an existing enterprise system doesn’t necessarily mean modernizing the system itself. Sometimes the right integration layer is enough.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03c4ada264d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing MCP Tools with Azure AD On-Behalf-Of (OBO)]]></title>
            <link>https://medium.com/@khansaima/securing-mcp-tools-with-azure-ad-on-behalf-of-obo-29b1ada1e505?source=rss-2b5cea454596------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b1ada1e505</guid>
            <dc:creator><![CDATA[Saima Khan]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 08:14:37 GMT</pubDate>
            <atom:updated>2025-09-26T11:47:50.639Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the third post in my MCP series. If you’re new to the concept of Model Context Protocol (MCP), check out the first two parts:</em></p><ul><li><a href="https://medium.com/@khansaima/from-monolith-to-modular-part-1-understanding-mcp-for-modern-ai-applications-c367036c1c5e">From Monolith to Modular (Part 1): Understanding MCP for Modern AI Applications</a></li><li><a href="https://medium.com/@khansaima/securing-mcp-servers-with-azure-ad-and-jwt-based-role-authorization-d8c8aeadb7f5">Securing MCP Servers with Azure AD and JWT-based Role Authorization</a></li></ul><p>In previous posts, I introduced the idea of MCP and how to secure MCP servers using Azure AD App Roles and JWT token verification (Tier-1 security). In this post, we go one step further exploring the <strong>On-Behalf-Of (OBO) pattern</strong>, which enables secure, <strong>runtime-level API authorization</strong> from within MCP tools.</p><h3>What is the OBO Pattern?</h3><p>The <strong>On-Behalf-Of (OBO)</strong> pattern is a delegated authentication flow defined by Microsoft that allows a service to call downstream APIs using a user’s identity.</p><p>In the OBO flow:</p><ol><li>The user authenticates and receives an access token.</li><li>The server (a confidential client) receives this token and exchanges it for another token <strong>targeted at the downstream resource</strong>.</li><li>The tool uses that new token to safely access external APIs <strong>on behalf of the user</strong>.</li></ol><p>📖 <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow">Microsoft Docs: OAuth 2.0 On-Behalf-Of flow</a></p><p>This pattern is particularly useful when your MCP tools need to access APIs such as:</p><ul><li>Azure DevOps (e.g., create work items, read PRs)</li><li>Microsoft Graph (e.g., fetch user profile or calendar)</li><li>Azure Cognitive Search (e.g., query secured indexes)</li></ul><p>While OBO is commonly used with Microsoft services (like the ones above), the core concept <strong>securely delegating access to a downstream API using an upstream token</strong> can be applied to <strong>any API</strong> that supports OAuth2 and scopes-based access control.</p><p>The only requirement is that:</p><ul><li>The downstream service must trust the identity provider issuing the exchanged token.</li><li>The application (confidential client) must be registered and authorized to request tokens for that downstream API.</li></ul><h3>Why OBO Matters in MCP</h3><p>In the previous post, we focused on <strong>App Role-based filtering</strong> where tools are either shown or hidden based on a user’s assigned role. That helps avoid accidental exposure to destructive or sensitive tools.</p><p>However, this visibility control alone isn’t always enough. What if a tool is correctly exposed but calls an <strong>external system that requires user-specific permissions</strong>?</p><blockquote>Without OBO, even users with minimal roles might be able to invoke tools that call protected APIs — potentially modifying, deleting, or accessing data they shouldn’t. This is especially risky when:</blockquote><ul><li>The downstream API (e.g., Azure DevOps, Cognitive Search) exposes privileged operations</li><li>MCP tools execute using a shared static token (e.g., a Service Principle, Service Credentials) that lacks user context</li></ul><p>This is where the <strong>On-Behalf-Of (OBO)</strong> pattern plays a critical role. Instead of granting blanket access via a shared service identity, OBO ensures that:</p><ul><li>Each API call happens in the <strong>true context of the user</strong></li><li>The external system enforces <strong>RBAC, ACLs, or policy checks</strong> based on the user’s actual permissions</li><li>Tools remain reusable, but execution is dynamically controlled</li></ul><h3>Architecture Overview</h3><p>Here’s a high-level view of how the On-Behalf-Of flow fits into the MCP architecture:</p><h4>OBO Flow: Step-by-Step</h4><p>Below is a sequence diagram representing the OBO token flow, including token caching, user interaction, and delegated API access:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERn3xeSIs4EQErTp1bS7PQ.png" /></figure><p>Here’s how the OBO flow plays out in the MCP context:</p><ol><li>The user logs into the MCP client and obtains an access token scoped for the MCP Server. This requires the appropriate app registrations in Entra ID.</li><li>The MCP Server validates the incoming token using FastMCP’s built-in token verification, ensuring it was issued by Entra ID and has the correct audience.</li><li>When the user invokes a tool (e.g., to interact with Azure Cognitive Search), the agent routes the request to the MCP tool handler.</li><li>The tool retrieves the original user token (using a helper in FastMCP), then performs an OBO token exchange to get a new token scoped for the external API.</li><li>The tool uses this new token to call the downstream API on behalf of the user and returns the result back through the MCP server to the client.</li></ol><p>This ensures that downstream APIs receive user-specific tokens, allowing them to enforce granular access policies.</p><h3>Setting Up OBO in Azure</h3><p>We are building an MCP Server that exposes one tool that queries <strong>Microsoft Graph access </strong>to list SharePoint sites accessible by the signed-in user. You need to configure <strong>two app registrations</strong> in Entra ID to support the OBO flow.</p><h4>Frontend App Registration (Client CLI / Interface)</h4><p>This app is responsible for acquiring the user token to access the MCP Server.</p><p>I will use the <strong>confidential client flow</strong>, with a browser-based login and redirect to obtain the user’s token using the authorization code grant.</p><p>Steps:</p><ol><li><strong>Create another App Registration</strong> (e.g., FastMCP-OBO-Client)</li><li>Go to <strong>Certificates &amp; secrets, a</strong>dd a client secret</li><li>Go to <strong>API Permissions</strong>:</li></ol><ul><li>Add <strong>delegated permission</strong> to access the backend API (access_as_user scope)</li></ul><p>4. Under <strong>Authentication,</strong> add a <strong>Redirect URI</strong> (e.g., http://localhost:8100/auth/callback) for use with Authorization Code Flow. This must match the one used in your client script. You can keep <strong>public client flows</strong> disabled.</p><h4>Backend App Registration (MCP Server)</h4><p>This app represents your FastMCP Server. It must be registered as a <strong>confidential client</strong>, since it will perform the token exchange on behalf of the user.</p><p>Steps:</p><ol><li><strong>Create an App Registration</strong> (e.g., FastMCP-OBO-Server)</li><li>Go to <strong>Expose an API</strong>:</li></ol><ul><li>Set an Application ID URI (e.g., api://&lt;client-id&gt;)</li><li>Add a custom scope — name it access_as_user (used by the client to request delegated access)</li></ul><p>3. Go to <strong>API Permissions</strong>:</p><ul><li>Add delegated permissions to <strong>Microsoft Graph</strong> → Sites.Read.All</li></ul><p>4. Go to <strong>Certificates &amp; secrets</strong>:</p><ul><li>Generate a <strong>client secret</strong> — this is required for the MCP Server to authenticate itself during the OBO token exchange flow</li></ul><h4>🔄 Link the Two Registrations</h4><p>In the <strong>backend app registration</strong>:</p><ul><li>Under <strong>Expose an API</strong> → <strong>Authorized client applications</strong>, add the <strong>client ID</strong> of the frontend app. This authorizes the frontend to call the backend using the access_as_user scope.</li></ul><h3>Sample Code for OBO in MCP Tool</h3><p>The following MCP server implementation includes a tool that uses the OBO flow to query Microsoft Graph and check whether a user has access to a given SharePoint site.</p><p>This is built using the FastMCP Python SDK. The server includes:</p><ul><li><strong>Tier-1 security</strong>: App Role-based filtering using a custom AuthorizationMiddleware, imported from the shared package — previously explained in <a href="https://medium.com/@khansaima/securing-mcp-servers-with-azure-ad-and-jwt-based-role-authorization-d8c8aeadb7f5">this article</a>. For this to work, ensure that app roles are defined in your backend app registration and assigned to users accordingly.</li><li><strong>Tier-2 security</strong>: Runtime access enforcement using the <strong>On-Behalf-Of (OBO)</strong> pattern to securely access Microsoft Graph with delegated user context</li></ul><p><em>Below is the full server file with inline comments</em></p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>FastMCP Server with Entra ID Authentication and OBO flow for Microsoft Graph<br>&quot;&quot;&quot;<br><br>import logging<br>import os<br>import jwt<br>import requests<br>from dotenv import load_dotenv<br><br>from fastmcp import FastMCP<br>from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware<br>from fastmcp.server.auth.providers.jwt import JWTVerifier  # Used for Tier-1 JWT token validation<br>from shared.middleware.authorization_middleware import AuthorizationMiddleware  # Role-based filtering<br>from fastmcp.server.dependencies import get_access_token, AccessToken<br><br>load_dotenv()<br><br># Server-level configuration<br>AUTH_ENABLED = os.getenv(&quot;AUTH_ENABLED&quot;, &quot;false&quot;).lower() == &quot;true&quot;<br>MIDDLEWARE_ENABLED = os.getenv(&quot;MIDDLEWARE_ENABLED&quot;, &quot;false&quot;).lower() == &quot;true&quot;<br>TENANT_ID = os.getenv(&quot;TENANT_ID&quot;)<br>CLIENT_ID = os.getenv(&quot;CLIENT_ID&quot;)<br>OBO_CLIENT_ID = os.getenv(&quot;OBO_CLIENT_ID&quot;)<br>OBO_CLIENT_SECRET = os.getenv(&quot;OBO_CLIENT_SECRET&quot;)<br>ISSUER = os.getenv(&quot;ISSUER&quot;)<br><br>if AUTH_ENABLED:<br>    bearer_auth = JWTVerifier(<br>            jwks_uri=f&quot;https://login.microsoftonline.com/{TENANT_ID}/discovery/v2.0/keys&quot;,<br>            issuer=ISSUER,<br>        )<br>    mcp = FastMCP(&quot;MCP Server with AUTH&quot;, auth=bearer_auth)<br>    mcp.add_middleware(ErrorHandlingMiddleware(include_traceback=True, transform_errors=True))<br>    if MIDDLEWARE_ENABLED:<br>        mcp.add_middleware(AuthorizationMiddleware(auth_context))<br>else:<br>    mcp = FastMCP(&quot;MCP Server without Auth&quot;)<br>    mcp.add_middleware(ErrorHandlingMiddleware(include_traceback=True, transform_errors=True))<br><br><br># ========== OBO Exchange Logic ==========<br>async def exchange_token(original_token: str, scope: str) -&gt; dict:<br>    obo_url = f&quot;https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token&quot;<br>    data = {<br>        &quot;grant_type&quot;: &quot;urn:ietf:params:oauth:grant-type:jwt-bearer&quot;,<br>        &quot;client_id&quot;: OBO_CLIENT_ID,<br>        &quot;client_secret&quot;: OBO_CLIENT_SECRET,<br>        &quot;assertion&quot;: original_token,<br>        &quot;scope&quot;: scope,<br>        &quot;requested_token_use&quot;: &quot;on_behalf_of&quot;,<br>    }<br>    try:<br>        response = requests.post(obo_url, data=data)<br>        if response.status_code == 200:<br>            return {&quot;success&quot;: True, &quot;access_token&quot;: response.json()[&quot;access_token&quot;]}<br>        return {&quot;success&quot;: False, &quot;error&quot;: response.text}<br>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}<br><br><br># ========== TOOL IMPLEMENTATION ==========  <br>@mcp.tool(tags={&quot;write&quot;})<br>async def test_write_tool() -&gt; dict:<br>    ## Explicit Tool level validation using app roles<br>    if AUTH_ENABLED:<br>        access_token: AccessToken = get_access_token()<br>        token_info = jwt.decode(access_token.token, options={&quot;verify_signature&quot;: False})<br>        role_access = any(<br>            role<br>            for role in token_info.get(&quot;roles&quot;, [])<br>            if role in (&quot;Task.All&quot;, &quot;Task.Write&quot;)<br>        )<br>        if not role_access:<br>            return {<br>                &quot;error&quot;: &quot;Access denied. You do not have permission to call this tool.&quot;<br>            }<br>    return {&quot;message&quot;: &quot;This is a write test tool response&quot;}<br><br>@mcp.tool(tags={&quot;read&quot;})<br>async def check_sharepoint_site_access(site_name: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Check if the user has access to a specific SharePoint site using Microsoft Graph.<br>    &quot;&quot;&quot;<br>    if not AUTH_ENABLED:<br>        return &quot;Authentication must be enabled.&quot;<br><br>    # Step 1: Get user token from request<br>    access_token: AccessToken = get_access_token()<br>    original_token = access_token.token<br><br>    # Step 2: Perform OBO token exchange<br>    graph_result = await exchange_token(<br>        original_token, scope=&quot;https://graph.microsoft.com/.default&quot;<br>    )<br>    if not graph_result[&quot;success&quot;]:<br>        return &quot;Token exchange failed.&quot;<br><br>    obo_token = graph_result[&quot;access_token&quot;]<br>    url = f&quot;https://graph.microsoft.com/v1.0/sites/riotinto.sharepoint.com:/sites/{site_name}&quot;<br>    headers = {&quot;Authorization&quot;: f&quot;Bearer {obo_token}&quot;}<br><br>    # Step 3: Make Graph API call<br>    response = requests.get(url, headers=headers)<br>    if response.status_code == 200:<br>        return f&quot;✅ Access granted to site: {site_name}&quot;<br>    elif response.status_code in [403, 404]:<br>        return f&quot;❌ Access denied to site: {site_name}&quot;<br>    else:<br>        return f&quot;⚠️ Error: {response.status_code}&quot;<br><br><br># ========== SERVER ENTRYPOINT ==========<br>def main():<br>    try:<br>        mcp.run(<br>            transport=&quot;streamable-http&quot;,<br>            host=&quot;0.0.0.0&quot;,<br>            port=8400,<br>        )<br>    except Exception as e:<br>        logging.error(f&quot;Server failed to start: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>I have also included the corresponding <strong>client implementation</strong> which:</p><ul><li>Authenticates the user using Authorization Code Flow via ConfidentialClientApplication</li><li>Starts a local HTTP server to receive the auth code</li><li>Acquires a token for the backend API (access_as_user scope)</li><li>Sends that token while invoking tools, including the Graph-connected one</li></ul><p><em>Below is full client code with browser login and tool</em></p><pre>import asyncio<br>import json<br>import logging<br>import os<br>import jwt<br>import sys<br>import threading<br>from http.server import BaseHTTPRequestHandler, HTTPServer<br>from urllib.parse import urlparse, parse_qs<br>import webbrowser<br><br>from dotenv import load_dotenv<br>from msal import ConfidentialClientApplication, SerializableTokenCache<br><br>from fastmcp.client import Client as MCPClient<br>from fastmcp.client.transports import StreamableHttpTransport<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(&quot;mcp-client-confidential&quot;)<br><br>load_dotenv(&quot;../servers/.env&quot;)<br><br># =========================<br># CONFIGURATION<br># =========================<br>TENANT_ID = os.getenv(&quot;TENANT_ID&quot;, &quot;&quot;).strip()<br>CLIENT_ID = os.getenv(&quot;CLIENT_ID&quot;, &quot;&quot;).strip()<br>CLIENT_SECRET = os.getenv(&quot;CLIENT_SECRET&quot;, &quot;&quot;).strip()<br>API_A_SCOPE = os.getenv(&quot;API_A_SCOPE&quot;, &quot;&quot;).strip()  # e.g., api://&lt;OBO_CLIENT_ID&gt;/access_as_user<br>AUTHORITY = f&quot;https://login.microsoftonline.com/{TENANT_ID}&quot;<br>REDIRECT_URI = os.getenv(&quot;REDIRECT_URI&quot;, &quot;http://localhost:8100/auth/callback&quot;).strip()<br>MCP_URL = os.getenv(&quot;MCP_URL&quot;, &quot;http://localhost:8400/mcp/&quot;).strip()<br>CACHE_PATH = os.getenv(&quot;MSAL_CACHE_PATH&quot;, &quot;.msal_token_cache.bin&quot;).strip()<br>AUTH_ENABLED = os.getenv(&quot;AUTH_ENABLED&quot;, &quot;false&quot;).lower() == &quot;true&quot;<br><br><br># =========================<br># LOCAL HTTP LISTENER<br># =========================<br>class _AuthCodeHandler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        parsed = urlparse(self.path)<br>        params = parse_qs(parsed.query)<br>        self.server.auth_code = params.get(&quot;code&quot;, [None])[0]<br>        self.send_response(200)<br>        self.end_headers()<br>        self.wfile.write(b&quot;You can now close this window.&quot;)<br><br><br>def _start_local_server(port):<br>    server = HTTPServer((&quot;localhost&quot;, port), _AuthCodeHandler)<br>    server.auth_code = None<br>    return server<br><br><br>def decode_token_info(token: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Decode token to show basic info (without verification)<br>    &quot;&quot;&quot;<br>    try:<br>        decoded = jwt.decode(token, options={&quot;verify_signature&quot;: False})<br>        return {<br>            &quot;audience&quot;: decoded.get(&quot;aud&quot;),<br>            &quot;issuer&quot;: decoded.get(&quot;iss&quot;),<br>            &quot;subject&quot;: decoded.get(&quot;sub&quot;),<br>            &quot;user_id&quot;: decoded.get(&quot;oid&quot;),<br>            &quot;preferred_username&quot;: decoded.get(&quot;upn&quot;),<br>            &quot;name&quot;: decoded.get(&quot;name&quot;),<br>            &quot;scopes&quot;: decoded.get(&quot;scp&quot;),<br>            &quot;expires&quot;: decoded.get(&quot;exp&quot;),<br>            &quot;roles&quot;: decoded.get(&quot;roles&quot;),<br>            &quot;app_id&quot;: decoded.get(&quot;appid&quot;),<br>        }<br>    except Exception as e:<br>        return {&quot;error&quot;: str(e)}<br><br><br># =========================<br># TOKEN ACQUISITION<br># =========================<br>def acquire_user_token():<br>    if not all([TENANT_ID, CLIENT_ID, CLIENT_SECRET, API_A_SCOPE]):<br>        raise RuntimeError(&quot;Missing required environment variables.&quot;)<br><br>    scopes = [API_A_SCOPE]<br>    cache = SerializableTokenCache()<br>    if os.path.exists(CACHE_PATH):<br>        try:<br>            cache.deserialize(open(CACHE_PATH, &quot;r&quot;).read())<br>        except Exception:<br>            logger.warning(&quot;Failed to deserialize cache. Starting fresh.&quot;)<br><br>    app = ConfidentialClientApplication(<br>        client_id=CLIENT_ID,<br>        client_credential=CLIENT_SECRET,<br>        authority=AUTHORITY,<br>        token_cache=cache,<br>    )<br><br>    accounts = app.get_accounts()<br>    result = None<br>    if accounts:<br>        result = app.acquire_token_silent(scopes, account=accounts[0])<br><br>    if not result:<br>        # Auth Code Flow<br>        port = urlparse(REDIRECT_URI).port or 8100<br>        server = _start_local_server(port)<br>        auth_url = app.get_authorization_request_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20scopes=scopes,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20redirect_uri=REDIRECT_URI,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20prompt=&quot;select_account&quot;,%3Cbr%3E)<br>        logger.info(f&quot;Open your browser: {auth_url}&quot;)<br>        webbrowser.open(auth_url)<br><br>        thread = threading.Thread(target=server.handle_request)<br>        thread.start()<br>        thread.join(timeout=300)<br><br>        if not server.auth_code:<br>            raise RuntimeError(&quot;Auth code not received.&quot;)<br><br>        result = app.acquire_token_by_authorization_code(<br>            code=server.auth_code,<br>            scopes=scopes,<br>            redirect_uri=REDIRECT_URI,<br>        )<br>    access_token = result.get(&quot;access_token&quot;)<br>    if not access_token:<br>        raise RuntimeError(f&quot;Token acquisition failed: {json.dumps(result, indent=2)}&quot;)<br><br>    # Optional: print user details<br>    id_token_claims = result.get(&quot;id_token_claims&quot;, {})<br>    id_token = id_token_claims if id_token_claims else decode_token_info(access_token)<br>    logger.info(<br>        f&quot;User signed in: {id_token.get(&#39;name&#39;)} ({id_token.get(&#39;preferred_username&#39;)})&quot;<br>    )<br><br>    with open(CACHE_PATH, &quot;w&quot;) as f:<br>        f.write(cache.serialize())<br>    return access_token<br><br><br># =========================<br># MCP CLIENT<br># =========================<br>async def run_client():<br>    headers = None<br>    if AUTH_ENABLED:<br>        token = acquire_user_token()<br>        headers = {&quot;Authorization&quot;: f&quot;Bearer {token}&quot;}<br><br>    client = MCPClient(transport=StreamableHttpTransport(url=MCP_URL, headers=headers))<br>    try:<br>        logger.info(&quot;Connecting to MCP server...&quot;)<br>        logger.info(f&quot;Client Connection: {client.is_connected()}&quot;)<br>        async with client:<br>            tools = await client.list_tools()<br>            logger.info(f&quot;Found {len(tools)} tools&quot;)<br><br>            result = await client.call_tool(&quot;test_write_tool&quot;)<br>            logger.info(f&quot;Test Write Tool Response: {result}&quot;)<br><br>            # OBO Example<br>            graph_result = await client.call_tool(<br>                &quot;check_sharepoint_site_access&quot;, {&quot;site_name&quot;: &quot;test-site&quot;}<br>            )<br>            logger.info(graph_result)<br><br>    except Exception as e:<br>        logger.error(f&quot;Client error: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        asyncio.run(run_client())<br>    except KeyboardInterrupt:<br>        sys.exit(0)</pre><h3>Best Practices</h3><ul><li><strong>Secure Your Secrets</strong><br> Use Azure Key Vault or a secure secrets manager to store client_id and client_secret. Avoid hardcoding credentials in your codebase.</li><li><strong>Use Short-Lived Tokens</strong><br> OBO tokens are short-lived by design. Avoid caching them long-term; perform token exchange per tool execution.</li><li><strong>Apply Principle of Least Privilege</strong><br> Only request the delegated Microsoft Graph permissions your tools require. For example, Sites.Read.All for SharePoint access. Avoid over-permissioning your app.</li><li><strong>Validate Tokens Server-Side</strong><br> Always validate tokens for issuer, audience, and expiration. FastMCP’s built-in bearer auth provider takes care of this when configured properly.</li><li><strong>Log Tool Usage and API Calls</strong><br> For audit and traceability, log who invoked each tool and whether external APIs were called especially for write/delete actions.</li></ul><h3>Summary</h3><ul><li><strong>Tier-1 Security (App Roles + Token Verification)</strong><br> Controls <em>what tools</em> a user can see and invoke based on assigned roles.</li><li><strong>Tier-2 Security (OBO Pattern)</strong><br> Ensures the tool’s <em>runtime actions</em> reflect the user’s real permissions on downstream systems like Microsoft Graph or Azure DevOps.</li></ul><p>This layered security model brings <strong>visibility control</strong>, <strong>runtime enforcement</strong>, and <strong>traceability</strong> — making your mcp tools more secure and enterprise-ready.</p><h3>Reference Documents</h3><ul><li><a href="https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-on-behalf-of-flow">Microsoft identity platform and OAuth2.0 On-Behalf-Of flow — Microsoft identity platform | Microsoft Learn</a></li><li><a href="https://gofastmcp.com/servers/middleware">MCP Middleware — FastMCP</a></li><li><a href="https://gofastmcp.com/servers/auth/token-verification">Token Verification — FastMCP</a></li><li><a href="https://gofastmcp.com/clients/auth/bearer">Bearer Token Authentication — FastMCP</a></li></ul><p><em>👋 Happy reading and feel free to share your feedback or questions!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b1ada1e505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing MCP Servers with Azure AD and JWT-based Role Authorization]]></title>
            <link>https://medium.com/@khansaima/securing-mcp-servers-with-azure-ad-and-jwt-based-role-authorization-d8c8aeadb7f5?source=rss-2b5cea454596------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8c8aeadb7f5</guid>
            <dc:creator><![CDATA[Saima Khan]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 05:54:46 GMT</pubDate>
            <atom:updated>2025-09-12T10:09:27.846Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>New to FastMCP? Start with these earlier posts:</em></blockquote><blockquote><a href="https://medium.com/@khansaima/from-monolith-to-modular-part-1-understanding-mcp-for-modern-ai-applications-c367036c1c5e">From Monolith to Modular (Part 1): Understanding MCP for Modern AI Applications</a></blockquote><blockquote><a href="https://medium.com/@khansaima/from-monolith-to-modular-part-2-how-i-integrated-mcp-using-fastmcp-and-langgraph-d4f29ab825e1">From Monolith to Modular (Part 2): How I Integrated MCP Using FastMCP and LangGraph</a></blockquote><p>This post explains how to configure authentication and authorization for a <strong>FastMCP Server</strong> using <strong>Azure AD</strong>, <strong>JWT tokens</strong>, and <strong>custom middleware</strong> for fine-grained <strong>role-based access control (RBAC)</strong> all demonstrated through a weather-based test server example.</p><h3>A Note on Approaches to Securing MCP</h3><p>There are two primary approaches for securing FastMCP workflows: a strong <strong>first-tier layer based on Azure App Roles</strong>, and an optional <strong>second-tier layer using delegated access via On-Behalf-Of (OBO) flow</strong>.</p><h3>Tier 1 — App Role-Based Access Control (Recommended Baseline)</h3><p>This post focuses on Tier 1, which uses <strong>Azure AD App Roles</strong> to control access at the <strong>MCP Server level</strong>. It acts as a gatekeeper — restricting which tools, resources, or prompts a user is even allowed to see based on their assigned roles.</p><p><strong><em>Why Tier 1 is critical:</em></strong></p><ul><li>It hides high-risk tools (e.g., delete, truncate, shutdown) from users who shouldn’t even know they exist.</li><li>Prevents accidental or irreversible actions in sensitive systems (e.g., deleting IP ranges in IPAM) before they happen.</li><li>Protects weakly secured downstream systems by never exposing risky operations at all.</li><li>Serves as a <strong>default safeguard</strong> — ensuring dangerous tools are disabled unless explicitly approved.</li></ul><p>You can also use this layer to <strong>withhold destructive tools</strong> until a rollback mechanism (like restore or undo) tool is available. This is especially useful for critical domains like network, infrastructure, or production control.</p><h3>Tier 2 — API-Level Restrictions with OBO</h3><p>In more advanced use cases, you can complement Tier 1 with <strong>runtime-level API permission checks</strong> inside the tools themselves. This is done using the <strong>On-Behalf-Of (OBO)</strong> pattern — a delegated flow that enables your MCP tool to call external APIs using the user’s identity.</p><p><em>This is ideal when:</em></p><ul><li>Your tools call cloud services like Azure DevOps, Microsoft Graph, or Azure Cognitive Search etc.</li><li>You want to validate not just tool visibility, but real-time permission to take an action (e.g., read/write PRs, access private indexes).</li></ul><p>In this pattern:</p><ul><li>The user logs in and receives a token.</li><li>Your MCP Server exchanges it for a downstream-access token via OBO.</li><li>Tool execution is allowed only if the downstream system grants access.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXi6giql0QFnC57cSr7z0w.png" /><figcaption>2 tier security approach</figcaption></figure><p><strong>TL;DR:</strong> Always implement <strong>Tier 1</strong> to avoid unintended exposure and give you control over what enters the system. Use <strong>Tier 2</strong> to fine-tune permissions at execution time when interacting with external APIs.</p><p>Both layers are valuable — but <strong>Tier 1 is essential.</strong></p><h3>Why Token Verification Over Remote OAuth</h3><p><a href="https://gofastmcp.com/">FastMCP</a> provides several auth mechanisms, including <a href="https://gofastmcp.com/servers/auth/remote-oauth">Remote OAuth</a> and <a href="https://gofastmcp.com/servers/auth/token-verification"><strong>Token Verification</strong></a>. While <strong>Remote OAuth</strong> supports integrations like WorkOS, it requires <strong>Dynamic Client Registration (DCR)</strong> — something <strong>Azure AD (Entra ID)</strong> does not support natively (<a href="https://learn.microsoft.com/en-us/answers/questions/1328487/does-azure-ad-supports-dynamic-client-registration">Does Azure AD supports Dynamic Client Registration? — Microsoft Q&amp;A</a>).</p><p>In contrast, Azure AD requires pre-registration of applications and static configuration of client IDs and secrets. This makes it incompatible with OAuth flows that expect clients to dynamically register themselves at runtime.</p><p>So instead of Remote OAuth, we use the <strong>Token Verification</strong> method, which works perfectly with Azure App Registrations. MCP validates pre-issued JWTs via the public keys exposed at Azure’s OpenID configuration endpoint.</p><h3>High-Level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZtzcehPh8eMDn-P8MVfzw.png" /></figure><h3>Azure App Registration Setup</h3><p>To configure your MCP Server with Azure AD authentication and role-based access control, follow these steps:</p><ol><li><strong>Register your application</strong> in <a href="https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app">Azure Portal.</a></li></ol><ul><li>Click “+ New Registration”</li><li>Choose a name and set the redirect URI (e.g. <a href="http://localhost:8000/auth/callback)">http://localhost:8000/auth/callback)</a></li></ul><p>2. In the <strong>Authentication</strong> blade:</p><ul><li>Enable the <strong>ID tokens</strong> checkbox under “Implicit grant and hybrid flows”</li><li>Confirm your <strong>redirect URI</strong> is correctly added</li></ul><p>3. Go to <strong>App Roles</strong> under “Manifest” or “App Roles” blade (if visible):</p><ul><li>Define custom roles like:</li></ul><pre>{<br>  &quot;allowedMemberTypes&quot;: [&quot;User&quot;],<br>  &quot;displayName&quot;: &quot;Task Read Access&quot;,<br>  &quot;id&quot;: &quot;...&quot;,<br>  &quot;isEnabled&quot;: true,<br>  &quot;description&quot;: &quot;Allows reading tools&quot;,<br>  &quot;value&quot;: &quot;Task.Read&quot;<br>}</pre><ul><li>Repeat for roles such as Task.Write and Task.All</li><li>Microsoft Docs: <a href="https://learn.microsoft.com/en-us/entra/identity-platform/howto-add-app-roles-in-apps">Define app roles</a></li></ul><p><strong>4. Assign users or groups</strong> to the app roles:</p><p>Go to <strong>Enterprise Applications</strong> &gt; Your App &gt; <strong>Users and Groups</strong> &gt; “+ Add User”</p><ul><li>Choose the appropriate role per user or group</li><li>Microsoft Docs: <a href="https://learn.microsoft.com/en-us/entra/identity-platform/howto-add-app-roles-in-apps#assign-users-and-groups-to-app-roles">Assign users and groups to roles</a></li></ul><p>5. The JWT issued by Azure will include these roles in the roles claim, which are later used in middleware for access filtering (<a href="https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference">Token Reference</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G619H1Cny3by9R4BTfEoPg.png" /></figure><h3>Auth Flow in Code (FastAPI + MSAL + Redis)</h3><p><strong>Directory Structure Tip:</strong> To keep the project clean and modular, we split out reusable components into a shared/ folder:</p><pre>project-root/<br>├── shared/<br>│   ├── auth_context.py              # Azure AD + MSAL integration<br>│   ├── redis_token_store.py        # Token + auth code management<br>│   └── middleware/<br>│       └── authorization_middleware.py  # Custom FastMCP RBAC enforcement</pre><p>To support the login and token handling flow, we built two core components:</p><h4>RedisTokenStore — Lightweight Token Manager</h4><p>Handles token storage and one-time code management using Azure Redis:</p><pre>import redis<br>import json<br>import time<br>from typing import Optional<br><br>class RedisTokenStore:<br>    def __init__(self, host, port, password, ssl=True, prefix=&quot;token&quot;):<br>        self.client = redis.Redis(host=host, port=port, password=password, ssl=ssl, ssl_cert_reqs=None)<br>        self.prefix = prefix<br><br>    def _make_key(self, user_oid):<br>        return f&quot;{self.prefix}:{user_oid}&quot;<br><br>    def _make_authcode_key(self, auth_code):<br>        return f&quot;authcode:{auth_code}&quot;<br><br>    def save_token(self, user_oid, token_data):<br>        key = self._make_key(user_oid)<br>        ttl = int(token_data.get(&quot;expires_at&quot;, time.time() + 3600) - time.time())<br>        self.client.set(key, json.dumps(token_data), ex=ttl)<br><br>    def load_token(self, user_oid) -&gt; Optional[dict]:<br>        val = self.client.get(self._make_key(user_oid))<br>        return json.loads(val) if val else None<br><br>    def set_auth_code(self, auth_code, user_oid, ttl=120):<br>        self.client.setex(self._make_authcode_key(auth_code), ttl, user_oid)<br><br>    def get_auth_code(self, auth_code) -&gt; Optional[str]:<br>        val = self.client.get(self._make_authcode_key(auth_code))<br>        return val.decode() if val else None<br><br>    def delete_auth_code(self, auth_code):<br>        self.client.delete(self._make_authcode_key(auth_code))</pre><h4>AuthContext — Azure AD Auth Helper</h4><p>Encapsulates MSAL setup and JWT verification for MCP:</p><pre>import time<br>from msal import ConfidentialClientApplication<br>from fastmcp.server.auth.providers.jwt import JWTVerifier<br><br>class AuthContext:<br>    def __init__(self, tenant_id, client_id, client_secret):<br>        self.tenant_id = tenant_id<br>        self.client_id = client_id<br>        self.client_secret = client_secret<br>        self.scope = [f&quot;api://{client_id}/access_as_user&quot;]<br>        self.authority = f&quot;https://login.microsoftonline.com/{tenant_id}&quot;<br><br>        self.msal_app = ConfidentialClientApplication(<br>            client_id=client_id,<br>            client_credential=client_secret,<br>            authority=self.authority<br>        )<br><br>        self.bearer_auth = JWTVerifier(<br>            jwks_uri=f&quot;https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys&quot;,<br>            issuer=f&quot;https://sts.windows.net/{tenant_id}/&quot;,<br>            audience=f&quot;api://{client_id}&quot;<br>        )<br><br>    def get_token_data(self, result: dict) -&gt; dict:<br>        return {<br>            &quot;access_token&quot;: result.get(&quot;access_token&quot;),<br>            &quot;refresh_token&quot;: result.get(&quot;refresh_token&quot;),<br>            &quot;expires_at&quot;: time.time() + result.get(&quot;expires_in&quot;, 3600),<br>            &quot;id_token_claims&quot;: result.get(&quot;id_token_claims&quot;)</pre><p>This section explains how we built a secure login flow that keeps tokens off the browser and enables server-side validation and refresh. Each stage of the login and token retrieval is broken down into dedicated endpoints, using MSAL for OAuth and Redis for session storage.</p><h4>Initiate Login</h4><p>This endpoint starts the MSAL authorization code flow by generating an auth URI and redirecting the user to Microsoft’s login page.</p><pre>@app.get(&quot;/auth/login&quot;)<br>def login():<br>    flow = auth_context.msal_app.initiate_auth_code_flow(<br>        scopes=auth_context.scope,<br>        redirect_uri=REDIRECT_URI<br>    )<br>    flow_store[flow[&quot;state&quot;]] = flow<br>    return RedirectResponse(flow[&quot;auth_uri&quot;])</pre><h4><strong>Callback + Store Token</strong></h4><p>This callback endpoint receives the authorization code from Microsoft, exchanges it for tokens, and stores them in Redis against the user’s oid.</p><pre>@app.get(&quot;/auth/callback&quot;)<br>def callback(request: Request):<br>    result = auth_context.msal_app.acquire_token_by_auth_code_flow(flow, dict(request.query_params))<br>    oid = result[&quot;id_token_claims&quot;][&quot;oid&quot;]<br>    redis_token_store.save_token(oid, {<br>        &quot;access_token&quot;: result[&quot;access_token&quot;],<br>        &quot;refresh_token&quot;: result.get(&quot;refresh_token&quot;),<br>        &quot;expires_at&quot;: time.time() + result.get(&quot;expires_in&quot;, 3600),<br>        &quot;id_token_claims&quot;: result.get(&quot;id_token_claims&quot;)<br>    })<br>    auth_code = str(uuid.uuid4())<br>    redis_token_store.set_auth_code(auth_code, oid, 120)<br>    return HTMLResponse(f&quot;Login successful. Use this code to exchange for token: &lt;pre&gt;{auth_code}&lt;/pre&gt;&quot;)</pre><h4>Token Exchange (Backend-safe)</h4><p>This endpoint allows clients to exchange a one-time auth code for access and refresh tokens, keeping credentials off the browser.</p><pre>@app.post(&quot;/auth/exchange&quot;)<br>def exchange_auth_code(payload: dict):<br>    auth_code = payload.get(&quot;auth_code&quot;)<br>    user_oid = redis_token_store.get_auth_code(auth_code)<br>    token_data = redis_token_store.load_token(user_oid)<br>    redis_token_store.delete_auth_code(auth_code)<br>    return token_data</pre><h3>Example MCP Server with Secure Tools</h3><pre>from fastapi import FastAPI<br>from fastmcp import FastMCP<br>from shared.auth_context import AuthContext  # helper class to configure Azure App Registration, MSAL, and JWT verifier<br>from shared.redis_token_store import RedisTokenStore  # handles secure token and auth code storage via Redis<br>from shared.middleware.authorization_middleware import AuthorizationMiddleware  # custom FastMCP middleware for enforcing RBAC<br><br># --- Setup Auth + Token Store ---<br>auth_context = AuthContext(<br>    tenant_id=&quot;&lt;TENANT_ID&gt;&quot;,<br>    client_id=&quot;&lt;CLIENT_ID&gt;&quot;,<br>    client_secret=&quot;&lt;CLIENT_SECRET&gt;&quot;<br>)<br><br>redis_token_store = RedisTokenStore(<br>    host=&quot;&lt;REDIS_HOST&gt;&quot;,<br>    port=6380,<br>    password=&quot;&lt;REDIS_PASSWORD&gt;&quot;,<br>    ssl=True<br>)<br><br># --- Configure MCP ---<br>mcp = FastMCP(&quot;Test Weather MCP Server&quot;, auth=auth_context.bearer_auth)<br>mcp.add_middleware(AuthorizationMiddleware(auth_context, redis_token_store))<br><br>@mcp.tool(tags={&quot;read&quot;})<br>def get_weather(city: str) -&gt; str: ...<br><br>@mcp.tool(tags={&quot;write&quot;})<br>def get_alerts(state: str) -&gt; str: ...<br><br><br># --- Mount MCP Server ---<br>app = FastAPI()<br>app.mount(&quot;/weather-mcp&quot;, mcp.http_app())<br><br># 🔐 Also include the auth routes from earlier:<br># - /auth/login → Initiates the MSAL login flow<br># - /auth/callback → Handles the redirect from Azure and stores tokens<br># - /auth/exchange → Allows secure token exchange using a one-time code<br><br>@app.get(&quot;/health&quot;, tags=[&quot;Health&quot;])<br>def health_check():<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p><strong><em>Each tool is tagged (</em></strong><strong><em>read, </em></strong><strong><em>write) - our middleware will use these tags to enforce access control.</em></strong></p><h3>Authorization Middleware Logic</h3><p>FastMCP middleware is protocol-aware and allows developers to hook into the lifecycle of messages exchanged between clients and tools. Instead of operating purely at the HTTP layer, FastMCP middleware can intercept protocol-level events such as tool calls, prompt reads, and message dispatching.</p><p><strong>Official Docs Reference:</strong> <a href="https://gofastmcp.com/servers/middleware">FastMCP Middleware Documentation</a></p><p>A middleware class can implement any of the following lifecycle hooks:</p><ul><li>on_message: all messages (requests + notifications)</li><li>on_request: only request-type messages</li><li>on_call_tool: just before a tool is executed</li><li>on_list_tools: when a client requests available tools (ideal for role filtering)</li><li>on_get_prompt / on_read_resource: for filtering prompt/resource access</li></ul><h3>Execution Flow (Top-Down Order)</h3><p>When a message reaches the MCP server, middleware hooks execute in this rough order:</p><ol><li>on_message → catch-all</li><li>on_request → request-specific messages</li><li>Specialized hooks like on_list_tools, on_call_tool, etc.</li></ol><p>In our implementation, we created a custom AuthorizationMiddleware to:</p><ol><li><strong>Parse JWT tokens</strong> in on_request to get user roles and identity.</li><li><strong>Filter tools</strong> in on_list_tools so users only see what&#39;s allowed.</li><li><strong>Optionally audit tool usage</strong> in on_call_tool.</li></ol><p><em>Full code of Authorization Middleware</em></p><pre>from fastmcp.server.middleware import Middleware, MiddlewareContext<br>from fastmcp.exceptions import ToolError<br>from starlette.requests import Request<br>from fastmcp.server.dependencies import get_access_token, AccessToken, get_http_request, get_http_headers<br>import jwt<br><br>class AuthorizationMiddleware(Middleware):<br>    def __init__(self, auth_context, redis_token_store=None):<br>        self.auth_context = auth_context<br>        self.redis_token_store = redis_token_store<br><br>    async def on_request(self, context: MiddlewareContext, call_next):<br>        access_token: AccessToken = get_access_token().token<br>        self.claims = jwt.decode(access_token, options={&quot;verify_signature&quot;: False})<br>        self.roles = self.claims.get(&#39;roles&#39;)<br>        self.user_id = self.claims.get(&#39;upn&#39;)<br>        self.oid = self.claims.get(&#39;oid&#39;)<br>        return await call_next(context)<br><br>    async def on_list_tools(self, context: MiddlewareContext, call_next):<br>        result = await call_next(context)<br>        filtered_tools = []<br>        for role in self.roles:<br>            if role == &#39;Task.Write&#39;:<br>                filtered_tools.extend([t for t in result if &quot;write&quot; in t.tags])<br>            if role == &#39;Task.Read&#39;:<br>                filtered_tools.extend([t for t in result if &quot;read&quot; in t.tags])<br>            if role == &#39;Task.All&#39;:<br>                filtered_tools = result<br><br>        available_tool_names = [tool.name for tool in filtered_tools]<br><br>        if context.fastmcp_context:<br>            try:<br>                tool_manager = context.fastmcp_context.fastmcp._tool_manager<br>                for tool in result:<br>                    if tool.name not in available_tool_names:<br>                        tool_manager.remove_tool(tool.name)<br>            except Exception as e:<br>                print(f&quot;Tool manager sync error: {str(e)}&quot;)<br>        return filtered_tools<br><br>    async def on_call_tool(self, context: MiddlewareContext, call_next):<br>        if context.fastmcp_context:<br>            try:<br>                tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)<br>                print(f&quot;Calling tool: {tool.name} with args: {context.message.args}&quot;)<br>            except Exception:<br>                pass<br>        return await call_next(context)</pre><h4>Role-Based Tool Filtering</h4><p>The <strong>on_list_tools</strong> method is responsible for filtering what tools a user can see in the MCP interface. Based on the roles embedded in the decoded JWT token, it compares each tool&#39;s tags to the allowed access levels and builds a filtered list accordingly.</p><p>This method intercepts the tool listing phase and limits visibility based on the user’s Azure App Role.</p><h4>Optional Tool Manager Sync</h4><p>This extra step is not required by FastMCP but is useful if you want to proactively remove tools from the runtime registry so unauthorized tools aren’t accidentally invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9QIs2lSluS0Yn41sB1unw.png" /></figure><h3>Sample Client Code</h3><p>Here’s an example of listing tools, with error handling:</p><p><strong>Once your server is running and protected with Azure AD + JWT, here’s how a client can authenticate and fetch available tools:</strong></p><pre>from fastmcp import Client<br>from fastmcp.client.transports import StreamableHttpTransport<br><br># Assuming you have obtained a valid bearer token via /auth/exchange<br>token = get_valid_token()<br><br>client = Client(StreamableHttpTransport(<br>    &quot;http://localhost:8000/weather-mcp/mcp/&quot;,<br>    auth=token<br>))<br><br>async def test():<br>    try:<br>        async with client:<br>            result = await client.list_tools()<br>            if not result:<br>                print(&quot;No tools available for this user.&quot;)<br>            for tool in result:<br>                print(tool.name)<br>    except Exception as e:<br>        print(f&quot;Failed to list tools: {e}&quot;)<br><br>await test()Example Output</pre><p>Based on the roles embedded in your JWT token, the list of tools returned might vary.</p><h4>For a user with Task.Read:</h4><pre>get_weather</pre><h4>For a user with Task.Write:</h4><pre>get_alerts</pre><h4>For a user with Task.All:</h4><pre>get_weather<br>get_alerts</pre><p>If a user has no matching roles, the tool list will be empty and optionally logged by the server depending on your AuthorizationMiddleware setup.</p><p><strong>Snippet of a run where my user has<em> Read only access</em>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-BCfqdvfSE1xxFB1uFI8g.png" /></figure><h3>Reference Documents</h3><p>Here are all the key references used in this post:</p><ul><li><a href="https://gofastmcp.com/servers/auth/token-verification">FastMCP Token Verification</a></li><li><a href="https://gofastmcp.com/servers/middleware">FastMCP Middleware System</a></li><li><a href="https://gofastmcp.com/servers/auth/remote-oauth">FastMCP Remote OAuth</a></li><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app">Microsoft: Register an App</a></li><li><a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps">Microsoft: Add App Roles</a></li><li><a href="https://learn.microsoft.com/en-us/answers/questions/1328487/does-azure-ad-supports-dynamic-client-registration">Microsoft Q&amp;A: Azure AD and DCR</a></li></ul><h3>Wrapping Up</h3><p>You’ve now seen how to secure a FastMCP Server using Azure AD and JWTs, while applying middleware-based authorization to tailor access per user role.</p><p><strong>What you achieved:</strong><br>- 🛡️ Secured authentication using Azure AD and bearer tokens<br>- 🔁 Managed access and refresh tokens with Redis and MSAL<br>- ⚙️ Enforced RBAC using FastMCP’s middleware framework<br>- 🧪 Validated access through Python client examples</p><p><strong>Next steps:</strong><br>- Enforce role checks in `call_tool`, `get_prompt`, etc.<br>- Add token expiry/refresh logic to clients<br>- Wrap into a CI/CD pipeline for production usage</p><p>Happy building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8c8aeadb7f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolith to Modular (Part 2): How I Integrated MCP Using FastMCP and LangGraph]]></title>
            <link>https://medium.com/@khansaima/from-monolith-to-modular-part-2-how-i-integrated-mcp-using-fastmcp-and-langgraph-d4f29ab825e1?source=rss-2b5cea454596------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f29ab825e1</guid>
            <dc:creator><![CDATA[Saima Khan]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 08:48:51 GMT</pubDate>
            <atom:updated>2025-07-11T08:48:51.314Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous <a href="https://medium.com/@khansaima/from-monolith-to-modular-part-1-understanding-mcp-for-modern-ai-applications-c367036c1c5e">post</a>, I introduced the challenges of building scalable LLM applications using traditional monolithic architectures, and how the <strong>Model Context Protocol (MCP)</strong> helps solve them by enabling modular, reusable, and interoperable systems.</p><p>In this follow-up, I’ll walk through how I <strong>implemented a real-world Cyber PR Evaluation Workflow</strong> using a multi-agent system orchestrated by a <strong>LangGraph Supervisor Agent</strong>, with each agent interacting with its own <strong>MCP Server</strong> to access tools and prompts.</p><p>This post covers:</p><ol><li>What is the Cyber PR Evaluation Workflow?</li><li>Implementing the Workflow Using LangGraph (Without MCP Servers)</li><li>What Changes With MCP Servers?</li><li>Implementing MCP Servers with FastMCP</li><li>Hosting the MCP Servers in Azure App Service</li><li>Plugging MCP Servers into LangGraph Agents</li></ol><h3>What is the Cyber PR Evaluation Workflow?</h3><p>The Cyber PR Evaluation Workflow automates the review of pull requests (PRs) that propose changes to cloud networking policies — such as firewall or NSG rules. Traditionally, these PRs were manually reviewed by the Cyber team to ensure compliance with security standards, validate ServiceNow change request (CHG) numbers, and confirm proper justifications for high-risk changes like bidirectional rules.</p><p>This manual process was time-consuming and error-prone, often delaying merges.</p><p>With automation, the workflow is triggered whenever a PR is created. It uses <strong>LLMs guided by Cyber-defined policies</strong> to:</p><ul><li>Analyze the policy file changes</li><li>Check the PR title and description for valid CHG/SRA numbers</li><li>Cross-verify identifiers with ServiceNow</li><li>Post a detailed evaluation report as a PR comment, highlighting violations and recommendations</li></ul><p>The result is faster reviews, improved compliance, and reduced manual overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-y6f3wBcsHf7WaEEhbqZg.png" /><figcaption>Automated PR Evaluation Workflow using LLMs</figcaption></figure><h3>Implementing the Workflow Using LangGraph (Without MCP Servers)</h3><p>I used the <strong>LangGraph Supervisor Pattern</strong> to implement the Cyber PR Evaluation Workflow.</p><h4>What is LangGraph?</h4><p><a href="https://github.com/langchain-ai/langgraph"><strong>LangGraph</strong></a> is an open-source framework for building multi-agent workflows and stateful AI applications using <strong>graph-based orchestration</strong>. Unlike linear chains or single-agent flows, LangGraph enables developers to define complex, branching logic between agents — where each node in the graph represents an agent or tool, and edges define routing logic based on intermediate results or context.</p><h4>The Supervisor Pattern in LangGraph</h4><p>One of LangGraph’s most powerful patterns is the <strong>Supervisor Agent</strong>. Rather than hardcoding fixed sequences of execution, a central supervisor agent:</p><ul><li>Receives the user task or trigger</li><li>Evaluates current context or partial results</li><li>Determines which specialized agent to invoke next</li><li>Delegates the task and collects the response</li><li>Repeats the loop until the full workflow is complete</li></ul><p>This model is well-suited for workflows like Cyber PR Evaluation, where multiple validation steps — such as policy diff analysis, metadata checks, and ServiceNow validation — need to be handled dynamically and conditionally by different agents.</p><p>I will not be attaching code snippets for this pattern here, as our focus is primarily on the <strong>MCP-based modular implementation</strong>. However, for clarity and context, I’ve included the following architecture diagram to illustrate how the LangGraph-only version of the workflow operates without MCP Servers and code link for developing the supervisor pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VP17iTQ0FEVNROM_nuZgsA.png" /></figure><p>Supervisor Pattern: <a href="https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/#research-agent">Agent Supervisor</a></p><h3>What Changes With MCP?</h3><p>While the <strong>LangGraph Supervisor Pattern</strong> provides powerful orchestration for multi-agent workflows, the internal logic of each agent — including tools, prompts, and service integrations — still resides <strong>within the LangGraph application</strong>. This creates tightly coupled agents that are difficult to:</p><ul><li>Reuse across different workflows or teams</li><li>Test and update independently</li><li>Maintain consistent input/output schemas</li><li>Separate model logic from infrastructure access</li></ul><p>This is where the <strong>Model Context Protocol (MCP)</strong> transforms the architecture.</p><p>With MCP:</p><ul><li>Tools and prompts are hosted externally as <strong>MCP Servers</strong> — lightweight, schema-driven services</li><li>LangGraph agents become <strong>MCP Clients</strong>, invoking tools through the langchain-mcp-adapters library</li><li>The entire workflow evolves into a <strong>modular client-server architecture</strong>, where capabilities can be plugged in, updated, and reused independently</li></ul><h4>Before vs. After: Azure DevOps Agent Example</h4><p>The diagram below compares how <strong>Azure DevOps agents</strong> are implemented with and without MCP.</p><ul><li>On the <strong>left</strong>, each agent contains its own embedded tools and prompts, tightly bound to the LangGraph graph. Any new agent or tool requires code duplication and workflow updates.</li><li>On the <strong>right</strong>, all DevOps-related tools and prompts are externalized in a dedicated <strong>DevOps MCP Server</strong>. Any agent needing those capabilities simply connects via MCP — no duplication, no redeployment.</li></ul><blockquote>This shift enables modularity, reusability, and testability across workflows and teams.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_SxIvtxM2FG-UaI3gNzmw.png" /></figure><h3>Implementing MCP Servers with FastMCP</h3><h4>What is FastMCP?</h4><p><a href="https://gofastmcp.com/getting-started/welcome"><strong>FastMCP</strong></a> is a lightweight Python framework for building <strong>spec-compliant MCP Servers</strong>. It allows you to expose tools, prompts, and structured capabilities over the <strong>Model Context Protocol (MCP)</strong> using simple JSON schemas and Python functions.</p><p>Let’s walk through the <strong>Cyber Evaluation Server</strong> implementation.</p><h4>Project Setup</h4><p>I used uv with a pyproject.toml file to manage dependencies and environment isolation:</p><pre>[project]<br>name = &quot;mcp-cyber-eval-server&quot;<br>description = &quot;Model Context Protocol (MCP) server for Cyber Evaluation&quot;<br>version = &quot;0.1.0&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>dependencies = [<br>    &quot;deepdiff==8.4.2&quot;,<br>    &quot;fastapi&gt;=0.115.13&quot;,<br>    &quot;fastmcp&gt;=2.7.1&quot;,<br>    &quot;mcp&gt;=1.9.1&quot;,<br>    &quot;uvicorn&gt;=0.34.3&quot;,<br>]<br><br>[tool.pyright]<br>exclude = [<br>    &quot;**/node_modules&quot;,<br>    &quot;**/__pycache__&quot;,<br>    &quot;**/.*&quot;,<br>    &quot;docs/&quot;,<br>    &quot;pyproject.toml&quot;<br>]</pre><p>To run locally:</p><pre>&quot;uvicorn&quot;, &quot;mcp_cyber_eval.server:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;</pre><p>The Cyber Eval Server consist of following tools and prompts:</p><h4>Tools: Diffing Firewall and NSG Rules</h4><p>The Cyber Evaluation server exposes two tools:</p><ul><li>get_diff_and_changed_firewall_rules</li><li>get_diff_and_changed_nsg_rules</li></ul><p>Each tool takes source/target file paths as input and returns structured diffs of rule changes. These are later passed to the LLM for evaluation.</p><p>Supporting utilities like flatten_firewall_rules, read_file_content, and get_diff help format and extract the changes using DeepDiff.</p><p>Example tool registration:</p><pre>#tools.py<br>from mcp_cyber_eval.common import (get_diff, flatten_firewall_rules,<br>                                                       flatten_nsg_rules,<br>                                                       read_file_content)<br>## Defining tools <br>def register_tools(mcp) -&gt; None:<br>    &quot;&quot;&quot;<br>    Register cyber file tools with the MCP server.<br>    <br>    Args:<br>        mcp: The FastMCP server instance<br>    &quot;&quot;&quot;<br>   @mcp.tool(tags={&quot;pr-eval&quot;,&quot;utility&quot;})<br>    def get_diff_and_changed_firewall_rules(<br>        source_firewall_local_filepath: str,<br>        target_firewall_local_filepath: str,<br>    ) -&gt; list:<br>        &quot;&quot;&quot;<br>        Read the content from source and target local filepaths for firewall and get the differences between the two rules.<br>        Args:<br>            source_firewall_local_filepath: The localpath to source branch firewall rule file.<br>            target_firewall_local_filepath: The localpath to target branch firewall rule file.<br>        Returns:<br>            A list of dictionaries containing the differences between the two sets of rules and new rule added.<br>        &quot;&quot;&quot;<br>        old_firewall_policy = read_file_content(target_firewall_local_filepath)<br>        new_firewall_policy = read_file_content(source_firewall_local_filepath)<br>        old = flatten_firewall_rules(json.loads(old_firewall_policy))<br>        new = flatten_firewall_rules(json.loads(new_firewall_policy))<br><br>        return get_diff(old, new, &quot;firewall&quot;)<br><br>    @mcp.tool(tags={&quot;pr-eval&quot;,&quot;utility&quot;})<br>    def get_diff_and_changed_nsg_rules(<br>        source_firewall_local_filepath: str,<br>        target_firewall_local_filepath: str,<br>    ) -&gt; list:<br>  ....<br></pre><pre>from deepdiff import DeepDiff<br>from copy import deepcopy<br>from collections import defaultdict<br><br><br>def read_file_content(file_path):<br>    &quot;&quot;&quot;<br>    Read the content of a file from the local filesystem.<br>    <br>    Args:<br>        file_path: The path to the file.<br>        <br>    Returns:<br>        The content of the file as a string.<br>    &quot;&quot;&quot;<br>    with open(file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>        content = f.read()<br>    return content.strip()<br><br>    <br>def extract_path_keys(path):<br>    &quot;&quot;&quot;<br>    Convert DeepDiff path like &quot;root[&#39;targetFqdns&#39;][2]&quot; → [&#39;targetFqdns&#39;, 2]<br>    &quot;&quot;&quot;<br>    import re<br>    matches = re.findall(r&quot;\[&#39;([^&#39;]+)&#39;\]|\[(\d+)\]&quot;, path)<br>    return [int(b) if b else a for a, b in matches]<br><br>def flatten_firewall_rules(firewall_data):<br>    &quot;&quot;&quot;<br>    Flatten firewall rules into a name → rule mapping<br>    &quot;&quot;&quot;<br>    rule_map = {}<br>    for policy in firewall_data:<br>        for rc in policy.get(&quot;ruleCollections&quot;, []):<br>            for rule in rc.get(&quot;rules&quot;, []):<br>                rule_map[rule[&quot;name&quot;]] = rule<br>    return rule_map<br><br>def flatten_nsg_rules(nsg_data):<br>    &quot;&quot;&quot;<br>    Flatten NSG rules into a name → rule mapping<br>    &quot;&quot;&quot;<br>    rule_map = {}<br>    for rule in nsg_data:<br>        rule_map[rule[&quot;name&quot;]] = rule<br>    return rule_map<br><br>def get_diff(old, new, rule_type):<br>    &quot;&quot;&quot;<br>    Get the difference between two rules.<br>    <br>    Args:<br>        old: The original rule.<br>        new: The modified rule.<br>        <br>    Returns:<br>        A list containing the differences.<br>    &quot;&quot;&quot;<br>    changed_rules = []<br>    for name, new_rule in new.items():<br>        old_rule = old.get(name)<br>        if not old_rule:<br>            # Entirely new rule<br>            new_with_diff = deepcopy(new_rule)<br>            new_with_diff[&quot;diff&quot;] = {<br>                &quot;status&quot;: &quot;NewRule&quot;,<br>                &quot;new_value&quot;: &quot;Entire rule is newly added&quot;<br>            }<br>            changed_rules.append(new_with_diff)<br>            continue<br><br>        diff = DeepDiff(old_rule, new_rule, ignore_order=True)<br>        if not diff:<br>            continue  # No change<br><br>        full_rule = deepcopy(new_rule)<br>        diff_summary = defaultdict(list)<br><br>        for change_type, changes in diff.items():<br>            for path, value in changes.items():<br>                keys = extract_path_keys(path)<br><br>                # We&#39;re only interested in changes under &#39;properties&#39;<br>                if not keys:<br>                    if rule_type == &quot;firewall&quot;:<br>                        continue<br>                elif rule_type == &quot;nsg&quot;:<br>                    if keys[0] != &quot;properties&quot;:<br>                        continue<br><br>                # Get the field name from &#39;properties&#39;<br>                if rule_type == &quot;firewall&quot;:<br>                    field = keys[0] if isinstance(keys[0], str) else keys[-2]  # top-level field in the rule<br>                elif rule_type == &quot;nsg&quot;:<br>                    field = keys[1]<br><br>                if change_type == &quot;values_changed&quot;:<br>                    diff_summary[field].append({<br>                        &quot;status&quot;: &quot;Modified&quot;,<br>                        &quot;old_value&quot;: value[&quot;old_value&quot;],<br>                        &quot;new_value&quot;: value[&quot;new_value&quot;]<br>                    })<br><br>                elif change_type == &quot;iterable_item_added&quot;:<br>                    diff_summary[field].append({<br>                        &quot;status&quot;: &quot;Added&quot;,<br>                        &quot;new_value&quot;: value<br>                    })<br><br>                elif change_type == &quot;iterable_item_removed&quot;:<br>                    diff_summary[field].append({<br>                        &quot;status&quot;: &quot;Removed&quot;,<br>                        &quot;new_value&quot;: value<br>                    })<br><br>        full_rule[&quot;diff&quot;] = dict(diff_summary)<br>        changed_rules.append(full_rule)<br><br>    return changed_rules</pre><h4>Prompt: Evaluate Cyber Policies</h4><p>I also defined an LLM-facing prompt named evaluate_cyber_policies, which:</p><ul><li>Takes a list of policy files and their diffs</li><li>Applies rule-specific instructions (e.g., for bidirectional rule detection)</li><li>Returns a structured JSON evaluation report</li></ul><pre># prompt.py<br>def register_prompt(mcp: FastMCP) -&gt; None:<br>@mcp.prompt(name=&quot;evaluate_cyber_policies&quot;, description=&quot;Evaluate policy diffs and return violations&quot;)<br>def evaluate_cyber_policies() -&gt; str:<br>    return f&quot;&quot;&quot;You will be provided with a list &lt;changed_files_list&gt; ...<br>    Use tools based on file_type from this map:<br>    {FILE_TYPE_MAP}<br>    ...<br>    Output a JSON object with structure:<br>    {{<br>        &quot;evaluation_results&quot;: [...],<br>        &quot;bidirectional_rules&quot;: [...]<br>    }}<br>    &quot;&quot;&quot;</pre><p>Instructions are modular, with mappings for firewall and NSG rule types defined in FILE_TYPE_MAP</p><h4>Server Integration with FastAPI</h4><p>Finally, I used <strong>FastAPI</strong> to expose the server with the MCP capabilities. For more details refer <a href="https://gofastmcp.com/deployment/asgi#fastapi-integration">Integrating FastMCP in ASGI Applications — FastMCP</a>.</p><pre>from dotenv import load_dotenv<br>from fastapi import FastAPI<br>from fastapi.responses import JSONResponse<br>from fastmcp import FastMCP<br>load_dotenv()<br><br><br>from mcp_cyber_eval.tools import register_tools<br>from mcp_cyber_eval.prompt import register_prompt<br><br># Create a FastMCP server instance with a name<br>mcp = FastMCP(&quot;Cyber PR Evaluation&quot;)<br><br># Register all features<br>register_tools(mcp)<br>register_prompt(mcp)<br><br># Get a Starlette app instance for SSE HTTP Transport<br>http_app = mcp.http_app(transport=&#39;sse&#39;)<br><br># Create a FastAPI app and mount the MCP server<br>app = FastAPI(lifespan=http_app.lifespan)<br>app.mount(&quot;/azurecybereval-mcp&quot;, http_app)<br><br>@app.get(&quot;/health&quot;, tags=[&quot;Health&quot;])<br>async def health_check():<br>    return JSONResponse(content={&quot;status&quot;: &quot;ok&quot;})</pre><p>A simple /health endpoint is added for monitoring.</p><h4>Other Servers</h4><p>I followed the same structure to implement additional MCP servers:</p><ul><li><strong>Azure DevOps Server</strong>: Referenced from <a href="https://github.com/Vortiago/mcp-azure-devops">Vortiago/mcp-azure-devops</a> (PR features are still evolving)</li><li><strong>ServiceNow Server</strong>: Custom-built to expose CHG number validation and metadata extraction</li></ul><p>You can explore more MCP server examples at:<br> 🔗 <a href="https://github.com/modelcontextprotocol/servers">modelcontextprotocol/servers</a></p><h3>Hosting the MCP Servers in Azure App Service</h3><p>Each MCP Server is containerized using a lightweight <strong>Dockerfile</strong>, making it easy to deploy and scale via <strong>Azure App Service</strong>. This setup ensures that all tools and prompts are accessible as modular, schema-driven APIs in a secure and controlled environment.</p><p>Here’s a simplified version of the Dockerfile I used:</p><pre># Use Python base image<br>FROM python:3.12.9<br><br># Set workdir<br>WORKDIR /app<br><br># Install uv (ultra-fast dependency manager)<br>RUN pip install --no-cache-dir uv<br><br># Copy project files<br>COPY pyproject.toml ./pyproject.toml<br>COPY mcp_cyber_eval./mcp_cyber_eval<br><br># Sync dependencies (will cache this layer unless deps change)<br>RUN uv pip install --system .<br><br># Expose FastAPI default port<br>EXPOSE 8000<br><br># Start the app<br>CMD [&quot;uvicorn&quot;, &quot;mcp_cyber_eval.server:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><blockquote><em>You can replicate this for other servers (e.g., DevOps or ServiceNow) with minimal changes.</em></blockquote><h4>Deploying to Azure App Service</h4><p>I used the <strong>Azure App Service for Containers</strong> setup with GitHub Actions for CI/CD. Here are resources to follow the same approach:</p><ul><li><a href="https://learn.microsoft.com/en-us/training/modules/deploy-run-container-app-service/">Deploy a containerized app to Azure App Service</a></li><li><a href="https://learn.microsoft.com/en-us/azure/app-service/configure-common#configure-app-settings">Configure App Service with environment variables/secrets</a></li></ul><blockquote><em>I mounted a shared file system (via Azure File Share) across Cyber and DevOps servers to persist PR changed files and corresponding master files.</em></blockquote><h3>Plugging MCP Servers into LangGraph Agents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URGpLz_nytU9oAWP7OuAjw.png" /></figure><p>Once the MCP servers are deployed and running, they can be connected to LangGraph agents using the <a href="https://github.com/langchain-ai/langgraph/tree/main/libs/langchain-mcp-adapters">langchain-mcp-adapters</a> and <a href="https://github.com/langchain-ai/langgraph/tree/main/libs/langgraph-supervisor">langgraph-supervisor</a> libraries.</p><p>Below is a simplified and <strong>sanitized</strong> version of how the Cyber PR Evaluation workflow is orchestrated using four agents: DevOps, CyberEval, ServiceNow, and PR Report Generator.</p><h4>Step 1: Connect to MCP Servers</h4><pre>from langchain_mcp_adapters.client import MultiServerMCPClient<br><br>client = MultiServerMCPClient(<br>    {<br>        &quot;devops&quot;: {<br>            &quot;url&quot;: &quot;https://&lt;your-devops-server&gt;/azuredevops-mcp/sse&quot;,<br>            &quot;transport&quot;: &quot;sse&quot;,<br>        },<br>        &quot;cybereval&quot;: {<br>            &quot;url&quot;: &quot;https://&lt;your-cyber-eval-server&gt;/azurecybereval-mcp/sse&quot;,<br>            &quot;transport&quot;: &quot;sse&quot;,<br>        },<br>        &quot;snow&quot;: {<br>            &quot;url&quot;: &quot;https://&lt;your-snow-server&gt;/snow-mcp/sse&quot;,<br>            &quot;transport&quot;: &quot;sse&quot;,<br>        },<br>    }<br>)<br>🔐 Replace actual URLs with environment variables or secrets in production deployments.</pre><h4>Step 2: Load Tools and Prompts from Each Server</h4><pre>from langchain_mcp_adapters.tools import load_mcp_tools<br>from langchain_mcp_adapters.prompts import load_mcp_prompt<br><br>ctx = client.session(&quot;cybereval&quot;)<br>cyber_eval_session = await ctx.__aenter__()<br>cyber_eval_tools = await load_mcp_tools(cyber_eval_session)<br>cyber_eval_prompt = await load_mcp_prompt(cyber_eval_session, &quot;evaluate_cyber_policies&quot;)</pre><p>Repeat this for DevOps and ServiceNow agents with their respective sessions and capabilities.</p><h4>Step 3: Create LangGraph Agents</h4><pre>from langgraph.prebuilt import create_react_agent<br>from langchain_openai import AzureChatOpenAI<br><br>model = AzureChatOpenAI(model=&quot;gpt-4.1&quot;)<br><br>cyber_eval_agent = create_react_agent(<br>    model,<br>    tools=cyber_eval_tools,<br>    prompt=cyber_eval_prompt[0].content,<br>    name=&quot;cyber_eval_agent&quot;<br>)<br><br># Similar for devops_agent, snow_agent, and pr_report_generation_agent</pre><h4>Step 4: Orchestrate Agents with a Supervisor</h4><pre>from langgraph_supervisor import create_supervisor<br><br>supervisor = create_supervisor(<br>    model=model,<br>    agents=[devops_agent, cyber_eval_agent, snow_agent, pr_report_generation_agent],<br>    prompt=&quot;&quot;&quot;<br>    You are a supervisor coordinating agents to evaluate a PR.<br>    - Use DevOps Agent for PR metadata tasks.<br>    - Use CyberEval Agent for policy evaluations.<br>    - Use ServiceNow Agent to validate CHG numbers.<br>    - Use PR Report Agent to generate final summary reports.<br>    &quot;&quot;&quot;,<br>    output_mode=&quot;full_history&quot;<br>).compile()</pre><h4>Step 5: Trigger the Workflow</h4><pre>result = await supervisor.ainvoke({<br>    &quot;messages&quot;: [<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;&quot;&quot;<br>                Evaluate a pull request. Check for CHG/SRA validity, detect bidirectional rules,<br>                and generate a report if violations are found.<br>            &quot;&quot;&quot;<br>        }<br>    ]<br>})</pre><p>The Supervisor will route tasks to the appropriate agents via MCP calls and generate a complete evaluation lifecycle — from data collection to policy analysis to structured PR feedback.</p><h3>Key Findings</h3><ul><li><strong>Streamable Transport Limitation:</strong> Azure App Service does <strong>not support </strong><strong>streamable_http</strong> transport for MCP servers. I had to switch to <strong>SSE (</strong><strong>server-sent events)</strong> to ensure proper compatibility and streaming responses.</li><li><strong>LangGraph Supervisor + MCP = Clean Orchestration:</strong> Delegating tasks across agents through schema-based capabilities made the workflow more maintainable and extensible.</li><li><strong>Docker + Azure App Service Works Well for MCP:</strong> Containerized deployment ensured each server stayed isolated, scalable, and CI/CD-friendly.</li><li><strong>Schema Contracts Help Ground LLMs:</strong> Providing structured I/O to the LLM via MCP tools reduced hallucination and made evaluation outputs more reliable.</li></ul><h3>📚 References</h3><ul><li><a href="https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/">LangGraph Supervisor Pattern</a></li><li><a href="https://langchain-ai.github.io/langgraph/agents/mcp/">LangGraph MCP Integration</a></li><li><a href="https://github.com/modelcontext/fastmcp">FastMCP GitHub Repo</a></li><li><a href="https://github.com/langchain-ai/langgraph/tree/main/libs/langchain-mcp-adapters">Langchain MCP Adapters GitHub</a></li><li><a href="https://github.com/modelcontextprotocol/servers">Model Context Protocol Servers (Community Repo)</a></li></ul><p><strong>That’s a wrap — on to building better, modular AI systems.</strong> 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f29ab825e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolith to Modular (Part 1): Understanding MCP for Modern AI Applications]]></title>
            <link>https://medium.com/@khansaima/from-monolith-to-modular-part-1-understanding-mcp-for-modern-ai-applications-c367036c1c5e?source=rss-2b5cea454596------2</link>
            <guid isPermaLink="false">https://medium.com/p/c367036c1c5e</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Saima Khan]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 14:32:58 GMT</pubDate>
            <atom:updated>2025-07-14T06:45:27.019Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem with LLM Apps Today</h3><p>Over the past year, we’ve seen an explosion of Large Language Model (LLM) apps — travel assistants, code copilots, research agents, customer service bots. While they look polished on the surface, most of these applications suffer from the same architectural trap:</p><p><em>They’re built as </em><strong><em>monolithic, app-specific bundles</em></strong><em> — closed systems where the LLM, its tools, prompts, and logic are all wired tightly together.</em></p><p>Let’s say you’re building a travel planning assistant. You might:</p><ul><li>Create a <strong>Weather Agent</strong> to pull forecasts from a public API.</li><li>Add a <strong>Booking Agent</strong> using Google Places, Hotels.com, or Skyscanner APIs.</li><li>Hardcode a workflow where your Travel Agent checks weather before suggesting bookings.</li></ul><p>That’s fine — until you try to:</p><ul><li>Reuse the Weather Agent in a calendar app.</li><li>Connect your Booking Agent to a different LLM.</li><li>Maintain and scale this logic across products and teams.</li></ul><p>You can’t. Because every tool, prompt, and logic chain lives <strong>inside</strong> the app. There’s no separation of concerns. No modularity. And zero reuse.</p><h3>The N × M Problem</h3><p>This tightly coupled design leads to what many teams are now calling the <strong>N × M problem</strong>:</p><ul><li><strong>N = Number of LLMs or clients</strong></li><li><strong>M = Number of tools, APIs, or knowledge sources</strong></li></ul><p>To integrate each LLM with every tool, you end up building N × M custom connections. It’s fragile. It’s repetitive. And it scales terribly.</p><p>This problem becomes even worse in enterprises, where different teams work on different agents, often duplicating logic and infrastructure without knowing it.</p><h3>The Consequences</h3><ul><li><strong>Redundant agents and prompts</strong> across teams</li><li><strong>Custom integrations</strong> for each app–tool pair</li><li><strong>Hard to debug</strong>, maintain, or extend</li><li><strong>Vendor lock-in</strong> due to deeply embedded tooling</li><li><strong>No shared memory</strong> across AI experiences</li></ul><h3>Visualizing the Chaos</h3><p>Here’s what this looks like in practice:</p><p>On the <strong>left</strong>, every app is a self-contained island. The Weather and Travel Agents are coded inside one app. No reusability. No shared access. Just a closed loop.</p><p>On the <strong>right</strong>, with <strong>MCP</strong>, you move to a <strong>client-server model</strong>:</p><ul><li>Tools and prompts are exposed via standardized <strong>MCP Servers</strong></li><li>Any app or agent can connect via the <strong>MCP protocol</strong></li><li>Agents can talk to one another, reuse tools, and work across applications</li></ul><p>It’s like going from hand-wired electronics to a <strong>universal socket system for AI</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7HD2rPuHGIdVSN0Y7Ao9A.png" /><figcaption>LLM App Architecture without MCP(left) and with MCP(right)</figcaption></figure><h3>What’s Next</h3><p>In the next section, we’ll break down <strong>what the Model Context Protocol (MCP)</strong> actually is, how it works under the hood, and why it’s being called the <strong>“USB-C for AI apps.”</strong></p><p>Ready to modularize your AI stack? Let’s dive in.</p><h3>What is MCP and How Does It Work?</h3><p>As AI agents evolve from prompt wrappers to fully interactive assistants, they need access to tools, APIs, and real-time data — just like humans do. But giving LLMs this access is messy without a shared standard.</p><p>That’s exactly what the <strong>Model Context Protocol (MCP)</strong> solves.</p><h4>MCP in a Nutshell</h4><p>The <strong>Model Context Protocol (MCP)</strong> is an <strong>open standard</strong> that defines how AI systems can discover, describe, and interact with external tools, data sources, and services.</p><p>In simple terms:</p><p><em>MCP standardizes how LLMs talk to the outside world.</em></p><p>Instead of hardcoding every API and tool into your app, MCP introduces a clean <strong>client-server architecture</strong>:</p><ul><li>The <strong>LLM app</strong> becomes an <strong>MCP client</strong></li><li>External tools (like APIs, scripts, or agents) are hosted as <strong>MCP servers</strong></li><li>Clients discover and invoke capabilities using a shared protocol (like JSON schemas + structured messages)</li></ul><p>The result? You can plug any tool into any LLM app — <strong>without rewriting glue code</strong> every time.</p><h3>Core Components of MCP</h3><p>MCP establishes a standardized framework that enables seamless communication between Large Language Model (LLM) applications and external tools, data sources, and services. Here’s a breakdown of its core components:</p><h4>MCP Client</h4><p>The <strong>MCP Client</strong> is the entity within the host application (e.g., an LLM-powered app) that initiates and manages connections to MCP Servers.</p><p><strong>Key Responsibilities:</strong></p><ul><li><strong>Discovery:</strong> Identifies available capabilities exposed by MCP Servers.</li><li><strong>Invocation:</strong> Sends structured requests to invoke specific capabilities.</li><li><strong>Handling Responses:</strong> Processes the results returned by the servers.</li></ul><p><strong>Examples:</strong></p><ul><li>An AI assistant in an Integrated Development Environment (IDE) accessing code analysis tools.</li><li>A chatbot retrieving user-specific data from external databases.</li></ul><h4>MCP Server</h4><p>The <strong>MCP Server</strong> provides one or more capabilities that can be utilized by MCP Clients. It acts as a bridge between the LLM application and external functionalities.</p><p><strong>Key Responsibilities:</strong></p><ul><li><strong>Capability Exposure:</strong> Offers tools, resources, or prompts that can be invoked by clients.</li><li><strong>Request Handling:</strong> Processes incoming requests and returns structured responses.</li><li><strong>Schema Definition:</strong> Defines input and output schemas for each capability to ensure clarity and consistency.</li></ul><p><strong>Examples:</strong></p><ul><li>A server exposing a weather API to provide real-time forecasts.</li><li>A server offering access to a company’s internal knowledge base.</li></ul><h4>Capabilities</h4><p><strong>Capabilities</strong> are the discrete functionalities exposed by MCP Servers. Each capability includes:</p><ul><li><strong>Name &amp; Description:</strong> Human-readable identifiers explaining the functionality.</li><li><strong>Input Schema:</strong> Defines the structure and types of inputs required.</li><li><strong>Output Schema:</strong> Specifies the structure of the response data.</li><li><strong>Examples:</strong> Optional usage examples to guide clients.</li></ul><p><strong>Examples:</strong></p><ul><li>get_weather(location: string) → WeatherData</li><li>search_documents(query: string) → DocumentList</li></ul><h4>Communication Protocol</h4><p>MCP utilizes a communication protocol based on <strong>JSON-RPC 2.0</strong>, facilitating structured and standardized message exchanges between clients and servers.</p><h4>Transport Layer</h4><p>MCP supports multiple transport mechanisms to accommodate various deployment scenarios:</p><ol><li><strong>Standard Input/Output (Stdio):</strong> Suitable for local processes, using the standard input and output streams for communication.</li><li><strong>HTTP Transport:</strong> Utilizes HTTP POST requests for client-to-server communication, with optional Server-Sent Events (SSE) for server-to-client streaming.</li></ol><h4>Host Application</h4><p>The <strong>Host</strong> is the overarching application that incorporates the MCP Client. It provides the environment in which the client operates and interacts with the user.</p><p><strong>Examples:</strong></p><ul><li>A desktop application integrating an AI assistant.</li><li>A web-based platform offering AI-driven features.</li></ul><p>By understanding these components and their interactions, developers can effectively leverage MCP to build modular, scalable, and interoperable AI applications.</p><h3>Why This Matters</h3><ul><li><strong>Reusable Agents</strong>: A Travel Agent exposed via MCP can be used by multiple apps or LLMs</li><li><strong>LLM Flexibility</strong>: Switch from OpenAI to Claude or Gemini without reworking your integration logic</li><li><strong>Composable AI</strong>: Chain tools, agents, and data providers like building blocks</li><li><strong>Security-Friendly</strong>: Each capability is isolated, inspectable, and schema-defined</li></ul><h3>My MCP Architecture in Action</h3><p>To put MCP to the test, I implemented it in a real-world use case: automating a <strong>Cyber Pull Request (PR) Evaluation Workflow</strong>.</p><p>This setup uses multiple LLM agents coordinated by a supervisor, each interacting with different services like Azure DevOps and ServiceNow — <strong>all via the Model Context Protocol.</strong></p><h4>Tech Stack Overview</h4><p>Here’s how the architecture is built:</p><ul><li><a href="https://gofastmcp.com/getting-started/welcome"><strong>FastMCP SDK</strong></a><br> Utilized to develop lightweight, spec-compliant <strong>MCP servers</strong>. Each server exposes one or more capabilities defined via JSON Schema, representing external systems like Azure DevOps, CyberEval, and ServiceNow.</li><li><a href="https://langchain-ai.github.io/langgraph/agents/mcp/"><strong>LangGraph with </strong></a><a href="https://langchain-ai.github.io/langgraph/agents/mcp/"><strong>langchain-mcp-adapters</strong></a><br> LangGraph serves as the orchestration framework. By integrating the langchain-mcp-adapters library, it enables agents to connect to multiple MCP servers. This setup allows for dynamic discovery and invocation of tools defined on these servers, facilitating seamless interaction between agents and external capabilities.</li><li><a href="https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/"><strong>LangGraph Supervisor Agent</strong></a><br> Acts as the central coordinator in a multi-agent system. The Supervisor Agent manages communication flow and task delegation, making decisions about which specialized agent to invoke based on the current context and task requirements. This structure ensures organized and efficient task execution across various agents.</li><li><strong>Azure App Service</strong><br> Hosts all MCP servers in a scalable cloud environment. A shared file mount is employed for cross-server data exchange, such as PR diffs and evaluation reports.</li></ul><h4>Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URGpLz_nytU9oAWP7OuAjw.png" /></figure><h4>Execution Flow: Step by Step</h4><ol><li><strong>Supervisor Agent </strong>begins orchestration based on the task (e.g., evaluate a pull request, get details of a pull request, post comment &lt;comment&gt; on PR, check change request number exist in Service Now).</li><li><strong>Agents</strong> (Cyber Evaluation, Azure DevOps, PR Report Generation, ServiceNow) are selected dynamically based on task type.</li><li><strong>MCP Clients (LangGraph agents)</strong> connect to their corresponding <strong>MCP Servers</strong>, which expose:</li></ol><ul><li><strong>Tools</strong> (e.g., fetch PR data, query ServiceNow change requests, evaluated difference b/w policy files)</li><li><strong>Prompts</strong> (e.g., evaluate code diff, generate a compliance summary)</li></ul><p>4. <strong>MCP Servers</strong> process structured requests and return responses that agents use for downstream actions.</p><p>5.<strong> A shared file mount </strong>mounted on both Cyber and Azure Devops App Service servers which enables cross-agent input/output reuse — like processed PR diffs.</p><h4>Why This Architecture Works</h4><ul><li><strong>Loosely coupled agents: </strong>Each service logic is encapsulated in its own MCP server — modular and testable.</li><li><strong>Reusability across apps: </strong>The same MCP servers can be used in other workflows — not tied to this specific LangGraph flow.</li><li><strong>Scalable &amp; maintainable: </strong>Adding a new tool? Just add the tool to the relevant MCP server. No need to touch existing agents.</li><li><strong>Secure separation of concerns: </strong>LLMs only see what they need — each capability is exposed with a clear schema boundary.</li></ul><h3>📚 References</h3><ol><li><strong><em>Model Context Protocol (Official Site): </em></strong><a href="https://modelcontextprotocol.io/introduction"><em>https://modelcontextprotocol.io/introduction</em></a></li><li><strong><em>MCP Architecture Concepts: </em></strong><a href="https://modelcontextprotocol.io/docs/concepts/architecture"><em>https://modelcontextprotocol.io/docs/concepts/architecture</em></a></li><li><strong><em>FastMCP SDK Documentation: </em></strong><a href="https://gofastmcp.com/getting-started/quickstart"><em>Quickstart — FastMCP</em></a></li><li><strong><em>LangGraph MCP Integration Guide: </em></strong><a href="https://langchain-ai.github.io/langgraph/agents/mcp/"><em>https://langchain-ai.github.io/langgraph/agents/mcp/</em></a></li><li><strong><em>LangGraph Supervisor Agent Pattern:</em></strong><em> </em><a href="https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/"><em>https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/</em></a></li></ol><h4>Github Repos:</h4><ul><li><a href="https://github.com/langchain-ai/langgraph/blob/main/examples/multi_agent/agent_supervisor.ipynb"><strong>General LangGraph Supervisor Pattern</strong></a></li><li><a href="http://fastmcp/examples%20at%20main%20%C2%B7%20jlowin/fastmcp"><strong>FastMcp</strong></a></li><li><a href="https://github.com/modelcontextprotocol"><strong>Model Context Protocol</strong></a></li></ul><h3>In this post, I explored why MCP matters, how it works, and how it can support more modular AI architectures.</h3><p>If you’re ready to go deeper — good news: <strong>Part 2 is now live!</strong></p><p>📘 <strong>Read Part 2:</strong> <a href="https://medium.com/@khansaima/from-monolith-to-modular-part-2-how-i-integrated-mcp-using-fastmcp-and-langgraph-d4f29ab825e1">From Monolith to Modular (Part 2): How I Integrated MCP Using FastMCP and LangGraph | by Saima Khan | Jul, 2025 | Medium</a></p><p>It covers:</p><ul><li>How I built and deployed MCP servers using <strong>FastMCP</strong></li><li>How I used <strong>LangGraph’s Supervisor pattern</strong> to orchestrate agents</li><li>Real code, schemas, and architecture examples from a production-ready setup</li></ul><p>Feel free to explore, share feedback, or adapt the approach for your own use case!</p><p><em>Happy reading — hope this gave you a clear glimpse into what MCP can unlock for AI systems.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c367036c1c5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>