<?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 Hardikwrites on Medium]]></title>
        <description><![CDATA[Stories by Hardikwrites on Medium]]></description>
        <link>https://medium.com/@hardikwrites?source=rss-ec8d177418d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KmA0QQD8xu0Gcbt-</url>
            <title>Stories by Hardikwrites on Medium</title>
            <link>https://medium.com/@hardikwrites?source=rss-ec8d177418d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:14:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hardikwrites/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[Supercharging Microsoft Copilot Studio: Intercept, Filter, and Rewrite Knowledge Before It Reaches…]]></title>
            <link>https://medium.com/@hardikwrites/supercharging-microsoft-copilot-studio-intercept-filter-and-rewrite-knowledge-before-it-reaches-f56eea9f2920?source=rss-ec8d177418d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f56eea9f2920</guid>
            <category><![CDATA[onknowledgerequested]]></category>
            <category><![CDATA[mcs-agent]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[microsoft-copilot-studio]]></category>
            <dc:creator><![CDATA[Hardikwrites]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 02:51:10 GMT</pubDate>
            <atom:updated>2026-04-13T02:51:10.586Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Supercharging Microsoft Copilot Studio: Intercept, Filter, and Rewrite Knowledge <em>Before</em> It Reaches the LLM</strong></h3><p>Modern copilots are only as powerful as the knowledge they can access. Microsoft Copilot Studio gives you strong out‑of‑the‑box connectors for SharePoint, Dataverse, SQL, Azure AI Search and many more, but real enterprise scenarios demand more. You often need to filter knowledge dynamically, enrich it, merge multiple sources, or even rewrite the content before the LLM sees it.</p><p>If your knowledge lives in Dataverse’s <strong>Knowledge Articles</strong> table, Copilot Studio will happily ingest all of it. But what if you want persona‑based filtering? Or product‑specific knowledge? Or custom search logic? The built‑in knowledge system can’t do that.</p><p>This is where the <strong>OnKnowledgeRequested</strong> trigger becomes your superpower.</p><p>It acts as a programmable middleware layer between the user’s question and the LLM’s grounding context, giving you full control over what knowledge is retrieved, how it’s transformed, and what ultimately gets passed to the model.</p><h3><strong>🧠 Why Custom Knowledge Pipeline Matters</strong></h3><p>Copilot Studio’s built‑in knowledge retrieval is great for many scenarios, but it has limitations that become blockers in enterprise environments:</p><ul><li>It <strong>cannot apply dynamic filtering</strong> (e.g., “only show content for Persona A”).</li><li>It <strong>cannot rewrite, enrich, or sanitize</strong> knowledge before sending it to the LLM.</li></ul><p>The <strong>OnKnowledgeRequested</strong> trigger solves all of these by letting you:</p><ul><li>Call your own search API (Azure AI Search, Dataverse queries, SQL, REST APIs, etc.)</li><li>Rewrite or expand the search query using system variables</li><li>Transform results into the exact schema Copilot Studio expects</li><li>Inject or remove knowledge dynamically</li><li>Combine multiple knowledge sources into a single grounding payload</li></ul><p>This is how you build a true enterprise‑grade copilot.</p><h3><strong>🧩 Key System Variables You Gain Access To</strong></h3><p>Inside an <strong>OnKnowledgeRequested</strong> topic, Copilot Studio exposes special system variables that aren’t available anywhere else:</p><ul><li><strong>System.SearchQuery</strong>: LLM‑optimized semantic search query</li><li><strong>System.KeywordSearchQuery</strong>: keyword‑optimized query for traditional search engines</li><li><strong>System.SearchResults</strong>: where you store the transformed knowledge snippets you want the LLM to use</li></ul><p>These variables form the backbone of your custom knowledge pipeline.</p><h3><strong>🛠️ Step‑by‑Step: Building Your Custom Knowledge Source</strong></h3><ol><li><strong>Create a Topic Using the OnKnowledgeRequested Trigger</strong></li></ol><p>Switch to <strong>Code View</strong> and define:</p><pre>kind: AdaptiveDialog<br>beginDialog:<br>  kind: OnKnowledgeRequested<br>  id: main<br>  intent: {}<br>  actions:<br>    # your actions here<br>inputType: {}<br>outputType: {}</pre><p>This topic will run <em>every time</em> the agent needs grounding knowledge.</p><p><strong>2. Retrieve Knowledge from Dataverse (or Any Search API)</strong></p><p>Use the Dataverse connector to fetch Knowledge Articles or call Azure AI Search, SQL, SharePoint, or a custom REST API.</p><p>This is where you apply persona‑based or context‑based filtering:</p><ul><li>Product</li><li>Region</li><li>User role</li><li>Security group</li><li>Conversation context</li></ul><p><strong>3.</strong> <strong>Transform Results into Copilot’s Required Schema</strong></p><p>Each knowledge snippet must include:</p><ul><li><strong>Content</strong>: the text you want the LLM to see</li><li><strong>ContentLocation</strong>: a URL or reference</li><li><strong>Title</strong>: a human‑readable title</li></ul><p><strong>4.</strong> <strong>Save the Final Snippets into System.SearchResults</strong></p><p>Example:</p><pre>- kind: SetVariable<br>  id: setSearchResults<br>  variable: System.SearchResults<br>  value: |-<br>    =ForAll(<br>      Topic.searchResults.results,<br>      {<br>        Content: snippet,<br>        ContentLocation: url,<br>        Title: title<br>      }<br>    )</pre><p>Whatever you store in System.SearchResults becomes the grounding context the LLM uses to answer the user’s question.</p><h3><strong>⚠️ A Critical Rule You Must Follow</strong></h3><p><strong>Do NOT add your Dataverse Knowledge Articles as a built‑in knowledge source in the agent.</strong></p><p>If you do, Copilot Studio will preload all articles and your interceptor will <em>not</em> be able to filter or override them.</p><p>Your custom pipeline only works when the agent has <strong>no built‑in knowledge source</strong> for that content.</p><h3><strong>🧭 Best Practices for High‑Quality Knowledge Retrieval</strong></h3><ul><li>Keep snippets short.</li><li>Return only the <strong>top 5–15</strong> most relevant knowledge documents.</li><li>Use <strong>System.SearchQuery</strong> for semantic search APIs.</li><li>Use <strong>System.KeywordSearchQuery</strong> for keyword‑based search.</li><li>Clean HTML before returning content.</li><li>Normalize formatting for consistency.</li></ul><h3><strong>🧱 Advanced Patterns You Can Implement</strong></h3><ol><li><strong>Role‑Based Knowledge Filtering</strong></li></ol><p>Use Dataverse security roles or Azure AD groups to determine which articles a user is allowed to see.</p><p><strong>2.</strong> <strong>Multi‑Source Knowledge Fusion</strong></p><p>Combine results from: Azure AI Search, Dataverse, SharePoint, SQL, Custom APIs</p><p>Merge them into a single grounding payload.</p><p><strong>3.</strong> <strong>Knowledge Rewriting</strong></p><p>Rewrite snippets to:</p><ul><li>Add missing context</li><li>Normalize terminology</li><li>Remove sensitive data</li><li>Expand acronyms</li><li>Improve clarity</li></ul><p><strong>4.</strong> <strong>Dynamic Knowledge Injection</strong></p><p>Inject knowledge based on: User profile, Conversation history, Product SKU, Region, Compliance rules</p><p>This is how you build a copilot that feels intelligent, adaptive, and enterprise‑ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f56eea9f2920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging APIs Locally with S2S authentication and Managed Identity (MI): A Secure and Scalable…]]></title>
            <link>https://medium.com/@hardikwrites/debugging-apis-locally-with-s2s-authetnication-and-managed-identity-mi-a-secure-and-scalable-3108e5e0e603?source=rss-ec8d177418d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3108e5e0e603</guid>
            <category><![CDATA[service-to-service]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[azure-managed-identities]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Hardikwrites]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 03:22:22 GMT</pubDate>
            <atom:updated>2026-04-02T14:25:43.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debugging APIs Locally with S2S authentication and Managed Identity (MI): A Secure and Scalable Approach</h3><p>Managed Identity (MI) is the gold standard for authentication when running workloads inside Azure. It removes secrets from code, simplifies credential management, and significantly improves security posture.</p><p>However, <strong>local debugging of APIs protected by AAD with S2S (Service-to-Service) authentication remains a common pain point</strong>. By default, MI tokens with API scopes can only be issued from within Azure-hosted environments, which makes local development and debugging awkward, brittle, or insecure.</p><p>In this blog, I’ll walk through a <strong>secure, scalable, and developer‑friendly approach</strong> that enables local debugging of AAD‑protected APIs with S2S authentication-without compromising production security.</p><p><strong>The Problem with Local Debugging and MI</strong></p><p>In production, the flow is straightforward:</p><ul><li>The service runs in Azure.</li><li>Azure injects a Managed Identity.</li><li>The service acquires a token seamlessly for specified API scopes.</li><li>The API validates the token and enforces authorization.</li></ul><p>Locally, however:</p><ul><li>There is no Managed Identity endpoint.</li><li>Developers often resort to <strong>manually generating tokens in Azure</strong> and passing them via HTTP headers.</li><li>This approach is error‑prone, hard to scale, and difficult to govern.</li></ul><p>I wanted a solution that:</p><ul><li>Works entirely locally</li><li>Uses Microsoft Entra ID (Azure AD) best practices</li><li>Scales cleanly across teams</li><li>Enforces least‑privilege access</li></ul><p><strong>A Different Approach: Enable Local Token Generation Securely</strong></p><p>Instead of generating tokens inside Azure and passing them to a local service, I flipped the model:</p><p><strong>Grant developers-controlled access directly on the API’s Entra application.</strong></p><p>This allows developers to:</p><ul><li>Generate access tokens locally</li><li>Call the API endpoint directly</li><li>Debug the application end‑to‑end with real authentication and authorization logic</li></ul><p><strong>Key Principle</strong></p><p>Only explicitly approved developers can generate tokens-and only for specific environments.</p><p><strong>Architecture Overview</strong></p><p>The approach hinges on Microsoft Entra application roles and group‑based access control.</p><h3><strong>High‑level flow:</strong></h3><ol><li>Create an Entra group</li><li>Assign application roles on the API’s Entra app</li><li>Grant the group access to those roles</li><li>Use DefaultAzureCredential locally to generate tokens</li></ol><h3><strong>Step 1: Create an Entra Group</strong></h3><p>By default, access tokens for API scopes <strong>cannot be generated locally</strong> unless the user has been granted access explicitly.</p><p>To enable this:</p><ul><li>Create a <strong>Microsoft Entra group</strong></li><li>Add yourself and relevant developers who need local debugging access</li></ul><p>✅ <strong>Important: </strong>Access is limited strictly to <strong>direct members</strong> of the group. <strong>Nested groups are not supported</strong> for app role assignments. This constraint is actually a security advantage-it prevents accidental permission sprawl.</p><h3><strong>Step 2: Create Application Roles on the API Entra App</strong></h3><p>Next, define <strong>application roles</strong> on the API’s Entra application. These roles can map cleanly to authorization logic in code, such as:</p><ul><li>Reader</li><li>Agent</li><li>Admin</li></ul><p><strong>Where to configure:</strong></p><ol><li>Azure Portal → Microsoft Entra ID</li><li>App registrations</li><li>Select your API’s app</li><li>Navigate to App roles</li><li>Create roles as needed</li></ol><p>These roles become first‑class authorization primitives inside your API.</p><h3><strong>Step 3: Assign the Entra Group to the Application Role</strong></h3><p>Once roles are created:</p><ol><li>Go to Enterprise Applications</li><li>Locate your API’s Entra app</li><li>Navigate to Users and Groups</li><li>Assign the Entra group to the appropriate app role</li></ol><p>Because you’re a member of the group, you can now generate an access token locally for the API scope.</p><p>While you <em>can</em> assign users individually, <strong>group‑based management scales far better</strong> and avoids operational overhead as teams grow.</p><p><strong>Generating an Access Token Locally</strong></p><p>With the permissions in place, token generation becomes straightforward. Here’s a sample using DefaultAzureCredential:</p><pre>var credential = new DefaultAzureCredential(<br>new DefaultAzureCredentialOptions<br>{<br>  ExcludeManagedIdentityCredential = true,<br>  InteractiveBrowserCredentialClientId = &quot;&lt;&lt;API Entra Client ID&gt;&gt;&quot;<br>});<br><br>var token = await credential.GetTokenAsync(<br>  new TokenRequestContext(<br>    new[] { &quot;api://&lt;&lt;API Entra Client ID&gt;&gt;/.default&quot; }<br>  )<br>);</pre><p>You can now:</p><ul><li>Attach this token as a Bearer token</li><li>Call your API endpoint locally</li><li>Debug authentication and authorization behavior exactly as it runs in Azure</li></ul><p><strong>Common Issues and How to Fix Them</strong></p><p><strong>❌ Error: TS003 or TS005 — No accounts found</strong></p><p><strong>Cause:</strong> No Azure account found.</p><p><strong>Resolution: </strong>Navigate to Visual Studio → Tools → Options → Azure Services Authentication and then add an account.</p><p><strong>❌ Error: AADSTS65001 — The user or administrator has not consented</strong></p><p><strong>Cause:</strong> The client (e.g., Visual Studio) is not allowed to request tokens for your API.</p><p><strong>Resolution: </strong>Allow the Visual Studio client ID in your API configuration. If using <strong>Easy Auth</strong>, add the client ID to the allowed list.</p><p><strong>Group Management Best Practices</strong></p><p>To keep this approach secure and compliant:</p><ol><li><strong>Review group membership monthly — </strong>Remove developers who no longer need access.</li><li><strong>Enable owner approval — </strong>Prevent self‑service access without oversight.</li><li><strong>Use Just‑In‑Time (JIT) access</strong></li></ol><ul><li>Require developers to activate access explicitly</li><li>Enforce approval during activation for sensitive APIs</li></ul><p>This ensures access is <strong>intentional, auditable, and time‑bound</strong>.</p><p><strong>Environment‑Specific Control</strong></p><p>One of the biggest advantages of this model is <strong>environment isolation</strong>:</p><p>✅ Pre‑production: Enable local debugging roles</p><p>❌ Production: Do not create or assign local roles</p><p>This makes it <strong>impossible</strong> to generate production tokens locally-by design.</p><p><strong>Benefits of This Approach</strong></p><p>✅ Tokens are generated locally and passed via HTTP requests</p><p>✅ Only explicitly assigned users or group members can generate tokens</p><p>✅ Access is tightly controlled and auditable</p><p>✅ Easy to manage at scale using Entra groups</p><p>✅ Strong security posture with JIT and approval workflows</p><p>✅ Clean separation between local, pre‑prod, and prod environments</p><h3><strong>Final Thoughts</strong></h3><p>Local debugging should never force teams to compromise on security. By leveraging <strong>Microsoft Entra application roles, group‑based access, and DefaultAzureCredential</strong>, you can achieve:</p><ul><li>A seamless developer experience</li><li>Production‑grade authentication locally</li><li>Strong governance and least‑privilege access</li></ul><p>This approach has worked extremely well for teams building AAD‑protected APIs at scale-and it strikes the right balance between <strong>developer productivity and enterprise security</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3108e5e0e603" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Microsoft’s Agent Framework Passes Context to MCP Tools Using Middleware]]></title>
            <link>https://medium.com/@hardikwrites/how-microsofts-agent-framework-passes-context-to-mcp-tools-using-middleware-78cfc2c8cc0f?source=rss-ec8d177418d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/78cfc2c8cc0f</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[microsoft-agent-framework]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[middleware]]></category>
            <dc:creator><![CDATA[Hardikwrites]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 20:00:42 GMT</pubDate>
            <atom:updated>2026-03-08T20:00:42.784Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been experimenting with Microsoft’s Agent Framework and the Model Context Protocol (MCP), you’ve probably noticed something interesting: tools often need more information than what the user provides.</p><p>Users give you the <em>intent</em>, but your system still needs things like correlation IDs, tenant IDs, or session metadata to make the call meaningful in a real application.</p><p>The question is:</p><p><strong>How do you pass this extra context to MCP tools without forcing the user to type it?</strong></p><p>That’s exactly the problem I wanted to solve, and the solution turned out to be surprisingly elegant thanks to the Agent Framework’s middleware pipeline.</p><p>To make this concrete, I built a small sample application that demonstrates the process end‑to‑end. You can find it here:</p><p><a href="https://github.com/hardikp81/agent-middleware-sample/tree/main/Agent.Middleware.Demo"><strong>https://github.com/hardikp81/agent-middleware-sample/tree/main/Agent.Middleware.Demo</strong></a></p><p>Let me walk you through how it works.</p><p><strong>The Setup: Two Small Projects Working Together</strong></p><p>The sample solution contains two projects:</p><h3><strong>1. MCP.WebApi</strong></h3><p>This is a simple MCP server that exposes one tool:</p><pre>GetAccountTransactionById(accountId, correlationId)</pre><p>The tool requires both parameters. But in a real chat scenario, you don’t want the user to type:</p><p>“Get the transaction for account 12345 with correlation ID 8f2c….”</p><p>Instead of requiring the user to provide the Correlation ID, the system should automatically forward that value to the MCP server.</p><h3><strong>2. Agent.Middleware.Demo (Console Chat App)</strong></h3><p>This is a lightweight console app that acts as the “agent client.”<br> The user interacts with an OpenAI‑powered agent, and the agent is configured to call the MCP tool when needed.</p><p>Here’s the important part:<br> <strong>The user only provides the account ID.</strong><br> The system automatically injects the correlation ID using middleware.</p><p><strong>Why Middleware Is the Right Tool for This Job</strong></p><p>The Microsoft Agent Framework treats tool calls — whether they’re MCP tools, REST tools, or custom functions — as part of a unified invocation pipeline.</p><p>That means you can intercept tool calls <em>before</em> they’re executed and modify the arguments.</p><p>This is exactly what middleware is designed for.</p><p>Instead of:</p><ul><li>modifying the MCP server</li><li>adding custom headers</li><li>or forcing the user to provide system-level metadata</li></ul><p>…you simply plug into the invocation pipeline and enrich the arguments.</p><p>It keeps your agent logic clean and your user experience natural.</p><p><strong>Injecting the Correlation ID Automatically</strong></p><p>Here’s the heart of the solution: a custom middleware.</p><p>It intercepts every tool call and adds a correlation ID when the tool is an MCP tool.</p><p>A simplified version looks like this:</p><pre>async ValueTask&lt;object?&gt; CustomFunctionCallingMiddleware(<br>    AIAgent agent,<br>    FunctionInvocationContext context,<br>    Func&lt;FunctionInvocationContext, CancellationToken, ValueTask&lt;object?&gt;&gt; next,<br>    CancellationToken cancellationToken)<br>{<br>    Console.WriteLine();<br>    Console.WriteLine($&quot;Function Name: {context!.Function.Name}&quot;);<br><br>    context.Arguments[&quot;correlationId&quot;] = Guid.NewGuid().ToString();<br>    Console.WriteLine($&quot;Function Arguments: {JsonConvert.SerializeObject(context!.Arguments)}&quot;);<br>    Console.WriteLine();<br><br>    var result = await next(context, cancellationToken);<br>    Console.WriteLine($&quot;Function Call Result: {result}&quot;);<br>    Console.WriteLine();<br><br>    return result;<br>}</pre><p></p><p>That’s it.<br> No special handling on the MCP server.<br> No changes to the user prompt.<br> No extra instructions to the LLM.</p><p>The middleware quietly injects the missing parameter and lets the rest of the pipeline continue.</p><p><strong>What the User Actually Experiences</strong></p><p>In the console app, the user might type:</p><p>Get the transaction for account 12345</p><p>The LLM interprets this and generates a tool call with:</p><p>{ “accountId”: “12345” }</p><p>The middleware steps in and transforms it into:</p><p>{ “accountId”: “12345”, “correlationId”: “c3f1e2b4-…” }</p><p>The MCP server receives both parameters and processes the request normally.</p><p>The user never sees the correlation ID.<br> The agent never asks for it.<br> The system stays clean and traceable.</p><p><strong>What Happens on the MCP Server Side</strong></p><p>On the server, the tool implementation is completely straightforward:</p><pre>public AccountTransaction GetAccountTransactionById(string accountId, string correlationId) <br>{ <br>  // correlationId is now available automatically <br>}</pre><p>The server doesn’t need to know anything about the middleware.<br> It just receives the parameters it expects.</p><p><strong>Why This Is So Useful</strong></p><p>Once you understand this approach, you start to see how powerful it is.</p><p>You can use the same middleware to inject:</p><ul><li>tenant IDs</li><li>user IDs</li><li>session IDs</li><li>timestamps</li><li>distributed tracing IDs</li><li>security tokens</li><li>audit metadata</li></ul><p>All without changing your MCP server or complicating your prompts.</p><p>It’s a clean separation of concerns:</p><ul><li><strong>User prompt</strong> → natural language</li><li><strong>LLM</strong> → intent extraction</li><li><strong>Middleware</strong> → system context</li><li><strong>MCP server</strong> → business logic</li></ul><p>This is exactly the kind of architecture you want in production systems.</p><p><strong>Try It Yourself</strong></p><p>If you want to see the full implementation, you can explore the sample here:</p><p>👉 <a href="https://github.com/hardikp81/agent-middleware-sample/tree/main/Agent.Middleware.Demo">https://github.com/hardikp81/agent-middleware-sample/tree/main/Agent.Middleware.Demo</a></p><p>Clone it, run the console app, and watch how the correlation ID flows through the system automatically.</p><p><strong>Final Thoughts</strong></p><p>The Microsoft Agent Framework gives developers a powerful way to build AI agents that interact with real systems. Middleware is one of the most underrated features in the framework, and when you combine it with MCP, you get a clean, scalable way to pass system context into tool calls.</p><p>If you’re building enterprise-grade AI applications — especially ones that require auditing, traceability, or multi-tenant behavior — this is worth adopting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78cfc2c8cc0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>