Compare commits

..
Author SHA1 Message Date
462f37e77d Apply suggestions from code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-02 18:19:34 -07:00
Azure SRE Agent 70c88d2150 docs: clarify checkpoint storage security model and deserialization trust boundaries
Add Security Model documentation sections to the checkpoint encoding and
Azure Functions serialization modules explaining:
- Checkpoint storage is a trusted data source requiring access controls
- The RestrictedUnpickler allowlist is defense-in-depth, not a security boundary
- Developer responsibilities for securing storage backends
- Guidance on using allowed_types and strip_pickle_markers

Co-authored-by: Azure SRE Agent <noreply@microsoft.com>
2026-06-03 01:01:00 +00:00
47 changed files with 132 additions and 4740 deletions
+1 -16
View File
@@ -8,7 +8,6 @@ function getPullRequest(context) {
return {
author: pullRequest.user.login,
authorType: pullRequest.user.type,
labels: pullRequest.labels?.map((label) => label.name).filter(Boolean) ?? [],
number: pullRequest.number,
};
@@ -50,10 +49,6 @@ function hasLabel(labels, labelName) {
return labels.some((label) => label.toLowerCase() === labelName.toLowerCase());
}
function isDependabotAuthor({ author, authorType }) {
return authorType === 'Bot' && author.toLowerCase() === 'dependabot[bot]';
}
function buildLimitMessage({ author, exemptLabelName, maxOpenPrs, openPrCount }) {
return [
`Thank you for your contribution, @${author}.`,
@@ -88,17 +83,7 @@ async function getOpenPrCount({ github, owner, repo, author, pullRequestNumber }
async function enforcePrLimit({ github, context, core, exemptLabelName, maxOpenPrs, labelName }) {
const { owner, repo } = context.repo;
const { author, authorType, labels, number } = getPullRequest(context);
if (isDependabotAuthor({ author, authorType })) {
core.info(`Author ${author} is Dependabot; skipping open PR limit enforcement.`);
return {
author,
closed: false,
dependabotExempt: true,
openPrCount: null,
};
}
const { author, labels, number } = getPullRequest(context);
if (hasLabel(labels, exemptLabelName)) {
core.info(`PR #${number} has the ${exemptLabelName} label; skipping open PR limit enforcement.`);
+1 -26
View File
@@ -16,7 +16,7 @@ const { enforcePrLimit } = require('../scripts/pr_limit_moderation.js');
// Helpers
// ---------------------------------------------------------------------------
function createContext({ author = 'community-user', authorType = 'User', labels = [], number = 123 } = {}) {
function createContext({ author = 'community-user', labels = [], number = 123 } = {}) {
return {
repo: {
owner: 'microsoft',
@@ -28,7 +28,6 @@ function createContext({ author = 'community-user', authorType = 'User', labels
labels: labels.map((name) => ({ name })),
user: {
login: author,
type: authorType,
},
},
},
@@ -297,30 +296,6 @@ describe('PR limit enforcement', () => {
assert.deepEqual(github.calls, []);
});
it('does not close Dependabot PRs', async () => {
const github = createGithub({
itemNumbers: [123, ...Array.from({ length: 25 }, (_, index) => index + 1)],
pullRequests: createPullRequestPage({
author: 'dependabot[bot]',
numbers: [123, ...Array.from({ length: 25 }, (_, index) => index + 1)],
}),
});
const result = await enforcePrLimit({
github,
context: createContext({ author: 'dependabot[bot]', authorType: 'Bot' }),
core: createCore(),
exemptLabelName: 'pr-limit-exempt',
maxOpenPrs: 10,
labelName: 'too-many-prs',
});
assert.equal(result.closed, false);
assert.equal(result.dependabotExempt, true);
assert.equal(result.openPrCount, null);
assert.deepEqual(github.calls, []);
});
it('counts the current PR when the author has more than one page of open PRs', async () => {
const github = createGithub({
itemNumbers: [123, ...Array.from({ length: 100 }, (_, index) => index + 1)],
+3 -3
View File
@@ -1,14 +1,14 @@
<Project>
<PropertyGroup>
<!-- Central version prefix - applies to all nuget packages. -->
<VersionPrefix>1.9.0</VersionPrefix>
<VersionPrefix>1.8.0</VersionPrefix>
<RCNumber>1</RCNumber>
<DateSuffix>260603</DateSuffix>
<DateSuffix>260528</DateSuffix>
<PackageVersion Condition="'$(IsReleaseCandidate)' == 'true'">$(VersionPrefix)-rc$(RCNumber)</PackageVersion>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' != ''">$(VersionPrefix)-$(VersionSuffix).$(DateSuffix).1</PackageVersion>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' == ''">$(VersionPrefix)-preview.$(DateSuffix).1</PackageVersion>
<PackageVersion Condition="'$(IsReleased)' == 'true'">$(VersionPrefix)</PackageVersion>
<GitTag>1.9.0</GitTag>
<GitTag>1.8.0</GitTag>
<Configurations>Debug;Release;Publish</Configurations>
<IsPackable>true</IsPackable>
@@ -10,11 +10,6 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient().AddLogging();
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -16,11 +16,6 @@ builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.TypeInfoResolverChain.Add(SampleJsonSerializerContext.Default));
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -10,11 +10,6 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient().AddLogging();
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -27,11 +27,6 @@ builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.TypeInfoResolverChain.Add(ApprovalJsonContext.Default));
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
app.UseHttpLogging();
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -17,11 +17,6 @@ builder.Services.AddAGUI();
// Configure to listen on port 8888
builder.WebHost.UseUrls("http://localhost:8888");
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -50,16 +50,12 @@ internal static partial class WorkflowHelper
/// <summary>
/// Executor that starts the concurrent processing by sending messages to the agents.
/// </summary>
[SendsMessage(typeof(List<ChatMessage>))]
[SendsMessage(typeof(TurnToken))]
private sealed partial class ConcurrentStartExecutor()
: Executor("ConcurrentStartExecutor", declareCrossRunShareable: true), IResettableExecutor
private sealed partial class ConcurrentStartExecutor() : Executor("ConcurrentStartExecutor")
{
[MessageHandler]
internal ValueTask RouteMessages(IEnumerable<ChatMessage> messages, IWorkflowContext context, CancellationToken cancellationToken)
internal ValueTask RouteMessages(List<ChatMessage> messages, IWorkflowContext context, CancellationToken cancellationToken)
{
List<ChatMessage> payload = messages as List<ChatMessage> ?? messages.ToList();
return context.SendMessageAsync(payload, cancellationToken: cancellationToken);
return context.SendMessageAsync(messages, cancellationToken: cancellationToken);
}
[MessageHandler]
@@ -67,16 +63,13 @@ internal static partial class WorkflowHelper
{
return context.SendMessageAsync(token, cancellationToken: cancellationToken);
}
public ValueTask ResetAsync() => default;
}
/// <summary>
/// Executor that aggregates the results from the concurrent agents.
/// </summary>
[YieldsOutput(typeof(string))]
private sealed partial class ConcurrentAggregationExecutor() :
Executor<List<ChatMessage>>("ConcurrentAggregationExecutor"), IResettableExecutor
[YieldsOutput(typeof(List<ChatMessage>))]
private sealed partial class ConcurrentAggregationExecutor() : Executor<List<ChatMessage>>("ConcurrentAggregationExecutor")
{
private readonly List<ChatMessage> _messages = [];
@@ -97,11 +90,5 @@ internal static partial class WorkflowHelper
await context.YieldOutputAsync(formattedMessages, cancellationToken);
}
}
public ValueTask ResetAsync()
{
this._messages.Clear();
return default;
}
}
}
@@ -15,7 +15,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -19,11 +19,6 @@ builder.Services.AddHttpClient().AddLogging();
builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.TypeInfoResolverChain.Add(AGUIDojoServerSerializerContext.Default));
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
app.UseHttpLogging();
@@ -49,9 +49,8 @@ var agent = new AzureOpenAIClient(
AGUIServerSerializerContext.Default.Options)
]);
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// When running in production, make sure to use an SessionIsolationKeyProvider, e.g. ClaimsIdentity-based
// if using Claims-based Identity for Authentication/Authorization
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
// Register the agent with the host and configure it to use an in-memory session store
@@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.AspNetCore\Microsoft.Agents.AI.Hosting.AspNetCore.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.AGUI\Microsoft.Agents.AI.AGUI.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
@@ -12,11 +12,6 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient().AddLogging();
builder.Services.AddAGUI();
// WARNING: When adding session persistence (e.g., WithInMemorySessionStore), or running in production,
// make sure to also register a SessionIsolationKeyProvider to scope sessions by principal in multi-user
// deployments, e.g.:
// builder.Services.UseClaimsBasedSessionIsolation(new() { ClaimType = ClaimTypes.NameIdentifier });
WebApplication app = builder.Build();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"] ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
@@ -1,9 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Agents.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Shared.DiagnosticIds;
namespace Microsoft.Extensions.AI;
@@ -34,19 +32,11 @@ public static class ChatClientHarnessExtensions
/// additional context providers, and chat history provider.
/// When <see langword="null"/>, the agent uses built-in default settings.
/// </param>
/// <param name="loggerFactory">
/// Optional logger factory for creating loggers used by the agent and its components.
/// </param>
/// <param name="services">
/// Optional service provider for resolving dependencies required by AI functions and other agent components.
/// </param>
/// <returns>A new <see cref="HarnessAgent"/> instance.</returns>
public static HarnessAgent AsHarnessAgent(
this IChatClient chatClient,
int maxContextWindowTokens,
int maxOutputTokens,
HarnessAgentOptions? options = null,
ILoggerFactory? loggerFactory = null,
IServiceProvider? services = null) =>
new(chatClient, maxContextWindowTokens, maxOutputTokens, options, loggerFactory, services);
HarnessAgentOptions? options = null) =>
new(chatClient, maxContextWindowTokens, maxOutputTokens, options);
}
@@ -10,7 +10,6 @@ using Microsoft.Agents.AI.Compaction;
using Microsoft.Agents.AI.Tools.Shell;
#endif
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Shared.DiagnosticIds;
using Microsoft.Shared.Diagnostics;
@@ -106,12 +105,6 @@ public sealed class HarnessAgent : DelegatingAIAgent
/// additional context providers, and chat history provider.
/// When <see langword="null"/>, the agent uses built-in default settings.
/// </param>
/// <param name="loggerFactory">
/// Optional logger factory for creating loggers used by the agent and its components.
/// </param>
/// <param name="services">
/// Optional service provider for resolving dependencies required by AI functions and other agent components.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="chatClient"/> is <see langword="null"/>.
/// </exception>
@@ -119,20 +112,18 @@ public sealed class HarnessAgent : DelegatingAIAgent
/// <paramref name="maxContextWindowTokens"/> is not positive, or
/// <paramref name="maxOutputTokens"/> is negative or greater than or equal to <paramref name="maxContextWindowTokens"/>.
/// </exception>
public HarnessAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options = null, ILoggerFactory? loggerFactory = null, IServiceProvider? services = null)
public HarnessAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options = null)
: base(BuildAgent(
Throw.IfNull(chatClient),
maxContextWindowTokens,
maxOutputTokens,
options,
loggerFactory,
services))
options))
{
}
private static AIAgent BuildAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options, ILoggerFactory? loggerFactory, IServiceProvider? services)
private static AIAgent BuildAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options)
{
ChatClientAgent innerAgent = BuildInnerAgent(chatClient, maxContextWindowTokens, maxOutputTokens, options, loggerFactory, services);
ChatClientAgent innerAgent = BuildInnerAgent(chatClient, maxContextWindowTokens, maxOutputTokens, options);
AIAgentBuilder builder = innerAgent.AsBuilder();
@@ -146,10 +137,10 @@ public sealed class HarnessAgent : DelegatingAIAgent
builder.UseOpenTelemetry(sourceName: options?.OpenTelemetrySourceName);
}
return builder.Build(services);
return builder.Build();
}
private static ChatClientAgent BuildInnerAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options, ILoggerFactory? loggerFactory, IServiceProvider? services)
private static ChatClientAgent BuildInnerAgent(IChatClient chatClient, int maxContextWindowTokens, int maxOutputTokens, HarnessAgentOptions? options)
{
var compactionStrategy = new ContextWindowCompactionStrategy(
maxContextWindowTokens: maxContextWindowTokens,
@@ -174,13 +165,13 @@ public sealed class HarnessAgent : DelegatingAIAgent
ChatOptions chatOptions = BuildChatOptions(options, instructions, maxOutputTokens);
var compactionProvider = new CompactionProvider(compactionStrategy, loggerFactory: loggerFactory);
var compactionProvider = new CompactionProvider(compactionStrategy);
IEnumerable<AIContextProvider> contextProviders = BuildContextProviders(options, loggerFactory);
IEnumerable<AIContextProvider> contextProviders = BuildContextProviders(options);
return chatClient
.AsBuilder()
.UseFunctionInvocation(loggerFactory, configure: options?.MaximumIterationsPerRequest is int maxIterations
.UseFunctionInvocation(configure: options?.MaximumIterationsPerRequest is int maxIterations
? ficc => ficc.MaximumIterationsPerRequest = maxIterations
: null)
.UseMessageInjection()
@@ -198,9 +189,7 @@ public sealed class HarnessAgent : DelegatingAIAgent
RequirePerServiceCallChatHistoryPersistence = true,
WarnOnChatHistoryProviderConflict = false,
ThrowOnChatHistoryProviderConflict = false,
},
loggerFactory,
services);
});
}
private static ChatOptions BuildChatOptions(HarnessAgentOptions? options, string instructions, int maxOutputTokens)
@@ -226,7 +215,7 @@ public sealed class HarnessAgent : DelegatingAIAgent
return result;
}
private static List<AIContextProvider> BuildContextProviders(HarnessAgentOptions? options, ILoggerFactory? loggerFactory)
private static List<AIContextProvider> BuildContextProviders(HarnessAgentOptions? options)
{
var providers = new List<AIContextProvider>();
@@ -266,8 +255,8 @@ public sealed class HarnessAgent : DelegatingAIAgent
if (options?.DisableAgentSkillsProvider is not true)
{
AgentSkillsProvider skillsProvider = options?.AgentSkillsSource is AgentSkillsSource source
? new AgentSkillsProvider(source, loggerFactory: loggerFactory)
: new AgentSkillsProvider(Directory.GetCurrentDirectory(), loggerFactory: loggerFactory);
? new AgentSkillsProvider(source)
: new AgentSkillsProvider(Directory.GetCurrentDirectory());
providers.Add(skillsProvider);
}
@@ -103,16 +103,7 @@ public static class AGUIEndpointRouteBuilderExtensions
ArgumentNullException.ThrowIfNull(aiAgent);
var agentSessionStore = endpoints.ServiceProvider.GetKeyedService<AgentSessionStore>(aiAgent.Name);
// Ensure that we have an IsolationKeyScopedAgentSessionStore registered.
var isolationKeyProvider = endpoints.ServiceProvider.GetService<SessionIsolationKeyProvider>();
if (agentSessionStore?.GetService<IsolationKeyScopedAgentSessionStore>() is null)
{
agentSessionStore ??= new NoopAgentSessionStore();
agentSessionStore = new IsolationKeyScopedAgentSessionStore(agentSessionStore, isolationKeyProvider, new() { Strict = isolationKeyProvider != null });
}
var hostAgent = new AIHostAgent(aiAgent, agentSessionStore);
var hostAgent = new AIHostAgent(aiAgent, agentSessionStore ?? new NoopAgentSessionStore());
return endpoints.MapPost(pattern, async ([FromBody] RunAgentInput? input, HttpContext context, CancellationToken cancellationToken) =>
{
@@ -27,14 +27,6 @@ internal sealed class InvokeMcpToolExecutor(
WorkflowFormulaState state) :
DeclarativeActionExecutor<InvokeMcpTool>(model, state)
{
private const string ApprovalSnapshotStateKey = nameof(_approvalSnapshot);
/// <summary>
/// Snapshot of evaluated parameters at approval-request time.
/// Used to prevent TOCTOU attacks where state mutates during the approval window.
/// </summary>
private ApprovalSnapshot? _approvalSnapshot;
/// <summary>
/// Step identifiers for the MCP tool invocation workflow.
/// </summary>
@@ -83,10 +75,6 @@ internal sealed class InvokeMcpToolExecutor(
if (requireApproval)
{
// Snapshot the evaluated parameters to prevent TOCTOU attacks.
// If state mutates during the approval window, the approved values are used on resume.
this._approvalSnapshot = new ApprovalSnapshot(serverUrl, serverLabel, toolName, arguments, connectionName);
// Create tool call content for approval request.
// Transport headers (e.g. Authorization) are intentionally excluded from the
// approval event: they must not cross into the externally-surfaced approval request.
@@ -149,14 +137,13 @@ internal sealed class InvokeMcpToolExecutor(
return;
}
// Approved - use the snapshot from approval-request time to prevent TOCTOU attacks.
// Headers are re-evaluated (they may contain auth secrets that should not be persisted).
string serverUrl = this._approvalSnapshot?.ServerUrl ?? this.GetServerUrl();
string? serverLabel = this._approvalSnapshot?.ServerLabel ?? this.GetServerLabel();
string toolName = this._approvalSnapshot?.ToolName ?? this.GetToolName();
Dictionary<string, object?>? arguments = this._approvalSnapshot?.Arguments ?? this.GetArguments();
// Approved - now invoke the tool
string serverUrl = this.GetServerUrl();
string? serverLabel = this.GetServerLabel();
string toolName = this.GetToolName();
Dictionary<string, object?>? arguments = this.GetArguments();
Dictionary<string, string>? headers = this.GetHeaders();
string? connectionName = this._approvalSnapshot?.ConnectionName ?? this.GetConnectionName();
string? connectionName = this.GetConnectionName();
McpServerToolResultContent resultContent = await mcpToolHandler.InvokeToolAsync(
serverUrl,
@@ -175,33 +162,9 @@ internal sealed class InvokeMcpToolExecutor(
/// </summary>
public async ValueTask CompleteAsync(IWorkflowContext context, ActionExecutorResult message, CancellationToken cancellationToken)
{
// Clear the approval snapshot after successful completion.
this._approvalSnapshot = null;
await ClearSnapshotStateAsync(context, cancellationToken).ConfigureAwait(false);
await context.RaiseCompletionEventAsync(this.Model, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
/// <remarks>
/// Persists the approval snapshot to workflow state so it survives checkpoint/restore cycles.
/// </remarks>
protected override async ValueTask OnCheckpointingAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
await context.QueueStateUpdateAsync(ApprovalSnapshotStateKey, this._approvalSnapshot, null, cancellationToken).ConfigureAwait(false);
await base.OnCheckpointingAsync(context, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
/// <remarks>
/// Restores the approval snapshot from workflow state after a checkpoint restore.
/// </remarks>
protected override async ValueTask OnCheckpointRestoredAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
await base.OnCheckpointRestoredAsync(context, cancellationToken).ConfigureAwait(false);
this._approvalSnapshot = await context.ReadStateAsync<ApprovalSnapshot>(ApprovalSnapshotStateKey, null, cancellationToken).ConfigureAwait(false);
}
private async ValueTask ProcessResultAsync(IWorkflowContext context, McpServerToolResultContent resultContent, CancellationToken cancellationToken)
{
bool autoSend = this.GetAutoSendValue();
@@ -402,24 +365,4 @@ internal sealed class InvokeMcpToolExecutor(
return result;
}
/// <summary>
/// Clears the persisted approval snapshot state after a successful tool invocation.
/// </summary>
private static async ValueTask ClearSnapshotStateAsync(IWorkflowContext context, CancellationToken cancellationToken)
{
await context.QueueStateUpdateAsync<ApprovalSnapshot?>(ApprovalSnapshotStateKey, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stores the evaluated parameters at approval-request time so that
/// <see cref="CaptureResponseAsync"/> uses the values the user reviewed,
/// even if <see cref="WorkflowFormulaState"/> mutates during the approval window.
/// </summary>
internal sealed record ApprovalSnapshot(
string ServerUrl,
string? ServerLabel,
string ToolName,
Dictionary<string, object?>? Arguments,
string? ConnectionName);
}
@@ -9,7 +9,6 @@ using System.Threading.Tasks;
using Microsoft.Agents.AI.Tools.Shell;
#endif
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Moq;
namespace Microsoft.Agents.AI.UnitTests;
@@ -1461,131 +1460,4 @@ public class HarnessAgentTests
#endregion
#endif
#region LoggerFactory and ServiceProvider
/// <summary>
/// Verify that the constructor succeeds when loggerFactory is provided.
/// </summary>
[Fact]
public void Constructor_SucceedsWithLoggerFactory()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var loggerFactory = new Mock<ILoggerFactory>().Object;
// Act
var agent = new HarnessAgent(chatClient, TestMaxContextWindowTokens, TestMaxOutputTokens, CreateAllDisabledOptions(), loggerFactory);
// Assert
Assert.NotNull(agent);
}
/// <summary>
/// Verify that the constructor succeeds when serviceProvider is provided.
/// </summary>
[Fact]
public void Constructor_SucceedsWithServiceProvider()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var services = new Mock<IServiceProvider>().Object;
// Act
var agent = new HarnessAgent(chatClient, TestMaxContextWindowTokens, TestMaxOutputTokens, CreateAllDisabledOptions(), services: services);
// Assert
Assert.NotNull(agent);
}
/// <summary>
/// Verify that the constructor succeeds when both loggerFactory and serviceProvider are provided.
/// </summary>
[Fact]
public void Constructor_SucceedsWithLoggerFactoryAndServiceProvider()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var loggerFactory = new Mock<ILoggerFactory>().Object;
var services = new Mock<IServiceProvider>().Object;
// Act
var agent = new HarnessAgent(chatClient, TestMaxContextWindowTokens, TestMaxOutputTokens, CreateAllDisabledOptions(), loggerFactory, services);
// Assert
Assert.NotNull(agent);
}
/// <summary>
/// Verify that AsHarnessAgent extension method accepts loggerFactory and serviceProvider.
/// </summary>
[Fact]
public void AsHarnessAgent_SucceedsWithLoggerFactoryAndServiceProvider()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var loggerFactory = new Mock<ILoggerFactory>().Object;
var services = new Mock<IServiceProvider>().Object;
// Act
var agent = chatClient.AsHarnessAgent(TestMaxContextWindowTokens, TestMaxOutputTokens, CreateAllDisabledOptions(), loggerFactory, services);
// Assert
Assert.NotNull(agent);
}
/// <summary>
/// Verify that ILoggerFactory is threaded to downstream components by confirming CreateLogger is called.
/// </summary>
[Fact]
public void Constructor_LoggerFactoryIsUsedByDownstreamComponents()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory
.Setup(lf => lf.CreateLogger(It.IsAny<string>()))
.Returns(new Mock<ILogger>().Object);
// Act — use options that leave CompactionProvider and AgentSkillsProvider enabled
var options = new HarnessAgentOptions
{
DisableToolApproval = true,
DisableOpenTelemetry = true,
DisableFileMemory = true,
DisableFileAccess = true,
DisableWebSearch = true,
DisableTodoProvider = true,
DisableAgentModeProvider = true,
};
var agent = new HarnessAgent(chatClient, TestMaxContextWindowTokens, TestMaxOutputTokens, options, mockLoggerFactory.Object);
// Assert — CreateLogger should have been called by one or more downstream components
Assert.NotNull(agent);
mockLoggerFactory.Verify(lf => lf.CreateLogger(It.IsAny<string>()), Times.AtLeastOnce());
}
/// <summary>
/// Verify that IServiceProvider is propagated through the agent pipeline by confirming
/// it is queried during agent construction.
/// </summary>
[Fact]
public void Constructor_ServiceProviderIsQueriedDuringBuild()
{
// Arrange
var chatClient = new Mock<IChatClient>().Object;
var mockServices = new Mock<IServiceProvider>();
mockServices
.Setup(sp => sp.GetService(It.IsAny<Type>()))
.Returns(null!);
// Act
var agent = new HarnessAgent(chatClient, TestMaxContextWindowTokens, TestMaxOutputTokens, CreateAllDisabledOptions(), services: mockServices.Object);
// Assert — the service provider should have been queried during pipeline construction
Assert.NotNull(agent);
mockServices.Verify(sp => sp.GetService(It.IsAny<Type>()), Times.AtLeastOnce());
}
#endregion
}
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.Events;
@@ -12,9 +11,7 @@ using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
using Microsoft.Extensions.AI;
using Microsoft.PowerFx.Types;
using Moq;
using ApprovalSnapshot = Microsoft.Agents.AI.Workflows.Declarative.ObjectModel.InvokeMcpToolExecutor.ApprovalSnapshot;
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.ObjectModel;
@@ -845,313 +842,6 @@ public sealed class InvokeMcpToolExecutorTest(ITestOutputHelper output) : Workfl
#endregion
#region Approval Snapshot Security Tests
/// <summary>
/// Verifies that mutating the tool name variable after approval does not change
/// which tool is actually invoked. The originally-approved tool name must be used.
/// </summary>
[Fact]
public async Task InvokeMcpToolCaptureResponseUsesApprovedToolNameNotMutatedAsync()
{
// Arrange
const string ApprovedToolName = "safe_readonly_query";
const string MutatedToolName = "dangerous_admin_tool";
this.State.Set("TargetTool", FormulaValue.New(ApprovedToolName));
this.State.InitializeSystem();
this.State.Bind();
InvokeMcpTool model = this.CreateModelWithVariableToolName(
displayName: nameof(InvokeMcpToolCaptureResponseUsesApprovedToolNameNotMutatedAsync),
serverUrl: TestServerUrl,
variableName: "TargetTool");
string? capturedToolName = null;
Mock<IMcpToolHandler> mockProvider = new();
mockProvider.Setup(provider => provider.InvokeToolAsync(
It.IsAny<string>(),
It.IsAny<string?>(),
It.IsAny<string>(),
It.IsAny<IDictionary<string, object?>?>(),
It.IsAny<IDictionary<string, string>?>(),
It.IsAny<string?>(),
It.IsAny<CancellationToken>()))
.Callback<string, string?, string, IDictionary<string, object?>?, IDictionary<string, string>?, string?, CancellationToken>(
(_, _, toolName, _, _, _, _) => capturedToolName = toolName)
.ReturnsAsync(new McpServerToolResultContent("capture-call-id")
{
Outputs = [new TextContent("result")]
});
MockAgentProvider mockAgentProvider = new();
InvokeMcpToolExecutor action = new(model, mockProvider.Object, mockAgentProvider.Object, this.State);
// Act - trigger ExecuteAsync to store the approval snapshot
Mock<IWorkflowContext> mockContext = CreateMockWorkflowContext();
await action.HandleAsync(new ActionExecutorResult(action.Id), mockContext.Object, CancellationToken.None);
// Simulate parallel branch mutating state during the approval window
this.State.Set("TargetTool", FormulaValue.New(MutatedToolName));
this.State.Bind();
// User clicks approve (they saw "safe_readonly_query" in the approval UI)
McpServerToolCallContent toolCall = new(action.Id, ApprovedToolName, TestServerUrl);
ToolApprovalRequestContent approvalRequest = new(action.Id, toolCall);
ToolApprovalResponseContent approvalResponse = approvalRequest.CreateResponse(approved: true);
ExternalInputResponse response = new(new ChatMessage(ChatRole.User, [approvalResponse]));
// Resume after approval
await action.CaptureResponseAsync(mockContext.Object, response, CancellationToken.None);
// Assert - the originally-approved tool name must be used, not the mutated one
Assert.NotNull(capturedToolName);
Assert.Equal(ApprovedToolName, capturedToolName);
}
/// <summary>
/// Verifies that mutating an argument variable after approval does not change
/// the arguments actually passed to the MCP tool. The originally-approved arguments must be used.
/// </summary>
[Fact]
public async Task InvokeMcpToolCaptureResponseUsesApprovedArgumentsNotMutatedAsync()
{
// Arrange
const string ApprovedQuery = "SELECT * FROM users LIMIT 10";
const string MutatedQuery = "DROP TABLE users CASCADE; --";
this.State.Set("SqlQuery", FormulaValue.New(ApprovedQuery));
this.State.InitializeSystem();
this.State.Bind();
InvokeMcpTool model = this.CreateModelWithVariableArgument(
displayName: nameof(InvokeMcpToolCaptureResponseUsesApprovedArgumentsNotMutatedAsync),
serverUrl: TestServerUrl,
toolName: TestToolName,
argumentKey: "query",
variableName: "SqlQuery");
IDictionary<string, object?>? capturedArguments = null;
Mock<IMcpToolHandler> mockProvider = new();
mockProvider.Setup(provider => provider.InvokeToolAsync(
It.IsAny<string>(),
It.IsAny<string?>(),
It.IsAny<string>(),
It.IsAny<IDictionary<string, object?>?>(),
It.IsAny<IDictionary<string, string>?>(),
It.IsAny<string?>(),
It.IsAny<CancellationToken>()))
.Callback<string, string?, string, IDictionary<string, object?>?, IDictionary<string, string>?, string?, CancellationToken>(
(_, _, _, arguments, _, _, _) => capturedArguments = arguments)
.ReturnsAsync(new McpServerToolResultContent("capture-call-id")
{
Outputs = [new TextContent("result")]
});
MockAgentProvider mockAgentProvider = new();
InvokeMcpToolExecutor action = new(model, mockProvider.Object, mockAgentProvider.Object, this.State);
// Act - trigger ExecuteAsync to store the approval snapshot
Mock<IWorkflowContext> mockContext = CreateMockWorkflowContext();
await action.HandleAsync(new ActionExecutorResult(action.Id), mockContext.Object, CancellationToken.None);
// Simulate parallel branch mutating state during the approval window
this.State.Set("SqlQuery", FormulaValue.New(MutatedQuery));
this.State.Bind();
// User clicks approve
McpServerToolCallContent toolCall = new(action.Id, TestToolName, TestServerUrl);
ToolApprovalRequestContent approvalRequest = new(action.Id, toolCall);
ToolApprovalResponseContent approvalResponse = approvalRequest.CreateResponse(approved: true);
ExternalInputResponse response = new(new ChatMessage(ChatRole.User, [approvalResponse]));
// Resume after approval
await action.CaptureResponseAsync(mockContext.Object, response, CancellationToken.None);
// Assert - the originally-approved argument must be used, not the mutated one
Assert.NotNull(capturedArguments);
Assert.Equal(ApprovedQuery, capturedArguments["query"]?.ToString());
}
/// <summary>
/// Verifies that mutating the server URL variable after approval does not redirect
/// the MCP tool call to a different server. The originally-approved server URL must be used.
/// </summary>
[Fact]
public async Task InvokeMcpToolCaptureResponseUsesApprovedServerUrlNotMutatedAsync()
{
// Arrange
const string ApprovedServerUrl = "https://internal-mcp.corp";
const string MutatedServerUrl = "https://attacker.evil/steal";
this.State.Set("McpEndpoint", FormulaValue.New(ApprovedServerUrl));
this.State.InitializeSystem();
this.State.Bind();
InvokeMcpTool model = this.CreateModelWithVariableServerUrl(
displayName: nameof(InvokeMcpToolCaptureResponseUsesApprovedServerUrlNotMutatedAsync),
variableName: "McpEndpoint",
toolName: TestToolName);
string? capturedServerUrl = null;
Mock<IMcpToolHandler> mockProvider = new();
mockProvider.Setup(provider => provider.InvokeToolAsync(
It.IsAny<string>(),
It.IsAny<string?>(),
It.IsAny<string>(),
It.IsAny<IDictionary<string, object?>?>(),
It.IsAny<IDictionary<string, string>?>(),
It.IsAny<string?>(),
It.IsAny<CancellationToken>()))
.Callback<string, string?, string, IDictionary<string, object?>?, IDictionary<string, string>?, string?, CancellationToken>(
(serverUrl, _, _, _, _, _, _) => capturedServerUrl = serverUrl)
.ReturnsAsync(new McpServerToolResultContent("capture-call-id")
{
Outputs = [new TextContent("result")]
});
MockAgentProvider mockAgentProvider = new();
InvokeMcpToolExecutor action = new(model, mockProvider.Object, mockAgentProvider.Object, this.State);
// Act - trigger ExecuteAsync to store the approval snapshot
Mock<IWorkflowContext> mockContext = CreateMockWorkflowContext();
await action.HandleAsync(new ActionExecutorResult(action.Id), mockContext.Object, CancellationToken.None);
// Simulate parallel branch mutating state during the approval window
this.State.Set("McpEndpoint", FormulaValue.New(MutatedServerUrl));
this.State.Bind();
// User clicks approve
McpServerToolCallContent toolCall = new(action.Id, TestToolName, ApprovedServerUrl);
ToolApprovalRequestContent approvalRequest = new(action.Id, toolCall);
ToolApprovalResponseContent approvalResponse = approvalRequest.CreateResponse(approved: true);
ExternalInputResponse response = new(new ChatMessage(ChatRole.User, [approvalResponse]));
// Resume after approval
await action.CaptureResponseAsync(mockContext.Object, response, CancellationToken.None);
// Assert - the originally-approved server URL must be used, not the mutated one
Assert.NotNull(capturedServerUrl);
Assert.Equal(ApprovedServerUrl, capturedServerUrl);
}
/// <summary>
/// Verifies that the approval snapshot survives a checkpoint/restore cycle.
/// After restore, the originally-approved tool name must still be used even if state was mutated.
/// </summary>
[Fact]
public async Task InvokeMcpToolCaptureResponseUsesSnapshotAfterCheckpointRestoreAsync()
{
// Arrange
const string ApprovedToolName = "safe_readonly_query";
const string MutatedToolName = "dangerous_admin_tool";
this.State.Set("TargetTool", FormulaValue.New(ApprovedToolName));
this.State.InitializeSystem();
this.State.Bind();
InvokeMcpTool model = this.CreateModelWithVariableToolName(
displayName: nameof(InvokeMcpToolCaptureResponseUsesSnapshotAfterCheckpointRestoreAsync),
serverUrl: TestServerUrl,
variableName: "TargetTool");
string? capturedToolName = null;
Mock<IMcpToolHandler> mockProvider = new();
mockProvider.Setup(provider => provider.InvokeToolAsync(
It.IsAny<string>(),
It.IsAny<string?>(),
It.IsAny<string>(),
It.IsAny<IDictionary<string, object?>?>(),
It.IsAny<IDictionary<string, string>?>(),
It.IsAny<string?>(),
It.IsAny<CancellationToken>()))
.Callback<string, string?, string, IDictionary<string, object?>?, IDictionary<string, string>?, string?, CancellationToken>(
(_, _, toolName, _, _, _, _) => capturedToolName = toolName)
.ReturnsAsync(new McpServerToolResultContent("capture-call-id")
{
Outputs = [new TextContent("result")]
});
MockAgentProvider mockAgentProvider = new();
InvokeMcpToolExecutor action = new(model, mockProvider.Object, mockAgentProvider.Object, this.State);
// Act - trigger ExecuteAsync to store the approval snapshot
Mock<IWorkflowContext> mockContext = CreateMockWorkflowContextWithStateStore();
await action.HandleAsync(new ActionExecutorResult(action.Id), mockContext.Object, CancellationToken.None);
// Simulate checkpoint: persist to state store
await InvokeProtectedMethodAsync(action, "OnCheckpointingAsync", mockContext.Object, CancellationToken.None);
// Simulate restore on a "new" executor instance by clearing the in-memory field via reflection
// (In production, a new executor instance would be created with _approvalSnapshot == null)
typeof(InvokeMcpToolExecutor)
.GetField("_approvalSnapshot", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(action, null);
// Restore from state store
await InvokeProtectedMethodAsync(action, "OnCheckpointRestoredAsync", mockContext.Object, CancellationToken.None);
// Mutate state after restore (simulating parallel branch)
this.State.Set("TargetTool", FormulaValue.New(MutatedToolName));
this.State.Bind();
// User clicks approve
McpServerToolCallContent toolCall = new(action.Id, ApprovedToolName, TestServerUrl);
ToolApprovalRequestContent approvalRequest = new(action.Id, toolCall);
ToolApprovalResponseContent approvalResponse = approvalRequest.CreateResponse(approved: true);
ExternalInputResponse response = new(new ChatMessage(ChatRole.User, [approvalResponse]));
// Resume after approval
await action.CaptureResponseAsync(mockContext.Object, response, CancellationToken.None);
// Assert - the originally-approved tool name must be used, not the mutated one
Assert.NotNull(capturedToolName);
Assert.Equal(ApprovedToolName, capturedToolName);
}
private static Mock<IWorkflowContext> CreateMockWorkflowContext()
{
Mock<IWorkflowContext> mockContext = new();
mockContext.Setup(c => c.AddEventAsync(It.IsAny<WorkflowEvent>(), It.IsAny<CancellationToken>()))
.Returns(default(ValueTask));
mockContext.Setup(c => c.QueueStateUpdateAsync(It.IsAny<string>(), It.IsAny<object?>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Returns(default(ValueTask));
mockContext.Setup(c => c.SendMessageAsync(It.IsAny<object>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Returns(default(ValueTask));
return mockContext;
}
/// <summary>
/// Creates a mock workflow context that actually stores state values (for checkpoint/restore tests).
/// </summary>
private static Mock<IWorkflowContext> CreateMockWorkflowContextWithStateStore()
{
Dictionary<string, object?> stateStore = new();
Mock<IWorkflowContext> mockContext = new();
mockContext.Setup(c => c.AddEventAsync(It.IsAny<WorkflowEvent>(), It.IsAny<CancellationToken>()))
.Returns(default(ValueTask));
mockContext.Setup(c => c.QueueStateUpdateAsync(It.IsAny<string>(), It.IsAny<ApprovalSnapshot?>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Callback<string, ApprovalSnapshot?, string?, CancellationToken>((key, value, _, _) => stateStore[key] = value)
.Returns(default(ValueTask));
mockContext.Setup(c => c.SendMessageAsync(It.IsAny<object>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Returns(default(ValueTask));
mockContext.Setup(c => c.ReadStateAsync<ApprovalSnapshot>(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Returns<string, string?, CancellationToken>((key, _, _) =>
new ValueTask<ApprovalSnapshot?>(stateStore.TryGetValue(key, out object? val) ? val as ApprovalSnapshot : null));
mockContext.Setup(c => c.ReadStateKeysAsync(It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new HashSet<string>());
return mockContext;
}
/// <summary>
/// Invokes a protected method on an executor via reflection (for testing checkpoint hooks).
/// </summary>
private static async ValueTask InvokeProtectedMethodAsync(InvokeMcpToolExecutor action, string methodName, IWorkflowContext context, CancellationToken cancellationToken)
{
MethodInfo method = typeof(InvokeMcpToolExecutor)
.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance)!;
ValueTask result = (ValueTask)method.Invoke(action, [context, cancellationToken])!;
await result.ConfigureAwait(false);
}
#endregion
#region CompleteAsync Tests
[Fact]
@@ -1261,50 +951,6 @@ public sealed class InvokeMcpToolExecutorTest(ITestOutputHelper output) : Workfl
return AssignParent<InvokeMcpTool>(builder);
}
private InvokeMcpTool CreateModelWithVariableToolName(string displayName, string serverUrl, string variableName)
{
InvokeMcpTool.Builder builder = new()
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
ServerUrl = new StringExpression.Builder(StringExpression.Literal(serverUrl)),
ToolName = new StringExpression.Builder(
StringExpression.Variable(PropertyPath.TopicVariable(variableName))),
RequireApproval = new BoolExpression.Builder(BoolExpression.Literal(true)),
};
return AssignParent<InvokeMcpTool>(builder);
}
private InvokeMcpTool CreateModelWithVariableArgument(
string displayName, string serverUrl, string toolName, string argumentKey, string variableName)
{
InvokeMcpTool.Builder builder = new()
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
ServerUrl = new StringExpression.Builder(StringExpression.Literal(serverUrl)),
ToolName = new StringExpression.Builder(StringExpression.Literal(toolName)),
RequireApproval = new BoolExpression.Builder(BoolExpression.Literal(true)),
};
builder.Arguments.Add(argumentKey,
ValueExpression.Variable(PropertyPath.TopicVariable(variableName)));
return AssignParent<InvokeMcpTool>(builder);
}
private InvokeMcpTool CreateModelWithVariableServerUrl(string displayName, string variableName, string toolName)
{
InvokeMcpTool.Builder builder = new()
{
Id = this.CreateActionId(),
DisplayName = this.FormatDisplayName(displayName),
ServerUrl = new StringExpression.Builder(
StringExpression.Variable(PropertyPath.TopicVariable(variableName))),
ToolName = new StringExpression.Builder(StringExpression.Literal(toolName)),
RequireApproval = new BoolExpression.Builder(BoolExpression.Literal(true)),
};
return AssignParent<InvokeMcpTool>(builder);
}
#endregion
#region Mock MCP Tool Provider
@@ -14,6 +14,24 @@ This module adds:
- reconstruct_to_type: for HITL responses where external data (without type markers)
needs to be reconstructed to a known type
- resolve_type: resolves 'module:class' type keys to Python types
Security Model
--------------
The underlying Azure Durable Functions storage (Azure Storage account) is the
trusted persistence layer for serialized checkpoint data. The
``RestrictedUnpickler`` in the core encoding module provides defense-in-depth
type filtering, but checkpoint storage itself must be properly access-controlled:
- Ensure the Azure Storage account used by Durable Functions is not publicly
writable and uses appropriate RBAC / shared-access policies.
- Never route untrusted user input directly into ``deserialize_value`` without
first calling :func:`strip_pickle_markers` to neutralize injection of
pickle markers into the data path.
- Configure your checkpoint storage with ``allowed_checkpoint_types`` (or call
``decode_checkpoint_value(..., allowed_types=...)`` directly) to restrict the set of types that can be deserialized.
See :mod:`agent_framework._workflows._checkpoint_encoding` for the full
security model documentation.
"""
from __future__ import annotations
+1 -14
View File
@@ -56,7 +56,7 @@ agent_framework/
- **`AgentMiddleware`** - Intercepts agent `run()` calls
- **`ChatMiddleware`** - Intercepts chat client `get_response()` calls
- **`FunctionMiddleware`** - Intercepts function/tool invocations
- **`AgentContext`** / **`ChatContext`** / **`FunctionInvocationContext`** - Context objects passed through middleware. A tool can declare a `FunctionInvocationContext` parameter to receive it; `context.tools` is the live, mutable tools list for the run, and `context.add_tools(...)` / `context.remove_tools(...)` enable progressive tool exposure (changes apply on the next function-calling iteration).
- **`AgentContext`** / **`ChatContext`** / **`FunctionInvocationContext`** - Context objects passed through middleware
### Sessions (`_sessions.py`)
@@ -76,19 +76,6 @@ agent_framework/
- **`SkillScriptRunner`** - Protocol for file-based script execution. Any callable matching `(skill, script, args) -> Any` satisfies it. Code-defined scripts do not use a runner.
- **`SkillsProvider`** - Context provider (extends `ContextProvider`) that discovers file-based skills from `SKILL.md` files and/or accepts code-defined `Skill` instances. Follows progressive disclosure: advertise → load → read resources / run scripts.
### Model Context Protocol (`_mcp.py`)
- **`MCPTool`** - Base wrapper that owns the MCP `ClientSession` and exposes the remote server's tools as `FunctionTool`s.
- **`MCPStdioTool`** / **`MCPStreamableHTTPTool`** / **`MCPWebsocketTool`** - Transport-specific subclasses.
- **`MCPTaskOptions`** (experimental, `MCP_LONG_RUNNING_TASKS` feature, **frozen**) - Per-tool-instance options controlling the SEP-2663 long-running task lifecycle. When the server advertises a tool with `execution.taskSupport == "required"`, `MCPTool.call_tool` transparently routes through `call_tool_as_task`, which sends an augmented `tools/call`, polls `tasks/get` until terminal, and reinterprets `tasks/result` as a normal `CallToolResult`. Instances are immutable; replace via `MCPTool.task_options = MCPTaskOptions(...)`. Fields:
- `default_ttl: timedelta | None` — forwarded to the server as `params.task.ttl` (milliseconds). When `None`, the server's default applies.
- `cancel_remote_task_on_local_cancellation: bool = True` — only gates the `CancelledError` path. Abandonment paths (see below) always cancel.
- `max_task_wait: timedelta | None` — client-side deadline for the whole post-create lifecycle (poll + result fetch). When exceeded, raises `ToolExecutionException` and fires a best-effort `tasks/cancel`. `None` (default) means no client-side bound. Bounds sleeps, sends, AND reconnects via `asyncio.wait_for`.
- **Permissive fallback**: servers that ignore the augmentation (return `CallToolResult` directly) or reject the unknown `task` field with `METHOD_NOT_FOUND` / `INVALID_PARAMS` fall back to the plain `session.call_tool(...)` path so legacy servers keep working. An unparseable success response (server accepted the augmented call but returned a payload that is neither `CreateTaskResult` nor `CallToolResult`) **does not** fall back — it raises `ToolExecutionException` to avoid double-executing a side-effecting tool.
- **Submit-vs-track reconnect policy**: a dropped connection before a `task_id` is known raises `ToolExecutionException("connection lost; task state unknown")` without re-issuing the augmented `tools/call`, so a server that accepted the request but lost the response cannot be made to start the same operation twice; once a `task_id` exists, `tasks/get` / `tasks/result` reconnect once and retry against the same id (a shared `_send_with_one_reconnect` helper).
- **Cancel-on-abandonment vs terminal failure**: any path where the remote task may still be running (max-wait exceeded, hard `McpError` in poll, malformed `tasks/get`, second connection loss in poll/fetch, reconnect failure) fires best-effort `tasks/cancel` before raising. Terminal failures (`failed`/`cancelled`/`input_required` server-side, `completed+isError`, malformed `tasks/result` after server completed) do **not** cancel — the server is already done. `_MCPTaskAbandoned` is the private marker distinguishing the two.
- **Transient poll retry**: a slow `tasks/get` that surfaces as `McpError(code=408 REQUEST_TIMEOUT)` is retried (bounded by `max_task_wait`). All other non-connection `McpError`s during poll are treated as abandonment. `tasks/result` does not get transient retry — the server has already completed, so a slow payload fetch is anomalous.
### File Access Harness (`_harness/_file_access.py`)
- **`AgentFileStore`** - Abstract async store backing the file-access harness. Implementations expose `write_file`, `read_file`, `delete_file`, `list_files`, `file_exists`, `search_files`, and `create_directory` over forward-slash relative paths.
@@ -124,7 +124,7 @@ from ._harness._todo import (
TodoSessionStore,
TodoStore,
)
from ._mcp import MCPStdioTool, MCPStreamableHTTPTool, MCPTaskOptions, MCPWebsocketTool
from ._mcp import MCPStdioTool, MCPStreamableHTTPTool, MCPWebsocketTool
from ._middleware import (
AgentContext,
AgentMiddleware,
@@ -168,9 +168,6 @@ from ._skills import (
InlineSkillResource,
InlineSkillScript,
InMemorySkillsSource,
MCPSkill,
MCPSkillResource,
MCPSkillsSource,
Skill,
SkillFrontmatter,
SkillResource,
@@ -444,12 +441,8 @@ __all__ = [
"InlineSkillResource",
"InlineSkillScript",
"LocalEvaluator",
"MCPSkill",
"MCPSkillResource",
"MCPSkillsSource",
"MCPStdioTool",
"MCPStreamableHTTPTool",
"MCPTaskOptions",
"MCPWebsocketTool",
"MemoryContextProvider",
"MemoryFileStore",
@@ -58,9 +58,6 @@ class ExperimentalFeature(str, Enum):
FOUNDRY_PREVIEW_TOOLS = "FOUNDRY_PREVIEW_TOOLS"
FUNCTIONAL_WORKFLOWS = "FUNCTIONAL_WORKFLOWS"
HARNESS = "HARNESS"
MCP_LONG_RUNNING_TASKS = "MCP_LONG_RUNNING_TASKS"
MCP_SKILLS = "MCP_SKILLS"
PROGRESSIVE_TOOLS = "PROGRESSIVE_TOOLS"
SKILLS = "SKILLS"
TO_PROMPT_AGENT = "TO_PROMPT_AGENT"
+40 -598
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
import base64
import contextlib
import contextvars
import json
import logging
@@ -13,14 +12,12 @@ import sys
from abc import abstractmethod
from collections.abc import Callable, Collection, Coroutine, Mapping, Sequence
from contextlib import AsyncExitStack, _AsyncGeneratorContextManager # type: ignore
from dataclasses import dataclass
from datetime import timedelta
from functools import partial
from typing import TYPE_CHECKING, Any, Literal, TypedDict, cast
from opentelemetry import propagate
from ._feature_stage import ExperimentalFeature, experimental
from ._tools import FunctionTool
from ._types import (
ChatOptions,
@@ -152,73 +149,6 @@ def _url_origin(url: Any) -> tuple[str, str, int | None]:
return (url.scheme, url.host or "", port)
# Internal polling bounds for MCP long-running tasks. Not user-tunable today;
# promote to MCPTaskOptions if a concrete need arises.
_MCP_TASK_MIN_POLL_INTERVAL = timedelta(milliseconds=500)
_MCP_TASK_MAX_POLL_INTERVAL = timedelta(seconds=5)
_MCP_TASK_CANCEL_TIMEOUT = timedelta(seconds=5)
_MCP_TASK_TERMINAL_STATUSES: frozenset[str] = frozenset({"completed", "failed", "cancelled", "input_required"})
# Total send attempts for a Phase 2 request (initial try + one reconnect-and-retry).
# A single transient disconnect should not abort a long-running task; sustained outages
# surface as ``_MCPTaskAbandoned`` after the second failure.
_MCP_RECONNECT_ATTEMPTS = 2
class _MCPTaskAbandoned(ToolExecutionException):
"""Raised when the remote MCP task may still be running and must be cancelled.
Subclass of ToolExecutionException so callers see a normal tool failure.
"""
class _MCPDeadlineExpired(Exception):
"""Internal marker for ``max_task_wait`` expiry; distinct from inner TimeoutError."""
@experimental(feature_id=ExperimentalFeature.MCP_LONG_RUNNING_TASKS)
@dataclass(frozen=True)
class MCPTaskOptions:
"""Options controlling how MCPTool drives the MCP long-running task lifecycle.
When an MCP server advertises a tool with ``execution.taskSupport == "required"``,
the framework transparently drives the SEP-2663 ``tools/call`` → ``tasks/get``
(polled) → ``tasks/result`` lifecycle so the agent sees a normal tool result.
Instances are immutable; replace the whole object via
``MCPTool.task_options = MCPTaskOptions(...)`` to change behavior.
Attributes:
default_ttl: Optional task-record retention time forwarded to the server as
``params.task.ttl`` (milliseconds, integer). The server keeps the task
record around this long after the task reaches a terminal status so the
client can still call ``tasks/get`` / ``tasks/result``; it does not
cancel a running task. When ``None``, the server applies its own default.
Must be positive if set (zero would expire the record before any client
could read it).
cancel_remote_task_on_local_cancellation: If True (default), a local
cancellation of the awaiting coroutine triggers a best-effort
``tasks/cancel`` on the server before re-raising ``CancelledError``.
Only gates ``CancelledError``; abandonment paths (max-wait,
unrecoverable poll errors, lost connection after task_id is known)
always cancel regardless of this flag.
max_task_wait: Optional client-side deadline for the whole post-create
lifecycle (poll + result fetch). When exceeded, raises
``ToolExecutionException`` and fires a best-effort ``tasks/cancel``.
``None`` (default) means no client-side bound. Must be positive if set.
"""
default_ttl: timedelta | None = None
cancel_remote_task_on_local_cancellation: bool = True
max_task_wait: timedelta | None = None
def __post_init__(self) -> None:
if self.default_ttl is not None and self.default_ttl.total_seconds() <= 0:
raise ValueError("MCPTaskOptions.default_ttl must be positive.")
if self.max_task_wait is not None and self.max_task_wait.total_seconds() <= 0:
raise ValueError("MCPTaskOptions.max_task_wait must be positive.")
def streamable_http_client(*args: Any, **kwargs: Any) -> _AsyncGeneratorContextManager[Any, None]:
"""Lazily import the MCP streamable HTTP transport."""
try:
@@ -287,7 +217,6 @@ class MCPTool:
request_timeout: int | None = None,
client: SupportsChatGetResponse | None = None,
additional_properties: dict[str, Any] | None = None,
task_options: MCPTaskOptions | None = None,
) -> None:
"""Initialize the MCP Tool base.
@@ -319,9 +248,6 @@ class MCPTool:
request_timeout: Timeout in seconds for MCP requests.
client: A chat client for sampling callbacks.
additional_properties: Additional properties for the tool.
task_options: Options controlling how long-running MCP tasks are driven for
tools that advertise ``execution.taskSupport == "required"``. When ``None``,
the defaults from :class:`MCPTaskOptions` are used.
"""
self.name = name
self.description = description or ""
@@ -333,10 +259,6 @@ class MCPTool:
self.parse_tool_results = parse_tool_results
self.load_prompts_flag = load_prompts
self.parse_prompt_results = parse_prompt_results
# Defer constructing the default MCPTaskOptions so the experimental warning
# only fires when LRO is actually engaged (lazy-resolved by _effective_task_options).
self._task_options_explicit: MCPTaskOptions | None = task_options
self._task_options_default: MCPTaskOptions | None = None
self._exit_stack = AsyncExitStack()
self._lifecycle_lock = asyncio.Lock()
self._lifecycle_request_lock = asyncio.Lock()
@@ -348,7 +270,6 @@ class MCPTool:
self.client = client
self._functions: list[FunctionTool] = []
self._tool_call_meta_by_name: dict[str, dict[str, Any]] = {}
self._tool_task_support_by_name: dict[str, str] = {}
self.is_connected: bool = False
self._tools_loaded: bool = False
self._prompts_loaded: bool = False
@@ -1210,7 +1131,6 @@ class MCPTool:
# Track existing function names to prevent duplicates
existing_names = {func.name for func in self._functions}
tool_call_meta_by_name: dict[str, dict[str, Any]] = {}
tool_task_support_by_name: dict[str, str] = {}
params: types.PaginatedRequestParams | None = None
while True:
@@ -1248,10 +1168,6 @@ class MCPTool:
if tool.meta is not None:
tool_call_meta_by_name[tool.name] = dict(tool.meta)
task_support = getattr(getattr(tool, "execution", None), "taskSupport", None)
if task_support is not None:
tool_task_support_by_name[tool.name] = task_support
normalized_name = _normalize_mcp_name(tool.name)
local_name = _build_prefixed_mcp_name(normalized_name, self.tool_name_prefix)
@@ -1300,7 +1216,6 @@ class MCPTool:
params = types.PaginatedRequestParams(cursor=tool_list.nextCursor)
self._tool_call_meta_by_name = tool_call_meta_by_name
self._tool_task_support_by_name = tool_task_support_by_name
async def _close_on_owner(self) -> None:
# Cancel any pending reload tasks before tearing down the session.
@@ -1377,29 +1292,6 @@ class MCPTool:
inner_exception=ex,
) from ex
def _effective_task_options(self) -> MCPTaskOptions:
"""Return the effective MCPTaskOptions, lazily constructing defaults on first use.
Defers the implicit ``MCPTaskOptions()`` so the experimental warning only
fires when LRO is actually engaged (server advertises ``taskSupport=required``).
"""
explicit = self._task_options_explicit
if explicit is not None:
return explicit
if self._task_options_default is None:
self._task_options_default = MCPTaskOptions()
return self._task_options_default
@property
def task_options(self) -> MCPTaskOptions:
"""The effective MCPTaskOptions for this tool (lazy defaults)."""
return self._effective_task_options()
@task_options.setter
def task_options(self, value: MCPTaskOptions | None) -> None:
self._task_options_explicit = value
self._task_options_default = None
async def call_tool(self, tool_name: str, **kwargs: Any) -> str | list[Content]:
"""Call a tool with the given arguments.
@@ -1430,12 +1322,47 @@ class MCPTool:
"Tools are not loaded for this server, please set load_tools=True in the constructor."
)
# Tools advertising taskSupport == "required" cannot complete via plain tools/call;
# route through the long-running task lifecycle transparently.
if self._tool_task_support_by_name.get(tool_name) == "required":
return await self.call_tool_as_task(tool_name, **kwargs)
raw_user_meta: object | None = kwargs.get("_meta")
user_meta: dict[str, Any] | None = None
if raw_user_meta is not None and not isinstance(raw_user_meta, dict):
raise ToolExecutionException("MCP tool metadata provided via _meta must be a dict.")
if isinstance(raw_user_meta, dict):
raw_user_meta_dict = cast(Mapping[object, object], raw_user_meta)
user_meta = {}
for key, value in raw_user_meta_dict.items():
if not isinstance(key, str):
raise ToolExecutionException("MCP tool metadata provided via _meta must use string keys.")
user_meta[key] = value
filtered_kwargs, meta = self._prepare_call_kwargs(tool_name, kwargs)
# Filter out framework kwargs that cannot be serialized by the MCP SDK.
# These are internal objects passed through the function invocation pipeline
# that should not be forwarded to external MCP servers.
# conversation_id is an internal tracking ID used by services like Azure AI.
# options contains metadata/store used by AG-UI for Azure AI client requirements.
# response_format is a Pydantic model class used for structured output (not serializable).
filtered_kwargs = {
k: v
for k, v in kwargs.items()
if k
not in {
"chat_options",
"tools",
"tool_choice",
"session",
"thread",
"conversation_id",
"options",
"response_format",
"_meta",
}
}
# Some MCP proxies require their tools/list metadata to be echoed on tools/call.
tool_meta = self._tool_call_meta_by_name.get(tool_name)
request_meta = dict(tool_meta) if tool_meta is not None else None
if user_meta is not None:
request_meta = {**(request_meta or {}), **user_meta}
meta = _inject_otel_into_mcp_meta(request_meta)
parser = self.parse_tool_results or self._parse_tool_result_from_mcp
# Try the operation, reconnecting once if the connection is closed
@@ -1484,479 +1411,6 @@ class MCPTool:
raise ToolExecutionException(f"Failed to call tool '{tool_name}'.", inner_exception=ex) from ex
raise ToolExecutionException(f"Failed to call tool '{tool_name}' after retries.")
def _prepare_call_kwargs(
self, tool_name: str, kwargs: dict[str, Any]
) -> tuple[dict[str, Any], dict[str, Any] | None]:
"""Filter framework-only kwargs and build the merged MCP request metadata."""
raw_user_meta: object | None = kwargs.get("_meta")
user_meta: dict[str, Any] | None = None
if raw_user_meta is not None and not isinstance(raw_user_meta, dict):
raise ToolExecutionException("MCP tool metadata provided via _meta must be a dict.")
if isinstance(raw_user_meta, dict):
raw_user_meta_dict = cast(Mapping[object, object], raw_user_meta)
user_meta = {}
for key, value in raw_user_meta_dict.items():
if not isinstance(key, str):
raise ToolExecutionException("MCP tool metadata provided via _meta must use string keys.")
user_meta[key] = value
# Filter out framework kwargs that cannot be serialized by the MCP SDK.
# These are internal objects passed through the function invocation pipeline
# that should not be forwarded to external MCP servers.
# conversation_id is an internal tracking ID used by services like Azure AI.
# options contains metadata/store used by AG-UI for Azure AI client requirements.
# response_format is a Pydantic model class used for structured output (not serializable).
filtered_kwargs = {
k: v
for k, v in kwargs.items()
if k
not in {
"chat_options",
"tools",
"tool_choice",
"session",
"thread",
"conversation_id",
"options",
"response_format",
"_meta",
}
}
# Some MCP proxies require their tools/list metadata to be echoed on tools/call.
tool_meta = self._tool_call_meta_by_name.get(tool_name)
request_meta = dict(tool_meta) if tool_meta is not None else None
if user_meta is not None:
request_meta = {**(request_meta or {}), **user_meta}
meta = _inject_otel_into_mcp_meta(request_meta)
return filtered_kwargs, meta
async def call_tool_as_task(self, tool_name: str, **kwargs: Any) -> str | list[Content]:
"""Call an MCP tool via the long-running task lifecycle (SEP-2663).
Issues an augmented ``tools/call`` with ``params.task`` set from
``self.task_options``, then polls ``tasks/get`` until the server reports a
terminal status. On ``completed`` the payload is fetched via ``tasks/result``,
validated as a ``CallToolResult`` and parsed identically to :meth:`call_tool`.
Local cancellation triggers a best-effort ``tasks/cancel`` (controlled by
:attr:`MCPTaskOptions.cancel_remote_task_on_local_cancellation`) before
``asyncio.CancelledError`` is re-raised.
Args:
tool_name: The remote MCP tool name.
Keyword Args:
kwargs: Arguments forwarded to the tool. See :meth:`call_tool` for the
framework kwargs that are filtered out.
Returns:
A list of Content items (or a string when a custom ``parse_tool_results``
callback is configured).
"""
from anyio import ClosedResourceError
from mcp.shared.exceptions import McpError
if not self.load_tools_flag:
raise ToolExecutionException(
"Tools are not loaded for this server, please set load_tools=True in the constructor."
)
filtered_kwargs, meta = self._prepare_call_kwargs(tool_name, kwargs)
parser = self.parse_tool_results or self._parse_tool_result_from_mcp
# Submit the task: issue augmented tools/call. Do NOT retry on connection loss here:
# the server may have accepted the request and created a task before the
# response was lost, so retrying could start the long-running operation twice.
# Reconnect-and-retry is only safe after the task_id is known.
try:
task_id, fallback_result = await self._call_tool_as_task_create(tool_name, filtered_kwargs, meta)
except (ClosedResourceError, McpError) as ex:
if not self._is_connection_lost(ex):
error_message = ex.error.message if isinstance(ex, McpError) else str(ex)
raise ToolExecutionException(error_message, inner_exception=ex) from ex
raise ToolExecutionException(
f"Failed to call tool '{tool_name}' - connection lost; task state unknown.",
inner_exception=ex,
) from ex
except ToolExecutionException:
raise
except Exception as ex:
raise ToolExecutionException(f"Failed to call tool '{tool_name}'.", inner_exception=ex) from ex
# Server returned a CallToolResult (no task created) or fell back to plain tools/call.
if fallback_result is not None:
if fallback_result.isError:
parsed = parser(fallback_result)
text = (
"\n".join(c.text for c in parsed if c.type == "text" and c.text)
if isinstance(parsed, list)
else str(parsed)
)
raise ToolExecutionException(text or str(parsed))
return parser(fallback_result)
if task_id is None:
raise ToolExecutionException(
f"MCP server did not return a task_id or fallback result for '{tool_name}'."
)
# Track to completion: poll until terminal, then fetch payload. Never re-issue
# tools/call past this point; reconnect-and-retry only against the same task_id.
opts = self._effective_task_options()
max_wait_s = opts.max_task_wait.total_seconds() if opts.max_task_wait is not None else None
async def _await_task_completion() -> str | list[Content]:
terminal = await self._poll_task_until_terminal(task_id)
return await self._handle_terminal_task(tool_name, task_id, terminal, parser)
try:
if max_wait_s is not None:
try:
result = await self._await_with_deadline(_await_task_completion(), max_wait_s)
return cast("str | list[Content]", result)
except _MCPDeadlineExpired as ex:
self._spawn_best_effort_cancel(task_id)
raise ToolExecutionException(
f"MCP task '{task_id}' exceeded max_task_wait of {max_wait_s}s.",
inner_exception=ex,
) from ex
else:
return await _await_task_completion()
except asyncio.CancelledError:
if opts.cancel_remote_task_on_local_cancellation:
self._spawn_best_effort_cancel(task_id)
raise
except _MCPTaskAbandoned:
# Pre-terminal abandonment (hard poll error, malformed get, second
# disconnect, reconnect failure): cancel + re-raise as plain
# ToolExecutionException to the function-calling loop.
self._spawn_best_effort_cancel(task_id)
raise
# Plain ToolExecutionException from terminal failures (failed/cancelled/
# input_required, completed+isError, malformed result post-completion)
# propagates without cancel — server is already done.
async def _call_tool_as_task_create(
self, tool_name: str, arguments: dict[str, Any], meta: dict[str, Any] | None
) -> tuple[str | None, types.CallToolResult | None]:
"""Send the augmented tools/call.
Returns ``(task_id, None)`` when the server created a task,
``(None, CallToolResult)`` when it returned a non-task result, falling back
to plain ``tools/call`` if the server rejects the ``task`` field outright.
"""
from mcp import types
from mcp.shared.exceptions import McpError
from pydantic import ValidationError
opts = self._effective_task_options()
ttl_ms: int | None = None
if opts.default_ttl is not None:
ttl_ms = int(opts.default_ttl.total_seconds() * 1000)
# Always send TaskMetadata to mark the call as task-augmented; ttl may be omitted.
task_metadata = types.TaskMetadata(ttl=ttl_ms)
request_meta = types.RequestParams.Meta(**meta) if meta else None
params = types.CallToolRequestParams(
name=tool_name,
arguments=arguments,
task=task_metadata,
_meta=request_meta, # type: ignore[call-arg]
)
request = types.ClientRequest(types.CallToolRequest(params=params))
# Use the lenient Result type so we can extract the task_id even when
# the strict CreateTaskResult schema rejects the payload (the MCP Python
# SDK requires Task.ttl, but servers may legitimately omit it).
try:
lenient = await self.session.send_request( # type: ignore[union-attr]
request,
types.Result,
)
except McpError as ex:
if ex.error.code not in (types.METHOD_NOT_FOUND, types.INVALID_PARAMS):
raise
logger.debug(
"Server rejected augmented tools/call for '%s' (code=%s); falling back.",
tool_name,
ex.error.code,
)
fallback = await self.session.call_tool(tool_name, arguments=arguments, meta=meta) # type: ignore[union-attr]
return None, fallback
# Inspect the raw payload: a CreateTaskResult carries `task.taskId`;
# a legacy CallToolResult carries `content` and/or `isError`.
raw: dict[str, Any] = lenient.model_dump(by_alias=True, exclude_none=True)
raw.pop("_meta", None)
task_field = raw.get("task")
if isinstance(task_field, dict):
task_id_val = cast(dict[str, Any], task_field).get("taskId")
if isinstance(task_id_val, str):
return task_id_val, None
try:
legacy = types.CallToolResult.model_validate(raw)
except ValidationError as ex:
# Augmented call succeeded server-side; re-issuing a plain tools/call
# could double-execute a side-effecting tool.
raise ToolExecutionException(
f"MCP server returned an unparseable response to augmented tools/call "
f"for '{tool_name}'; cannot safely retry (server may have started the operation).",
inner_exception=ex,
) from ex
return None, legacy
async def _poll_task_until_terminal(self, task_id: str) -> types.GetTaskResult:
"""Poll ``tasks/get`` until the task reaches a terminal status."""
import httpx
from mcp import types
from mcp.shared.exceptions import McpError
# SDK raises McpError(code=httpx.REQUEST_TIMEOUT=408) on session read timeout.
transient_codes: frozenset[int] = frozenset({int(httpx.codes.REQUEST_TIMEOUT)})
while True:
request = types.ClientRequest(
types.GetTaskRequest(params=types.GetTaskRequestParams(taskId=task_id))
)
try:
# GetTaskResult.ttl is required-but-Optional in the SDK; coerce below.
lenient = await self._send_with_one_reconnect(
request, types.Result, operation="tasks/get", task_id=task_id
)
except McpError as ex:
if ex.error.code in transient_codes:
logger.debug(
"Transient %s on tasks/get for '%s'; will retry.", ex.error.code, task_id
)
await asyncio.sleep(_MCP_TASK_MIN_POLL_INTERVAL.total_seconds())
continue
# Hard server error mid-poll: task may still be running.
raise _MCPTaskAbandoned(ex.error.message, inner_exception=ex) from ex
try:
snapshot = self._coerce_get_task_result(lenient, task_id)
except ToolExecutionException as ex:
# Malformed tasks/get response; task may still be running.
raise _MCPTaskAbandoned(str(ex), inner_exception=ex) from ex
if snapshot.status in _MCP_TASK_TERMINAL_STATUSES:
return snapshot
await asyncio.sleep(self._compute_poll_delay(snapshot.pollInterval).total_seconds())
@staticmethod
def _coerce_get_task_result(lenient: types.Result, task_id: str) -> types.GetTaskResult:
"""Coerce a lenient Result into GetTaskResult, defaulting ``ttl`` when absent."""
from mcp import types
raw = lenient.model_dump(by_alias=True, exclude_none=True)
raw.pop("_meta", None)
raw.setdefault("ttl", None)
try:
return types.GetTaskResult.model_validate(raw)
except Exception as ex:
raise ToolExecutionException(
f"MCP server returned a malformed tasks/get response for task '{task_id}'.",
inner_exception=ex,
) from ex
@staticmethod
def _compute_poll_delay(server_interval_ms: int | None) -> timedelta:
"""Clamp the server-suggested poll interval to ``[min, max]``."""
if server_interval_ms is None or server_interval_ms <= 0:
return _MCP_TASK_MIN_POLL_INTERVAL
suggested = timedelta(milliseconds=server_interval_ms)
if suggested < _MCP_TASK_MIN_POLL_INTERVAL:
return _MCP_TASK_MIN_POLL_INTERVAL
if suggested > _MCP_TASK_MAX_POLL_INTERVAL:
return _MCP_TASK_MAX_POLL_INTERVAL
return suggested
async def _handle_terminal_task(
self,
tool_name: str,
task_id: str,
snapshot: types.GetTaskResult,
parser: Callable[[types.CallToolResult], str | list[Content]],
) -> str | list[Content]:
"""Map a terminal task snapshot to either a parsed result or an exception."""
status = snapshot.status
if status == "completed":
payload = await self._fetch_task_result(task_id)
if payload.isError:
parsed = parser(payload)
text = (
"\n".join(c.text for c in parsed if c.type == "text" and c.text)
if isinstance(parsed, list)
else str(parsed)
)
raise ToolExecutionException(text or str(parsed))
return parser(payload)
# Non-completed terminal statuses surface as ToolExecutionException so the
# function-calling loop sees a normal failure for tool_name.
message = snapshot.statusMessage or f"MCP task ended with status '{status}'."
if status == "input_required":
# Spec-non-terminal; treated as terminal here because the framework does
# not implement the interactive input flow.
message = snapshot.statusMessage or "MCP task requires additional input and cannot continue."
raise ToolExecutionException(f"Tool '{tool_name}' task {status}: {message}")
async def _fetch_task_result(self, task_id: str) -> types.CallToolResult:
"""Send ``tasks/result`` and reinterpret the open-typed payload as a CallToolResult."""
from mcp import types
from mcp.shared.exceptions import McpError
from pydantic import ValidationError
request = types.ClientRequest(
types.GetTaskPayloadRequest(params=types.GetTaskPayloadRequestParams(taskId=task_id))
)
# Connection-loss retry only via the helper; no transient-code retry — server
# has already completed the task, so a slow payload fetch is anomalous.
try:
payload = await self._send_with_one_reconnect(
request, types.GetTaskPayloadResult, operation="tasks/result", task_id=task_id
)
except McpError as ex:
# Server reported completed; a hard fetch error is a plain failure (no cancel).
raise ToolExecutionException(ex.error.message, inner_exception=ex) from ex
# GetTaskPayloadResult carries the tool result via extra fields; reinterpret as CallToolResult.
payload_dict = payload.model_dump(by_alias=True, exclude_none=True)
payload_dict.pop("_meta", None)
try:
return types.CallToolResult.model_validate(payload_dict)
except ValidationError as ex:
# Server reported completed; malformed payload is a plain failure (no cancel needed).
raise ToolExecutionException(
f"MCP task '{task_id}' result payload could not be parsed as a CallToolResult.",
inner_exception=ex,
) from ex
async def _send_with_one_reconnect(
self,
request: types.ClientRequest,
result_type: type[Any],
*,
operation: str,
task_id: str,
) -> Any:
"""Send ``request`` with one reconnect-and-retry on connection loss.
After a second loss (or reconnect failure), raise ``_MCPTaskAbandoned``.
Non-connection errors propagate unchanged.
"""
from anyio import ClosedResourceError
from mcp.shared.exceptions import McpError
for attempt in range(_MCP_RECONNECT_ATTEMPTS):
try:
return await self.session.send_request(request, result_type) # type: ignore[union-attr]
except (ClosedResourceError, McpError) as ex:
if not self._is_connection_lost(ex):
raise
if attempt < _MCP_RECONNECT_ATTEMPTS - 1:
logger.info(
"MCP connection lost during %s; reconnecting (task_id=%s).", operation, task_id
)
try:
await self.connect(reset=True)
except Exception as reconn_ex:
# Reconnect failure: task may still be running.
raise _MCPTaskAbandoned(
"Failed to reconnect to MCP server.", inner_exception=reconn_ex
) from reconn_ex
continue
# Final attempt also lost the connection: task may still be running.
raise _MCPTaskAbandoned(
f"MCP connection lost; task state unknown (task_id={task_id}).",
inner_exception=ex,
) from ex
raise AssertionError(f"unreachable: {operation} for {task_id}") # pragma: no cover
@staticmethod
async def _await_with_deadline(coro: Coroutine[Any, Any, Any], timeout_s: float) -> Any:
"""Await ``coro`` with a deadline; raise ``_MCPDeadlineExpired`` only on deadline.
Unlike ``asyncio.wait_for``, an ``asyncio.TimeoutError`` raised by ``coro``
itself propagates unchanged so callers can distinguish their own deadline
from a stray inner timeout.
"""
inner = asyncio.ensure_future(coro)
try:
done, _pending = await asyncio.wait({inner}, timeout=timeout_s)
except BaseException:
# Outer caller cancelled (or another exception): cancel inner + drain.
inner.cancel()
with contextlib.suppress(BaseException):
await inner
raise
if inner in done:
return inner.result()
# Deadline fired before inner finished.
inner.cancel()
with contextlib.suppress(BaseException):
await inner
raise _MCPDeadlineExpired
def _spawn_best_effort_cancel(self, task_id: str) -> None:
"""Fire-and-forget ``tasks/cancel`` so local cancellation propagates server-side."""
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
cancel_task = loop.create_task(self._try_cancel_task(task_id))
# Reuse pending-reload bookkeeping so close-on-owner waits/cancels these too.
self._pending_reload_tasks.add(cancel_task)
cancel_task.add_done_callback(self._pending_reload_tasks.discard)
async def _try_cancel_task(self, task_id: str) -> None:
"""Send ``tasks/cancel``; bounded by ``_MCP_TASK_CANCEL_TIMEOUT``.
Failures log at warning so unattributed orphan tasks are debuggable.
"""
from mcp import types
request = types.ClientRequest(
types.CancelTaskRequest(params=types.CancelTaskRequestParams(taskId=task_id))
)
try:
await asyncio.wait_for(
self.session.send_request(request, types.CancelTaskResult), # type: ignore[union-attr]
timeout=_MCP_TASK_CANCEL_TIMEOUT.total_seconds(),
)
except asyncio.CancelledError:
raise
except asyncio.TimeoutError:
logger.warning(
"Best-effort tasks/cancel for '%s' timed out after %.1fs; "
"remote task may still be running.",
task_id,
_MCP_TASK_CANCEL_TIMEOUT.total_seconds(),
)
except Exception:
logger.warning(
"Best-effort tasks/cancel for '%s' failed; remote task may still be running.",
task_id,
exc_info=True,
)
@staticmethod
def _is_connection_lost(ex: BaseException) -> bool:
"""Return True if *ex* indicates the MCP transport was torn down."""
from anyio import ClosedResourceError
from mcp.shared.exceptions import McpError
if isinstance(ex, ClosedResourceError):
return True
if isinstance(ex, McpError):
return "session terminated" in ex.error.message.lower()
return False
async def get_prompt(self, prompt_name: str, **kwargs: Any) -> str:
"""Call a prompt with the given arguments.
@@ -2100,7 +1554,6 @@ class MCPStdioTool(MCPTool):
encoding: str | None = None,
client: SupportsChatGetResponse | None = None,
additional_properties: dict[str, Any] | None = None,
task_options: MCPTaskOptions | None = None,
**kwargs: Any,
) -> None:
"""Initialize the MCP stdio tool.
@@ -2145,8 +1598,6 @@ class MCPStdioTool(MCPTool):
env: The environment variables to set for the command.
encoding: The encoding to use for the command output.
client: The chat client to use for sampling.
task_options: Options for tools that advertise
``execution.taskSupport == "required"``. See :class:`MCPTaskOptions`.
kwargs: Any extra arguments to pass to the stdio client.
"""
super().__init__(
@@ -2163,7 +1614,6 @@ class MCPStdioTool(MCPTool):
load_prompts=load_prompts,
parse_prompt_results=parse_prompt_results,
request_timeout=request_timeout,
task_options=task_options,
)
self.command = command
self.args = args or []
@@ -2237,7 +1687,6 @@ class MCPStreamableHTTPTool(MCPTool):
additional_properties: dict[str, Any] | None = None,
http_client: AsyncClient | None = None,
header_provider: Callable[[dict[str, Any]], dict[str, str]] | None = None,
task_options: MCPTaskOptions | None = None,
**kwargs: Any,
) -> None:
"""Initialize the MCP streamable HTTP tool.
@@ -2290,8 +1739,6 @@ class MCPStreamableHTTPTool(MCPTool):
of HTTP headers to inject into every outbound request to the MCP server.
Use this to forward per-request context (e.g. authentication tokens set in
agent middleware) without creating a separate ``httpx.AsyncClient``.
task_options: Options for tools that advertise
``execution.taskSupport == "required"``. See :class:`MCPTaskOptions`.
kwargs: Additional keyword arguments (accepted for backward compatibility but not used).
"""
super().__init__(
@@ -2308,7 +1755,6 @@ class MCPStreamableHTTPTool(MCPTool):
load_prompts=load_prompts,
parse_prompt_results=parse_prompt_results,
request_timeout=request_timeout,
task_options=task_options,
)
self.url = url
self.terminate_on_close = terminate_on_close
@@ -2416,7 +1862,6 @@ class MCPWebsocketTool(MCPTool):
allowed_tools: Collection[str] | None = None,
client: SupportsChatGetResponse | None = None,
additional_properties: dict[str, Any] | None = None,
task_options: MCPTaskOptions | None = None,
**kwargs: Any,
) -> None:
"""Initialize the MCP WebSocket tool.
@@ -2459,8 +1904,6 @@ class MCPWebsocketTool(MCPTool):
allowed_tools: A list of tools that are allowed to use this tool.
additional_properties: Additional properties.
client: The chat client to use for sampling.
task_options: Options for tools that advertise
``execution.taskSupport == "required"``. See :class:`MCPTaskOptions`.
kwargs: Any extra arguments to pass to the WebSocket client.
"""
super().__init__(
@@ -2477,7 +1920,6 @@ class MCPWebsocketTool(MCPTool):
load_prompts=load_prompts,
parse_prompt_results=parse_prompt_results,
request_timeout=request_timeout,
task_options=task_options,
)
self.url = url
self._client_kwargs = kwargs
@@ -11,7 +11,6 @@ from enum import Enum
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast, overload
from ._clients import SupportsChatGetResponse
from ._feature_stage import ExperimentalFeature, experimental
from ._types import (
AgentResponse,
AgentResponseUpdate,
@@ -215,12 +214,6 @@ class FunctionInvocationContext:
result: Function execution result. Can be observed after calling ``call_next()``
to see the actual execution result or can be set to override the execution result.
kwargs: Additional runtime keyword arguments forwarded to the function invocation.
tools: The live, mutable list of tools available to the model for the current
agent run, or ``None`` when the function is invoked outside of a
function-calling loop (for example via ``FunctionTool.invoke`` directly).
Tools can add or remove tools during execution using :meth:`add_tools`
and :meth:`remove_tools` (progressive tool exposure). Mutations take
effect on the **next** model iteration, not the in-flight batch.
Examples:
.. code-block:: python
@@ -239,18 +232,6 @@ class FunctionInvocationContext:
# Continue execution
await call_next()
Progressive tool exposure from inside a tool:
.. code-block:: python
from agent_framework import FunctionInvocationContext, tool
@tool(approval_mode="never_require")
def load_math_tools(ctx: FunctionInvocationContext) -> str:
ctx.add_tools([factorial, fibonacci])
return "Math tools are now available."
"""
def __init__(
@@ -261,7 +242,6 @@ class FunctionInvocationContext:
metadata: Mapping[str, Any] | None = None,
result: Any = None,
kwargs: Mapping[str, Any] | None = None,
tools: list[ToolTypes] | None = None,
) -> None:
"""Initialize the FunctionInvocationContext.
@@ -272,9 +252,6 @@ class FunctionInvocationContext:
metadata: Metadata dictionary for sharing data between function middleware.
result: Function execution result.
kwargs: Additional runtime keyword arguments forwarded to the function invocation.
tools: The live, mutable list of tools for the current agent run. When provided,
this is the same list object the model sees on the next iteration, so
appending or removing tools changes the model's available tools.
"""
self.function = function
self.arguments = arguments
@@ -282,96 +259,6 @@ class FunctionInvocationContext:
self.metadata: dict[str, Any] = dict(metadata) if metadata is not None else {}
self.result = result
self.kwargs: dict[str, Any] = dict(kwargs) if kwargs is not None else {}
self.tools = tools
@experimental(feature_id=ExperimentalFeature.PROGRESSIVE_TOOLS)
def add_tools(
self,
tools: ToolTypes | Callable[..., Any] | Sequence[ToolTypes | Callable[..., Any]],
) -> None:
"""Add one or more tools to the current agent run (progressive tool exposure).
Callable inputs are converted to :class:`FunctionTool`, and tool collections are
flattened, using the same normalization as the rest of the framework. Added tools
become available to the model on the **next** iteration of the function-calling
loop; they do not affect tool calls already requested in the in-flight batch.
Adding a tool whose name already exists is a no-op when it is the same object, and
raises ``ValueError`` when it is a different object with a duplicate name.
Args:
tools: A single tool/callable or a sequence of tools/callables to add.
Raises:
RuntimeError: If the context has no live tools list (for example when the
function is invoked outside of a function-calling loop).
ValueError: If a different tool with a duplicate name is added.
"""
from ._tools import _append_unique_tools, normalize_tools # type: ignore[reportPrivateUsage]
if self.tools is None:
raise RuntimeError(
"Cannot add tools: this FunctionInvocationContext is not bound to a live "
"agent run. add_tools is only available for functions invoked within an "
"agent's function-calling loop."
)
# Validate the whole batch against a throwaway copy first, so a duplicate-name
# clash partway through the batch raises before the live tool list is mutated
# (all-or-nothing semantics).
merged = _append_unique_tools(list(self.tools), normalize_tools(tools))
self.tools[:] = merged
@experimental(feature_id=ExperimentalFeature.PROGRESSIVE_TOOLS)
def remove_tools(
self,
tools: ToolTypes | Callable[..., Any] | Sequence[ToolTypes | Callable[..., Any]] | str | Sequence[str],
) -> None:
"""Remove one or more tools from the current agent run (progressive tool exposure).
Tools may be specified by name, by tool object, or by the original callable. Names
that are not currently present are ignored. Removals take effect on the **next**
iteration of the function-calling loop; tool calls already requested in the
in-flight batch still execute.
Args:
tools: A tool name, tool/callable, or a sequence of any of these to remove.
Raises:
RuntimeError: If the context has no live tools list (for example when the
function is invoked outside of a function-calling loop).
"""
from ._tools import _get_tool_name, normalize_tools # type: ignore[reportPrivateUsage]
if self.tools is None:
raise RuntimeError(
"Cannot remove tools: this FunctionInvocationContext is not bound to a live "
"agent run. remove_tools is only available for functions invoked within an "
"agent's function-calling loop."
)
names_to_remove: set[str] = set()
raw_items: list[Any]
if isinstance(tools, str):
raw_items = [tools]
elif isinstance(tools, Sequence) and not isinstance(tools, (bytes, bytearray)):
raw_items = list(cast("Sequence[Any]", tools))
else:
raw_items = [tools]
for item in raw_items:
if isinstance(item, str):
names_to_remove.add(item)
continue
for normalized in normalize_tools(item):
if name := _get_tool_name(normalized): # type: ignore[reportPrivateUsage]
names_to_remove.add(name)
if not names_to_remove:
return
self.tools[:] = [
tool
for tool in self.tools
if _get_tool_name(tool) not in names_to_remove # type: ignore[reportPrivateUsage]
]
class ChatContext:
@@ -44,7 +44,6 @@ Only use skills from trusted sources.
from __future__ import annotations
import asyncio
import base64
import inspect
import json
import logging
@@ -61,10 +60,6 @@ from ._sessions import ContextProvider
from ._tools import FunctionTool
if TYPE_CHECKING:
from mcp.client.session import ClientSession
from mcp.types import ReadResourceResult
from pydantic import AnyUrl
from ._agents import SupportsAgentRun
from ._sessions import AgentSession, SessionContext
@@ -3290,443 +3285,4 @@ class AggregatingSkillsSource(SkillsSource):
return result
# region MCP Skills
def _mcp_any_url(uri: str) -> AnyUrl:
"""Convert a string URI to a :class:`pydantic.AnyUrl` for MCP client calls."""
from pydantic import AnyUrl as _AnyUrl
return _AnyUrl(uri)
def _is_mcp_resource_not_found(ex: Exception) -> bool:
"""Return ``True`` when *ex* is an :class:`McpError` indicating a missing resource.
Two codes are treated as "not found":
* ``-32002`` — the MCP-spec "Resource not found" code returned by a
compliant server when the URI does not exist. Not exported as a
constant from ``mcp.types`` but defined by the resources subprotocol.
* ``METHOD_NOT_FOUND`` (``-32601``) — the server does not implement
``resources/read`` at all, which for the skills source is functionally
equivalent to "no skills available."
All other codes — ``INVALID_PARAMS``, ``INTERNAL_ERROR``, ``PARSE_ERROR``,
``CONNECTION_CLOSED``, auth rejections, and generic handler errors
(code ``0``) — are treated as real failures so that a misconfigured
token or crashing server is not silently mistaken for "the server has no
skills."
"""
from mcp.shared.exceptions import McpError as _McpError
if not isinstance(ex, _McpError):
return False
from mcp.types import METHOD_NOT_FOUND as _METHOD_NOT_FOUND
return ex.error.code in {-32002, _METHOD_NOT_FOUND}
def _mcp_join_text(result: ReadResourceResult) -> str:
"""Join all :class:`TextResourceContents` items in a result into a single string."""
from mcp.types import TextResourceContents as _TextResourceContents
return "\n".join(c.text for c in result.contents if isinstance(c, _TextResourceContents))
class _McpSkillIndexEntry: # noqa: B903
"""A single entry in the ``skill://index.json`` discovery document.
All fields are optional to support lenient deserialization; callers
validate required fields before use.
"""
def __init__(
self,
*,
name: str | None = None,
type: str | None = None,
description: str | None = None,
url: str | None = None,
digest: str | None = None,
) -> None:
self.name = name
self.type = type
self.description = description
self.url = url
self.digest = digest
class _McpSkillIndex:
"""DTO for the ``skill://index.json`` discovery document.
Represents the Agent Skills Discovery v0.2.0 schema as bound to MCP
by SEP-2640.
"""
def __init__(
self,
*,
schema: str | None = None,
skills: list[_McpSkillIndexEntry] | None = None,
) -> None:
self.schema = schema
self.skills: list[_McpSkillIndexEntry] = skills if skills is not None else []
def _parse_mcp_skill_index(text: str) -> _McpSkillIndex:
"""Parse a JSON string into a :class:`_McpSkillIndex`.
Args:
text: Raw JSON text from ``skill://index.json``.
Returns:
A populated :class:`_McpSkillIndex` instance.
Raises:
json.JSONDecodeError: If the text is not valid JSON.
ValueError: If the top-level value is not a JSON object.
"""
raw: dict[str, Any] = json.loads(text)
if not isinstance(raw, dict):
raise ValueError("skill://index.json must be a JSON object")
entries: list[_McpSkillIndexEntry] = []
raw_skills: list[Any] = raw.get("skills") or []
for item in raw_skills:
if isinstance(item, dict):
d = cast(dict[str, Any], item)
entries.append(
_McpSkillIndexEntry(
name=d.get("name"),
type=d.get("type"),
description=d.get("description"),
url=d.get("url"),
digest=d.get("digest"),
)
)
return _McpSkillIndex(schema=raw.get("$schema"), skills=entries)
@experimental(feature_id=ExperimentalFeature.MCP_SKILLS)
class MCPSkillResource(SkillResource):
"""A :class:`SkillResource` backed by content fetched from an MCP server.
The :class:`~mcp.types.ReadResourceResult` is fetched eagerly by
:meth:`MCPSkill.get_resource` at construction time; :meth:`read`
extracts text or binary content from the result.
"""
def __init__(self, *, name: str, result: ReadResourceResult) -> None:
"""Initialize an MCPSkillResource.
Args:
name: The resource name (e.g. a relative path or identifier).
result: The result returned by the MCP server's ``resources/read`` request.
"""
super().__init__(name=name)
self._result = result
async def read(self, **kwargs: Any) -> Any:
"""Read the resource content.
Returns:
A ``bytes`` object when the resource contains binary content,
a ``str`` when it contains text, or ``None`` when the server
returned no content blocks.
"""
from mcp.types import BlobResourceContents, TextResourceContents
for content in self._result.contents:
if isinstance(content, BlobResourceContents):
blob = content.blob
# Strip data-URI prefix if present (some MCP servers send
# full data URIs instead of raw base64).
if blob.startswith("data:"):
blob = blob.split(",", 1)[-1]
return base64.b64decode(blob)
text = "\n".join(c.text for c in self._result.contents if isinstance(c, TextResourceContents))
return text if text else None
@experimental(feature_id=ExperimentalFeature.MCP_SKILLS)
class MCPSkill(Skill):
"""A :class:`Skill` discovered from an MCP server exposing the Agent Skills convention.
The skill is constructed from ``skill://index.json`` discovery metadata;
:meth:`get_content` fetches the full ``SKILL.md`` content from the MCP
server on demand via ``resources/read``.
Per SEP-2640, resources referenced inside SKILL.md are fetched on demand
via the originating MCP server: :meth:`get_resource` resolves a relative
resource name against the skill's root URI, issues a ``resources/read``
request, and returns an :class:`MCPSkillResource` with pre-fetched content.
"""
_SKILL_MD_SUFFIX: Final[str] = "SKILL.md"
def __init__(
self,
frontmatter: SkillFrontmatter,
skill_md_uri: str,
client: ClientSession,
) -> None:
"""Initialize an MCPSkill.
Args:
frontmatter: The parsed frontmatter metadata for this skill.
skill_md_uri: The full MCP resource URI of the ``SKILL.md`` resource
(e.g. ``skill://unit-converter/SKILL.md``). The skill's root URI
is derived by stripping the trailing ``SKILL.md`` segment.
client: The MCP client session used to fetch resources on demand.
"""
self._frontmatter = frontmatter
self._skill_md_uri = skill_md_uri
self._skill_root_uri = self._compute_skill_root_uri(skill_md_uri)
self._client = client
self._content: str | None = None
@property
def frontmatter(self) -> SkillFrontmatter:
"""The L1 discovery metadata for this skill."""
return self._frontmatter
async def get_content(self) -> str:
"""Get the full SKILL.md content from the MCP server.
Fetches the content via ``resources/read`` on the first call and
caches the result for subsequent calls.
Returns:
The SKILL.md content string.
Raises:
ValueError: If the MCP server returned no text content for the
SKILL.md resource.
"""
if self._content is not None:
return self._content
result = await self._client.read_resource(_mcp_any_url(self._skill_md_uri))
text = _mcp_join_text(result)
if not text:
raise ValueError(
f"The MCP server returned no text content for SKILL.md resource '{self._skill_md_uri}'."
)
self._content = text
return text
async def get_resource(self, name: str) -> SkillResource | None:
"""Get a sibling resource by name from the MCP server.
Resolves *name* as a relative path against the skill's root URI,
issues a ``resources/read`` request to the MCP server, and returns
an :class:`MCPSkillResource` with the pre-fetched content.
Args:
name: The resource name (e.g. ``references/checklist.md``).
Returns:
An :class:`MCPSkillResource`, or ``None`` when the name is empty
or the resource does not exist on the server.
"""
if not name or not name.strip():
return None
normalized = self._validate_resource_name(name)
if normalized is None:
return None
uri = self._skill_root_uri + normalized
try:
result = await self._client.read_resource(_mcp_any_url(uri))
except Exception as ex:
if _is_mcp_resource_not_found(ex):
logger.debug("MCP resource '%s' not available: %s", uri, ex)
return None
raise
return MCPSkillResource(name=name, result=result)
@staticmethod
def _validate_resource_name(name: str) -> str | None:
"""Validate a resource name and return the normalized form.
Defense in depth: refuses names that could escape the skill root
(absolute paths, embedded URI schemes, parent-traversal segments).
The MCP server is the authority on URI resolution, but rejecting
obviously unsafe shapes client-side avoids leaking escape attempts
upstream.
Args:
name: The raw resource name to validate.
Returns:
The normalized name with backslashes replaced by forward slashes,
or ``None`` if the name is unsafe.
"""
normalized = name.replace("\\", "/")
if (
normalized.startswith("/")
or "://" in normalized
or any(seg == ".." for seg in normalized.split("/"))
):
logger.debug("Rejecting resource name with unsafe path components: %r", name)
return None
return normalized
@staticmethod
def _compute_skill_root_uri(skill_md_uri: str) -> str:
"""Strip the trailing ``SKILL.md`` from the URI to produce the skill root.
If the URI doesn't end with ``SKILL.md``, ensures it ends with a
trailing slash.
"""
if skill_md_uri.endswith(MCPSkill._SKILL_MD_SUFFIX):
return skill_md_uri[: -len(MCPSkill._SKILL_MD_SUFFIX)]
if skill_md_uri.endswith("/"):
return skill_md_uri
return skill_md_uri + "/"
@experimental(feature_id=ExperimentalFeature.MCP_SKILLS)
class MCPSkillsSource(SkillsSource):
"""A :class:`SkillsSource` that discovers Agent Skills served over MCP.
Discovery follows the SEP-2640 recommended approach: the source reads
the well-known ``skill://index.json`` resource and constructs one
:class:`MCPSkill` per ``skill-md`` entry directly from the entry's
``name``, ``description``, and ``url`` fields.
The referenced ``SKILL.md`` resource is **not** read during discovery;
the host fetches its body on demand via ``resources/read`` when the
skill content is needed.
Only index entries of type ``skill-md`` are supported; entries of any
other type are silently skipped.
If ``skill://index.json`` is absent, unreadable, empty, or fails to
parse, this source returns an empty list.
Examples:
.. code-block:: python
from mcp.client.session import ClientSession
source = MCPSkillsSource(client=session)
skills = await source.get_skills()
"""
_INDEX_URI: Final[str] = "skill://index.json"
_SKILL_MD_TYPE: Final[str] = "skill-md"
def __init__(self, client: ClientSession) -> None:
"""Initialize an MCPSkillsSource.
Args:
client: An MCP client session connected to a server that
exposes Agent Skills resources.
"""
self._client = client
async def get_skills(self) -> list[Skill]:
"""Discover and return skills from the MCP server.
Reads ``skill://index.json``, parses it, and creates an
:class:`MCPSkill` for each valid ``skill-md`` entry.
Returns:
A list of discovered :class:`MCPSkill` instances.
"""
index = await self._try_read_index()
if index is None:
return []
skills: list[Skill] = []
for entry in index.skills:
result = self._try_create_skill(entry)
if result is not None:
skills.append(result)
logger.info("Loaded MCP skill: %s", result.frontmatter.name)
else:
logger.debug(
"Skipping skill index entry '%s'",
entry.name or "(unnamed)",
)
logger.info("Successfully loaded %d skills from MCP server", len(skills))
return skills
async def _try_read_index(self) -> _McpSkillIndex | None:
"""Attempt to read and parse ``skill://index.json`` from the MCP server.
Returns:
A parsed :class:`_McpSkillIndex`, or ``None`` if the index is
absent, empty, or malformed.
"""
try:
result = await self._client.read_resource(_mcp_any_url(self._INDEX_URI))
except Exception as ex:
if _is_mcp_resource_not_found(ex):
logger.debug("No skill://index.json resource available on MCP server: %s", ex)
return None
logger.warning("Failed to read skill://index.json from MCP server.", exc_info=True)
raise
index_text = _mcp_join_text(result)
if not index_text:
logger.debug("skill://index.json on MCP server returned empty/non-text contents")
return None
try:
return _parse_mcp_skill_index(index_text)
except (json.JSONDecodeError, ValueError):
logger.warning("Failed to parse skill://index.json JSON document.", exc_info=True)
return None
def _try_create_skill(self, entry: _McpSkillIndexEntry) -> MCPSkill | None:
"""Attempt to create an :class:`MCPSkill` from an index entry.
Args:
entry: A single entry from the skill index.
Returns:
An :class:`MCPSkill` if the entry is valid, or ``None`` if the
entry should be skipped.
"""
if entry.type != self._SKILL_MD_TYPE:
logger.debug(
"Skipping entry '%s': unsupported type '%s'",
entry.name or "(unnamed)",
entry.type or "(none)",
)
return None
if not entry.name or not entry.name.strip():
logger.debug("Skipping entry: missing required 'name' field")
return None
if not entry.description or not entry.description.strip():
logger.debug("Skipping entry '%s': missing required 'description' field", entry.name)
return None
if not entry.url or not entry.url.strip():
logger.debug("Skipping entry '%s': missing required 'url' field", entry.name)
return None
try:
fm = SkillFrontmatter(name=entry.name, description=entry.description)
except ValueError as ex:
logger.debug("Skipping entry '%s': invalid metadata: %s", entry.name, ex)
return None
return MCPSkill(frontmatter=fm, skill_md_uri=entry.url, client=self._client)
# endregion
@@ -1418,7 +1418,6 @@ async def _auto_invoke_function(
sequence_index: int | None = None,
request_index: int | None = None,
middleware_pipeline: FunctionMiddlewarePipeline | None = None,
live_tools: list[ToolTypes] | None = None,
) -> Content:
"""Invoke a function call requested by the agent, applying middleware that is defined.
@@ -1433,8 +1432,6 @@ async def _auto_invoke_function(
sequence_index: The index of the function call in the sequence.
request_index: The index of the request iteration.
middleware_pipeline: Optional middleware pipeline to apply during execution.
live_tools: The live, mutable tools list for the current agent run, exposed on
the FunctionInvocationContext so tools can add/remove tools at runtime.
Returns:
The function result content.
@@ -1526,7 +1523,6 @@ async def _auto_invoke_function(
arguments=args,
session=invocation_session,
kwargs=runtime_kwargs.copy(),
tools=live_tools,
)
function_result = await tool.invoke(
arguments=args,
@@ -1541,10 +1537,6 @@ async def _auto_invoke_function(
except UserInputRequiredException:
raise
except Exception as exc:
logger.warning(
f"Function '{tool.name}' raised an exception; returning an error result to the "
f"model. Set include_detailed_errors=True for the full detail. Exception: {exc!r}"
)
message = "Error: Function failed."
if config.get("include_detailed_errors", False):
message = f"{message} Exception: {exc}"
@@ -1560,7 +1552,6 @@ async def _auto_invoke_function(
arguments=args,
session=invocation_session,
kwargs=runtime_kwargs.copy(),
tools=live_tools,
)
call_id = function_call_content.call_id
@@ -1617,10 +1608,6 @@ async def _auto_invoke_function(
except UserInputRequiredException:
raise
except Exception as exc:
logger.warning(
f"Function '{tool.name}' raised an exception; returning an error result to the "
f"model. Set include_detailed_errors=True for the full detail. Exception: {exc!r}"
)
message = "Error: Function failed."
if config.get("include_detailed_errors", False):
message = f"{message} Exception: {exc}"
@@ -1672,9 +1659,6 @@ async def _try_execute_function_calls(
from ._types import Content
tool_map = _get_tool_map(tools)
# The live tools list (when tools is the run-local list) is exposed on the
# FunctionInvocationContext so tools can add/remove tools during the run.
live_tools: list[ToolTypes] | None = cast("list[ToolTypes]", tools) if isinstance(tools, list) else None
approval_tools = [tool_name for tool_name, tool in tool_map.items() if tool.approval_mode == "always_require"]
logger.debug(
"_try_execute_function_calls: tool_map keys=%s, approval_tools=%s",
@@ -1749,7 +1733,6 @@ async def _try_execute_function_calls(
request_index=attempt_idx,
middleware_pipeline=middleware_pipeline,
config=config,
live_tools=live_tools,
)
return (result, False)
except MiddlewareTermination as exc:
@@ -2388,13 +2371,6 @@ class FunctionInvocationLayer(Generic[OptionsCoT]):
function_invocation_kwargs=function_invocation_kwargs,
client_kwargs=filtered_kwargs,
)
# Establish a single, run-local mutable tools list so that tools can add or remove
# tools during the run (progressive tool exposure). A fresh list is created via
# normalize_tools so the caller's original tools container is never mutated, while
# the same list object is shared with the model (options["tools"]) and the tool map
# rebuilt on every loop iteration.
if mutable_options.get("tools"):
mutable_options["tools"] = normalize_tools(mutable_options["tools"])
if not stream:
async def _get_response() -> ChatResponse[Any]:
@@ -13,6 +13,35 @@ during deserialization. The default built-in safe set covers common Python
value types (primitives, datetime, uuid, ...), all ``agent_framework`` internal
types, and all ``openai.types`` types. Callers can extend the set by passing
additional ``"module:qualname"`` strings.
Security Model
--------------
Checkpoint storage is treated as a **trusted data source**. The serialization
format uses Python's ``pickle`` module which can execute arbitrary code during
deserialization. The ``RestrictedUnpickler`` provides a defense-in-depth
allowlist that limits instantiable classes, but it is **not** a security
boundary — certain allowlisted builtins (e.g. ``getattr``) are required for
legitimate object reconstruction (enums, named tuples) and cannot be removed
without breaking compatibility.
Developers **must** ensure that:
1. The checkpoint storage backend (file system, Cosmos DB, Azure Blob, Durable
Functions storage) is access-controlled and not writable by untrusted
parties.
2. Data flowing into ``decode_checkpoint_value`` originates exclusively from
the application's own checkpoint storage — never from user-supplied HTTP
requests, message payloads, or other untrusted sources.
3. The ``allowed_types`` parameter is specified whenever possible to restrict
the set of reconstructible types to the minimum required by the application.
4. Never pass untrusted external input to ``decode_checkpoint_value``. If you
must accept external JSON that might contain checkpoint markers, sanitize it
first (for example, :func:`agent_framework_azurefunctions._serialization.strip_pickle_markers`).
The allowlist is a mitigation that reduces attack surface but does not
eliminate the inherent risks of deserializing untrusted pickle data. Treat
your checkpoint storage with the same access controls you would apply to
application secrets or database credentials.
"""
from __future__ import annotations
@@ -3975,425 +3975,3 @@ async def test_user_input_request_empty_contents_returns_fallback(chat_client_ba
]
assert len(function_results) >= 1
assert any("user input" in (fr.result or "").lower() for fr in function_results)
# region Progressive tool exposure (FunctionInvocationContext.add_tools / remove_tools)
def _pte_function_call_response(call_id: str, name: str, arguments: str = "{}") -> ChatResponse:
return ChatResponse(
messages=Message(
role="assistant",
contents=[Content.from_function_call(call_id=call_id, name=name, arguments=arguments)],
)
)
def _pte_text_response(text: str = "done") -> ChatResponse:
return ChatResponse(messages=Message(role="assistant", contents=[text]))
@tool(name="factorial", approval_mode="never_require")
def _pte_factorial(n: int) -> int:
"""Compute the factorial of n."""
result = 1
for value in range(2, n + 1):
result *= value
return result
async def test_context_exposes_live_tools(chat_client_base: SupportsChatGetResponse):
from agent_framework import FunctionTool
seen_names: list[str] = []
@tool(name="inspect_tools", approval_mode="never_require")
def inspect_tools(ctx: FunctionInvocationContext) -> str:
assert ctx.tools is not None
seen_names.extend(t.name for t in ctx.tools if isinstance(t, FunctionTool))
return "inspected"
chat_client_base.run_responses = [
_pte_function_call_response("1", "inspect_tools"),
_pte_text_response(),
]
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [inspect_tools]},
)
assert "inspect_tools" in seen_names
async def test_add_tools_available_next_iteration(chat_client_base: SupportsChatGetResponse):
exec_counter = 0
@tool(name="factorial", approval_mode="never_require")
def factorial(n: int) -> int:
nonlocal exec_counter
exec_counter += 1
return 120
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(factorial)
return "math tools loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_function_call_response("2", "factorial", '{"n": 5}'),
_pte_text_response(),
]
response = await chat_client_base.get_response(
[Message(role="user", contents=["compute 5!"])],
options={"tool_choice": "auto", "tools": [load_math]},
)
assert exec_counter == 1
assert response.messages[-1].text == "done"
async def test_add_tools_model_sees_added_tools_in_options(chat_client_base: SupportsChatGetResponse):
from agent_framework import FunctionTool
recorded: list[list[str]] = []
client_cls = type(chat_client_base)
original = client_cls._get_non_streaming_response
async def recording(self: Any, *, messages: Any, options: dict[str, Any], **kwargs: Any) -> ChatResponse:
tools = options.get("tools") or []
recorded.append([t.name for t in tools if isinstance(t, FunctionTool)])
return await original(self, messages=messages, options=options, **kwargs)
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(_pte_factorial)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_function_call_response("2", "factorial", '{"n": 5}'),
_pte_text_response(),
]
monkey = pytest.MonkeyPatch()
monkey.setattr(client_cls, "_get_non_streaming_response", recording)
try:
await chat_client_base.get_response(
[Message(role="user", contents=["compute 5!"])],
options={"tool_choice": "auto", "tools": [load_math]},
)
finally:
monkey.undo()
assert recorded[0] == ["load_math"]
assert "factorial" in recorded[1]
async def test_remove_tools_next_iteration(chat_client_base: SupportsChatGetResponse):
from agent_framework import FunctionTool
recorded: list[list[str]] = []
client_cls = type(chat_client_base)
original = client_cls._get_non_streaming_response
async def recording(self: Any, *, messages: Any, options: dict[str, Any], **kwargs: Any) -> ChatResponse:
tools = options.get("tools") or []
recorded.append([t.name for t in tools if isinstance(t, FunctionTool)])
return await original(self, messages=messages, options=options, **kwargs)
@tool(name="get_weather", approval_mode="never_require")
def get_weather(location: str) -> str:
return "sunny"
@tool(name="drop_weather", approval_mode="never_require")
def drop_weather(ctx: FunctionInvocationContext) -> str:
ctx.remove_tools("get_weather")
return "removed"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "drop_weather"),
_pte_text_response(),
]
monkey = pytest.MonkeyPatch()
monkey.setattr(client_cls, "_get_non_streaming_response", recording)
try:
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [get_weather, drop_weather]},
)
finally:
monkey.undo()
assert set(recorded[0]) == {"get_weather", "drop_weather"}
assert "get_weather" not in recorded[1]
async def test_add_tools_does_not_mutate_caller_tools_list(chat_client_base: SupportsChatGetResponse):
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(_pte_factorial)
return "loaded"
original_tools: list[Any] = [load_math]
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_text_response(),
]
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": original_tools},
)
assert original_tools == [load_math]
async def test_add_tools_persists_across_iterations(chat_client_base: SupportsChatGetResponse):
from agent_framework import FunctionTool
recorded: list[list[str]] = []
client_cls = type(chat_client_base)
original = client_cls._get_non_streaming_response
async def recording(self: Any, *, messages: Any, options: dict[str, Any], **kwargs: Any) -> ChatResponse:
tools = options.get("tools") or []
recorded.append([t.name for t in tools if isinstance(t, FunctionTool)])
return await original(self, messages=messages, options=options, **kwargs)
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(_pte_factorial)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 4 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_function_call_response("2", "factorial", '{"n": 5}'),
_pte_function_call_response("3", "factorial", '{"n": 3}'),
_pte_text_response(),
]
monkey = pytest.MonkeyPatch()
monkey.setattr(client_cls, "_get_non_streaming_response", recording)
try:
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [load_math]},
)
finally:
monkey.undo()
assert "factorial" in recorded[1]
assert "factorial" in recorded[2]
async def test_add_tools_through_function_middleware(chat_client_base: SupportsChatGetResponse):
exec_counter = 0
class PassthroughMiddleware(FunctionMiddleware):
async def process(self, context: FunctionInvocationContext, call_next: Any) -> None:
await call_next()
@tool(name="factorial", approval_mode="never_require")
def factorial(n: int) -> int:
nonlocal exec_counter
exec_counter += 1
return 120
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(factorial)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_function_call_response("2", "factorial", '{"n": 5}'),
_pte_text_response(),
]
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [load_math]},
middleware=[PassthroughMiddleware()],
)
assert exec_counter == 1
async def test_add_tools_with_approval_required_tool(chat_client_base: SupportsChatGetResponse):
@tool(name="secure_tool", approval_mode="always_require")
def secure_tool(value: str) -> str:
return f"secure: {value}"
@tool(name="load_secure", approval_mode="never_require")
def load_secure(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(secure_tool)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_secure"),
_pte_function_call_response("2", "secure_tool", '{"value": "x"}'),
_pte_text_response(),
]
response = await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [load_secure]},
)
assert any(item.type == "function_approval_request" for msg in response.messages for item in msg.contents)
async def test_add_tools_accepts_plain_callable(chat_client_base: SupportsChatGetResponse):
exec_counter = 0
def plain_factorial(n: int) -> int:
"""Compute factorial."""
nonlocal exec_counter
exec_counter += 1
return 120
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(plain_factorial)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.run_responses = [
_pte_function_call_response("1", "load_math"),
_pte_function_call_response("2", "plain_factorial", '{"n": 5}'),
_pte_text_response(),
]
await chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
options={"tool_choice": "auto", "tools": [load_math]},
)
assert exec_counter == 1
async def test_add_tools_streaming(chat_client_base: SupportsChatGetResponse):
exec_counter = 0
@tool(name="factorial", approval_mode="never_require")
def factorial(n: int) -> int:
nonlocal exec_counter
exec_counter += 1
return 120
@tool(name="load_math", approval_mode="never_require")
def load_math(ctx: FunctionInvocationContext) -> str:
ctx.add_tools(factorial)
return "loaded"
chat_client_base.function_invocation_configuration["max_iterations"] = 3 # type: ignore[attr-defined]
chat_client_base.streaming_responses = [
[
ChatResponseUpdate(
contents=[Content.from_function_call(call_id="1", name="load_math", arguments="{}")],
role="assistant",
)
],
[
ChatResponseUpdate(
contents=[Content.from_function_call(call_id="2", name="factorial", arguments='{"n": 5}')],
role="assistant",
)
],
[ChatResponseUpdate(contents=[Content.from_text("done")], role="assistant", finish_reason="stop")],
]
async for _ in chat_client_base.get_response(
[Message(role="user", contents=["hi"])],
stream=True,
options={"tool_choice": "auto", "tools": [load_math]},
):
pass
assert exec_counter == 1
def test_add_tools_duplicate_same_object_is_noop():
@tool(name="dup", approval_mode="never_require")
def dup(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=dup, arguments={}, tools=[dup])
ctx.add_tools(dup)
assert ctx.tools is not None
assert len(ctx.tools) == 1
def test_add_tools_duplicate_name_different_object_raises():
@tool(name="dup", approval_mode="never_require")
def dup_a(x: int) -> int:
return x
@tool(name="dup", approval_mode="never_require")
def dup_b(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=dup_a, arguments={}, tools=[dup_a])
with pytest.raises(ValueError):
ctx.add_tools(dup_b)
def test_add_tools_batch_with_duplicate_is_atomic():
"""A duplicate-name clash partway through a batch must leave the live list unchanged."""
@tool(name="existing", approval_mode="never_require")
def existing(x: int) -> int:
return x
@tool(name="fresh", approval_mode="never_require")
def fresh(x: int) -> int:
return x
@tool(name="existing", approval_mode="never_require")
def clashing(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=existing, arguments={}, tools=[existing])
with pytest.raises(ValueError):
ctx.add_tools([fresh, clashing])
assert ctx.tools is not None
# The valid "fresh" tool must not have been committed before the clash raised.
assert ctx.tools == [existing]
def test_remove_tools_by_name_and_object():
@tool(name="a", approval_mode="never_require")
def a(x: int) -> int:
return x
@tool(name="b", approval_mode="never_require")
def b(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=a, arguments={}, tools=[a, b])
ctx.remove_tools("a")
assert ctx.tools is not None
assert [t.name for t in ctx.tools] == ["b"]
ctx.remove_tools(b)
assert ctx.tools == []
def test_remove_tools_unknown_name_is_noop():
@tool(name="a", approval_mode="never_require")
def a(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=a, arguments={}, tools=[a])
ctx.remove_tools("nonexistent")
assert ctx.tools is not None
assert [t.name for t in ctx.tools] == ["a"]
def test_progressive_tools_helpers_raise_without_live_tools():
@tool(name="a", approval_mode="never_require")
def a(x: int) -> int:
return x
ctx = FunctionInvocationContext(function=a, arguments={})
assert ctx.tools is None
with pytest.raises(RuntimeError):
ctx.add_tools(a)
with pytest.raises(RuntimeError):
ctx.remove_tools("a")
# endregion
File diff suppressed because it is too large Load Diff
@@ -1,667 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
"""Tests for MCP-based skills (MCPSkillsSource, MCPSkill, MCPSkillResource)."""
from __future__ import annotations
import base64
import json
from unittest.mock import AsyncMock
import pytest
from mcp.shared.exceptions import McpError
from mcp.types import (
BlobResourceContents,
ErrorData,
ReadResourceResult,
TextResourceContents,
)
from pydantic import AnyUrl
from agent_framework import MCPSkill, MCPSkillResource, MCPSkillsSource
from agent_framework._skills import _parse_mcp_skill_index
# ---------------------------------------------------------------------------
# Fixtures & helpers
# ---------------------------------------------------------------------------
SAMPLE_SKILL_MD = """\
---
name: unit-converter
description: Convert between common units.
---
# Unit Converter
Body content here.
"""
SAMPLE_SKILL_INDEX = json.dumps(
{
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
"skills": [
{
"name": "unit-converter",
"type": "skill-md",
"description": "Convert between common units.",
"url": "skill://unit-converter/SKILL.md",
}
],
}
)
def _make_text_result(text: str, uri: str = "skill://test") -> ReadResourceResult:
"""Create a ReadResourceResult with a single TextResourceContents."""
return ReadResourceResult(
contents=[TextResourceContents(uri=AnyUrl(uri), text=text, mimeType="text/markdown")]
)
def _make_blob_result(
data: bytes,
uri: str = "skill://test",
mime_type: str = "application/octet-stream",
) -> ReadResourceResult:
"""Create a ReadResourceResult with a single BlobResourceContents."""
return ReadResourceResult(
contents=[BlobResourceContents(uri=AnyUrl(uri), blob=base64.b64encode(data).decode(), mimeType=mime_type)]
)
def _make_empty_result() -> ReadResourceResult:
"""Create a ReadResourceResult with no contents."""
return ReadResourceResult(contents=[])
def _make_client(**read_resource_responses: ReadResourceResult) -> AsyncMock:
"""Create a mock ClientSession whose read_resource returns different results per URI.
Args:
**read_resource_responses: Mapping of URI string to ReadResourceResult.
Any URI not in this mapping raises McpError with the MCP-spec
"Resource not found" code (-32002).
"""
client = AsyncMock()
async def _read_resource(uri: AnyUrl) -> ReadResourceResult:
uri_str = str(uri)
if uri_str in read_resource_responses:
return read_resource_responses[uri_str]
raise McpError(error=ErrorData(code=-32002, message=f"Resource not found: {uri_str}"))
client.read_resource = AsyncMock(side_effect=_read_resource)
return client
# ---------------------------------------------------------------------------
# _parse_mcp_skill_index tests
# ---------------------------------------------------------------------------
class TestParseMCPSkillIndex:
"""Tests for the _parse_mcp_skill_index helper."""
def test_parses_valid_index(self) -> None:
index = _parse_mcp_skill_index(SAMPLE_SKILL_INDEX)
assert index.schema == "https://schemas.agentskills.io/discovery/0.2.0/schema.json"
assert len(index.skills) == 1
assert index.skills[0].name == "unit-converter"
assert index.skills[0].type == "skill-md"
assert index.skills[0].url == "skill://unit-converter/SKILL.md"
def test_parses_empty_skills_array(self) -> None:
index = _parse_mcp_skill_index('{"$schema": "test", "skills": []}')
assert index.skills == []
def test_parses_missing_skills_key(self) -> None:
index = _parse_mcp_skill_index('{"$schema": "test"}')
assert index.skills == []
def test_raises_on_non_object(self) -> None:
with pytest.raises(ValueError, match="must be a JSON object"):
_parse_mcp_skill_index("[]")
def test_raises_on_invalid_json(self) -> None:
with pytest.raises(json.JSONDecodeError):
_parse_mcp_skill_index("not json")
def test_skips_non_dict_entries(self) -> None:
index = _parse_mcp_skill_index('{"skills": ["not-a-dict", {"name": "ok", "type": "skill-md"}]}')
assert len(index.skills) == 1
assert index.skills[0].name == "ok"
# ---------------------------------------------------------------------------
# MCPSkillResource tests
# ---------------------------------------------------------------------------
class TestMCPSkillResource:
"""Tests for MCPSkillResource."""
@pytest.mark.asyncio
async def test_read_text_content(self) -> None:
result = _make_text_result("hello world")
resource = MCPSkillResource(name="test.md", result=result)
content = await resource.read()
assert content == "hello world"
@pytest.mark.asyncio
async def test_read_binary_content(self) -> None:
data = bytes([0x01, 0x02, 0x03, 0x04])
result = _make_blob_result(data)
resource = MCPSkillResource(name="icon.bin", result=result)
content = await resource.read()
assert content == data
@pytest.mark.asyncio
async def test_read_empty_returns_none(self) -> None:
result = _make_empty_result()
resource = MCPSkillResource(name="empty", result=result)
content = await resource.read()
assert content is None
@pytest.mark.asyncio
async def test_read_multiple_text_contents_joined(self) -> None:
result = ReadResourceResult(
contents=[
TextResourceContents(uri=AnyUrl("skill://a"), text="line1", mimeType="text/plain"),
TextResourceContents(uri=AnyUrl("skill://b"), text="line2", mimeType="text/plain"),
]
)
resource = MCPSkillResource(name="multi", result=result)
content = await resource.read()
assert content == "line1\nline2"
@pytest.mark.asyncio
async def test_binary_takes_precedence_over_text(self) -> None:
data = b"\xff\xfe"
result = ReadResourceResult(
contents=[
TextResourceContents(uri=AnyUrl("skill://a"), text="text", mimeType="text/plain"),
BlobResourceContents(
uri=AnyUrl("skill://b"),
blob=base64.b64encode(data).decode(),
mimeType="application/octet-stream",
),
]
)
resource = MCPSkillResource(name="mixed", result=result)
content = await resource.read()
# The implementation iterates all contents checking for BlobResourceContents
# first, so when both text and binary are present, binary is returned.
assert content == data
# ---------------------------------------------------------------------------
# MCPSkill tests
# ---------------------------------------------------------------------------
class TestMCPSkill:
"""Tests for MCPSkill."""
@pytest.mark.asyncio
async def test_get_content_fetches_and_caches(self) -> None:
client = _make_client(**{"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD)})
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="unit-converter", description="Convert between common units.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://unit-converter/SKILL.md", client=client)
content1 = await skill.get_content()
content2 = await skill.get_content()
assert "Body content here." in content1
assert content1 == content2
# Only one MCP call should be made (cached)
assert client.read_resource.call_count == 1
@pytest.mark.asyncio
async def test_get_content_raises_on_empty(self) -> None:
client = _make_client(**{"skill://empty/SKILL.md": _make_empty_result()})
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="empty-skill", description="Empty skill.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://empty/SKILL.md", client=client)
with pytest.raises(ValueError, match="no text content"):
await skill.get_content()
@pytest.mark.asyncio
async def test_get_resource_text(self) -> None:
client = _make_client(
**{
"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD),
"skill://unit-converter/references/checklist.md": _make_text_result("- check thing 1\n- check thing 2"),
}
)
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="unit-converter", description="Convert between common units.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://unit-converter/SKILL.md", client=client)
resource = await skill.get_resource("references/checklist.md")
assert resource is not None
content = await resource.read()
assert content == "- check thing 1\n- check thing 2"
@pytest.mark.asyncio
async def test_get_resource_binary(self) -> None:
data = bytes([0x01, 0x02, 0x03, 0x04])
client = _make_client(
**{
"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD),
"skill://unit-converter/assets/icon.bin": _make_blob_result(data),
}
)
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="unit-converter", description="Convert between common units.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://unit-converter/SKILL.md", client=client)
resource = await skill.get_resource("assets/icon.bin")
assert resource is not None
content = await resource.read()
assert content == data
@pytest.mark.asyncio
async def test_get_resource_unknown_returns_none(self) -> None:
client = _make_client(**{"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD)})
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="unit-converter", description="Convert between common units.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://unit-converter/SKILL.md", client=client)
resource = await skill.get_resource("references/does-not-exist.md")
assert resource is None
@pytest.mark.asyncio
@pytest.mark.parametrize(
"name",
[
"../escape.md",
"references/../../escape.md",
"..",
"..\\escape.md",
"/etc/passwd",
"http://attacker.example.com/payload",
],
)
async def test_get_resource_path_traversal_returns_none(self, name: str) -> None:
# Register a permissive mock that would happily return content for any URI,
# so the test fails unless the client-side validation rejects the name
# before issuing the read.
client = AsyncMock()
client.read_resource = AsyncMock(return_value=_make_text_result("should never be returned"))
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="unit-converter", description="Convert between common units.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://unit-converter/SKILL.md", client=client)
resource = await skill.get_resource(name)
assert resource is None
client.read_resource.assert_not_called()
@pytest.mark.asyncio
async def test_get_resource_empty_name_returns_none(self) -> None:
client = _make_client()
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
assert await skill.get_resource("") is None
assert await skill.get_resource(" ") is None
@pytest.mark.asyncio
async def test_get_script_returns_none(self) -> None:
client = _make_client()
from agent_framework import SkillFrontmatter
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
assert await skill.get_script("anything") is None
def test_compute_skill_root_uri_strips_suffix(self) -> None:
assert MCPSkill._compute_skill_root_uri("skill://unit-converter/SKILL.md") == "skill://unit-converter/"
def test_compute_skill_root_uri_trailing_slash(self) -> None:
assert MCPSkill._compute_skill_root_uri("skill://unit-converter/") == "skill://unit-converter/"
def test_compute_skill_root_uri_no_suffix_adds_slash(self) -> None:
assert MCPSkill._compute_skill_root_uri("skill://unit-converter") == "skill://unit-converter/"
# ---------------------------------------------------------------------------
# MCPSkillsSource tests
# ---------------------------------------------------------------------------
class TestMCPSkillsSource:
"""Tests for MCPSkillsSource."""
@pytest.mark.asyncio
async def test_index_based_discovery_returns_skill(self) -> None:
client = _make_client(
**{
"skill://index.json": _make_text_result(SAMPLE_SKILL_INDEX, uri="skill://index.json"),
"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD),
}
)
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert len(skills) == 1
assert skills[0].frontmatter.name == "unit-converter"
assert skills[0].frontmatter.description == "Convert between common units."
# Content is fetched on demand, not during discovery
content = await skills[0].get_content()
assert "Body content here." in content
@pytest.mark.asyncio
async def test_no_index_returns_empty(self) -> None:
client = _make_client() # No resources at all
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_does_not_read_skill_md_during_discovery(self) -> None:
# Index points to a skill, but SKILL.md is not registered on the server.
# Discovery should succeed because it only reads the index.
client = _make_client(
**{"skill://index.json": _make_text_result(SAMPLE_SKILL_INDEX, uri="skill://index.json")}
)
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert len(skills) == 1
assert skills[0].frontmatter.name == "unit-converter"
@pytest.mark.asyncio
async def test_invalid_name_is_skipped(self) -> None:
index_json = json.dumps(
{
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
"skills": [
{
"name": "UnitConverter", # Invalid: uppercase
"type": "skill-md",
"description": "Convert between common units.",
"url": "skill://UnitConverter/SKILL.md",
}
],
}
)
client = _make_client(**{"skill://index.json": _make_text_result(index_json, uri="skill://index.json")})
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_missing_required_fields_is_skipped(self) -> None:
index_json = json.dumps(
{
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
"skills": [
{
"name": "unit-converter",
"type": "skill-md",
# Missing description and url
}
],
}
)
client = _make_client(**{"skill://index.json": _make_text_result(index_json, uri="skill://index.json")})
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_unsupported_type_is_skipped(self) -> None:
index_json = json.dumps(
{
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
"skills": [
{
"name": "some-skill",
"type": "archive",
"description": "Packaged skill.",
"url": "skill://some-skill.tar.gz",
}
],
}
)
client = _make_client(**{"skill://index.json": _make_text_result(index_json, uri="skill://index.json")})
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_template_type_is_skipped(self) -> None:
index_json = json.dumps(
{
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
"skills": [
{
"type": "mcp-resource-template",
"description": "Per-product documentation skill",
"url": "skill://docs/{product}/SKILL.md",
}
],
}
)
client = _make_client(**{"skill://index.json": _make_text_result(index_json, uri="skill://index.json")})
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_empty_index_returns_empty(self) -> None:
client = _make_client(
**{"skill://index.json": _make_text_result('{"skills": []}', uri="skill://index.json")}
)
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_malformed_index_json_returns_empty(self) -> None:
client = _make_client(
**{"skill://index.json": _make_text_result("not valid json", uri="skill://index.json")}
)
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_sibling_text_resource(self) -> None:
client = _make_client(
**{
"skill://index.json": _make_text_result(SAMPLE_SKILL_INDEX, uri="skill://index.json"),
"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD),
"skill://unit-converter/references/checklist.md": _make_text_result("- check thing 1\n- check thing 2"),
}
)
source = MCPSkillsSource(client=client)
skill = (await source.get_skills())[0]
resource = await skill.get_resource("references/checklist.md")
assert resource is not None
content = await resource.read()
assert content == "- check thing 1\n- check thing 2"
@pytest.mark.asyncio
async def test_sibling_binary_resource(self) -> None:
data = bytes([0x01, 0x02, 0x03, 0x04])
client = _make_client(
**{
"skill://index.json": _make_text_result(SAMPLE_SKILL_INDEX, uri="skill://index.json"),
"skill://unit-converter/SKILL.md": _make_text_result(SAMPLE_SKILL_MD),
"skill://unit-converter/assets/icon.bin": _make_blob_result(data),
}
)
source = MCPSkillsSource(client=client)
skill = (await source.get_skills())[0]
resource = await skill.get_resource("assets/icon.bin")
assert resource is not None
content = await resource.read()
assert content == data
# ---------------------------------------------------------------------------
# McpError code branching tests
# ---------------------------------------------------------------------------
class TestMCPSkillsSourceErrorCodeBranching:
"""Tests that MCPSkillsSource and MCPSkill branch on McpError.error.code.
Only "not found" codes (RESOURCE_NOT_FOUND -32002, METHOD_NOT_FOUND -32601)
should be silently swallowed as "no skills available." Other McpError codes
and non-McpError exceptions must propagate so that auth failures, server
crashes, and connection drops are visible.
"""
@pytest.mark.asyncio
async def test_index_method_not_found_returns_empty(self) -> None:
"""METHOD_NOT_FOUND (-32601) -> server doesn't support resources/read."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=McpError(error=ErrorData(code=-32601, message="Method not found")))
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_index_resource_not_found_returns_empty(self) -> None:
"""MCP-spec "Resource not found" (-32002) -> server has no index."""
client = AsyncMock()
client.read_resource = AsyncMock(
side_effect=McpError(error=ErrorData(code=-32002, message="Resource not found"))
)
source = MCPSkillsSource(client=client)
skills = await source.get_skills()
assert skills == []
@pytest.mark.asyncio
async def test_index_invalid_params_propagates(self) -> None:
"""INVALID_PARAMS (-32602) is a real bug, must propagate (not "not found")."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=McpError(error=ErrorData(code=-32602, message="Invalid params")))
source = MCPSkillsSource(client=client)
with pytest.raises(McpError):
await source.get_skills()
@pytest.mark.asyncio
async def test_index_internal_error_propagates(self) -> None:
"""INTERNAL_ERROR (-32603) must propagate, not silently return empty."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=McpError(error=ErrorData(code=-32603, message="Internal error")))
source = MCPSkillsSource(client=client)
with pytest.raises(McpError):
await source.get_skills()
@pytest.mark.asyncio
async def test_index_connection_closed_propagates(self) -> None:
"""CONNECTION_CLOSED (-32000) must propagate."""
client = AsyncMock()
client.read_resource = AsyncMock(
side_effect=McpError(error=ErrorData(code=-32000, message="Connection closed"))
)
source = MCPSkillsSource(client=client)
with pytest.raises(McpError):
await source.get_skills()
@pytest.mark.asyncio
async def test_index_generic_error_code_propagates(self) -> None:
"""Generic handler error (code 0) must propagate."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=McpError(error=ErrorData(code=0, message="Some handler error")))
source = MCPSkillsSource(client=client)
with pytest.raises(McpError):
await source.get_skills()
@pytest.mark.asyncio
async def test_index_non_mcp_error_propagates(self) -> None:
"""Non-McpError exceptions (connection drop, timeout) must propagate."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=ConnectionError("connection lost"))
source = MCPSkillsSource(client=client)
with pytest.raises(ConnectionError):
await source.get_skills()
@pytest.mark.asyncio
async def test_get_resource_internal_error_propagates(self) -> None:
"""McpError with INTERNAL_ERROR on get_resource must propagate."""
from agent_framework import SkillFrontmatter
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=McpError(error=ErrorData(code=-32603, message="Server crashed")))
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
with pytest.raises(McpError):
await skill.get_resource("references/file.md")
@pytest.mark.asyncio
async def test_get_resource_not_found_returns_none(self) -> None:
"""McpError with RESOURCE_NOT_FOUND (-32002) on get_resource returns None."""
from agent_framework import SkillFrontmatter
client = AsyncMock()
client.read_resource = AsyncMock(
side_effect=McpError(error=ErrorData(code=-32002, message="Resource not found"))
)
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
result = await skill.get_resource("references/file.md")
assert result is None
@pytest.mark.asyncio
async def test_get_resource_connection_error_propagates(self) -> None:
"""A plain ConnectionError on get_resource must propagate, not return None."""
from agent_framework import SkillFrontmatter
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=ConnectionError("connection lost"))
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
with pytest.raises(ConnectionError):
await skill.get_resource("references/file.md")
@pytest.mark.asyncio
async def test_get_resource_timeout_error_propagates(self) -> None:
"""A TimeoutError on get_resource must propagate, not return None."""
from agent_framework import SkillFrontmatter
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=TimeoutError("read timed out"))
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
with pytest.raises(TimeoutError):
await skill.get_resource("references/file.md")
@pytest.mark.asyncio
async def test_get_resource_generic_mcp_error_propagates(self) -> None:
"""McpError with a generic code (0) on get_resource must propagate."""
from agent_framework import SkillFrontmatter
client = AsyncMock()
client.read_resource = AsyncMock(
side_effect=McpError(error=ErrorData(code=0, message="Handler error"))
)
fm = SkillFrontmatter(name="test-skill", description="Test.")
skill = MCPSkill(frontmatter=fm, skill_md_uri="skill://test/SKILL.md", client=client)
with pytest.raises(McpError):
await skill.get_resource("references/file.md")
@pytest.mark.asyncio
async def test_index_timeout_error_propagates(self) -> None:
"""A TimeoutError reading skill://index.json must propagate."""
client = AsyncMock()
client.read_resource = AsyncMock(side_effect=TimeoutError("read timed out"))
source = MCPSkillsSource(client=client)
with pytest.raises(TimeoutError):
await source.get_skills()
-8
View File
@@ -13,12 +13,9 @@ The Model Context Protocol (MCP) is an open standard for connecting AI agents to
| **Agent as MCP Server** | [`agent_as_mcp_server.py`](agent_as_mcp_server.py) | Shows how to expose an Agent Framework agent as an MCP server that other AI applications can connect to |
| **API Key Authentication** | [`mcp_api_key_auth.py`](mcp_api_key_auth.py) | Demonstrates API key authentication with MCP servers using `header_provider`, runtime invocation kwargs, and a command-line API key argument |
| **GitHub Integration with PAT** | [`mcp_github_pat.py`](mcp_github_pat.py) | Demonstrates connecting to GitHub's MCP server using Personal Access Token (PAT) authentication |
| **Long-Running Task** | [`mcp_long_running_task.py`](mcp_long_running_task.py) | Demonstrates transparent SEP-2663 long-running task handling for MCP tools that advertise `taskSupport=required`. Self-spawns a stdio MCP child server |
## Prerequisites
Most samples in this folder use OpenAI:
- `OPENAI_API_KEY` environment variable
- `OPENAI_CHAT_MODEL` environment variable
@@ -26,8 +23,3 @@ Run `mcp_api_key_auth.py` with the MCP API key as the first command-line argumen
For `mcp_github_pat.py`:
- `GITHUB_PAT` - Your GitHub Personal Access Token (create at https://github.com/settings/tokens)
For `mcp_long_running_task.py` (uses Azure OpenAI via Entra-ID):
- Run `az login` once
- `AZURE_OPENAI_ENDPOINT` - your Azure OpenAI resource endpoint, e.g. `https://<resource>.openai.azure.com/`
- `AZURE_OPENAI_CHAT_MODEL` (or `AZURE_OPENAI_MODEL`) - the deployment name (e.g. `gpt-4o-mini`)
@@ -1,181 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
"""
MCP Long-Running Task (SEP-2663) Example
Demonstrates that ``MCPStdioTool`` transparently drives the MCP long-running
task lifecycle for tools that advertise ``execution.taskSupport == "required"``.
The agent observes a single function-call result; the framework handles the
``tools/call`` → ``tasks/get`` (polled) → ``tasks/result`` sequence in the
background.
Run it as a single file. The script doubles as both the client and the stdio
MCP child server (the child branch is selected via ``--server``):
python mcp_long_running_task.py
Requirements:
- Azure CLI sign-in (``az login``) — used for Entra-ID auth against Azure OpenAI.
- ``AZURE_OPENAI_ENDPOINT`` — your Azure OpenAI resource endpoint, e.g.
``https://<resource>.openai.azure.com/``.
- ``AZURE_OPENAI_CHAT_MODEL`` (or ``AZURE_OPENAI_MODEL``) — the deployment name,
e.g. ``gpt-4o-mini``.
This sample uses the lower-level ``mcp.server.lowlevel.Server`` so it can:
1. Advertise a tool with ``execution=ToolExecution(taskSupport="required")``.
2. Enable the SDK's experimental task support for the ``tasks/*`` lifecycle.
"""
import asyncio
import sys
from datetime import timedelta
from typing import Any
from agent_framework import Agent, MCPStdioTool, MCPTaskOptions
from agent_framework.openai import OpenAIChatClient
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
load_dotenv()
# ---------------------------------------------------------------------------
# MCP stdio server (child-process branch)
# ---------------------------------------------------------------------------
async def _run_server() -> None:
"""Run a minimal stdio MCP server exposing one long-running tool."""
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.stdio import stdio_server
server: Server[Any, Any] = Server("mcp-long-running-task-demo")
# Auto-registers handlers for tasks/get, tasks/result, tasks/cancel, tasks/list
# backed by an in-memory store.
server.experimental.enable_tasks()
@server.list_tools()
async def _list_tools() -> list[types.Tool]: # pyright: ignore[reportUnusedFunction]
return [
types.Tool(
name="slow_summary",
description=(
"Produces a short summary of the supplied text after simulating several seconds of expensive work."
),
inputSchema={
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "Text to summarize.",
}
},
"required": ["text"],
},
# Advertise that this tool MUST be invoked via the task lifecycle.
execution=types.ToolExecution(taskSupport="required"),
)
]
@server.call_tool()
async def _call_tool(name: str, arguments: dict[str, Any]) -> Any: # pyright: ignore[reportUnusedFunction]
if name != "slow_summary":
raise ValueError(f"Unknown tool: {name}")
ctx = server.request_context
async def _work(task: Any) -> types.CallToolResult:
await task.update_status("Thinking...")
await asyncio.sleep(15.0)
text: str = (arguments.get("text") or "").strip()
words = text.split()
preview = " ".join(words[:6]) + ("..." if len(words) > 6 else "")
summary = (
f"Summarized {len(words)} word(s). First few words: '{preview}'."
if words
else "No input text was provided."
)
return types.CallToolResult(
content=[types.TextContent(type="text", text=summary)],
isError=False,
)
if not ctx.experimental.is_task:
# Client invoked the tool without task augmentation. Return a hard
# error so a misconfigured client surfaces the problem clearly.
return types.CallToolResult(
content=[
types.TextContent(
type="text",
text="'slow_summary' must be invoked as a task.",
)
],
isError=True,
)
return await ctx.experimental.run_task(_work)
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream, server.create_initialization_options())
# ---------------------------------------------------------------------------
# Agent client (default branch)
# ---------------------------------------------------------------------------
async def _run_client() -> None:
mcp_tool = MCPStdioTool(
name="LongRunningDemo",
description="Demo MCP server exposing a tool that advertises taskSupport=required.",
command=sys.executable,
args=[__file__, "--server"],
# Optional: cap individual tasks at two minutes. The server may apply its
# own default if this is omitted.
task_options=MCPTaskOptions(default_ttl=timedelta(minutes=2)),
)
async with Agent(
client=OpenAIChatClient(credential=AzureCliCredential()),
name="LROAgent",
instructions=(
"You are a helpful assistant. Use the slow_summary tool when the user "
"asks for a summary. Wait for the result and present it directly."
),
tools=mcp_tool,
) as agent:
prompt = (
"Please summarize the following text using your slow_summary tool: "
"'The Model Context Protocol lets language models talk to external "
"tools and resources through a small JSON-RPC surface.'"
)
print("=== run() ===")
print(f"User: {prompt}")
response = await agent.run(prompt)
print(f"Agent: {response.text}\n")
print("=== run(stream=True) ===")
print(f"User: {prompt}")
print("Agent: ", end="", flush=True)
async for update in agent.run(prompt, stream=True):
if update.text:
print(update.text, end="", flush=True)
print()
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main() -> None:
if len(sys.argv) > 1 and sys.argv[1] == "--server":
asyncio.run(_run_server())
return
asyncio.run(_run_client())
if __name__ == "__main__":
main()
@@ -27,7 +27,6 @@ This folder contains Azure AI Foundry and Foundry Local samples for Agent Framew
| [`foundry_chat_client_with_local_mcp.py`](foundry_chat_client_with_local_mcp.py) | Foundry Chat Client with local MCP |
| [`foundry_chat_client_with_session.py`](foundry_chat_client_with_session.py) | Foundry Chat Client with session management |
| [`foundry_chat_client_with_toolbox.py`](foundry_chat_client_with_toolbox.py) | Foundry Chat Client connected to a toolbox via its MCP endpoint using `MCPStreamableHTTPTool` |
| [`foundry_chat_client_with_toolbox_skills.py`](foundry_chat_client_with_toolbox_skills.py) | Foundry Chat Client that discovers MCP-based skills from a Foundry Toolbox endpoint via `MCPSkillsSource` (uses an Azure AD bearer token and the toolbox preview header) |
## FoundryLocalClient Samples
@@ -1,87 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from collections.abc import Generator
import httpx
from agent_framework import Agent, MCPSkillsSource, SkillsProvider
from agent_framework.foundry import FoundryChatClient
from azure.core.credentials import TokenCredential
from azure.identity import AzureCliCredential, get_bearer_token_provider
from dotenv import load_dotenv
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
# Load environment variables from .env file
load_dotenv()
"""
Foundry Chat Client with Toolbox-Hosted Skills
Discover Agent Skills served by a Microsoft Foundry Toolbox MCP endpoint
and inject them into a ``FoundryChatClient`` agent via ``MCPSkillsSource``.
The toolbox's discovery document (``skill://index.json``) is read once at
startup; SKILL.md bodies are fetched on demand as the agent uses them.
Prerequisites:
- A Microsoft Foundry project with a toolbox that exposes
``skill://index.json`` with ``skill-md`` entries
- FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL environment variables set
- FOUNDRY_TOOLBOX_MCP_SERVER_URL: the toolbox's MCP endpoint URL, e.g.
``https://<account>.services.ai.azure.com/api/projects/<project>/toolboxes/<name>/mcp?api-version=v1``
- Azure CLI authentication (``az login``)
"""
class _BearerAuth(httpx.Auth):
"""Attach a fresh Foundry bearer token to every request."""
def __init__(self, credential: TokenCredential) -> None:
self._get_token = get_bearer_token_provider(credential, "https://ai.azure.com/.default")
def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
request.headers["Authorization"] = f"Bearer {self._get_token()}"
yield request
async def main() -> None:
"""Example showing toolbox-hosted MCP skills for a Foundry Chat Client agent."""
credential = AzureCliCredential()
# HTTP client that signs every request with a fresh Foundry bearer token
# and advertises the toolbox preview feature flag, plus the MCP streamable
# HTTP transport that uses it.
async with (
httpx.AsyncClient(
auth=_BearerAuth(credential),
headers={"Foundry-Features": "Toolboxes=V1Preview"},
timeout=httpx.Timeout(30.0, read=300.0),
follow_redirects=True,
) as http_client,
streamable_http_client(
url=os.environ["FOUNDRY_TOOLBOX_MCP_SERVER_URL"],
http_client=http_client,
) as (read, write, _),
ClientSession(read, write) as session,
):
await session.initialize()
# Discover skills served by the toolbox and inject them as a context provider.
skills_provider = SkillsProvider(MCPSkillsSource(client=session))
async with Agent(
client=FoundryChatClient(credential=credential),
name="ToolboxMCPSkillsAgent",
instructions="You are a helpful assistant. Use available skills to answer the user.",
context_providers=[skills_provider],
) as agent:
query = input("User: ").strip() # noqa: ASYNC250
if not query:
return
response = await agent.run(query)
print(f"Assistant: {response.text}")
if __name__ == "__main__":
asyncio.run(main())
@@ -12,7 +12,6 @@ Start with file-based or code-defined skills, then explore combining them and ad
| [**code_defined_skill**](code_defined_skill/) | Define skills entirely in Python code using `Skill`, `@skill.resource`, and `@skill.script` decorators. Uses a code-defined unit-converter skill. |
| [**class_based_skill**](class_based_skill/) | Define skills as Python classes using `ClassSkill` with `@ClassSkill.resource` and `@ClassSkill.script` decorators for auto-discovery. Uses a class-based unit-converter skill. |
| [**mixed_skills**](mixed_skills/) | Combine code-defined, class-based, and file-based skills in a single agent. Uses a code-defined volume-converter, a class-based temperature-converter, and a file-based unit-converter. |
| [**mcp_based_skill**](mcp_based_skill/) | Discover skills served over the [Model Context Protocol (MCP)](https://modelcontextprotocol.io) via `MCPSkillsSource`. Connects to a remote MCP server that exposes skills as `skill://...` resources following the SEP-2640 convention. |
| [**script_approval**](script_approval/) | Require human-in-the-loop approval before executing skill scripts |
## Key Concepts
@@ -1,51 +0,0 @@
# MCP-Based Agent Skills Sample
This sample demonstrates how to discover **Agent Skills served over MCP** with an `Agent`.
## What it demonstrates
- Connecting to a remote MCP server (over streamable HTTP) that exposes skill
resources following the SEP-2640 convention.
- Building a `SkillsProvider` from an `MCPSkillsSource`, which reads
`skill://index.json` (SEP-2640 canonical discovery) and constructs skills from
the index entries.
- The progressive disclosure pattern across MCP: advertise → load → read
resources, exactly as for filesystem-backed skills.
## Running the Sample
### Prerequisites
- Python 3.10+
- An [Azure AI Foundry](https://ai.azure.com/) project with a deployed model
- Azure CLI authentication (`az login`)
- A running MCP server that hosts SEP-2640 skill resources (see "Providing
an MCP server" below)
### Setup
Set the following environment variables (in a `.env` file or your shell):
```powershell
$env:FOUNDRY_PROJECT_ENDPOINT="https://your-endpoint.services.ai.azure.com/api/projects/your-project"
$env:FOUNDRY_MODEL="gpt-4o-mini"
$env:MCP_SKILLS_SERVER_URL="https://your-mcp-server.example.com/mcp"
```
### Run
```powershell
python mcp_based_skill.py
```
## Providing an MCP server
This sample is a **consumer**: it does not host an MCP server itself. To try
it end-to-end you need an MCP server that exposes the SEP-2640 skill
resources (`skill://index.json` plus per-skill `SKILL.md`).
- See [`samples/02-agents/mcp/agent_as_mcp_server.py`](../../mcp/agent_as_mcp_server.py)
for an example of hosting an MCP server via the Agent Framework.
- The Model Context Protocol working group maintains reference MCP-skills
servers at
[`modelcontextprotocol/experimental-ext-skills`](https://github.com/modelcontextprotocol/experimental-ext-skills).
@@ -1,75 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
# Uncomment this filter to suppress the experimental Skills warning before
# using the sample's Skills APIs.
# import warnings
# warnings.filterwarnings("ignore", message=r"\[SKILLS\].*", category=FutureWarning)
from agent_framework import Agent, MCPSkillsSource, SkillsProvider
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
"""
MCP-Based Agent Skills
This sample demonstrates how to discover Agent Skills served over the
Model Context Protocol (MCP) using :class:`MCPSkillsSource`.
The sample connects to a remote MCP server that exposes skill resources
under the ``skill://`` URI scheme:
* ``skill://index.json`` — discovery document listing all skills
* ``skill://<skill-name>/SKILL.md`` — the skill instructions
To run, set ``MCP_SKILLS_SERVER_URL`` to the streamable HTTP endpoint of an
MCP server that hosts the skill resources.
"""
async def main() -> None:
"""Connect to a remote MCP skills server and run the agent."""
load_dotenv()
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
deployment = os.environ.get("FOUNDRY_MODEL", "gpt-4o-mini")
mcp_url = os.environ["MCP_SKILLS_SERVER_URL"]
print("Discovering MCP-based skills")
print("-" * 60)
# 1. Connect to the MCP server over streamable HTTP.
async with streamable_http_client(url=mcp_url) as (read, write, _), ClientSession(read, write) as session:
await session.initialize()
# 2. Build a SkillsProvider that discovers skills over MCP.
# MCPSkillsSource reads skill://index.json and creates one
# MCPSkill per skill-md entry; SKILL.md bodies are fetched
# on demand via resources/read.
skills_provider = SkillsProvider(MCPSkillsSource(client=session))
# 3. Run the agent.
client = FoundryChatClient(
project_endpoint=endpoint,
model=deployment,
credential=AzureCliCredential(),
)
async with Agent(
client=client,
instructions="You are a helpful assistant. Use available skills to answer the user.",
context_providers=[skills_provider],
) as agent:
query = input("User: ").strip() # noqa: ASYNC250
if not query:
return
response = await agent.run(query)
print(f"Agent: {response}\n")
if __name__ == "__main__":
asyncio.run(main())
-75
View File
@@ -1,75 +0,0 @@
# Tools
Samples that show how to define, configure, and control function tools for an
agent — from basic declarations to approvals, invocation limits, session
injection, and dynamic (progressive) tool exposure.
## Function tools
| File | Demonstrates |
|------|--------------|
| [`function_tool_with_explicit_schema.py`](function_tool_with_explicit_schema.py) | Defining a tool with an explicit JSON schema. |
| [`function_tool_declaration_only.py`](function_tool_declaration_only.py) | A declaration-only tool (schema without a local implementation). |
| [`function_tool_with_kwargs.py`](function_tool_with_kwargs.py) | Passing extra keyword arguments into a tool. |
| [`function_tool_from_dict_with_dependency_injection.py`](function_tool_from_dict_with_dependency_injection.py) | Dependency injection into a tool defined from a dict. |
| [`function_tool_with_session_injection.py`](function_tool_with_session_injection.py) | Injecting the session into a tool. |
| [`tool_in_class.py`](tool_in_class.py) | Using a method on a class as a tool. |
| [`agent_as_tool_with_session_propagation.py`](agent_as_tool_with_session_propagation.py) | Exposing an agent as a tool with session propagation. |
## Approvals & invocation control
| File | Demonstrates |
|------|--------------|
| [`function_tool_with_approval.py`](function_tool_with_approval.py) | Requiring human approval before a tool runs. |
| [`function_tool_with_approval_and_sessions.py`](function_tool_with_approval_and_sessions.py) | Tool approvals combined with sessions. |
| [`function_invocation_configuration.py`](function_invocation_configuration.py) | Configuring function-invocation settings (e.g. max iterations). |
| [`control_total_tool_executions.py`](control_total_tool_executions.py) | All the ways to cap how many times tools run. |
| [`function_tool_with_max_invocations.py`](function_tool_with_max_invocations.py) | Limiting the number of invocations per tool. |
| [`function_tool_with_max_exceptions.py`](function_tool_with_max_exceptions.py) | Limiting the number of exceptions a tool may raise. |
| [`function_tool_recover_from_failures.py`](function_tool_recover_from_failures.py) | Returning errors so the agent can recover from tool failures. |
## Progressive tool exposure (dynamic loading)
| File | Demonstrates |
|------|--------------|
| [`dynamic_tool_exposure.py`](dynamic_tool_exposure.py) | A "loader" tool that adds more tools at runtime via `FunctionInvocationContext`. |
Frontloading a model with hundreds of tools hurts tool-selection accuracy,
bloats context, and raises cost. Instead, start with a small set of loader
tools and let the model pull in more on demand. Inside a tool, the injected
`ctx: FunctionInvocationContext` exposes a live `ctx.tools` list plus
`ctx.add_tools(...)` / `ctx.remove_tools(...)` helpers. Tools added or removed
take effect on the **next iteration** of the function-calling loop.
> [!NOTE]
> Progressive tool exposure applies to the standard function-calling loop. It
> does **not** apply to CodeAct providers (`agent-framework-monty`,
> `agent-framework-hyperlight`). In CodeAct the model only sees a single
> `execute_code` tool, and host tools are exposed *inside the sandbox* as typed
> Python functions rather than as model tool-schemas. Host tools there are
> invoked without a `FunctionInvocationContext`, so `ctx.add_tools()` is not
> available; the helpers fail fast with a clear `RuntimeError` instead of
> silently doing nothing. To change a CodeAct agent's tool set, use the
> provider's own `add_tools` / `remove_tool` / `clear_tools` methods (applied
> between runs). The recommended provider-driven path for Monty and Hyperlight
> is shown in [`../context_providers/code_act/`](../context_providers/code_act/)
> ([`code_act.py`](../context_providers/code_act/code_act.py) for Hyperlight,
> [`monty_code_act.py`](../context_providers/code_act/monty_code_act.py) for
> Monty).
## Local shell & code interpreters
| Path | Demonstrates |
|------|--------------|
| [`local_shell_with_allowlist.py`](local_shell_with_allowlist.py) | `LocalShellTool` restricted by a strict command allow-list. |
| [`local_shell_with_environment_provider.py`](local_shell_with_environment_provider.py) | `LocalShellTool` wired with a `ShellEnvironmentProvider`. |
| [`local_code_interpreter/`](local_code_interpreter/) | Hyperlight-backed sandboxed code interpreter (standalone tool — *extra* pattern). |
| [`monty_code_interpreter/`](monty_code_interpreter/) | Monty-backed sandboxed code interpreter (standalone tool — *extra* pattern). |
> [!TIP]
> The `local_code_interpreter/` and `monty_code_interpreter/` samples show the
> standalone-tool wiring and are provided as *extra* reference. For most
> Monty/Hyperlight use cases the **recommended** path is the provider-driven
> CodeAct setup in
> [`../context_providers/code_act/`](../context_providers/code_act/), which adds
> dynamic tool / capability management.
@@ -1,79 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated
from agent_framework import Agent, FunctionInvocationContext, tool
from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv
from pydantic import Field
# Load environment variables from .env file
load_dotenv()
"""
Dynamic Tool Exposure (Progressive Tool Loading) Example
This example demonstrates "progressive tool exposure": a tool that adds more tools to
the agent at runtime, in the same run, via ``FunctionInvocationContext``.
Frontloading a model with hundreds of tools hurts tool-selection accuracy, bloats
context, and raises cost. Instead, you can start with a small set of "loader" tools and
let the model pull in additional tools on demand. Tools added with ``ctx.add_tools(...)``
(or removed with ``ctx.remove_tools(...)``) become available to the model on the next
iteration of the function-calling loop.
"""
# These math tools are not registered on the agent up front. They are added on demand by
# the ``load_math_tools`` tool below, and only then become callable by the model.
@tool(approval_mode="never_require")
def factorial(n: Annotated[int, Field(description="A non-negative integer.")]) -> str:
"""Compute the factorial of n."""
if n < 0:
return "Error: n must be a non-negative integer."
result = 1
for value in range(2, n + 1):
result *= value
return f"{n}! = {result}"
@tool(approval_mode="never_require")
def fibonacci(n: Annotated[int, Field(description="The 0-based index in the Fibonacci sequence.")]) -> str:
"""Compute the n-th Fibonacci number."""
if n < 0:
return "Error: n must be a non-negative integer."
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return f"fib({n}) = {a}"
# The only tool the agent starts with. When called, it exposes the math tools above so the
# model can use them on the next turn. Note the ``ctx`` parameter is injected by the
# framework and is not visible to the model.
@tool(approval_mode="never_require")
def load_math_tools(ctx: FunctionInvocationContext) -> str:
"""Load additional math tools (factorial, fibonacci) so they can be used."""
ctx.add_tools([factorial, fibonacci])
return "Loaded math tools: factorial, fibonacci. You can now call them."
async def main() -> None:
agent = Agent(
client=OpenAIChatClient(),
name="MathAgent",
instructions=(
"You are a math assistant. If you need math capabilities that are not yet "
"available, call load_math_tools first, then use the newly available tools."
),
tools=[load_math_tools],
)
# The agent starts with only ``load_math_tools``. To answer the question it must first
# load the math tools, then call ``factorial`` on the next iteration.
print(f"Agent: {await agent.run('What is 5 factorial?')}")
if __name__ == "__main__":
asyncio.run(main())
+9 -102
View File
@@ -562,7 +562,7 @@ requires-dist = [
{ name = "agent-framework-core", editable = "packages/core" },
{ name = "azure-ai-agentserver-core", specifier = ">=2.0.0b3,<3" },
{ name = "azure-ai-agentserver-invocations", specifier = ">=1.0.0b3,<2" },
{ name = "azure-ai-agentserver-responses", specifier = ">=1.0.0b7,<2" },
{ name = "azure-ai-agentserver-responses", specifier = ">=1.0.0b5,<2" },
]
[[package]]
@@ -1171,18 +1171,19 @@ wheels = [
[[package]]
name = "azure-ai-agentserver-core"
version = "2.0.0b5"
version = "2.0.0b3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "azure-monitor-opentelemetry-exporter", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "hypercorn", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "microsoft-opentelemetry", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-exporter-otlp-proto-grpc", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-sdk", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "starlette", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a5/06/7c88b6506d26ee625a967cef762e6a155ed7ab8812f3f1e45ec1a950b8ae/azure_ai_agentserver_core-2.0.0b5.tar.gz", hash = "sha256:f03dc737351e5d847e9fc18c5b78b261436de368f1317a0c29957cc2179c37d1", size = 46273, upload-time = "2026-05-25T12:48:01.739Z" }
sdist = { url = "https://files.pythonhosted.org/packages/84/29/1a9606d5252b02d77070a1b633dd0c26fe65a0f4a0fb0cfdaa751e2ed458/azure_ai_agentserver_core-2.0.0b3.tar.gz", hash = "sha256:e295b19a65d53c513929f52f0862bbb815cc9e9fc29d2a2825452f3136260123", size = 42573, upload-time = "2026-04-23T04:13:16.717Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/68/80/a43a269601512793b220c36dc0864b44d806b969dbfe14f1ecc3b5f5202b/azure_ai_agentserver_core-2.0.0b5-py3-none-any.whl", hash = "sha256:0d00c298892e2ff466b32235d5d9c55b57054f0e8fcedb0726eacd7684e1aa89", size = 31521, upload-time = "2026-05-25T12:48:03.072Z" },
{ url = "https://files.pythonhosted.org/packages/7f/9b/1fc87c05b55821f33c46c5e8a3b97a573aa2fc4bff387e75cca1a87800b4/azure_ai_agentserver_core-2.0.0b3-py3-none-any.whl", hash = "sha256:5ef921eb9fd9c0f15682fe930320fae50dccfa915d7518f9a16d99014bbcb3cb", size = 29127, upload-time = "2026-04-23T04:13:17.976Z" },
]
[[package]]
@@ -1199,7 +1200,7 @@ wheels = [
[[package]]
name = "azure-ai-agentserver-responses"
version = "1.0.0b7"
version = "1.0.0b5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
@@ -1207,9 +1208,9 @@ dependencies = [
{ name = "azure-core", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "isodate", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/f1/53/febb6f3453f5dc1e0b6dc47d4e5198b64605d1f83c847255946f74bc300e/azure_ai_agentserver_responses-1.0.0b7.tar.gz", hash = "sha256:2f67cdfc0219cb0ab86800dadb1cfdb40ab4aa0413dae7ffa5ea4ea84eec3eb0", size = 419032, upload-time = "2026-05-25T12:48:38.81Z" }
sdist = { url = "https://files.pythonhosted.org/packages/e6/27/3ecb7fe704ff8764199bfbe4cc1e584a520a9affe042470d9d50b6e1e73a/azure_ai_agentserver_responses-1.0.0b5.tar.gz", hash = "sha256:0b627b810359c792ea7b6fa6782abaf6df32d9bc9e5a569ad722afcffd0ce8d9", size = 410908, upload-time = "2026-04-23T04:31:15.414Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/94/48825357e009f7db3b6b5d0a9344a7ab3304e32f06f50328b2393e3b06cb/azure_ai_agentserver_responses-1.0.0b7-py3-none-any.whl", hash = "sha256:efb5271f24a297bacde9769359308e54e870f66ad4d3b4826ae97a77e40e94d4", size = 268063, upload-time = "2026-05-25T12:48:40.817Z" },
{ url = "https://files.pythonhosted.org/packages/44/91/1e5c0d7ce95ca8b022e69e4ca6b23e413fc2d57f0191429c4633e02213d2/azure_ai_agentserver_responses-1.0.0b5-py3-none-any.whl", hash = "sha256:4c2a6ab56e71eeb330aa52b7cb2cc71b8ec6b5bbe0e7dc84310f2c7fbda393a3", size = 268362, upload-time = "2026-04-23T04:31:17.014Z" },
]
[[package]]
@@ -3886,41 +3887,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/1b/543ddaa2daf8593911a02a07a6a78366d4a6a0053ec86a557c19fa97b60e/microsoft_agents_hosting_core-0.3.1-py3-none-any.whl", hash = "sha256:a4b41556b15321b74f539c5a0a89f70955459b7ec57e9e4b24e61bba27f1cbbc", size = 94573, upload-time = "2025-09-09T23:19:53.855Z" },
]
[[package]]
name = "microsoft-opentelemetry"
version = "1.3.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "azure-core", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "azure-core-tracing-opentelemetry", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "azure-monitor-opentelemetry-exporter", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-exporter-otlp-proto-http", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-django", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-fastapi", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-flask", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-httpx", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-logging", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-openai-agents-v2", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-openai-v2", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-psycopg2", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-requests", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-urllib", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation-urllib3", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-resource-detector-azure", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-sdk", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-util-genai", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "pyjwt", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "requests", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "wrapt", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a2/cf/74885d07d38e225b84b63a8a2720de846e518fe4c7e89457f4c150a9c7d5/microsoft_opentelemetry-1.3.2.tar.gz", hash = "sha256:d36f31731740170624b53f370358a9700f503bb4f9bd25c7f81c0c88c66f511c", size = 178031, upload-time = "2026-05-29T22:05:53.442Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/22/8d/6960be61c8fe236fef730b0cae1d97a1898f62355b2d6679ef46abe1e4be/microsoft_opentelemetry-1.3.2-py3-none-any.whl", hash = "sha256:65292474ce7efee115f671457188e92edc4a8d432fad163e49e504155be66ae5", size = 198419, upload-time = "2026-05-29T22:05:54.849Z" },
]
[[package]]
name = "mistralai"
version = "2.4.2"
@@ -4667,22 +4633,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3e/41/619f3530324a58491f2d20f216a10dd7393629b29db4610dda642a27f4ed/opentelemetry_instrumentation_flask-0.61b0-py3-none-any.whl", hash = "sha256:e8ce474d7ce543bfbbb3e93f8a6f8263348af9d7b45502f387420cf3afa71253", size = 15996, upload-time = "2026-03-04T14:19:31.304Z" },
]
[[package]]
name = "opentelemetry-instrumentation-httpx"
version = "0.61b0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-semantic-conventions", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-util-http", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "wrapt", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/cd/2a/e2becd55e33c29d1d9ef76e2579040ed1951cb33bacba259f6aff2fdd2a6/opentelemetry_instrumentation_httpx-0.61b0.tar.gz", hash = "sha256:6569ec097946c5551c2a4252f74c98666addd1bf047c1dde6b4ef426719ff8dd", size = 24104, upload-time = "2026-03-04T14:20:34.752Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/af/88/dde310dce56e2d85cf1a09507f5888544955309edc4b8d22971d6d3d1417/opentelemetry_instrumentation_httpx-0.61b0-py3-none-any.whl", hash = "sha256:dee05c93a6593a5dc3ae5d9d5c01df8b4e2c5d02e49275e5558534ee46343d5e", size = 17198, upload-time = "2026-03-04T14:19:33.585Z" },
]
[[package]]
name = "opentelemetry-instrumentation-logging"
version = "0.61b0"
@@ -4696,35 +4646,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/0e/2137db5239cc5e564495549a4d11488a7af9b48fc76520a0eea20e69ddae/opentelemetry_instrumentation_logging-0.61b0-py3-none-any.whl", hash = "sha256:6d87e5ded6a0128d775d41511f8380910a1b610671081d16efb05ac3711c0074", size = 17076, upload-time = "2026-03-04T14:19:36.765Z" },
]
[[package]]
name = "opentelemetry-instrumentation-openai-agents-v2"
version = "0.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-semantic-conventions", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-util-genai", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/00/15/b6a303454d2800d772cdebc490c1d598d06d0e541619db80195eb9ea85c6/opentelemetry_instrumentation_openai_agents_v2-0.1.0.tar.gz", hash = "sha256:1033f4b261ce07f65d197ac0e9c499302c805eae987a6cc4e7f99bb279363477", size = 22423, upload-time = "2025-10-15T19:04:59.912Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cd/0a/b6f47734e1d7f936cbc52ef8e673d3e08d9c3c8a13d9549c03f978758076/opentelemetry_instrumentation_openai_agents_v2-0.1.0-py3-none-any.whl", hash = "sha256:e4e3dfba32bd6eeee0624eca9be54341ab7cc4f7a3bb895354f2f9d6f7afe2f3", size = 25002, upload-time = "2025-10-15T19:04:58.562Z" },
]
[[package]]
name = "opentelemetry-instrumentation-openai-v2"
version = "2.3b0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-semantic-conventions", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/38/4e/21f8cd16ccb471dd217ed85eb817796a10c4f2718ae2c91e752a57180cf0/opentelemetry_instrumentation_openai_v2-2.3b0.tar.gz", hash = "sha256:5de9d70cc9536eea1fe48ea016e0c5f25735fa9a13709076a64b20657fadb6ba", size = 170838, upload-time = "2025-12-24T13:20:58.33Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/02/7ff0a9282520592772a356dd39d1559f3726610ccc3854a2f598b756c66f/opentelemetry_instrumentation_openai_v2-2.3b0-py3-none-any.whl", hash = "sha256:c6aca87be0da0289ea1d8167fea4b0f227ea5ef0e90496e2822121e47340d36a", size = 18053, upload-time = "2025-12-24T13:20:57.233Z" },
]
[[package]]
name = "opentelemetry-instrumentation-psycopg2"
version = "0.61b0"
@@ -4851,20 +4772,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b2/37/cc6a55e448deaa9b27377d087da8615a3416d8ad523d5960b78dbeadd02a/opentelemetry_semantic_conventions-0.61b0-py3-none-any.whl", hash = "sha256:fa530a96be229795f8cef353739b618148b0fe2b4b3f005e60e262926c4d38e2", size = 231621, upload-time = "2026-03-04T14:17:19.33Z" },
]
[[package]]
name = "opentelemetry-util-genai"
version = "0.3b0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "opentelemetry-api", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-instrumentation", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
{ name = "opentelemetry-semantic-conventions", marker = "sys_platform == 'darwin' or sys_platform == 'linux' or sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a2/d8/4dd2fb622d26ec45b10ef63eb87fd512f5d7467c7bd35ce390629bd6dff8/opentelemetry_util_genai-0.3b0.tar.gz", hash = "sha256:83e127789a9ad615b8ca65f05fc36955a67ce257b06142bfd46159a3b7ed73d3", size = 31800, upload-time = "2026-02-20T16:16:14.807Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/18/e5/fada54909e445d7b4007f8b96221d571999efeab9446f3127cc1cebe5e07/opentelemetry_util_genai-0.3b0-py3-none-any.whl", hash = "sha256:ebc2b01bcb891ddc7218452470d189d3321cd742653299ff8e7de45debcfb986", size = 28426, upload-time = "2026-02-20T16:16:12.027Z" },
]
[[package]]
name = "opentelemetry-util-http"
version = "0.61b0"