-
Notifications
You must be signed in to change notification settings - Fork 1.9k
.NET: Add MCP-based skills support (skill-md type) #6108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e7c3293
Add MCP-based skills support
semenshi 8ed6511
Merge branch 'main' into feature/mcp-based-skills
semenshi b980d7a
Remove unnecessary [Experimental] attributes from MCP package
semenshi d7265b7
Make Agent_Step06_McpBasedSkills self-contained and add to verify-sam…
semenshi 7df3516
Sort usings
semenshi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
...ples/02-agents/AgentSkills/Agent_Step06_McpBasedSkills/Agent_Step06_McpBasedSkills.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
73 changes: 73 additions & 0 deletions
73
dotnet/samples/02-agents/AgentSkills/Agent_Step06_McpBasedSkills/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| // | ||
| // 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"); | ||
| } | ||
35 changes: 35 additions & 0 deletions
35
dotnet/samples/02-agents/AgentSkills/Agent_Step06_McpBasedSkills/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
133 changes: 133 additions & 0 deletions
133
dotnet/src/Microsoft.Agents.AI.Mcp/Skills/AgentMcpSkill.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 + "/"; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.