Invoking Microsoft Foundry Hosted Agent from C# application

My previous article demonstrated the agent deployment to Microsoft Foundry as an hosted agent and tested its execution through the Foundry Agent Playground.
But you wouldn't want the end user to have access to the Foundry portal to interact with the agent.
In this article I have delved into the details of setting up the user access levels and how the end user can interact with the hosted agent through a client application.
Recall from the previous article that the hosted agent will invoke two functions:
- ReturnCityTemperature
- ReturnCountryCapital
The agent is strictly instructed to return only the data provided by these two functions and should not provide any external data as the output on which the model is trained on.
To understand the approach that I used in this article, you’ll need to familiarize with the concepts covered in my previous two articles.
- Authentication Tokens for Azure AI Foundry Data Agents through Entra Service Principal -Part 2 : Link
- Customize ClientSecretCredential class for OneLake authentication in Microsoft Fabric : Link
Setup
I am using an existing app registration called Fabric MSAL from the Entra account
Important : We need to grant IAM permission to the signed-in user to the Foundry Project and not the hosted agent.
In the very first step, grant the Application registration API permissions to Azure Machine Learning Services.
Setting this permission ensures that the generated access token contains the aud value of https://ai.azure.com
Not doing so, the token gets rejected with the following error
The resource id marked in the error above, is the Azure Machine Learning Services Application(client ID).
Once the Azure Machine Learning Services API permission is assigned to the service principal, the assigned permission should be visible under the Configured permissions window under API permissions of the App registrations.
In the next step, grant the RBAC permissions to the signed in user.
Following are the four possible roles that could be granted
We will grant the least privileged user permission which is Foundry User to the signed in user sachin_nandanwar @ azureguru.net
I am not using the usual login sachin.nandanwar @ azureguru.net that I normally do. This is because this login is auto assigned as the Owner to the project as its scope is Subscription(Inherited).
To assign the Foundry User role to the user, navigate to the Foundry resource and under Job Function roles >> select Foundry User
and then click Next and select the user login that you want to assign the role to. In this case it is sachin_nandanwar @ azureguru.net
Then click Review + assign
If you want to want to do it the hard way, I mean the Azure CLI way 😁, you can assign the role with the following script
az role assignment create --assignee "Your Service principal object id"
--role "Foundry User"
--scope "/subscriptions/{subscriptionid}/resourceGroups/{ResourceGroup}/providers/Microsoft.CognitiveServices/accounts/{resource name}"
Now that we have the set up ready, create a new C# console application.
Code
Add the following references/NuGet packages to the console application.
dotnet add package Azure.Core
dotnet add package Azure.AI.Extensions.OpenAIdo
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
dotnet add package System.IdentityModel.Tokens.Jwt
dotnet add package OpenAI.Responses
dotnet add package Microsoft.Extensions.Configuration
Declare a class AccessTokenCredential to override ClientSecretCredential
using Azure.Core;
using Azure.Identity;
using System.IdentityModel.Tokens.Jwt;
namespace Call_Hosted_Function_In_Foundry
{
public class AccessTokenCredential : ClientSecretCredential
{
public AccessTokenCredential(string accessToken)
{
AccessToken = accessToken;
}
private string AccessToken;
public AccessToken FetchAccessToken()
{
JwtSecurityToken token = new JwtSecurityToken(AccessToken);
return new AccessToken(AccessToken, token.ValidTo);
}
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new ValueTask<AccessToken>(FetchAccessToken());
}
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
JwtSecurityToken token = new JwtSecurityToken(AccessToken);
return new AccessToken(AccessToken, token.ValidTo);
}
}
}
This converts the bearer token to AuthenticationTokenProvider.
Now why is this required ?
Because the AIProjectClientrequires AuthenticationTokenProvider to connect to the Foundry endpoint.
We cannot pass the Bearer access token to the endpoint as the expected argument is AuthenticationTokenProvider
We have to use the PublicClientApplicationBuilder class from Microsoft Authentication Library (MSAL) for .NET to generate the access token.
public static async Task<AuthenticationResult> ClientApplicationBuilder(string[] Scopes, string clientId)
{
PublicClientApplicationBuilder PublicClientAppBuilder =
PublicClientApplicationBuilder.Create(clientId)
.WithAuthority("https://login.microsoftonline.com/organizations")
.WithCacheOptions(CacheOptions.EnableSharedCacheOptions)
.WithRedirectUri("http://localhost");
IPublicClientApplication PublicClientApplication = PublicClientAppBuilder.Build();
var accounts = await PublicClientApplication.GetAccountsAsync();
AuthenticationResult result;
try
{
result = await PublicClientApplication.AcquireTokenSilent(Scopes, accounts.First())
.ExecuteAsync()
.ConfigureAwait(false);
}
catch
{
result = await PublicClientApplication.AcquireTokenInteractive(Scopes)
.ExecuteAsync()
.ConfigureAwait(false);
}
return result;
}
Note : To understand more about MSAL, I would strongly recommend to read Microsoft’s official documentation on MSAL here.
Next, declare a function called GenerateAccessTokenForAzureAI that calls PublicClientApplicationBuilder that was defined earlier.
public static async Task<string> GenerateAccessTokenForAzureAI()
{
AuthenticationResult result = await ClientApplicationBuilder(scopes,clientId);
return result.AccessToken;
}
Now that we have all set, we call these functions in our console application.
In Progam.cs of the console application add the following references
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Call_Hosted_Function_In_Foundry;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using OpenAI.Responses;
In the next step, declare a bunch of variables
static string projectEndpoint = "Your AI foundry resource endpoint";
static string[] scopes = new string[] { "https://ai.azure.com/.default" };
static string clientId = "App registration Client Id";
static AccessTokenCredential TokenCredentials = new("");
This is the implementation of the application's Main method
public async static Task Main(string[] args)
{
var response_token = await GenerateAccessTokenForAzureAI();
TokenCredentials = new(response_token);
AIProjectClient projectClient = new(new Uri({Foundry Project endpoint}), TokenCredentials);
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient
.GetProjectResponsesClientForAgentEndpoint({Hosted Agent Name});
while (true)
{
Console.Write("\nYou:");
string? input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
ResponseResult response = await responsesClient.CreateResponseAsync(input);
Console.WriteLine($"Agent response: {response.GetOutputText()}");
}
#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
}
ProjectResponsesClient used above is currently under evaluation so set the #pragma warning OPENAI001 in the code.
The Main method generates the access token post interactive user login and then convert the generated access token to AuthenticationTokenProvider.
Then through AIProjectClient invoke the foundry project by passing the project endpoint and AuthenticationTokenProvider.
Create ProjectResponsesClient that invokes the deployed hosted agent and then GetProjectResponsesClientForAgentEndpoint returns ResponseResult that finally display output through the GetOutputText property of responsesClient.
Execution :
During execution, we'll run the prompts in parallel, in the Foundry Playground and the console application
Conclusion :
In this article, we explored how to invoke a Microsoft Foundry Hosted Agent from a C# application. We also looked at the authentication process, the role of TokenCredential and how IAM permissions are evaluated at the Foundry Project level rather than at the individual hosted agent level.
This approach provides a way to integrate Foundry Hosted Agents into .NET applications while leveraging Microsoft Entra ID for authentication and authorization.
Thanks for reading !!!
About the author
- From Synapse Analytics, Power BI, Spark, Microsoft Fabric,ASP.NET Core and recently Agentic AI on .NET I try to explore, learn and share all aspects of Microsoft Data Stack in this blog.
Comments
Join the discussionNo comments yet. Be the first to comment.
Microsoft Foundry with me
In this series I post my explorations and findings regarding Microsoft Foundry





