Skip to content

Commit e4309e5

Browse files
authored
.NET: Add Foundry hosted session client samples (#8227)
* .NET: Add Foundry hosted session client samples * .NET: Handle closed input in hosted clients * .NET: Clarify user isolation sample trust boundary * .NET: Keep preview flag on direct Toolbox MCP calls
1 parent 3abfddf commit e4309e5

14 files changed

Lines changed: 555 additions & 78 deletions

File tree

‎dotnet/agent-framework-dotnet.slnx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,9 +388,11 @@
388388
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-Steering/HostedSteering.csproj" />
389389
</Folder>
390390
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/">
391+
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/FoundryHostedSession/FoundryHostedSession.csproj" />
391392
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/Hosted-Toolbox-AuthPaths-Client/Hosted-Toolbox-AuthPaths-Client.csproj" />
392393
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/SessionFilesClient/SessionFilesClient.csproj" />
393394
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/SimpleAgent/SimpleAgent.csproj" />
395+
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/UserIsolationAgent/UserIsolationAgent.csproj" />
394396
</Folder>
395397
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Using-E2E-Resilience/">
396398
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-E2E-Resilience/Using-E2E-Resilience.csproj" />

‎dotnet/samples/02-agents/AgentProviders/foundry/Agent_Step25_FoundryToolboxMcp/Program.cs‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
// discovers the toolbox's tools at runtime and invokes them locally.
77

88
using System.ClientModel;
9-
using System.ClientModel.Primitives;
109
using System.Net.Http.Headers;
1110
using Azure.AI.Projects;
1211
using Azure.AI.Projects.Agents;
@@ -81,10 +80,7 @@ static async Task<string> CreateSampleToolboxAsync(string name, string endpoint,
8180
// script, not the application itself. This helper exists so the sample can
8281
// be run end-to-end without first setting a toolbox up by hand.
8382

84-
// The Foundry-Features header is currently required for toolbox CRUD operations.
85-
var options = new AgentAdministrationClientOptions();
86-
options.AddPolicy(new FoundryFeaturesPolicy("Toolboxes=V1Preview"), PipelinePosition.PerCall);
87-
var adminClient = new AgentAdministrationClient(new Uri(endpoint), credential, options);
83+
var adminClient = new AgentAdministrationClient(new Uri(endpoint), credential);
8884
var toolboxClient = adminClient.GetAgentToolboxes();
8985

9086
// Delete existing toolbox if present (ignore 404).
@@ -114,26 +110,6 @@ static async Task<string> CreateSampleToolboxAsync(string name, string endpoint,
114110
return $"{endpoint}/toolboxes/{created.Name}/mcp?api-version=v{created.Version}";
115111
}
116112

117-
// ---------------------------------------------------------------------------
118-
// Pipeline policy: adds the Foundry-Features header for toolbox CRUD calls
119-
// ---------------------------------------------------------------------------
120-
internal sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
121-
{
122-
private const string FeatureHeader = "Foundry-Features";
123-
124-
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
125-
{
126-
message.Request.Headers.Add(FeatureHeader, feature);
127-
ProcessNext(message, pipeline, currentIndex);
128-
}
129-
130-
public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
131-
{
132-
message.Request.Headers.Add(FeatureHeader, feature);
133-
return ProcessNextAsync(message, pipeline, currentIndex);
134-
}
135-
}
136-
137113
// ---------------------------------------------------------------------------
138114
// DelegatingHandler: attaches a fresh Azure AI bearer token to every request
139115
// ---------------------------------------------------------------------------

‎dotnet/samples/03-workflows/Declarative/InvokeFoundryToolboxMcp/Program.cs‎

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
// through the reserved tools/list operation, then calls microsoft_docs_search from the workflow.
66

77
using System.ClientModel;
8-
using System.ClientModel.Primitives;
98
using System.Collections.Concurrent;
109
using System.Net.Http.Headers;
1110
using Azure.AI.Projects;
@@ -19,8 +18,6 @@
1918
using Shared.Workflows;
2019

2120
#pragma warning disable OPENAI001 // Experimental API
22-
#pragma warning disable AAIP001 // AgentToolboxes is experimental
23-
2421
namespace Demo.Workflows.Declarative.InvokeFoundryToolboxMcp;
2522

2623
/// <summary>
@@ -148,9 +145,7 @@ Be concise.
148145

149146
private static async Task<string> CreateSampleToolboxAsync(string name, string serverLabel, Uri foundryEndpoint, TokenCredential credential)
150147
{
151-
AgentAdministrationClientOptions options = new();
152-
options.AddPolicy(new FoundryFeaturesPolicy("Toolboxes=V1Preview"), PipelinePosition.PerCall);
153-
AgentAdministrationClient adminClient = new(foundryEndpoint, credential, options);
148+
AgentAdministrationClient adminClient = new(foundryEndpoint, credential);
154149
AgentToolboxes toolboxClient = adminClient.GetAgentToolboxes();
155150

156151
try
@@ -199,21 +194,4 @@ protected override async Task<HttpResponseMessage> SendAsync(
199194
return await base.SendAsync(request, cancellationToken);
200195
}
201196
}
202-
203-
private sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
204-
{
205-
private const string FeatureHeader = "Foundry-Features";
206-
207-
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
208-
{
209-
message.Request.Headers.Add(FeatureHeader, feature);
210-
ProcessNext(message, pipeline, currentIndex);
211-
}
212-
213-
public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
214-
{
215-
message.Request.Headers.Add(FeatureHeader, feature);
216-
return ProcessNextAsync(message, pipeline, currentIndex);
217-
}
218-
}
219197
}

‎dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AgentSkills/Program.cs‎

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
#pragma warning disable AAIP001 // ProjectAgentSkills is experimental
2121

2222
using System.ClientModel;
23-
using System.ClientModel.Primitives;
2423
using Azure.AI.Projects;
2524
using Azure.AI.Projects.Agents;
2625
using Azure.Identity;
@@ -65,10 +64,7 @@
6564
var credential = new DefaultAzureCredential();
6665

6766
AIProjectClient projectClient = new(new Uri(endpoint), credential);
68-
var adminOptions = new AgentAdministrationClientOptions();
69-
adminOptions.AddPolicy(new FoundryFeaturesPolicy("Skills=V1Preview"), PipelinePosition.PerCall);
70-
var adminClient = new AgentAdministrationClient(new Uri(endpoint), credential, adminOptions);
71-
ProjectAgentSkills skillsClient = adminClient.GetAgentSkills();
67+
ProjectAgentSkills skillsClient = projectClient.AgentAdministrationClient.GetAgentSkills();
7268

7369
// ── Provision skills (sample convenience only — NOT a production pattern) ─────
7470
// In production, skills are provisioned externally (e.g., via CI/CD or a management script).
@@ -153,7 +149,6 @@ static async Task DownloadSkillsAsync(ProjectAgentSkills skillsClient, string[]
153149
$"Downloaded skill '{name}' did not contain a SKILL.md at the root.");
154150
}
155151
}
156-
157152
}
158153

159154
// Ensures each requested skill is provisioned in Foundry. For each skill name, checks whether
@@ -183,24 +178,3 @@ static async Task EnsureSkillsProvisionedAsync(ProjectAgentSkills skillsClient,
183178
}
184179
}
185180
}
186-
187-
// Skills is a preview data-plane surface and requires an explicit feature opt-in on every call.
188-
internal sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
189-
{
190-
private const string FeatureHeader = "Foundry-Features";
191-
192-
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
193-
{
194-
message.Request.Headers.Add(FeatureHeader, feature);
195-
ProcessNext(message, pipeline, currentIndex);
196-
}
197-
198-
public override ValueTask ProcessAsync(
199-
PipelineMessage message,
200-
IReadOnlyList<PipelinePolicy> pipeline,
201-
int currentIndex)
202-
{
203-
message.Request.Headers.Add(FeatureHeader, feature);
204-
return ProcessNextAsync(message, pipeline, currentIndex);
205-
}
206-
}

‎dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AgentSkills/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,9 @@ Do not substitute `Azure AI Developer`; Microsoft documents that role as insuffi
165165
hosted agents. Recreate the role assignment when the agent is deleted and created again, because
166166
the new agent receives a new identity.
167167

168-
The Skills API is a preview surface. `Program.cs` adds the required
169-
`Foundry-Features: Skills=V1Preview` header and downloads skills into the writable temporary
170-
directory. The source-deploy application directory (`/app`) is read-only.
168+
The Skills API is a preview surface. `Azure.AI.Projects` applies its required feature opt-in
169+
internally. `Program.cs` downloads skills into the writable temporary directory. The source-deploy
170+
application directory (`/app`) is read-only.
171171

172172
### Step 4: clean up
173173

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
FOUNDRY_PROJECT_ENDPOINT=https://<account>.services.ai.azure.com/api/projects/<project>
2+
AZURE_AI_AGENT_NAME=<deployed-hosted-agent-name>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>net10.0</TargetFrameworks>
6+
<Nullable>enable</Nullable>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
9+
<RootNamespace>FoundryHostedSessionClient</RootNamespace>
10+
<AssemblyName>foundry-hosted-session-client</AssemblyName>
11+
<NoWarn>$(NoWarn);MEAI001;NU1605;OPENAI001</NoWarn>
12+
</PropertyGroup>
13+
14+
<ItemGroup>
15+
<PackageReference Include="Azure.AI.Projects" />
16+
<PackageReference Include="Azure.Identity" />
17+
<PackageReference Include="DotNetEnv" />
18+
</ItemGroup>
19+
20+
<ItemGroup>
21+
<ProjectReference Include="..\..\..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
22+
</ItemGroup>
23+
24+
</Project>
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
// Creates a Foundry hosted session explicitly, pins an Agent Framework session to it,
4+
// reuses the hosted sandbox across turns, and deletes the hosted session on exit.
5+
6+
#pragma warning disable MEAI001 // Foundry hosted session helpers are experimental.
7+
8+
using Azure.AI.Projects;
9+
using Azure.AI.Projects.Agents;
10+
using Azure.Identity;
11+
using DotNetEnv;
12+
using Microsoft.Agents.AI;
13+
using Microsoft.Agents.AI.Foundry;
14+
15+
Env.TraversePath().Load();
16+
17+
Uri projectEndpoint = new(Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
18+
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set."));
19+
string agentName = Environment.GetEnvironmentVariable("AZURE_AI_AGENT_NAME")
20+
?? throw new InvalidOperationException("AZURE_AI_AGENT_NAME is not set.");
21+
Uri agentEndpoint = new($"{projectEndpoint.ToString().TrimEnd('/')}/agents/{agentName}/endpoint/protocols/openai");
22+
23+
var credential = new AzureCliCredential();
24+
var projectClient = new AIProjectClient(projectEndpoint, credential);
25+
FoundryAgent agent = projectClient.AsAIAgent(agentEndpoint);
26+
AgentAdministrationClient adminClient = projectClient.AgentAdministrationClient;
27+
28+
Console.WriteLine("Creating a Foundry hosted session...");
29+
ProjectsAgentRecord agentRecord = await adminClient.GetAgentAsync(agentName);
30+
string agentVersion = agentRecord.GetLatestVersion().Version;
31+
ProjectAgentSession hostedSession = await adminClient.CreateSessionAsync(
32+
agentName,
33+
new VersionRefIndicator(agentVersion));
34+
string hostedSessionId = hostedSession.AgentSessionId;
35+
36+
try
37+
{
38+
await WaitForSessionActiveAsync(adminClient, agentName, hostedSessionId);
39+
40+
ChatClientAgentSession session = await agent.CreateFoundryHostedAgentSessionAsync(
41+
hostedSessionId: hostedSessionId);
42+
43+
Console.ForegroundColor = ConsoleColor.Cyan;
44+
Console.WriteLine($"""
45+
============================================================
46+
Foundry Hosted Session Sample
47+
Agent: {agentName}
48+
Hosted session: {session.FoundryHostedAgentSessionId}
49+
50+
Every turn uses the same Foundry sandbox. Conversation history
51+
remains a separate concern and is carried by this AgentSession.
52+
Type a message or 'quit' to exit.
53+
============================================================
54+
""");
55+
Console.ResetColor();
56+
57+
while (true)
58+
{
59+
Console.ForegroundColor = ConsoleColor.Green;
60+
Console.Write("You> ");
61+
Console.ResetColor();
62+
63+
string? input = Console.ReadLine();
64+
if (input is null)
65+
{
66+
break;
67+
}
68+
69+
if (string.IsNullOrWhiteSpace(input))
70+
{
71+
continue;
72+
}
73+
74+
if (input.Equals("quit", StringComparison.OrdinalIgnoreCase))
75+
{
76+
break;
77+
}
78+
79+
Console.ForegroundColor = ConsoleColor.Yellow;
80+
Console.Write("Agent> ");
81+
Console.ResetColor();
82+
83+
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, session))
84+
{
85+
Console.Write(update);
86+
}
87+
88+
Console.WriteLine();
89+
Console.WriteLine();
90+
}
91+
}
92+
finally
93+
{
94+
Console.WriteLine($"Deleting hosted session {hostedSessionId}...");
95+
await adminClient.DeleteSessionAsync(agentName, hostedSessionId);
96+
}
97+
98+
static async Task WaitForSessionActiveAsync(
99+
AgentAdministrationClient adminClient,
100+
string agentName,
101+
string sessionId,
102+
CancellationToken cancellationToken = default)
103+
{
104+
TimeSpan timeout = TimeSpan.FromMinutes(3);
105+
DateTimeOffset deadline = DateTimeOffset.UtcNow + timeout;
106+
ProjectAgentSession session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken);
107+
108+
while (session.Status != AgentSessionStatus.Active)
109+
{
110+
if (session.Status == AgentSessionStatus.Failed
111+
|| session.Status == AgentSessionStatus.Deleted
112+
|| session.Status == AgentSessionStatus.Expired)
113+
{
114+
throw new InvalidOperationException(
115+
$"Hosted session '{sessionId}' entered terminal status '{session.Status}'.");
116+
}
117+
118+
if (DateTimeOffset.UtcNow >= deadline)
119+
{
120+
throw new TimeoutException(
121+
$"Hosted session '{sessionId}' did not become active within {timeout.TotalSeconds:F0} seconds. Last status: {session.Status}.");
122+
}
123+
124+
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
125+
session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken);
126+
}
127+
}

0 commit comments

Comments
 (0)