<?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 Aneep Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Aneep Agrawal on Medium]]></description>
        <link>https://medium.com/@aneepagrawal?source=rss-e274efb7b683------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Aneep Agrawal on Medium</title>
            <link>https://medium.com/@aneepagrawal?source=rss-e274efb7b683------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:25:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aneepagrawal/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[Building Secure AI Agents: MCP Server Integration with AWS Bedrock Agent Core and Azure AD…]]></title>
            <link>https://medium.com/@aneepagrawal/building-secure-ai-agents-mcp-server-integration-with-aws-bedrock-agent-core-and-azure-ad-db8d607b37e2?source=rss-e274efb7b683------2</link>
            <guid isPermaLink="false">https://medium.com/p/db8d607b37e2</guid>
            <dc:creator><![CDATA[Aneep Agrawal]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 03:48:59 GMT</pubDate>
            <atom:updated>2025-09-30T04:12:56.308Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Secure AI Agents: MCP Server Integration with AWS Bedrock Agent Core and Azure AD Authentication</strong></h3><p><strong>Introduction</strong></p><p>In the rapidly evolving landscape of AI applications, the need for secure, scalable, and interoperable agent systems has never been greater. This article explores how to build a comprehensive AI agent solution using the Model Context Protocol (MCP), AWS Bedrock Agent Core, and Azure Active Directory authentication.</p><p><strong>What is MCP (Model Context Protocol)?</strong></p><p>The Model Context Protocol (MCP) is an open standard that enables seamless communication between AI applications and external data sources or tools. Think of MCP as a universal translator that allows AI models to interact with various services, databases, and APIs in a standardized way.</p><p><strong>Key Benefits of MCP:</strong></p><blockquote><strong>Standardized Communication</strong>: Consistent interface for tool integration</blockquote><blockquote><strong>Extensibility</strong>: Easy addition of new tools and capabilities</blockquote><blockquote><strong>Security</strong>: Built-in authentication and authorization mechanisms</blockquote><blockquote><strong>Interoperability</strong>: Works across different AI platforms and models</blockquote><p><strong>What is AWS Bedrock Agent Core?</strong></p><p>AWS Bedrock Agent Core is a managed service that provides the infrastructure for deploying and running AI agents at scale. It handles:</p><blockquote><strong>Agent Hosting</strong>: Containerized deployment of AI agents</blockquote><blockquote><strong>Runtime Management</strong>: Automatic scaling and resource allocation</blockquote><blockquote><strong>Security</strong>: Built-in authentication and network isolation</blockquote><blockquote><strong>Integration</strong>: Seamless connection with other AWS services</blockquote><p><strong>Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzT68x-p_ffxw7iUFJ3bRA.png" /></figure><p><em>Below are the required steps to achieve this:</em></p><ol><li><strong>Building the MCP Server</strong></li></ol><p>Our MCP server provides three essential tools for demonstration:</p><pre>## Building the MCP Server<br><br><br># mcp_server.py<br>from mcp.server.fastmcp import FastMCP<br><br>mcp = FastMCP(host=&quot;0.0.0.0&quot;, stateless_http=True)<br><br>@mcp.tool()<br>def add_numbers(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Add two numbers together&quot;&quot;&quot;<br>    return a + b<br><br>@mcp.tool()<br>def multiply_numbers(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiply two numbers together&quot;&quot;&quot;<br>    return a * b<br><br>@mcp.tool()<br>def greet_user(name: str) -&gt; str:<br>    &quot;&quot;&quot;Greet a user by name&quot;&quot;&quot;<br>    return f&quot;Hello, {name}! Nice to meet you.&quot;<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;streamable-http&quot;)<br></pre><p>Create a requirements.txt file</p><pre># requirements.txt<br><br>mcp</pre><p><strong>2. Containerization with Docker</strong></p><p>2.1 Create a docker file and built the image locally</p><pre>FROM public.ecr.aws/docker/library/python:3.10-slim<br>WORKDIR /app<br>COPY requirements.txt requirements.txt<br>RUN pip install -r requirements.txt<br>RUN pip install aws-opentelemetry-distro&gt;=0.10.1<br>ENV AWS_REGION=ap-southeast-2<br>ENV AWS_DEFAULT_REGION=ap-southeast-2<br>ENV DOCKER_CONTAINER=1<br>RUN useradd -m -u 1000 bedrock_agentcore<br>USER bedrock_agentcore<br>EXPOSE 8080<br>EXPOSE 8000<br>COPY . .<br>CMD [&quot;opentelemetry-instrument&quot;, &quot;python&quot;, &quot;-m&quot;, &quot;mcp_server&quot;]</pre><p>2.2 Build the Docker Image:</p><pre># Build the image with a tag<br>docker build -t mcp-server:latest .<br># Verify the image was created<br>docker images | grep mcp-server</pre><p>2.3 Create AWS ECR Repository If Not Exists In Account</p><pre>export AWS_REGION=&quot;&quot; # Add Region<br>export AWS_ACCOUNT_ID=&quot;&quot; #Add Account Id<br>export REPO_NAME=mcp-server<br># Create ECR repository<br>aws ecr create-repository \<br> - repository-name $REPO_NAME \<br> - region $AWS_REGION</pre><p>2.4 Get Login Token</p><pre>aws ecr get-login-password - region $AWS_REGION | \<br>docker login - username AWS - password-stdin \<br>$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com</pre><p>2.5 Tag and Push to ECR</p><pre>docker tag mcp-server:latest \<br>$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO_NAME:latest<br># Also tag with version<br>docker tag mcp-server:latest \<br>$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO_NAME:v1.0.0<br># Push latest tag<br>docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO_NAME:latest<br># Push version tag<br>docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO_NAME:v1.0.0</pre><p><strong>3. Create Azure App Registration and Add Required Permissions</strong></p><p>3.1. Create an App Registration</p><p>1. Navigate to the <strong>Azure Portal</strong> → <strong>Azure Active Directory</strong>→ <strong>App registrations</strong>. <br> 2. Click <strong>New registration</strong>. <br> 3. Fill out the form: <br> — <strong>Name</strong>: <em>MCP Agent Web App</em><br> — <strong>Supported account types</strong>:<em> Single tenant</em><br> — <strong>Redirect URI</strong>: <br> — Platform: <em>Web</em> <br> — URI: <a href="http://localhost:5000/callback%60"><em>http://localhost:5000/callback</em></a><br> 4. Hit <strong>Register</strong>.</p><p>3.2. Configure Authentication</p><p>1. In your new app registration, go to <strong>Authentication </strong>→ <strong>Platform configurations</strong>. <br> 2. Enable <strong>Implicit gran</strong>t by checking<strong> ID tokens.</strong> <br> 3. Save your changes.</p><p>3.3 Assign API Permissions</p><p>1. Navigate to <strong>API permissions</strong> → <strong>Add a permission</strong>. <br> 2. Choose <strong>Microsoft Graph</strong> → <strong>Delegated permissions</strong>. <br> 3. Select the following scopes: <br> — <em>User.Read</em><br> — <em>openid</em><br> — <em>profile</em><br> — <em>email</em><br> 4. Click <strong>Add permissions</strong>. <br> 5. Grant <strong>admin consent</strong> for your organization.</p><p>3.4. Generate a Client Secret</p><p>1. Go to <strong>Certificates &amp; secrets</strong> → <strong>Client secrets</strong>. <br>2. Click <strong>New client secret</strong>. <br>3. Provide a description (e.g., <em>MCP Web App Secret</em>) and set the expiry (e.g., 24 months). <br>4. After creating it, <strong>copy the secret value immediately</strong> — it won’t be shown again.</p><p>From the <strong>Overview</strong> tab of your app registration, copy these values: <br>- <strong>Application (client) ID</strong><br>- <strong>Directory (tenant) ID</strong> <br>- <strong>Client Secret (from Step 4)</strong></p><p>We will use these in Flask app (Client Id Agent Core) to enable secure sign-in via Azure AD.</p><p><strong>4. Deployment of Agent to Amazon Bedrock Agent Core</strong></p><ul><li>Go to the <strong>Amazon Bedrock Agent Core</strong> console.</li><li>Click <strong>Host agent</strong></li><li>Add <strong>Agent Name i</strong>n Agent Detail</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_0sL8TVGGVMH-EAlGmyHg.png" /></figure><ul><li>Select deployed image from<em> ECR Repository </em>which was done in Step 2 in “Import docker image from Amazon ECR” Section</li><li>Select IAM Role</li><li>In Inbound Section Select Protocol as “MCP Protocol” and Use JWT as “Inbound Identity Type”</li><li>In <strong>JWT schema configuration </strong>select <strong>“</strong>Use existing Identity provider configurations”</li><li>Add <a href="https://login.microsoftonline.com/4341df80-fbe6-41bf-89b0-e6e2379c9c23/v2.0/.well-known/openid-configuration">https://login.microsoftonline.com/{tenant_id}/v2.0/.well-known/openid-configuration</a> as Issuer URL</li><li>Client Id in Allowed audiences</li><li>Click <strong>Host Agent, this will deploy MCP server on Amazon Bedrock Agent Core Runtime</strong></li></ul><p><strong>5. Accessing MCP Server via MCP Client:</strong></p><p>Project Structure</p><pre>├── mcp_web_app.py<br>├── requirements.txt<br>├── templates/<br>│ ├── index.html<br>│ └── chat.html</pre><pre><br><br>## Core Implementation<br><br>### 1. Basic Flask Setup<br><br>```python<br>from flask import Flask, render_template, request, redirect, session<br>import asyncio<br>from mcp import ClientSession<br>from mcp.client.streamable_http import streamablehttp_client<br>from datetime import timedelta<br>import secrets<br>import requests<br><br><br>app = Flask(__name__)<br>app.secret_key = secrets.token_hex(16)<br><br># OAuth2 Configuration<br><br>TENANT_ID = &quot;&lt;your-tenant-id&gt;&quot;<br>CLIENT_ID = &quot;&lt;your-client-id&gt;&quot;<br>CLIENT_SECRET = &quot;&lt;your-client-secret&gt;&quot;<br>AGENT_ARN_MCP = &quot;&lt;your-mcp-agent-arn-available-in-mcp-runtime&gt;&quot;<br><br>REDIRECT_URI = &quot;http://localhost:5001/callback&quot;<br>AUTH_URL = f&quot;https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize&quot;<br>TOKEN_URL = f&quot;https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token&quot;<br>SCOPES = [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;]<br><br>#OAuth2 Callback<br><br># Here, we:<br><br># Validate state (CSRF protection)<br><br># Exchange the authorization code for tokens<br><br># Extract user details from the id_token<br><br>@app.route(&quot;/login&quot;)<br>def login():<br>    state = secrets.token_urlsafe(16)<br>    session[&quot;state&quot;] = state<br><br>    params = {<br>        &quot;client_id&quot;: CLIENT_ID,<br>        &quot;response_type&quot;: &quot;code&quot;,<br>        &quot;redirect_uri&quot;: REDIRECT_URI,<br>        &quot;response_mode&quot;: &quot;query&quot;,<br>        &quot;scope&quot;: &quot; &quot;.join(SCOPES),<br>        &quot;state&quot;: state,<br>    }<br>    query = &quot;&amp;&quot;.join([f&quot;{k}={v}&quot; for k, v in params.items()])<br>    return redirect(f&quot;{AUTH_URL}?{query}&quot;)<br><br><br>@app.route(&quot;/callback&quot;)<br>def callback():<br>    if request.args.get(&quot;state&quot;) != session.get(&quot;state&quot;):<br>        return &quot;State mismatch&quot;, 400<br><br>    code = request.args.get(&quot;code&quot;)<br>    if not code:<br>        return &quot;No code returned&quot;, 400<br><br>    <br>    data = {<br>        &quot;grant_type&quot;: &quot;authorization_code&quot;,<br>        &quot;client_id&quot;: CLIENT_ID,<br>        &quot;client_secret&quot;: CLIENT_SECRET,<br>        &quot;code&quot;: code,<br>        &quot;redirect_uri&quot;: REDIRECT_URI,<br>    }<br><br>    resp = requests.post(TOKEN_URL, data=data)<br>    tokens = resp.json()<br><br>    if &quot;id_token&quot; in tokens:<br>        session[&quot;id_token&quot;] = tokens[&quot;id_token&quot;]<br><br>        # Decode token to extract user info<br>        import base64, json<br>        token_parts = tokens[&quot;id_token&quot;].split(&#39;.&#39;)<br>        payload = base64.b64decode(token_parts[1] + &#39;==&#39;).decode(&#39;utf-8&#39;)<br>        user_info = json.loads(payload)<br>        session[&quot;username&quot;] = user_info.get(&quot;name&quot;, &quot;User&quot;)<br><br>        return redirect(&quot;/chat&quot;)<br>    else:<br>        return f&quot;Authentication failed: {tokens}&quot;<br><br># chat route<br>@app.route(&quot;/chat&quot;)<br>def chat():<br>    if &quot;id_token&quot; not in session:<br>        return redirect(&quot;/&quot;)<br>    username = session.get(&quot;username&quot;, &quot;User&quot;)<br><br>    try:<br>        loop = asyncio.new_event_loop()<br>        asyncio.set_event_loop(loop)<br>        tools = loop.run_until_complete(get_tools(session[&#39;id_token&#39;]))<br>        loop.close()<br><br>        success_message = f&quot;Hi {username}! Successfully invoked MCP server with auth. Here are the available tools: {&#39;, &#39;.join(tools)}&quot;<br>        return render_template(&quot;chat.html&quot;, success_message=success_message)<br><br>    except Exception as e:<br>        return render_template(&quot;chat.html&quot;, success_message=f&quot;Hi {username}! Error connecting to MCP server: {str(e)}&quot;)<br><br># Function to list tools from MCP server<br>async def get_tools(bearer_token):<br>    encoded_arn = AGENT_ARN_MCP.replace(&#39;:&#39;, &#39;%3A&#39;).replace(&#39;/&#39;, &#39;%2F&#39;)<br>    mcp_url = f&quot;https://bedrock-agentcore.ap-southeast-2.amazonaws.com/runtimes/{encoded_arn}/invocations?qualifier=DEFAULT&amp;version=4&quot;<br>    headers = {&quot;authorization&quot;: f&quot;Bearer {bearer_token}&quot;, &quot;Content-Type&quot;: &quot;application/json&quot;}<br><br>    async with streamablehttp_client(mcp_url, headers, timeout=timedelta(seconds=120), terminate_on_close=False) as (<br>        read_stream,<br>        write_stream,<br>        _,<br>    ):<br>        async with ClientSession(read_stream, write_stream) as session:<br>            await session.initialize()<br>            tool_result = await session.list_tools()<br>            return [tool.name for tool in tool_result.tools]<br><br># Running the app<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True, port=5000)</pre><pre><br><br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;MCP Agent Chat&lt;/title&gt;<br>    &lt;style&gt;<br>        body { font-family: Arial, sans-serif; margin: 50px; }<br>        .container { max-width: 600px; margin: 0 auto; text-align: center; }<br>        .btn { padding: 10px 20px; background: #007cba; color: white; text-decoration: none; border-radius: 5px; }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h1&gt;MCP Agent Chat&lt;/h1&gt;<br>        &lt;p&gt;Welcome to the MCP-powered AI chat application&lt;/p&gt;<br>        &lt;a href=&quot;/login&quot; class=&quot;btn&quot;&gt;Login with Microsoft&lt;/a&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;MCP Chat&lt;/title&gt;<br>    &lt;style&gt;<br>        body { font-family: Arial, sans-serif; margin: 20px; }<br>        .container { max-width: 800px; margin: 0 auto; }<br>        .success-message { <br>            background: #d4edda; <br>            color: #155724; <br>            padding: 15px; <br>            border-radius: 5px; <br>            border: 1px solid #c3e6cb; <br>            margin: 20px 0; <br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;h1&gt;MCP Tools&lt;/h1&gt;<br>        {% if success_message %}<br>        &lt;div class=&quot;success-message&quot;&gt;{{ success_message }}&lt;/div&gt;<br>        {% endif %}<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This Flask app does follow:</p><ol><li>Authenticate users via <strong>Microsoft OAuth2</strong></li><li>Safely handle <strong>tokens and sessions</strong></li><li>Connect to <strong>AWS Bedrock MCP</strong> for tool listing</li><li>List all the available Tools present in <strong>MCP server</strong></li></ol><p>This guide demonstrated how to securely deploy and access an MCP server using Amazon Bedrock Agent Core with Azure AD authentication</p><p>I’d love to hear your feedback — share your thoughts, questions, or suggestions in the comments. Together, we can build AI applications that are smarter, safer, and more collaborative</p><p><strong>References</strong></p><ol><li><a href="https://aws.amazon.com/bedrock/agentcore/">Amazon Bedrock AgentCore (Preview) — AWS</a></li><li><a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html">What is Amazon Bedrock AgentCore? — Amazon Bedrock AgentCore</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8d607b37e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>