Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions dotnet/agent-framework-dotnet.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,18 @@
<Project Path="samples/02-agents/AgentSkills/Agent_Step03_ClassBasedSkills/Agent_Step03_ClassBasedSkills.csproj" />
<Project Path="samples/02-agents/AgentSkills/Agent_Step04_MixedSkills/Agent_Step04_MixedSkills.csproj" />
<Project Path="samples/02-agents/AgentSkills/Agent_Step05_SkillsWithDI/Agent_Step05_SkillsWithDI.csproj" />
<Project Path="samples/02-agents/AgentSkills/Agent_Step06_McpBasedSkills/Agent_Step06_McpBasedSkills.csproj" />
</Folder>
<Folder Name="/Samples/02-agents/Harness/">
<File Path="samples/02-agents/Harness/README.md" />
<Project Path="samples/02-agents/Harness/ConsoleReactiveComponents/ConsoleReactiveComponents.csproj" />
<Project Path="samples/02-agents/Harness/ConsoleReactiveFramework/ConsoleReactiveFramework.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Shared_Console/Harness_Shared_Console.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Shared_Console_OpenAI/Harness_Shared_Console_OpenAI.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Step01_Research/Harness_Step01_Research.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Step02_Research_WithBackgroundAgents/Harness_Step02_Research_WithBackgroundAgents.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Step03_DataProcessing/Harness_Step03_DataProcessing.csproj" />
<Project Path="samples/02-agents/Harness/Harness_Step04_CodeExecution/Harness_Step04_CodeExecution.csproj" />
<Project Path="samples/02-agents/Harness/ConsoleReactiveFramework/ConsoleReactiveFramework.csproj" />
<Project Path="samples/02-agents/Harness/ConsoleReactiveComponents/ConsoleReactiveComponents.csproj" />
</Folder>
<Folder Name="/Samples/02-agents/AGUI/Step05_StateManagement/">
<Project Path="samples/02-agents/AGUI/Step05_StateManagement/Client/Client.csproj" />
Expand Down Expand Up @@ -244,8 +245,8 @@
<Project Path="samples/03-workflows/Declarative/GenerateCode/GenerateCode.csproj" />
<Project Path="samples/03-workflows/Declarative/HostedWorkflow/HostedWorkflow.csproj" />
<Project Path="samples/03-workflows/Declarative/InputArguments/InputArguments.csproj" />
<Project Path="samples/03-workflows/Declarative/InvokeFunctionTool/InvokeFunctionTool.csproj" />
<Project Path="samples/03-workflows/Declarative/InvokeFoundryToolboxMcp/InvokeFoundryToolboxMcp.csproj" />
<Project Path="samples/03-workflows/Declarative/InvokeFunctionTool/InvokeFunctionTool.csproj" />
<Project Path="samples/03-workflows/Declarative/InvokeHttpRequest/InvokeHttpRequest.csproj" />
<Project Path="samples/03-workflows/Declarative/InvokeMcpTool/InvokeMcpTool.csproj" />
<Project Path="samples/03-workflows/Declarative/Marketing/Marketing.csproj" />
Expand Down Expand Up @@ -597,8 +598,8 @@
<Project Path="src/Microsoft.Agents.AI.DurableTask/Microsoft.Agents.AI.DurableTask.csproj" />
<Project Path="src/Microsoft.Agents.AI.Foundry.Hosting/Microsoft.Agents.AI.Foundry.Hosting.csproj" />
<Project Path="src/Microsoft.Agents.AI.Foundry/Microsoft.Agents.AI.Foundry.csproj" />
<Project Path="src/Microsoft.Agents.AI.Harness/Microsoft.Agents.AI.Harness.csproj" />
<Project Path="src/Microsoft.Agents.AI.GitHub.Copilot/Microsoft.Agents.AI.GitHub.Copilot.csproj" />
<Project Path="src/Microsoft.Agents.AI.Harness/Microsoft.Agents.AI.Harness.csproj" />
<Project Path="src/Microsoft.Agents.AI.Hosting.A2A.AspNetCore/Microsoft.Agents.AI.Hosting.A2A.AspNetCore.csproj" />
<Project Path="src/Microsoft.Agents.AI.Hosting.A2A/Microsoft.Agents.AI.Hosting.A2A.csproj" />
<Project Path="src/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj" />
Expand All @@ -624,8 +625,8 @@
<Project Path="tests/AnthropicChatCompletion.IntegrationTests/AnthropicChatCompletion.IntegrationTests.csproj" />
<Project Path="tests/AzureAIAgentsPersistent.IntegrationTests/AzureAIAgentsPersistent.IntegrationTests.csproj" />
<Project Path="tests/CopilotStudio.IntegrationTests/CopilotStudio.IntegrationTests.csproj" />
<Project Path="tests/Foundry.Hosting.IntegrationTests/Foundry.Hosting.IntegrationTests.csproj" />
<Project Path="tests/Foundry.Hosting.IntegrationTests.TestContainer/Foundry.Hosting.IntegrationTests.TestContainer.csproj" />
<Project Path="tests/Foundry.Hosting.IntegrationTests/Foundry.Hosting.IntegrationTests.csproj" />
<Project Path="tests/Foundry.IntegrationTests/Foundry.IntegrationTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/Microsoft.Agents.AI.DurableTask.IntegrationTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.GitHub.Copilot.IntegrationTests/Microsoft.Agents.AI.GitHub.Copilot.IntegrationTests.csproj" />
Expand All @@ -650,8 +651,8 @@
<Project Path="tests/Microsoft.Agents.AI.Declarative.UnitTests/Microsoft.Agents.AI.Declarative.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.DevUI.UnitTests/Microsoft.Agents.AI.DevUI.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.DurableTask.UnitTests/Microsoft.Agents.AI.DurableTask.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.Foundry.UnitTests/Microsoft.Agents.AI.Foundry.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.Foundry.Hosting.UnitTests/Microsoft.Agents.AI.Foundry.Hosting.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.Foundry.UnitTests/Microsoft.Agents.AI.Foundry.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.GitHub.Copilot.UnitTests/Microsoft.Agents.AI.GitHub.Copilot.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.Harness.UnitTests/Microsoft.Agents.AI.Harness.UnitTests.csproj" />
<Project Path="tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/Microsoft.Agents.AI.Hosting.A2A.UnitTests.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>

<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<NoWarn>$(NoWarn);MAAI001</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="ModelContextProtocol" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Mcp\Microsoft.Agents.AI.Mcp.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright (c) Microsoft. All rights reserved.

// This sample demonstrates how to discover Agent Skills served over MCP.
Comment thread
semenshi marked this conversation as resolved.
//
// It connects an McpClient to an external MCP server that exposes skill
// resources following the SEP-2640 convention (skill://<skill-path>/<file-path>),
// plus a canonical "skill://index.json" discovery document. The skills provider
// reads the index, constructs skills from the entries, and injects them into
// the agent — exactly as for filesystem-backed skills.

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using ModelContextProtocol.Client;
using OpenAI.Responses;

// --- Configuration ---
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";

string mcpEndpoint = Environment.GetEnvironmentVariable("MCP_SKILLS_ENDPOINT")
?? throw new InvalidOperationException("MCP_SKILLS_ENDPOINT is not set.");

// --- MCP client + skill discovery ---
Console.WriteLine($"Connecting to MCP skills endpoint: {mcpEndpoint}");

await using McpClient client = await McpClient.CreateAsync(
new HttpClientTransport(
new HttpClientTransportOptions
{
Endpoint = new Uri(mcpEndpoint),
Name = "skills-server",
TransportMode = HttpTransportMode.StreamableHttp,
}));

var skillsProvider = new AgentSkillsProviderBuilder()
.UseMcpSkills(client)
.Build();

// --- Agent ---
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
AIAgent agent = new AzureOpenAIClient(new Uri(openAiEndpoint), new DefaultAzureCredential())
.GetResponsesClient()
.AsAIAgent(new ChatClientAgentOptions
{
Name = "SkillsAgent",
ChatOptions = new()
{
Instructions = "You are a helpful assistant. Use available skills to answer the user.",
},
AIContextProviders = [skillsProvider],
},
model: deploymentName);

// --- Run ---
Console.WriteLine("\nType a message (or press Enter to quit):\n");

while (true)
{
Console.Write("User: ");
string? input = Console.ReadLine();

if (string.IsNullOrWhiteSpace(input))
{
break;
}

AgentResponse response = await agent.RunAsync(input);
Console.WriteLine($"Agent: {response.Text}\n");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# MCP-Based Agent Skills Sample

This sample demonstrates how to discover **Agent Skills served over MCP** with a `ChatClientAgent`.

## What it demonstrates

- Connecting an `McpClient` to an external MCP server via Streamable HTTP transport.
- Building an `AgentSkillsProvider` via `UseMcpSkills(client)`, 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

- .NET 10.0 SDK
- Azure OpenAI endpoint with a deployed model
- An MCP server that exposes Agent Skills resources following the
[SEP-2640](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2640) convention

### Setup

```powershell
$env:AZURE_OPENAI_ENDPOINT="https://your-endpoint.openai.azure.com/"
$env:AZURE_OPENAI_DEPLOYMENT_NAME="gpt-5.4-mini"
$env:MCP_SKILLS_ENDPOINT="https://your-mcp-server/mcp"
```

### Run

```powershell
dotnet run
```
1 change: 1 addition & 0 deletions dotnet/samples/02-agents/AgentSkills/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Samples demonstrating Agent Skills capabilities. Each sample shows a different w
| [Agent_Step03_ClassBasedSkills](Agent_Step03_ClassBasedSkills/) | Define skills as C# classes using `AgentClassSkill`. |
| [Agent_Step04_MixedSkills](Agent_Step04_MixedSkills/) | **(Advanced)** Combine file-based, code-defined, and class-based skills using `AgentSkillsProviderBuilder`. |
| [Agent_Step05_SkillsWithDI](Agent_Step05_SkillsWithDI/) | Use Dependency Injection with both code-defined (`AgentInlineSkill`) and class-based (`AgentClassSkill`) skills. |
| [Agent_Step06_McpBasedSkills](Agent_Step06_McpBasedSkills/) | Discover skills served over the [Model Context Protocol (MCP)](https://modelcontextprotocol.io) via `AgentMcpSkillsSource`. Spins up an in-process MCP server that exposes skills as resources (`skill://...`) and connects an `McpClient` to it. |

## Key Concepts

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
<TargetFrameworks>$(TargetFrameworksCore)</TargetFrameworks>
<RootNamespace>Microsoft.Agents.AI.Mcp</RootNamespace>
<VersionSuffix>alpha</VersionSuffix>
<NoWarn>$(NoWarn);MEAI001;MCPEXP001</NoWarn>
<NoWarn>$(NoWarn);MEAI001;MAAI001;MCPEXP001</NoWarn>

</PropertyGroup>

<Import Project="$(RepoRoot)/dotnet/nuget/nuget-package.props" />

<PropertyGroup>
<InjectSharedThrow>true</InjectSharedThrow>
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds>
<InjectTrimAttributesOnLegacy>true</InjectTrimAttributesOnLegacy>
</PropertyGroup>

Expand All @@ -34,4 +36,8 @@
<InternalsVisibleTo Include="Microsoft.Agents.AI.Mcp.UnitTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" />
</ItemGroup>

</Project>
133 changes: 133 additions & 0 deletions dotnet/src/Microsoft.Agents.AI.Mcp/Skills/AgentMcpSkill.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Shared.Diagnostics;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

namespace Microsoft.Agents.AI;

/// <summary>
/// An <see cref="AgentSkill"/> discovered from an MCP server exposing the Agent Skills convention.
/// </summary>
/// <remarks>
/// <para>
/// The skill is constructed from <c>skill://index.json</c> discovery metadata only; <see cref="GetContentAsync"/>
/// fetches the full <c>SKILL.md</c> content from the MCP server on demand via <c>resources/read</c>.
/// </para>
/// <para>
/// Per SEP-2640, resources referenced inside SKILL.md are fetched on demand via the originating MCP
/// server: <see cref="GetResourceAsync"/> resolves a relative resource name against the
/// skill's root URI, issues a <c>resources/read</c> request, and returns an <see cref="AgentMcpSkillResource"/>
/// with pre-fetched content.
/// </para>
/// </remarks>
internal sealed class AgentMcpSkill : AgentSkill
{
private const string SkillMdSuffix = "SKILL.md";

private readonly McpClient _client;
private readonly string _skillMdUri;
private readonly string _skillRootUri;
private string? _content;

/// <summary>
/// Initializes a new instance of the <see cref="AgentMcpSkill"/> class.
/// </summary>
/// <param name="frontmatter">The parsed frontmatter metadata for this skill.</param>
/// <param name="skillMdUri">
/// The full MCP resource URI of the <c>SKILL.md</c> resource (e.g. <c>skill://unit-converter/SKILL.md</c>).
/// Used by <see cref="GetContentAsync"/> to fetch the skill content on demand. The skill's root URI
/// (used to resolve sibling resources) is derived by stripping the trailing <c>SKILL.md</c> segment.
/// </param>
/// <param name="client">The MCP client used to fetch resources on demand.</param>
public AgentMcpSkill(AgentSkillFrontmatter frontmatter, string skillMdUri, McpClient client)
{
this.Frontmatter = Throw.IfNull(frontmatter);
this._skillMdUri = Throw.IfNullOrWhitespace(skillMdUri);
this._skillRootUri = ComputeSkillRootUri(skillMdUri);
this._client = Throw.IfNull(client);
}

/// <inheritdoc/>
public override AgentSkillFrontmatter Frontmatter { get; }

/// <inheritdoc/>
/// <remarks>
/// Fetches the <c>SKILL.md</c> content from the MCP server via <c>resources/read</c> on the first call
/// and caches the result.
/// </remarks>
public override async ValueTask<string> GetContentAsync(CancellationToken cancellationToken = default)
{
if (this._content is not null)
{
return this._content;
}

#pragma warning disable CA2234 // Pass system uri objects instead of strings
ReadResourceResult result = await this._client.ReadResourceAsync(this._skillMdUri, cancellationToken: cancellationToken).ConfigureAwait(false);
#pragma warning restore CA2234 // Pass system uri objects instead of strings

string text = string.Join("\n", result.Contents.OfType<TextResourceContents>().Select(c => c.Text));

if (text.Length == 0)
{
throw new InvalidOperationException($"The MCP server returned no text content for SKILL.md resource '{this._skillMdUri}'.");
}

return this._content = text;
}

/// <inheritdoc/>
/// <remarks>
/// Resolves <paramref name="name"/> as a relative path against the skill's root URI, issues a
/// <c>resources/read</c> request to the MCP server, and returns an <see cref="AgentMcpSkillResource"/>
/// with the pre-fetched content. Returns <see langword="null"/> when the name is empty, the server
/// returns no content, or the resource does not exist on the server.
/// </remarks>
public override async ValueTask<AgentSkillResource?> GetResourceAsync(string name, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}

string uri = this._skillRootUri + name;

ReadResourceResult result;
try
{
#pragma warning disable CA2234 // Pass system uri objects instead of strings
result = await this._client.ReadResourceAsync(uri, cancellationToken: cancellationToken).ConfigureAwait(false);
#pragma warning restore CA2234 // Pass system uri objects instead of strings
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return null;
}

return new AgentMcpSkillResource(name: name, result: result);
}

/// <summary>
/// Strips the trailing <c>SKILL.md</c> from the URI to produce the skill's root directory URI.
/// If the URI doesn't end with <c>SKILL.md</c>, ensures it ends with a trailing slash.
/// </summary>
private static string ComputeSkillRootUri(string skillMdUri)
{
if (skillMdUri.EndsWith(SkillMdSuffix, StringComparison.Ordinal))
{
return skillMdUri.Substring(0, skillMdUri.Length - SkillMdSuffix.Length);
}

if (skillMdUri.EndsWith("/", StringComparison.Ordinal))
{
return skillMdUri;
}

return skillMdUri + "/";
}
}
Loading
Loading