# Invoking Microsoft Foundry Hosted Agent from C# application

My previous [article](https://www.azureguru.net/deploy-an-ai-agent-leveraging-agent-identity-as-hosted-agent-to-microsoft-foundry) demonstrated the agent deployment to Microsoft Foundry as an hosted agent and tested its execution through the Foundry Agent Playground.

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/fc5547f3-ee89-4aca-ba73-ca15310398de.gif align="center")

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](https://www.azureguru.net/deploy-an-ai-agent-leveraging-agent-identity-as-hosted-agent-to-microsoft-foundry) 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](https://www.azureguru.net/authentication-tokens-for-azure-ai-foundry-data-agents-through-entra-service-principal-part-2)
- **Customize ClientSecretCredential class for OneLake authentication in Microsoft Fabric :** [Link](https://www.azureguru.net/customize-clientsecretcredential-class-for-onelake-authentication-in-microsoft-fabric)

### **Setup**

I am using an existing app registration called Fabric MSAL from the Entra account

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/bad3cce0-9d85-4747-8bfa-2a7fba777c61.png align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p><strong>Important</strong> : We need to grant IAM permission to the signed-in user to the Foundry Project and not the hosted agent.</p></div>
</div>

In the very first step, grant the Application registration API permissions to **Azure Machine Learning Services**.

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/f132be39-35d7-45b4-acc2-c12074b2023b.png align="center")

Setting this permission ensures that the generated access token contains the `aud` value of `https://ai.azure.com`

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/8c4e0990-2fe2-4787-8a23-c38ac23dc1df.png align="center")

Not doing so, the token gets rejected with the following error

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/a57ac2bc-7665-4471-b1e5-40c0ca3cf828.png align="center")

The resource id marked in the error above, is the Azure Machine Learning Services Application(client ID).

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/b753d9c6-398a-416b-8859-eb8071b8e4a6.png align="center")

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.

![Azure AI Foundry](https://cdn.hashnode.com/res/hashnode/image/upload/v1760022692191/d476f368-52e4-42dd-8aec-1dd8c89400ea.png align="center")

In the next step, grant the RBAC permissions to the signed in user.

Following are the four possible roles that could be granted

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/e4203810-5a04-4b24-bc41-f0ae90a072b3.png align="center")

We will grant the least privileged user permission which is Foundry User to the signed in user **sachin_nandanwar @** [**azureguru.net**](http://azureguru.net)

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>I am not using the usual login <strong>sachin.nandanwar @ azureguru.net </strong>that I normally do. This is because this login is auto assigned as the Owner to the project as its scope is Subscription(Inherited).</p></div>
</div>

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/f3fc7397-b0bb-4220-b554-8899d3fcf4f5.png align="center")

To assign the Foundry User role to the user, navigate to the Foundry resource and under **Job Function roles** >> select **Foundry User**

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/e1879f94-4e24-447b-b2e7-70b02e426be8.png align="center")

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**](http://azureguru.net)

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/5b7ba140-e419-428c-8bde-c2e9d536664a.png align="center")

Then click **Review + assign**

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/43ab04ee-016c-4924-a947-2e4492648d87.png align="center")

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/16f0c247-80cd-4af4-b27b-3be5a7a15062.png align="center")

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

```kotlin
az role assignment create  --assignee "Your Service principal object id"  
--role "Foundry User"  
--scope "/subscriptions/{subscriptionid}/resourceGroups/{ResourceGroup}/providers/Microsoft.CognitiveServices/accounts/{resource name}"
```

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/0a359fae-440a-4393-a44a-dc4d1b58a74d.png align="center")

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.

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/azure.identity.clientsecretcredential?view=azure-dotnet)

```csharp
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 `AIProjectClient`requires `AuthenticationTokenProvider` to connect to the Foundry endpoint.

We cannot pass the Bearer access token to the endpoint as the expected argument is `AuthenticationTokenProvider`

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/752c6394-94c7-438b-b888-b3a5d181cb7e.png align="center")

We have to use the [**PublicClientApplicationBuilder**](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.publicclientapplicationbuilder?view=msal-dotnet-latest) class from Microsoft Authentication Library (MSAL) for .NET to generate the access token.

```csharp
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 [**<u>here</u>**](https://learn.microsoft.com/en-us/entra/identity-platform/msal-overview).

Next, declare a function called **GenerateAccessTokenForAzureAI** that calls `PublicClientApplicationBuilder` that was defined earlier.

```csharp
 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

```csharp
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

```csharp
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

```csharp
  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.
    }
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p><code>ProjectResponsesClient</code> used above is currently under evaluation so set the #pragma warning <code>OPENAI001</code> in the code.</p></div>
</div>

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

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/45eeda61-2335-456a-8002-256da8acfe31.gif align="center")

### 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 !!!
