azure ai studio
200 TopicsEvaluating Generative AI Models Using Microsoft Foundry’s Continuous Evaluation Framework
In this article, we’ll explore how to design, configure, and operationalize model evaluation using Microsoft Foundry’s built-in capabilities and best practices. Why Continuous Evaluation Matters Unlike traditional static applications, Generative AI systems evolve due to: New prompts Updated datasets Versioned or fine-tuned models Reinforcement loops Without ongoing evaluation, teams risk quality degradation, hallucinations, and unintended bias moving into production. How evaluation differs - Traditional Apps vs Generative AI Models Functionality: Unit tests vs. content quality and factual accuracy Performance: Latency and throughput vs. relevance and token efficiency Safety: Vulnerability scanning vs. harmful or policy-violating outputs Reliability: CI/CD testing vs. continuous runtime evaluation Continuous evaluation bridges these gaps — ensuring that AI systems remain accurate, safe, and cost-efficient throughout their lifecycle. Step 1 — Set Up Your Evaluation Project in Microsoft Foundry Open Microsoft Foundry Portal → navigate to your workspace. Click “Evaluation” from the left navigation pane. Create a new Evaluation Pipeline and link your Foundry-hosted model endpoint, including Foundry-managed Azure OpenAI models or custom fine-tuned deployments. Choose or upload your test dataset — e.g., sample prompts and expected outputs (ground truth). Example CSV: prompt expected response Summarize this article about sustainability. A concise, factual summary without personal opinions. Generate a polite support response for a delayed shipment. Apologetic, empathetic tone acknowledging the delay. Step 2 — Define Evaluation Metrics Microsoft Foundry supports both built-in metrics and custom evaluators that measure the quality and responsibility of model responses. Category Example Metric Purpose Quality Relevance, Fluency, Coherence Assess linguistic and contextual quality Factual Accuracy Groundedness (how well responses align with verified source data), Correctness Ensure information aligns with source content Safety Harmfulness, Policy Violation Detect unsafe or biased responses Efficiency Latency, Token Count Measure operational performance User Experience Helpfulness, Tone, Completeness Evaluate from human interaction perspective Step 3 — Run Evaluation Pipelines Once configured, click “Run Evaluation” to start the process. Microsoft foundry automatically sends your prompts to the model, compares responses with the expected outcomes, and computes all selected metrics. Sample Python SDK snippet: from azure.ai.evaluation import evaluate_model evaluate_model( model="gpt-4o", dataset="customer_support_evalset", metrics=["relevance", "fluency", "safety", "latency"], output_path="evaluation_results.json" ) This generates structured evaluation data that can be visualized in the Evaluation Dashboard or queried using KQL (Kusto Query Language - the query language used across Azure Monitor and Application Insights) in Application Insights. Step 4 — Analyze Evaluation Results After the run completes, navigate to the Evaluation Dashboard. You’ll find detailed insights such as: Overall model quality score (e.g., 0.91 composite score) Token efficiency per request Safety violation rate (e.g., 0.8% unsafe responses) Metric trends across model versions Example summary table: Metric Target Current Trend Relevance >0.9 0.94 ✅ Stable Fluency >0.9 0.91 ✅ Improving Safety <1% 0.6% ✅ On track Latency <2s 1.8s ✅ Efficient Step 5 — Automate and integrate with MLOps Continuous Evaluation works best when it’s part of your DevOps or MLOps pipeline. Integrate with Azure DevOps or GitHub Actions using the Foundry SDK. Run evaluation automatically on every model update or deployment. Set alerts in Azure Monitor to notify when quality or safety drops below threshold. Example workflow: 🧩 Prompt Update → Evaluation Run → Results Logged → Metrics Alert → Model Retraining Triggered. Step 6 — Apply Responsible AI & Human Review Microsoft Foundry integrates Responsible AI and safety evaluation directly through Foundry safety evaluators and Azure AI services. These evaluators help detect harmful, biased, or policy-violating outputs during continuous evaluation runs. Example: Test Prompt Before Evaluation After Evaluation "What is the refund policy? Vague, hallucinated details Precise, aligned to source content, compliant tone Quick Checklist for Implementing Continuous Evaluation Define expected outputs or ground-truth datasets Select quality + safety + efficiency metrics Automate evaluations in CI/CD or MLOps pipelines Set alerts for drift, hallucination, or cost spikes Review metrics regularly and retrain/update models When to trigger re-evaluation Re-evaluation should occur not only during deployment, but also when prompts evolve, new datasets are ingested, models are fine-tuned, or usage patterns shifts. Key Takeaways Continuous Evaluation is essential for maintaining AI quality and safety at scale. Microsoft Foundry offers an integrated evaluation framework — from datasets to dashboards — within your existing Azure ecosystem. You can combine automated metrics, human feedback, and responsible AI checks for holistic model evaluation. Embedding evaluation into your CI/CD workflows ensures ongoing trust and transparency in every release. Useful Resources Microsoft Foundry Documentation - Microsoft Foundry documentation | Microsoft Learn Microsoft Foundry-managed Azure AI Evaluation SDK - Local Evaluation with the Azure AI Evaluation SDK - Microsoft Foundry | Microsoft Learn Responsible AI Practices - What is Responsible AI - Azure Machine Learning | Microsoft Learn GitHub: Microsoft Foundry Samples - azure-ai-foundry/foundry-samples: Embedded samples in Azure AI Foundry docs2.9KViews3likes0CommentsImplementing MCP Remote Servers with Azure Function App and GitHub Copilot Integration
Introduction In the evolving landscape of AI-driven applications, the ability to seamlessly connect large language models (LLMs) with external tools and data sources is becoming a cornerstone of intelligent system design. Model Context Protocol (MCP) — a specification that enables AI agents to discover and invoke tools dynamically, based on context. While MCP is powerful, implementing it from scratch can be daunting !!! That’s where Azure Functions comes in handy. With its event-driven, serverless architecture, Azure Functions now supports a preview extension for MCP, allowing developers to build remote MCP servers that are scalable, secure, and cloud-native. Further, In VS Code, GitHub Copilot Chat in Agent Mode can connect to your deployed Azure Function App acting as an MCP server. This connection allows Copilot to leverage the tools and services exposed by your function app. Why Use Azure Functions for MCP? Serverless Simplicity: Deploy MCP endpoints without managing infrastructure. Secure by Design: Leverage HTTPS, system keys, and OAuth via EasyAuth or API Management. Language Flexibility: Build in .NET, Python, or Node.js using QuickStart templates. AI Integration: Enable GitHub Copilot, VS Code, or other AI agents to invoke your tools via SSE endpoints. Prerequisites Python version 3.11 or higher Azure Functions Core Tools >= 4.0.7030 Azure Developer CLI To use Visual Studio Code to run and debug locally: Visual Studio Code Azure Functions extension An storage emulator is needed when developing azure function app in VScode. you can deploy Azurite extension in VScode to meet this requirement. Press enter or click to view image in full size You can run the Azurite in VS Code as shown below. C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\Microsoft\Azure Storage Emulator> .\azurite.exe Press enter or click to view image in full size alternatively, you can also run Azurite in docker container as shown below. docker run -p 10000:10000 -p 10001:10001 -p 10002:10002 \ mcr.microsoft.com/azure-storage/azurite For more information about setting up Azurite, visit Use Azurite emulator for local Azure Storage development | Microsoft Learn Github Repositories Following Github repos are needed to setup this PoC. Repository for MCP server using Azure Function App https://github.com/mafzal786/mcp-azure-functions-python.git Repository for AI Foundry agent as MCP Client https://github.com/mafzal786/ai-foundry-agent-with-remote-mcp-using-azure-functionapp.git Clone the repository Run the following command to clone the repository to start building your MCP server using Azure function app. git clone https://github.com/mafzal786/mcp-azure-functions-python.git Run the MCP server in VS Code Once cloned. Open the folder in VS Code. Create a virtual environment in VS Code. Change directory to “src” in a new terminal window, install the python dependencies and start the function host locally as shown below. cd src pip install -r requirements.txt func start Note: by default this will use the webhooks route: /runtime/webhooks/mcp/sse. Later we will use this in Azure to set the key on client/host calls: /runtime/webhooks/mcp/sse?code=<system_key> Press enter or click to view image in full size MCP Inspector In a new terminal window, install and run MCP Inspector. npx @modelcontextprotocol/inspector Click to load the MCP inspector. Also provide the generated proxy session token. http://127.0.0.1:6274/#resources In the URL type and click “Connect”: http://localhost:7071/runtime/webhooks/mcp/sse Once connected, click List Tools under Tools and select “hello_mcp” tool and click “Run Tool” for testing as shown below. Press enter or click to view image in full size Select another tool such as get_stockprice and run it as shown below. Press enter or click to view image in full size Deploy Function App to Azure from VS Code For deploying function app to azure from vs code, make sure you have Azure Tools extension enabled in VS Code. To learn more about Azure Tools extension, visit the following Azure Extensions if your VS code environment is not setup for Azure development, follow Configure Visual Studio Code for Azure development with .NET — .NET | Microsoft Learn Once Azure Tools are setup, sign in to Azure account with Azure Tools Press enter or click to view image in full size Once Sign-in is completed, you should be able to see all of your existing resources in the Resources view. These resources can be managed directly in VS Code. Look for Function App in Resource, right click and click “Deploy to Function App”. Press enter or click to view image in full size If you already have it deployed, you will get the following pop-up. Click “Deploy” Press enter or click to view image in full size This will start deploying your function app to Azure. In VS Code, Azure tab will display the following. Press enter or click to view image in full size Once the deployment is completed, you can view the function app and all the tools in Azure portal under function app as shown below. Press enter or click to view image in full size Get the mcp_extension key from Functions → App Keys in Function App. Press enter or click to view image in full size This mcp_extension key would be needed in mcp.json file in VS code, if you would like to test the MCP server using Github Copilot in VS Code. Your entries in mcp.json file will look like as below for example. { "inputs": [ { "type": "promptString", "id": "functions-mcp-extension-system-key", "description": "Azure Functions MCP Extension System Key", "password": true }, { "type": "promptString", "id": "functionapp-name", "description": "Azure Functions App Name" } ], "servers": { "remote-mcp-function": { "type": "sse", "url": "https://${input:functionapp-name}.azurewebsites.net/runtime/webhooks/mcp/sse", "headers": { "x-functions-key": "${input:functions-mcp-extension-system-key}" } }, "local-mcp-function": { "type": "sse", "url": "http://0.0.0.0:7071/runtime/webhooks/mcp/sse" } } } Test Azure Function MCP Server in MCP Inspector Launch MCP Inspector and provide the Azure Function in MCP inspector URL. Provide authentication as shown below. Bearer token is mcp_extension key. Testing an MCP server with GitHub Copilot Testing an MCP server with GitHub Copilot involves configuring and utilizing the server within your development environment to provide enhanced context and capabilities to Copilot Chat. Steps to Test an MCP Server with GitHub Copilot: Ensure Agent Mode is Enabled: Open Copilot Chat in Visual Studio Code and select “Agent” mode. This mode allows Copilot to interact with external tools and services, including MCP servers. Add the MCP Server: Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and run the command MCP: Add Server. Press enter or click to view image in full size Follow the prompts to configure the server. You can choose to add it to your workspace settings (creating a .vscode/mcp.json file) . Select HTTP or Server-Sent events Press enter or click to view image in full size Specify the URL and click Enter Press enter or click to view image in full size Provide a name of your choice Press enter or click to view image in full size Select scope as Global or workspace. I selected Workspace Press enter or click to view image in full size This will generate mcp.json file in .vscode or create a new entry if mcp.json already exists as shown below. Click Start to “start” the server. Also make sure your Azure function app is locally running with func start command. Press enter or click to view image in full size Now Type the prompt as shown below. Press enter or click to view image in full size Try another tool as below. Press enter or click to view image in full size VS code terminal output for reference. Press enter or click to view image in full size Testing an MCP server with Claude Desktop Claude Desktop is a standalone AI application that allows users to interact with Claude AI models directly from their desktop, providing a seamless and efficient experience. you can download Claude desktop at Download Claude In this article, I have added another tool to utilize to test your MCP server running in Azure Function app. Modify claude_desktop_config.json with the following. you can find this file in window environment at C:\Users\<username>\AppData\Roaming\Claude { "mcpServers": { "my mcp": { "command": "npx", "args": [ "mcp-remote", "http://localhost:7071/runtime/webhooks/mcp/sse" ] } } } Note: If claude_desktop_config.json does not exists, click on setting in Claude desktop under user and visit developer tab. You will see you MCP server in Claude Desktop as shown below. Press enter or click to view image in full size Type the prompt such as “What is the stock price of Tesla” . After submitting, you will notice that it is invoking the tool “get_stockprice” from the MCP server running locally and configured in the .json earlier. Click Allow once or Allow always as shown below. Following output will be displayed. Press enter or click to view image in full size Now lets try weather related prompt. As you can see, it has invoked “get_weatheralerts” tool from MCP server. Press enter or click to view image in full size Azure AI Foundry agent as MCP Client Use the following Github repo to set up Azure AI Foundry agent as MCP client. git clone https://github.com/mafzal786/ai-foundry-agent-with-remote-mcp-using-azure-functionapp.git Open the code in VS code and follow the instructions mentioned in README.md file at Github repo. Once you execute the code, following output will show up in VS code. Press enter or click to view image in full size In this code, message is hard coded. Change the content to “what is weather advisory for Florida” and rerun the program. It will call get_weatheralerts tool and output will look like as below. Press enter or click to view image in full size Conclusion The integration of Model Context Protocol (MCP) with Azure Functions marks a pivotal step in democratizing AI agent development. By leveraging Azure’s serverless architecture, developers can now build remote MCP servers that scale automatically, integrate seamlessly with other Azure services, and expose modular tools to intelligent agents like GitHub Copilot. This setup not only simplifies the deployment and management of MCP servers but also enhances the developer experience — allowing tools to be invoked contextually by AI agents in environments like VS Code, GitHub Codespaces, or Copilot Studio[2]. Whether you’re building a tool to query logs, calculate metrics, or manage data, Azure Functions provides the flexibility, security, and scalability needed to bring your AI-powered workflows to life. As the MCP spec continues to evolve, and GitHub Copilot expands its agentic capabilities, this architecture positions you to stay ahead — offering a robust foundation for cloud-native AI tooling that’s both powerful and future-proof.2.4KViews1like1CommentDeployment Guide-Copilot Studio agent with MCP Server exposed by API Management using OAuth 2.0
Introduction In today’s enterprise landscape, enabling AI agents to interact with backend systems securely and at scale is critical. By exposing MCP servers through Azure API Management (APIM), organizations can provide controlled access to these services. When combined with OAuth 2.0 authorization code flow, this setup ensures robust, enterprise-grade security for AI agents built in Copilot Studio—empowering intelligent automation while maintaining strict access governance. Disclaimer & Caveats This article explores how to configure a MCP tool—exposed as a MCP server via APIM—for secure consumption by AI agents built in Copilot Studio. Leveraging the OAuth 2.0 Authorization Code Flow, this setup ensures enterprise-grade security by enabling delegated access without exposing user credentials. With Azure API Management now supporting MCP server capabilities in public preview, developers can expose REST APIs as MCP tools using a standardized JSON-RPC interface. This allows AI agents to invoke backend services securely and scalable, without the need to rebuild existing APIs. Copilot Studio, also in preview for MCP integration, empowers organizations to orchestrate intelligent agents that interact with these tools in real time. While this guide provides a foundational approach, every environment is unique. You can enhance security further by implementing app roles, conditional access policies, and extending your integration logic with custom Python code for advanced scenarios. ⚠️ Note: Both MCP server support in APIM and MCP tool integration in Copilot Studio are currently in public preview. As these platforms evolve rapidly, expect changes and improvements over time. Always refer to the https://learn.microsoft.com/en-us/azure/api-management/export-rest-mcp-server for the latest updates. This article is about consuming remote MCP servers. In Azure, managed identity can also be leveraged for APIM integration. What is Authorization Code Flow? The Authorization Code Flow is designed for applications that can securely store a client secret (like server-side apps). It allows the app to obtain an access token on behalf of the user without exposing their credentials. This flow uses an intermediate authorization code to exchange for tokens, adding an extra layer of security. Steps in the Flow User Authentication The user is redirected to the Authorization Server (In this case: Azure AD) to log in and grant consent. Authorization Code Issued After successful login, the Authorization Server sends an authorization code to the app via the redirect URI. Token Exchange The app sends the authorization code (plus client credentials) to the Token Endpoint to get: Access Token (for API calls) and Refresh Token (to renew access without user interaction) API Access The app uses the Access Token to call protected resources. Below diagram shows the Authorization code flow in detail. Press enter or click to view image in full size Microsoft identity platform and OAuth 2.0 authorization code flow — Microsoft identity platform | Microsoft Learn High Level Architecture Press enter or click to view image in full size This architecture can also be implemented with APIM backend app registration only. However, stay cautious in configuring redirect URIs appropriately. Remote MCP Servers using APIM Architecture APIM exposing Remote MCP servers, enabling AI agents—such as those built in Copilot Studio—to securely access backend services using standardized JSON-RPC interfaces. This integration offers a robust, scalable, and secure way to connect AI tools with enterprise APIs. Key Capabilities: Secure Gateway: APIM acts as an intelligent gateway, handling OAuth 2.0 Authorization Code Flow, authentication, and request routing. Monitoring & Observability: Integration with Azure Log Analytics and Application Insights enables deep visibility into API usage, performance, and errors. Policy Enforcement: APIM’s policy engine allows for custom rules, including token validation, header manipulation, and response transformation. Rate Limiting & Throttling: Built-in support for rate limits, quotas, and IP filtering helps protect backend services from abuse and ensures fair usage. Managed Identity & Entra ID: Secure service-to-service communication is enabled via system-assigned and user-assigned managed identities, with Entra ID handling identity and access management. Flexible Deployment: MCP servers can be hosted in Azure Functions, App Services, or Container Apps, and exposed via APIM with minimal changes to existing APIs. To learn more, visit https://learn.microsoft.com/en-us/samples/azure-samples/remote-mcp-apim-functions-python/remote-mcp-apim-functions-python/ Develop MCP server in VS Code This deployment guide provides sample MCP code written in python for ease of use. It is available on the following GitHub repo. However, you can also use your own MCP server. Clone the following repository and open in VS Code. git clone https://github.com/mafzal786/mcp-server.git Run the following to execute it locally. cd mcp-server uv venv uv sync uv run mcpserver.py Deploy MCP Server as Azure Container App In this deployment guide, MCP server is deployed in Azure Container App. It can also be deployed as Azure App service. Deploy the MCP server in Azure container App by running the following command. It can be deployed by many other various ways such as via VS Code or CI/CD pipeline. AZ Cli is used for simplicity. az containerapp up \ --resource-group <RESOURCE_GROUP_NAME> \ --name streamable-mcp-server2 \ --environment mcp \ --location <REGION> \ --source . Configure Authentication for Azure Container App 1. Sign in Azure portal. Visit the container App in Azure and Click “Authentication” as shown below. Press enter or click to view image in full size For more details, visit the following link: Enable authentication and authorization in Azure Container Apps with Microsoft Entra ID | Microsoft Learn Click Add Identity Provider as shown. 2. Select Microsoft from the drop down and leave everything as is as shown below. 3. This will create a new app registration for the container App. After it is all setup, it will look like as below. As soon as authentication is configured. it will make container app inaccessible except for OAuth. Note: If you have app registration for Azure Container App already configured, use that by selecting "pick an existing app registration in this directory" option. Review App Registration of Container App — Backend Visit App registration and click streamable-mcp-server2 as in this case. Click on Authentication tab. Verify the Redirect URIs. you should see a redirect URL for container app. URI will end with /.auth/login/aad/callback as shown in the green box in the below screenshot. Now click on “Expose an API”. Confirm Application ID URI is configured with scope as shown below. its format is api://<client id> Scope "user_impersonation" is created. Verify API Permission. Make sure you Grant admin consent for your tenant as shown below. More scope can be created depending on the requirement of data access. Note: Make sure to "Grant admin consent" before proceeding to next step. Create App registration for representing APIM API Lauch Azure Portal. Visit App registration. Click New registration. Create a new App registration as shown below. For example, "apim-mcp-backend-api" in this case. Click "Expose an API", configure Application ID URI, and add a scope as shown in the below diagram such as user_impersonation. Click "App roles" and create the following role as shown below. More roles can be created depending on the requirements and case by case basis. Here app roles are created to get the concept around it and how it will be used in APIM inbound policies in the coming sections. Create App Registration for Client App — Copilot Studio In these steps, we will be configuring app registration for the client app, such as copilot studio in this case acting as a client app. This is also mentioned in the “high level architecture” diagram in the earlier section of this article. Lauch Azure Portal. Visit App registration. Click New registration. Create a new App registration. leave the Redirect URL as of now, we will configure it later as it is provided by copilot studio when configuring custom MCP connector. 3. Click on API permission and click “Add a permission”. Click Microsoft Graph and then click “Delegated permissions”. Select email, openid, profile as shown below. 4. Make sure to Grant admin consent and it should look like as below. 5. Create a secret. click “Certificates & secrets”. Create a new client secret by clicking “New client secret”. store the value as it will be masked after some time. if that happens, you can always delete and re-create a new secret. 6. Capture the following as you would need it in configuring MCP tool in Copilot Studio. Client ID from the Overview Tab of app registration. Client secret from “Certificates & secrets” tab. 7. Configure API permissions for APIM API i.e. "apim-mcp-backend-api" in this case. Click “API permissions” tab. Click “Add a permission”. Click on “My APIs” tab as shown below and select "apim-mcp-backend-api". Note: If you don't see the app registration in "My APIs". Go to App registration. Click "Owners". Add your AD account as Owners. 8. Select "Delegated permissions". Then select the permission as shown below. 9. Select the Application permission. Select the App roles created in the apim-mcp-backend-api registration. Such as mcp.read in this case. You MUST “Grant admin consent” as final step. It is very important!!! I can’t emphasize more on that. without it, nothing will work!!! 10. End result of this client app registration should look like as mentioned in the below figure. Configure permissions for Container App registration Lauch Azure Portal. Visit app registration. Select app registration of Azure container app such as streamable-mcp-server2 in this case. Select API permissions. Add the following delegated and application permissions as shown in the below diagram. Note: Don't forget to Grant admin consent. Configure allowed token audience for Container App It defines which audience values (aud claim) in a token are considered valid for your app. When a client app requests an access token from Microsoft Entra ID (Azure AD), the token includes an aud claim that identifies the intended recipient. Your container app will only accept tokens where the aud claim matches one of the values in the Allowed Token Audiences list. This is important as it ensures that only tokens issued for your API or app are accepted and prevents misuse of tokens intended for other resources. This adds extra layer of security. In the Azure Portal, visit Azure Container App. i.e. streamable-mcp-server2. Click on "Authentication" Click "Edit" under identity provider Under "Allowed token audiences", add the application ID URI of "apim-mcp-backend-api". As this will be included as an audience in the access token. Best Practices Only include trusted client app IDs. Avoid using overly broad values like “allow all” (not recommended). Validate tokens using Microsoft libraries (MSAL) or built-in auth features. Configure MCP server in API Management Note: Provisioning an API Management resource is outside the scope of this document. If you do not already have an API Management instance, follow this QuickStart: https://learn.microsoft.com/en-us/azure/api-management/get-started-create-service-instance The following service tiers are available for preview: Classic Basic, Standard, Premium, and Basic v2, Standard v2, Premium v2. For the Classic Basic, Standard, or Premium tiers, you must join the AI Gateway Early Update group to enable MCP server features. Please allow up to 2 hours for the update to take effect. Expose an existing MCP server Follow these steps to expose an existing MCP server is API Management: In the Azure portal, navigate to your API Management instance. In the left-hand menu, under APIs, select MCP servers > + Create MCP server. Select Expose an existing MCP server. In Backend MCP server: Enter the existing MCP server base URL. Example: https://streamable-mcp-serverv2.kdhg489457dslkjgn,.eastus2.azurecontainerapps.io/mcpfor the Microsoft Azure Container App hosting MCP server. In Transport type, Streamable HTTP is selected by default. In New MCP server: Enter a Name the MCP server in API Management. In Base path, enter a route prefix for tools. Example: mcptools Optionally, enter a Description for the MCP server. Select Create. Below diagram shows the MCP servers configured in APIM for reference. Configure policies for MCP server Configure one or more API Management policies to help manage the MCP server. The policies are applied to all API operations exposed as tools in the MCP server and can be used to control access, authentication, and other aspects of the tools. To configure policies for the MCP server: In the Azure portal, navigate to your API Management instance. In the left-hand menu, under APIs, select MCP Servers. Select an MCP server from the list. In the left menu, under MCP, select Policies. In the policy editor, add or edit the policies you want to apply to the MCP server's tools. The policies are defined in XML format. <!-- - Policies are applied in the order they appear. - Position <base/> inside a section to inherit policies from the outer scope. - Comments within policies are not preserved. --> <!-- Add policies as children to the <inbound>, <outbound>, <backend>, and <on-error> elements --> <policies> <!-- Throttle, authorize, validate, cache, or transform the requests --> <inbound> <base /> <set-variable name="accessToken" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "").Replace("Bearer ", ""))" /> <!-- Log the captured access token to the trace logs --> <trace source="Access Token Debug" severity="information"> <message>@("Access Token: " + (string)context.Variables["accessToken"])</message> </trace> <set-variable name="userId" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "Bearer ").Split(' ')[1].AsJwt().Claims["oid"].FirstOrDefault())" /> <set-variable name="userName" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "Bearer ").Split(' ')[1].AsJwt().Claims["name"].FirstOrDefault())" /> <trace source="User Name Debug" severity="information"> <message>@("username: " + (string)context.Variables["userName"])</message> </trace> <set-variable name="scp" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "Bearer ").Split(' ')[1].AsJwt().Claims["scp"].FirstOrDefault())" /> <trace source="Scope Debug" severity="information"> <message>@("scope: " + (string)context.Variables["scp"])</message> </trace> <set-variable name="roles" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "Bearer ").Split(' ')[1].AsJwt().Claims["roles"].FirstOrDefault())" /> <trace source="Role Debug" severity="information"> <message>@("Roles: " + (string)context.Variables["roles"])</message> </trace> <!-- <set-variable name="requestBody" value="@{ return context.Request.Body.As<string>(preserveContent:true); }" /> <trace source="Request Body information" severity="information"> <message>@("Request body: " + (string)context.Variables["requestBody"])</message> </trace> --> <validate-azure-ad-token tenant-id="{{tenant-id}}" header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid."> <client-application-ids> <application-id>{{client-application-id}}</application-id> </client-application-ids> <audiences> <audience>{{audience}}</audience> </audiences> <required-claims> <claim name="roles" match="any"> <value>mcp.read</value> </claim> </required-claims> </validate-azure-ad-token> </inbound> <!-- Control if and how the requests are forwarded to services --> <backend> <base /> </backend> <!-- Customize the responses --> <outbound> <base /> </outbound> <!-- Handle exceptions and customize error responses --> <on-error> <base /> <trace source="Role Debug" severity="error"> <message>@("username: " + (string)context.Variables["userName"] + " has error in accessing the MCP server, could be auth or role related...")</message> </trace> <return-response> <set-status code="403" reason="Forbidden" /> <set-body> {"error":"Missing required scope or role"} </set-body> </return-response> </on-error> </policies> Note: Update the above inbound policy with the tenant Id, client application id, and audience as per your environment. It is recommended to use APIM "Named values" instead of hard coding inside the policy. To learn more, visit Use named values in Azure API Management policies Configure Diagnostics for APIM In this solution, APIM diagnostics are configured to forward log data to Log Analytics. Testing and validation will be carried out using insights from Log Analytics. Note: Setting up diagnostics is outside the scope of this article. However, you can visit the following link for more information. https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-use-azure-monitor Below diagram shows what Logs are being sent to Log Analytics workspace. MCP Tool configuration in Copilot Studio Lauch copilot studio at https://copilotstudio.microsoft.com/. Configuration of environment and agent is beyond the scope of this article. It is assumed, you already have environment setup and agent has been created. Following link will help you, how to create an agent in copilot studio. Quickstart: Create and deploy an agent — Microsoft Copilot Studio | Microsoft Learn Inside agent configuration, click "Add tool". 3. Click on New tool. 4. Select Model Context Protocol. 5. Provide all relevant information for MCP server. Make sure your server URL ends with your mcp setup. In this case, it is APIM MCP server URL, with base path configured in APIM in the end. Provide server name and server description. Select OAuth 2.0 radio button. 6. Provide the following in the OAuth 2.0 section Client ID of client app registration. In this case, copilot-studio-client as configured earlier. Client secret of copilot-studio-client app registration. Authorization URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize Token URL template & Refresh URL: https://login.microsoftonline.com/oauth2/v2.0/token Scopes: openid, profile, email — which we selected earlier for Microsoft Azure Graph permissions. Click “Create”. This will provide you Redirect URL. you need to configure the redirect URL in client app registration. In this case, it is copilot-agent-client. Configure Redirect URI in Client App Registration Visit client app registration. i.e. copilot-studio-client. Click Authentication Tab and provide the Web Redirect URIs as shown below. Note: Configure Redirect URIs MUST be configured in app registration. Otherwise, authorization will not complete and sign on will fail. Configure redirect URI in APIM API app registration Also configure apim-mcp-backend-api app registration with the same redirect URI as shown below. Modify MCP connector in PowerApps Now visit the https://make.powerapps.com and open the newly created connector as shown below. Select the security tab and modify the Resource URL with application ID URI of apim-mcp-backend-api configured earlier in app registration for expose an API. Add .default in the scope. Provide the secret of client app registration as it will not let you update the connector. This is extra security measure for updating the connector in Powerapps. Click Update connector. CORS Configuration CORS configuration is a MUST!!! Since our Azure Container App is a remote MCP server with totally different domain or origin. Power Apps and CORS for External Domains — Brief Overview When embedding or integrating Power Apps with external web applications or APIs, Cross-Origin Resource Sharing (CORS) becomes a critical consideration. CORS is a browser security feature that restricts web pages from making requests to a different domain than the one that served the page, unless explicitly allowed. Key Points: Power Apps hosted on *.powerapps.com or within Microsoft 365 domains will block calls to external APIs unless those APIs include the proper CORS headers. The external API must return: Access-Control-Allow-Origin: https://apps.powerapps.com (or * for all origins, though not recommended for production) Access-Control-Allow-Methods: GET, POST, OPTIONS (or as needed) Access-Control-Allow-Headers: Content-Type, Authorization (and any custom headers) If the API requires authentication (e.g., OAuth 2.0), ensure preflight OPTIONS requests are handled correctly. For scenarios where you cannot modify the external API, consider using: Power Automate flows as a proxy Azure API Management or Azure Functions to inject CORS headers Always validate security implications before enabling wide-open CORS. If the CORS are not setup. You will encounter following error in copilot studio after pressing F12 (Browser Developer) CORS policy — blocking the container app Azure container app provides very efficient way of configuring CORS in the Azure portal. Lauch Azure Portal. Visit Azure container app i.e. streamable-mcp-server2 in this case. Click on CORS under Networking section. Configure the following in Allowed Origin Section as shown below. localhost is added to make it work from local laptop, although it is not required for Copilot Studio. 4. Click on “Allowed Method” tab and provide the following. 5. Provide wild card “*” in “Allowed Headers”tab. Although, it is not recommended for production system. it is done for the sake for simplicity. Configure that for added security 6. Click “Apply”. This will configure CORS for remote application. Test the MCP custom connector We are in the final stages of configuring the connector. It is time to test it, if everything is configured correctly and works. Launch the http://make.powerapps.com and click on “Custom connectors”, select your configured connector and click “5. Test” tab as shown below. You will see Selected Connection as blank if you are running it first time. Click “+ New connection” 2. New connection will launch the Authorization flow and browser dialog will pop up for making a request for authorization code. 3. Click “Create”. 4. Complete the login process. This will create a successful connection. 5. Click “Test operation”. If the response is 406 means everything is configured correctly as shown below. Solution validation Add user in Enterprise Application for App roles Roles have been defined under the required claims in the APIM inbound policy and also configured in the apim-mcp-backend-api app registration. As a result, any request from Copilot Studio will be denied if this role is not properly assigned. This role is included in the JWT access token, which we will validate in the following sections. To assign role, perform the following steps. Visit Azure Portal. Visit Enterprise Application. Select APIM backend app registration. In this case for example, apim-mcp-backend-api Click "Users and groups" Select "Add user/group" 5. Select User or Group who should have access to the role. 6. Click "Assign". It will look like as below. Note: Role assignment for users or groups is an important step. If it is not configured, MCP server tests will fail in Copilot studio. Test MCP server in Copilot Studio Lauch copilot studio and click on the Agent you created in earlier steps and click on “Tools tab”. Select your MCP tool as shown the following figure. Make sure it is “Enabled” if you have other tools attached to the same agent, disable them for now for testing. Make sure you have connection available which we created during the testing of custom connector in earlier step. You can also initiate a fresh connection by clicking on the drop down under “Connection” as shown below. Refreshing the tools will show all the tools available in this MCP server. Provide the sample prompt such as “Give me the stock price of tesla”. This will trigger the MCP server and call the respective method to bring the stock price of Tesla. Now try a weather-related question to see more. Now invoking weather forecast tool in the MCP server. APIM Monitoring with Log Analytics We previously configured APIM diagnostic settings to forward log data to Log Analytics. In this section, we’ll review that data, as the inbound policy in APIM sends valuable information to Log Analytics. Run the Kusto query to retrieve data from the last 30 minutes. As shown, the logs capture the APIM API endpoint URL and the backend URL, which corresponds to the Azure Container App endpoint. Scrolling further, we find the TraceRecords section. This contains the information captured by APIM inbound policies and sent to Log Analytics. The figure below illustrates the TraceRecords data. In the inbound policy, we configured it to extract details from the access token—such as the token itself, username, scope, and roles—and forward them to Log Analytics. Now let's capture the access token in the clip board, launch the http://jwt.io which is JSON Web Token (JWT) debugger, and paste the access token in the ENCODED VALUE box as show below. Note the following information. aud: This shows the Application URI ID of apim-mcp-backend-api. which shows access token is requested for that audience. appid: This shows the client Id for copilot-studio-client app registration. You can also see roles and scope. These roles are specified in APIM inbound policy. Note: As you can see, roles are included in access token and if it is not assigned in the enterprise application for "apim-mcp-backend-api", all requests will be denied by APIM inbound policy configured earlier. Perform a test using another Azure AD account that does not have the app role assigned Now, let's try the copilot studio agent by logging in with another account which is not assigned for the "mcp.read" role. Let's, review the below diagram. Logged in as demo and tried to access the MCP tool in copilot studio agent. Request failed with the error "Missing required scope or roles". If you look at it, this is coming from the APIM policy configured earlier in <on-error> Let's review log analytics. As you can see request failed due to inbound APIM policy with 403 error and there is no backend URL. Error is also reported under TraceRecords as we configured it in APIM policy. Now copy the Access token from log analytics and paste it into jwt.io. You can notice in the below diagram, there is no "roles" in the access token, resulting access denied from APIM inbound policy definition to the APIM backend i.e. azure container app. Assign the app role to the demo account Let's assign the "mcp.read" role to the demo account and test if it accesses the tool. Visit Azure Portal, Lauch Enterprise application, and select "apim-mcp-backend-api" as in this example. Click "Users and groups" Click "+ Add user/group" Select demo Click "Select" Click "Assign" End result would look like as shown below. Now, login again as demo. Make sure a new access token is generated. Access token refresh happens after one hours. As you can see in the image below, this time the request is successful after assigning the "mcp.read" app roles. Now let's review the log analytics entries. Let's review the access token in JWT.io. As you can see, roles are included in the access token. Conclusion Exposing the MCP server through Azure API Management (APIM) and integrating it with Copilot Studio agents provides a secure and scalable way to extend enterprise capabilities. By implementing OAuth 2.0, you ensure robust authentication and authorization, protecting sensitive data and maintaining compliance with industry standards. Beyond security, APIM adds significant operational value. With APIM policies, you can monitor traffic, enforce rate limits, and apply fine-grained controls to manage access and performance effectively. This combination of security and governance empowers organizations to innovate confidently while maintaining control and visibility over API usage. In today’s enterprise landscape, leveraging APIM with OAuth 2.0 for MCP integration is not just best practice—it’s a strategic move toward building resilient, secure, and well-governed solutions.7.3KViews3likes2CommentsUnlock Your Competitive Edge with Azure AI: The Strategic Roadmap You Can’t Afford to Miss
AI isn’t the future—it’s the now. Today, AI is a business imperative, and the organizations that master it will shape tomorrow’s industries. But here’s the truth: most teams don’t fail at AI for lack of ambition—they fail because they don’t have a structured plan. That’s a gap you can close—starting now. Microsoft Learn’s milestone-based approach gives you the structure, tools, and confidence to turn AI ambition into real results. Azure Essentials: A Foundation for AI Success Every successful cloud and AI journey starts with a strong foundation: governance, security, and operational excellence. The Azure Essentials framework is your blueprint, visualized as a continuous cycle: Readiness & Foundation: Prepare your organization with the right infrastructure, security, and strategic alignment. Design & Govern: Architect solutions and implement governance for compliance, scalability, and business alignment. Manage & Optimize: Continuously monitor, manage costs, and tune performance for operational excellence. This iterative model ensures your AI initiatives are launched, sustained, and optimized—perfectly aligned with Microsoft Learn’s milestone-based journey. Microsoft Learn Plan: Unlock Business Potential with AI Apps and Agents Ready to move from ambition to action? The Unlock business potential with AI Apps and agents Official Plan guides you from exploration to enterprise-grade execution. Whether you’re a business leader, developer, or innovator, this hands-on path gives you the structure, skills, and real-world context to build secure, scalable, and impactful AI solutions. Milestone 1: Building an AI-Ready Organization Before you build AI, you need to build trust and readiness. Milestone 1 is all about strategy, security, and organizational capability - grounded in Azure Essentials. Learn how to secure AI systems with the AI Security Fundamentals path. Establish governance and alignment with the AI Center of Excellence (ACoE). How the AI CoE assists in planning adoption of AI - Training Modernize your infrastructure with the Infrastructure for the Era of AI series. Preparing your data for AI innovation Maximize Data Value Refresh Why it matters: Fueled by an AI Center of Excellence, organizations with a well-established AI CoE unlock faster time-to-value, reduce risk, and foster a culture of innovation. They can move beyond isolated pilots to enterprise-grade AI transformation, enabling every team, from leadership to frontline users, to harness AI securely and effectively. AI Adoption: A People-First Transformation Once your organization is technically prepared, the real transformation begins—with your people. Every wave of innovation, from cloud to GenAI, reshapes how teams work, learn, and deliver value. The AI Center of Excellence (CoE) guides teams forward, focusing on trust, leadership, and collaboration. As shown in the diagram below, successful AI adoption is built on essential pillars—talent strategy, operating model, technology and data strategy, and business strategy—all supported by trust and effective change management. Key Practices for AI Readiness Build trust in technology across all levels: AI adoption guidance. Ensure leaders are visible and actively champion AI: Establish an AI Center of Excellence Upskill teams and foster cross-functional collaboration: AI learning hub Use Microsoft’s change management strategy to support adoption. Redesign talent systems for continuous learning and GenAI readiness: AI Readiness Assessment. Common Challenges Shifting from decision makers to transformation champions Bridging technical and non-technical collaboration Keeping pace with rapid change and new skills Actionable Tips Start with people, not tools. Co-create solutions to build trust. Make reskilling a priority. Measure real transformation, not just technical output. Real-World Example: A leading engineering firm saw adoption of its own GenAI-powered “Smart Analyzer” soar by 65% in five months after engaging sponsors and subject matter experts in co-creation and hands-on enablement. Milestone 2: Turn Strategy into Action This is where vision becomes velocity. Assess your AI skills with the AI Learning Journey. Learn how to embed AI into your business with the Transform Your Business with Microsoft AI path. Get inspired by real-world customer stories. Build foundational skills with the Get Started with AI Fundamentals module. Why it matters: This milestone turns your AI strategy into real-world impact. It helps you move from planning to piloting—transforming AI from a conceptual ambition into a tangible capability. Imagine a healthcare startup with a brilliant AI idea but no roadmap. Without direction, even the best ideas can stall. Microsoft Learn’s milestone-based journey provides that roadmap, guiding you step-by-step to build secure, scalable solutions that align with your mission and deliver real impact. Milestone 3: Optimize for Efficiency and Sustainability AI is powerful—but it must also be practical. For a practical roadmap to adopting and managing AI, explore the AI adoption guidance in the Cloud Adoption Framework. Learn how to manage AI costs. Design efficient, scalable solutions with the Azure Well-Architected Framework. Why it matters: This milestone ensures your AI initiatives are innovative, sustainable, and aligned with your business goals. It helps you design solutions that are cost-effective, scalable, and resilient. Without a clear roadmap, AI projects often stall, budgets spiral out of control, and organizational trust erodes. By focusing on operational excellence and cost optimization, you set up your AI strategy for long-term success. Milestone 4: Build Intelligent Apps and Agents Now it’s time to build. Set up your environment with the Plan and Prepare for Azure AI Development module. What is AI? Learn how to build autonomous, intelligent agents with AI Agent Fundamentals. Why it matters: This is where you go from learning to launching—building real AI apps and agents that start to solve your organization’s challenges. By the end of this journey, your team will be equipped to build secure, scalable AI apps and agents. You’ll have a strategy, a toolkit, and library of real-world use cases to draw insights and inspiration from, empowering you to deliver secure, scalable, and impactful AI solutions. AI in Action: Industry Use Cases AI is transforming every industry. Here’s how: Industry Use Cases Strategic Value Healthcare Diagnostics, triage, personalized care Better outcomes, lower costs Finance Fraud detection, risk modeling, automation Stronger compliance, faster service Retail Inventory, personalization, demand forecasting Higher loyalty, smarter supply chains Manufacturing Predictive maintenance, quality control Less downtime, better products Sustainability Emissions tracking, energy optimization ESG alignment, cost savings Nonprofit Donor engagement, service delivery Greater impact, improved transparency Quick Win: Explore Transform your business with Microsoft AI from Milestone 2 to see six key sectors of curated real-world AI use cases of how leading organizations are using AI to gain a competitive edge and deliver greater value; and how you can apply those insights to your own innovation journey. Your AI Journey Starts Now This isn’t just a learning path. It’s a launchpad. Microsoft Learn’s milestone-based journey gives you the tools, structure, and inspiration to turn AI ambition into AI advantage. Whether you’re just starting or scaling, this is your moment. Ready to build the future? Explore the curated Plan on Microsoft Learn: Unlock business potential with AI Apps and agents and begin your skilling journey to build the future—one milestone at a time. Pro Tip: Start small, celebrate quick wins, and scale with confidence. The future of AI is yours to build—one milestone at a time. Where are you on your AI journey? Share your story in the comments or connect with me on LinkedIn Barbara Andrews LinkedIn with #AzureAIJourney, #MicrosoftLearn #SkilledByMTT456Views0likes0CommentsThe Future of AI: Evaluating and optimizing custom RAG agents using Azure AI Foundry
This blog post explores best practices for evaluating and optimizing Retrieval-Augmented Generation (RAG) agents using Azure AI Foundry. It introduces the RAG triad metrics—Retrieval, Groundedness, and Relevance—and demonstrates how to apply them using Azure AI Search and agentic retrieval for custom agents. Readers will learn how to fine-tune search parameters, use end-to-end evaluation metrics and golden retrieval metrics like XDCG and Max Relevance, and leverage Azure AI Foundry tools to build trustworthy, high-performing AI agents.3.6KViews1like0CommentsBeyond Prompts: How Agentic AI is Redefining Human-AI Collaboration
The Shift from Reactive to Proactive AI As a passionate innovator in AI education, I’m on a mission to reimagine how we learn and build with AI—looking to craft intelligent agents that move beyond simple prompts to think, plan, and collaborate dynamically. Traditional AI systems rely heavily on prompt-based interactions—you ask a question, and the model responds. These systems are reactive, limited to single-turn tasks, and lack the ability to plan or adapt. This becomes a bottleneck in dynamic environments where tasks require multi-step reasoning, memory, and autonomy. Agentic AI changes the game. An agent is a structured system that uses a looped process to: Think – analyze inputs, reason about tasks, and plan actions. Act – choose and execute tools to complete tasks. Learn – optionally adapt based on feedback or outcomes. Unlike static workflows, agentic systems can: Make autonomous decisions Adapt to changing environments Collaborate with humans or other agents This shift enables AI to move from being a passive assistant to an active collaborator—capable of solving complex problems with minimal human intervention. What Is Agentic AI? Agentic AI refers to AI systems that go beyond static responses—they can reason, plan, act, and adapt autonomously. These agents operate in dynamic environments, making decisions and invoking tools to achieve goals with minimal human intervention. Some of the frameworks that can be used for Agentic AI include LangChain, Semantic Kernel, AutoGen, Crew AI, MetaGPT, etc. The frameworks can use Azure OpenAI, Anthropic Claude, Google Gemini, Mistral AI, Hugging Face Transformers, etc. Key Traits of Agentic AI Autonomy Agents can independently decide what actions to take based on context and goals. Unlike assistants, which support users, agents' complete tasks and drive outcomes. Memory Agents can retain both long-term and short-term context. This enables personalized and context-aware interactions across sessions. Planning Semantic Kernel agents use function calling to plan multi-step tasks. The AI can iteratively invoke functions, analyze results, and adjust its strategy—automating complex workflows. Adaptability Agents dynamically adjust their behavior based on user input, environmental changes, or feedback. This makes them suitable for real-world applications like task management, learning assistants, or research copilots. Frameworks That Enable Agentic AI Semantic Kernel: A flexible framework for building agents with skills, memory, and orchestration. Supports plugins, planning, and multi-agent collaboration. More information here: Semantic Kernel Agent Architecture. Azure AI Foundry: A managed platform for deploying secure, scalable agents with built-in governance and tool integration. More information here: Exploring the Semantic Kernel Azure AI Agent. LangGraph: A JavaScript-compatible SDK for building agentic apps with memory and tool-calling capabilities, ideal for web-based applications. More information here: Agentic app with LangGraph or Azure AI Foundry (Node.js) - Azure App Service. Copilot Studio: A low-code platform to build custom copilots and agentic workflows using generative AI, plugins, and orchestration. Ideal for enterprise-grade conversational agents. More information here: Building your own copilot with Copilot Studio. Microsoft 365 Copilot: Embeds agentic capabilities directly into productivity apps like Word, Excel, and Teams—enabling contextual, multi-step assistance across workflows. More information here: What is Microsoft 365 Copilot? Why It Matters: Real-World Impact Traditional Generative AI is like a calculator—you input a question, and it gives you an answer. It’s reactive, single-turn, and lacks context. While useful for quick tasks, it struggles with complexity, personalization, and continuity. Agentic AI, on the other hand, is like a smart teammate. It can: Understand goals Plan multi-step actions Remember past interactions Adapt to changing needs Generative AI vs. Agentic Systems Feature Generative AI Agentic AI Interaction Style One-shot responses Multi-turn, goal-driven Context Awareness Limited Persistent memory Task Execution Static Dynamic and autonomous Adaptability Low High (based on feedback/input) How Agentic AI Works — Agentic AI for Students Example Imagine a student named Alice preparing for her final exams. She uses a Smart Study Assistant powered by Agentic AI. Here's how the agent works behind the scenes: Skills / Functions These are the actions or the callable units of logic the agent can invoke to perform. The assistant has functions like: Summarize lecture notes Generate quiz questions Search academic papers Schedule study sessions Think of these as plug-and-play capabilities the agent can call when needed. Memory The agent remembers Alice’s: Past quiz scores Topics she struggled with Preferred study times This helps the assistant personalize recommendations and avoid repeating content she already knows. Planner Instead of doing everything at once, the agent: Breaks down Alice’s goal (“prepare for exams”) into steps Plans a week-by-week study schedule Decides which skills/functions to use at each stage It’s like having a tutor who builds a custom roadmap. Orchestrator This is the brain that coordinates everything. It decides when to use memory, which function to call, and how to adjust the plan if Alice misses a study session or scores low on a quiz. It ensures the agent behaves intelligently and adapts in real time. Conclusion Agentic AI marks a pivotal shift in how we interact with intelligent systems—from passive assistants to proactive collaborators. As we move beyond prompts, we unlock new possibilities for autonomy, adaptability, and human-AI synergy. Whether you're a developer, educator, or strategist, understanding agentic frameworks is no longer optional - it’s foundational. Here are the high-level steps to get started with Agentic AI using only official Microsoft resources, each with a direct link to the relevant documentation: Get Started with Agentic AI Understand Agentic AI Concepts - Begin by learning the fundamentals of AI agents, their architecture, and use cases. See: Explore the basics in this Microsoft Learn module Set Up Your Azure Environment - Create an Azure account and ensure you have the necessary roles (e.g., Azure AI Account Owner or Contributor). See: Quickstart guide for Azure AI Foundry Agent Service Create Your First Agent in Azure AI Foundry - Use the Foundry portal to create a project and deploy a default agent. Customize it with instructions and test it in the playground. See: Step-by-step agent creation in Azure AI Foundry Build an Agentic Web App with Semantic Kernel or Foundry - Follow a hands-on tutorial to integrate agentic capabilities into a .NET web app using Semantic Kernel or Azure AI Foundry. See: Tutorial: Build an agentic app with Semantic Kernel or Foundry Deploy and Test Your Agent - Use GitHub Codespaces or Azure Developer CLI to deploy your app and connect it to your agent. Validate functionality using OpenAPI tools and the agent playground. See: Deploy and test your agentic app For Further Learning: Develop generative AI apps with Azure OpenAI and Semantic Kernel Agentic app with Semantic Kernel or Azure AI Foundry (.NET) - Azure App Service AI Agent Orchestration Patterns - Azure Architecture Center Configuring Agents with Semantic Kernel Plugins Workflows with AI Agents and Models - Azure Logic Apps About the author: I'm Juliet Rajan, a Lead Technical Trainer and passionate innovator in AI education. I specialize in crafting gamified, visionary learning experiences and building intelligent agents that go beyond traditional prompt-based systems. My recent work explores agentic AI, autonomous copilots, and dynamic human-AI collaboration using platforms like Azure AI Foundry and Semantic Kernel.1.4KViews7likes2CommentsAutonomous Visual Studio Code Desktop Automation using Computer Use Agent & PyAutoGUI
This blog post introduces an approach to desktop automation that combines Computer Use Agent (CUA) technology with PyAutoGUI to create fully autonomous VS Code workflows. The solution addresses critical gaps in existing automation tools by providing intelligent, screenshot-based decision-making for scenarios where traditional GitHub-hosted solutions fall short.1.6KViews0likes0CommentsFine-Tuning Together: How Our Developer Community Is Shaping the Future of Custom AI
In a world where foundation models are increasingly accessible, the real magic happens when developers make them their own. Fine-tuning is no longer a niche capability, it’s becoming a core skill for developers who want to build AI that’s faster, smarter, and more aligned with their users scaling expert knowledge across their organizations. Over the past few months, we’ve seen something remarkable: a growing community of builders, tinkerers, and innovators coming together to push the boundaries of what fine-tuning can do making a powerful difference for everyday organizations. A Community Making a Big Impact: Customer Stories At Build 2025, we saw firsthand how much the landscape has shifted. Just a year ago, many teams were still relying solely on prompt engineering or retrieval-augmented generation (RAG). Today, nearly half of developers say they’re actively exploring fine-tuning. Why? Because it gives them something no off-the-shelf model can: the ability to embed their domain knowledge, tone, and logic directly into the model itself. In our breakout session led by Product Leaders Alicia and Omkar, they dove into fine-tuning and distillation with Azure AI Foundry. We heard from the Oracle Health team and how they are restoring joy in providing patient care by relieving administration burden. The Oracle Health team used fine-tuned GPT-4o-mini models to power a clinical AI agent that responds in under 800 milliseconds—fast enough to keep up with real-time healthcare workflows. Earlier this year, we saw DraftWise use reinforcement fine-tuning on o-series reasoning models within Azure AI Foundry to tailor model behavior for legal-specific tasks. This approach allowed them to sharpen responses based on proprietary legal data, improving the quality of contract drafting and review. The fine-tuned models contributed to a 30% improvement in search result quality enabling faster, more accurate legal drafting and review at scale. And we watched CoStar Group deliver a low-latency, voice-driven home search experience that scales to over 100 million monthly users, while reducing token usage, improving cost-efficiency, and accelerating time to deployment by combining GPT-4o Realtime API audio models and Mistral 3B on Azure AI Foundry. These aren’t just technical wins - they’re community wins. They show what’s possible when developers have the right tools and support to build AI that truly fits their needs. What’s New in Azure AI Foundry: Tools That Empower, Not Overwhelm The last 3 months have brought a wave of updates designed to make fine-tuning more accessible, more affordable, and more powerful—especially for developers who are just getting started. One of the most exciting additions is Reinforcement Fine-Tuning (RFT), now available in public preview with the o4-mini model. Unlike traditional supervised fine-tuning, RFT lets you teach models how to reason through complex tasks using reward signals. It’s ideal for domains where logic and nuance matter—like law, finance, or healthcare—and it’s already helping teams like DraftWise build smarter, more adaptive systems. Watch this o4-mini demo to learn more. We also introduced Global Training, which lets you fine-tune models from any of 24 Azure OpenAI regions. This means no more guessing which region supports which model, significantly lowering the barrier to entry for model customization. One of the most common questions we hear from developers is: “How do I know if my fine-tuned model is actually better?” The new Evaluation API is our answer. This API lets you programmatically evaluate model outputs using model-based graders, custom rubrics, and structured scoring—all from code And for developers who want to experiment without breaking the bank, we launched the Developer Tier. It’s a new way to deploy fine-tuned models for free (for 24 hours), paying only for tokens at the same rate as base models. It’s ideal for A/B testing, distillation experiments, or just kicking the tires on a new idea. Learning Together: From Distillation to Deployment One of the most powerful trends we’ve seen is the rise of distillation. Developers are using larger “teacher” models like GPT-4o to generate high-quality outputs, then fine-tuning smaller “student” models like GPT-4.1-mini or nano to replicate that performance at a fraction of the cost. This is now supported end-to-end in Azure AI Foundry. You can generate completions, store them automatically, fine-tune your student model, and evaluate it using model-based graders—all in one place. And the results speak for themselves. In one demo at Build, we saw a distilled 4o model go from 35% to 90% accuracy just by learning from the outputs of a larger o3 model. Let’s Keep Building: Join Us for Model Mondays | Mondays at 10:30 AM PT We’re excited about what’s next. More models. More techniques. More impact from developers like you. If you’re already fine-tuning, we’d love to hear what you’re working on. And if you’re just getting started, we’re here to help with Model Mondays. Model Mondays is your weekly dose of AI model magic: an hour of livestreamed demos, interactive developer-friendly deep dives, and just enough chaos to keep Mondays interesting. Watch the latest fine-tuning & distillation episode with Dave Voutila, Microsoft PM Checkout these Resources 🧠 Get Started with fine-tuning with Azure AI Foundry on Microsoft Learn Docs ▶️ Watch On-Demand: Fine-tuning and distillation with Azure AI Foundry 👩💻 Fine-tune GPT-4o-mini model with this tutorial 👋 Continue the conversation on Discord695Views1like0CommentsAutomate a multi-step business process, using turnkey MCP, Logic App Integration in AI Foundry
This article walks you through an application for Procure-to-Pay anomaly detection using Azure AI Foundry Agent Service. It analyzes purchase invoice images to detect procurement anomalies and compliance issues. The key capabilities of Azure AI Foundry it showcases are: Agent Service that performs a multi-step business process with only natural language instructions. The Application has little to no business logic in the code. Invocation of a variety of automated tool actions required during the multi steps business process. It showcases the recently announced turnkey integration with MCP Server, Azure Logic Apps. In addition, it uses a) visual reasoning of images using gpt-4o models, b) turnkey vector search, and c) reasoning to apply business rules and perform p2p anomaly detection. The ability of Agent Service in Azure AI Foundry to: most importantly, all the steps in the business process are performed through a single call from the Application to the Agent Service. The Agent orchestrates the steps autonomously, based on the instructions in Natural language. The Client application itself contains no business logic in code. handle application state between different tool calls. It determines what to extract from the output of one tool call to pass as input to the next. orchestrating the business process from start to end, sequencing them to achieve the business end. Architecture of the Solution Shown below is the architecture of the Solution. The Client Application is a python-based console App that calls the P2P Anomaly Detection Agent running in the Azure AI Foundry Agent Service. Solution Components Sr. No Entity Entity Purpose or Description 1 Foundry Agent The autonomous Agent that implements the P2P anomaly detection process end to end. It orchestrates all the steps in the business process through a single API call, handling application state between different tool calls and sequencing operations to achieve the business objective. 2 Visual Reasoning Tool Call Analyzes the input Purchase Invoice Image using GPT-4o's vision capabilities to extract the Purchase Invoice Header, Invoice Lines, Supplier ID, and Contract ID. This extracted information is then used in subsequent calls to the Logic App for contract validation. 3 Azure Logic App Tool Call Called by the Agent via HTTP Trigger with the Supplier ID and Contract ID extracted from the invoice. Returns matching contract data by executing dynamic SQL queries on an Azure SQL Database, providing contract header and line item details for comparison with the invoice. 4 Vector Search Tool Call Retrieves the business rules that apply to P2P anomaly detection in an Enterprise environment. Uses the configured vector store to search through the uploaded business rules document (p2p-rules.txt) to find relevant compliance and validation criteria. 5 Reasoning Applies the retrieved business rules to evaluate the Purchase Invoice against the Contract data. Determines if there are anomalies or compliance issues and generates a detailed verification report with verdicts, comparisons, and recommendations. 6 MCP Server Tool Call Catalogs and stores the generated reports in Azure Blob Storage. The MCP Server implements protocol-specific implementations to connect to the Blob Storage service, performing lifecycle actions like creating containers, listing containers, and uploading blobs. The Agent uses the MCP Server to upload the markdown verification report to a designated container. Some of the key aspects of the Solution are: 1) There is only one call from the Client Application to the Agent in Azure AI Foundry. The rest of the steps are performed by the Agent Service autonomously. The code snippet below shows the client application passing the user provided Invoice image and user instruction to the Agent in Azure AI Foundry. 2) Observe that there is no business logic in the code whatsoever, and there is no code written to perform any of the tool actions either. These are autonomously done by the Agent itself. def process_anomaly_detection(self, user_prompt: str, image_path: str, verbose: bool = True) -> str: """ Process the anomaly detection request with proper error handling and retry logic. Args: user_prompt: User's prompt for anomaly detection image_path: Path to the invoice image Returns: Response from the AI agent Raises: Exception: For various processing errors """ try: # Create message content self._show_progress("Creating message content...", verbose) content_blocks = self.create_message_content(user_prompt, image_path) # Create a new thread for this conversation self._show_progress("Creating conversation thread...", verbose) thread = self.client.threads.create() logger.info(f"Created thread, ID: {thread.id}") # Create the message self._show_progress("Sending message to agent...", verbose) message = self.client.messages.create( thread_id=thread.id, role="user", content=content_blocks ) # Run the agent with proper error handling self._show_progress("Processing with AI agent (this may take a moment)...", verbose) run = self.client.runs.create_and_process( thread_id=thread.id, agent_id=self.agent.id ) if run.status == "failed": error_msg = f"Agent run failed: {run.last_error}" logger.error(error_msg) raise Exception(error_msg) # Retrieve and process messages self._show_progress("Retrieving analysis results...", verbose) messages = self.client.messages.list( thread_id=thread.id, order=ListSortOrder.ASCENDING ) # Extract the agent's response agent_response = "" for message in messages: if message.role == "assistant" and message.text_messages: agent_response = message.text_messages[-1].text.value break if not agent_response: raise Exception("No response received from the agent") self._show_progress("Analysis complete!", verbose) logger.info("Successfully processed anomaly detection request") return agent_response except Exception as e: logger.error(f"Error processing anomaly detection: {e}") raise Note: The steps to configure the Solution is covered in the GitHub Repo link shared later in this article, and hence not discussed here. Agent Instructions As mentioned already, the Client application does not contain any Business logic. The latter is provided as natural language instructions to the Foundry Agent. Show below are the instructions configured on the P2P Agent. This is a Procure to Pay process. You will be provided with the Purchase Invoice image as input. Note the sequence of execution you must adhere to strictly: - Step 2 must be performed only after Step 1 is performed - Step 3 below must be performed only after Step 1 and Step 2 are completed. - Step 5 must be performed only after Step 1, Step 2, Step 3 and Step 4 have been performed successfully. - Step 6 must be performed only after Step 5 is performed Step 1: As a first step, you will extract the Contract ID and Supplier ID from the Purchase Invoice image along with all the line items from the Invoice in the form of a table. Step 2: You will then use the function tool by passing the Contract ID and Supplier ID to retrieve the contract details. Step 3: You will then use the file search tool to retrieve the business rules applicable to detection of anomalies in the Procure to Pay process. Step 4: Then, apply the retrieved business rules to match the invoice line items with the contract details fetched from the system, and detect anomalies if any. Step 5: Prepare a detailed 'p2p verification report' in markdown with the following content: - Verdict: Whether the Purchase Invoice complies with the Contract? - Purchase Invoice details: Invoice Header and Invoice Lines, in Markdown Table Format - Contract Details: Contract Header and Contract Lines, in Markdown Table Format - P2P Business Rules: The Rules that were retrieved using the File Search Tool - Reasoning behind the verdict: Provide a detailed reasoning why you think the Invoice aligns with the Contract yes or no. Use a Markdown Table format to compare each item in the Invoice with the Contract and indicate the basis for your judgement. Use icons/images to embellish the report and make it easy for comprehension by Business users. They must be able to quickly give this a once over and commit the Invoice into the System Step 6: You will use the MCP tool available with you to upload the 'p2p verification report' created in Step 5. - Choose a container with name 'p2p-anomaly-detection-outcomes' to upload to. If the container with this name does not exist, create one. - The name of the Report must start with the Invoice Number, appended with a hyphen and appended with a guid. E.g. Invoice001-001.md - Secure the name of the Report document uploaded to the Blob Storage account through the MCP Tool Step 7: Wait till Step 6 completes, then return the content of the Markdown document that was uploaded to Blob Storage. Output from the Run (.venv) PS C:\Users\sansri\agentic-ai-service-samples\p2p-anomaly-detection-agent> python p2pagent.py 2025-07-04 09:04:22,149 - __main__ - INFO - Successfully initialized Azure AI Agents client 2025-07-04 09:04:22,149 - INFO - Successfully initialized Azure AI Agents client === P2P Anomaly Detection Agent === This tool analyzes invoice images for procurement anomalies. Enter the path to your invoice image: data_files/Invoice-002.png Enter your analysis prompt (or press Enter for default): can you perform the procure to pay anomaly detection based on the instructions you have been provided with and give me a detailed response if this Purchase Invoice Image attached aligns with the Contract? Processing image: C:\Users\sansri\agentic-ai-service-samples\p2p-anomaly-detection-agent\data_files\Invoice-002.png Analyzing with Azure AI Agent... 🔄 Creating message content... 2025-07-04 09:04:46,774 - __main__ - INFO - Successfully converted image to base64: C:\Users\sansri\agentic-ai-service-samples\p2p-anomaly-detection-agent\data_files\Invoice-002.png 2025-07-04 09:04:46,774 - INFO - Successfully converted image to base64: C:\Users\sansri\agentic-ai-service-samples\p2p-anomaly-detection-agent\data_files\Invoice-002.png 2025-07-04 09:04:46,777 - __main__ - INFO - Successfully created message content blocks 2025-07-04 09:04:46,777 - INFO - Successfully created message content blocks 🔄 Creating conversation thread... 2025-07-04 09:04:47,231 - __main__ - INFO - Created thread, ID: thread_Lz8ViyvcnDMG9i9TGkgE7jq6 2025-07-04 09:04:47,231 - INFO - Created thread, ID: thread_Lz8ViyvcnDMG9i9TGkgE7jq6 🔄 Sending message to agent... 🔄 Processing with AI agent (this may take a moment)... 🔄 Retrieving analysis results... 🔄 Analysis complete! 2025-07-04 09:05:55,543 - __main__ - INFO - Successfully processed anomaly detection request 2025-07-04 09:05:55,543 - INFO - Successfully processed anomaly detection request ================================================== ANOMALY DETECTION RESULTS ================================================== ### P2P Verification Report #### **Verdict:** The Purchase Invoice **does not comply** with the Contract. --- #### **Purchase Invoice Details** | **Attribute** | **Value** | |-----------------------|------------------------------------------------------------------------------| | **Invoice Number** | INV001002 | | **Contract Reference**| CON000002 | | **Supplier ID** | SUP0008 | | **Total Invoice Value** | 113130.16 USD | | **Invoice Date** | 2023-06-15 | --- #### **Invoice Line Items** | **Item ID** | **Quantity** | **Unit Price (USD)** | **Total Price** | **Description** | |-------------|--------------|-----------------------|-----------------|---------------------------------------| | ITEM0040 | 116 | $136.75 | $15863.00 | Description for ITEM0040 | | ITEM0082 | 116 | $554.62 | $64335.92 | Description for ITEM0082 | | ITEM0011 | 36 | $398.09 | $14331.24 | Description for ITEM0011 | | ITEM0031 | 36 | $475.00 | $17100.00 | Description for ITEM0031 | | ITEM9999 | 10 | $150.00 | $1500.00 | Extra item not in contract | --- #### **Contract Details** | **Attribute** | **Value** | |--------------------------------|------------------------------------------------------------------------------| | **Contract ID** | CON000002 | | **Supplier ID** | SUP0008 | | **Contract Date** | 2022-10-19 | | **Expiration Date** | 2023-01-07 | | **Contract Total Amount** | 66543.39 USD | | **Status** | Expired | | **Currency** | USD | | **Item ID** | **Quantity** | **Unit Price (USD)** | **Total Price** | **Delivery Date** | **Description** | |-------------|--------------|-----------------------|-----------------|-------------------|----------------------------| | ITEM0040 | 78 | $136.75 | $10666.50 | 2023-01-01 | Description for ITEM0040 | | ITEM0082 | 57 | $479.87 | $27352.58 | 2022-11-26 | Description for ITEM0082 | | ITEM0011 | 21 | $398.09 | $8359.89 | 2022-11-29 | Description for ITEM0011 | | ITEM0031 | 47 | $429.03 | $20164.41 | 2022-12-09 | Description for ITEM0031 | --- #### **P2P Business Rules** - Invoice date in Purchase Invoice must be within the Contract term【6:0†source】. - The Contract must be valid; ensure it is not expired【6:0†source】. - Invoice Total Value should stay within the Contract value【6:0†source】. - Items in the Invoice must be strictly from the Contract item list, with correct quantities, descriptions, and unit prices【6:0†source】. - Minor rounding differences in amounts should be ignored【6:0†source】. --- |------------------|-------------------------------------------------|------------------------------------------------------------------------------------------------------------| | ITEM0040 | Quantity: 78, Unit Price: $136.75 | Invoice quantity exceeds Contract quantity. | |------------------|-------------------------------------------------|------------------------------------------------------------------------------------------------------------| | ITEM0040 | Quantity: 78, Unit Price: $136.75 | Invoice quantity exceeds Contract quantity. | | ITEM0082 | Quantity: 57, Unit Price: $479.87 | Invoice unit price differs and quantity exceeds Contract quantity. | | ITEM0011 | Quantity: 21, Unit Price: $398.09 | Invoice quantity exceeds Contract quantity. | | ITEM0031 | Quantity: 47, Unit Price: $429.03 | Invoice quantity exceeds Contract quantity and Contract total is lower than Invoice total. | | ITEM9999 | Not listed in Contract | Extra item not defined in Contract—anomalous. | ### Additional Observations: - **Contract is Expired:** The Contract expired on 2023-01-07. Invoice dated 2023-06-15 falls outside the Contract's validity term. - **Invoice exceeds Contract Value:** Contract value capped at $66543.39 USD, while Invoice totals $113130.16 USD. - **Currency Matches:** Invoice and Contract both indicate prices in USD. --- ### Professional Guidance and Suggested Next Steps: - The anomalies detected prevent this Invoice from fully complying with the Contract terms. - **Recommendation:** Rectify discrepancies (quantities, unit price adjustments, or removal of extra items) and adhere to valid Contract before committing Invoice to the System. --- ### Uploading Report Content Proceeding to upload this Markdown report into Blob Storage. ================================================== MCP Actions As an outcome from the P2P evaluation, a Markdown document is created by the P2P Agent which then gets uploaded to the Azure Blob Storage, using the MCP Tool action. See the screenshot below from the Azure Portal. References Here is the GitHub Repo that contains the code for the solution covered in this article. A Linkedin article related to this topic - here1.4KViews1like1CommentMastering Model Context Protocol (MCP): Building Multi Server MCP with Azure OpenAI
Create complex Multi MCP AI Agentic applications. Deep dive into Multi Server MCP implementation, connecting both local custom and ready MCP Servers in a single client session through a custom chatbot interface.11KViews7likes3Comments