Microsoft.Extensions.AI.Abstractions integration (#25)

* MEAI integration
* README and xmldocs
This commit is contained in:
Peder Holdgaard Pedersen 2025-02-23 13:23:56 +01:00 • committed by GitHub
commit 89c4913ed7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 589 additions and 1 deletions

View file

@ -0,0 +1,26 @@
using McpDotNet.Protocol.Types;
using System.Text.Json;
namespace McpDotNet.Extensions.AI;
internal static class AIFunctionUtilities
{
/// <summary>
/// Maps a Tool to a JsonElement that represents the tool's schema (top-level and input schema/parameters).
/// </summary>
public static JsonElement MapToJsonElement(Tool tool)
{
// Create a JsonObject that matches the MEAI schema format
var schemaObj = new Dictionary<string, object>
{
["type"] = "object",
["title"] = tool.Name,
["description"] = tool.Description ?? string.Empty,
["properties"] = tool.InputSchema?.Properties ?? new(),
["required"] = tool.InputSchema?.Required ?? []
};
// Convert to JsonElement
return JsonSerializer.SerializeToElement(schemaObj);
}
}

View file

@ -0,0 +1,57 @@
using McpDotNet.Client;
using McpDotNet.Protocol.Types;
using Microsoft.Extensions.AI;
using System.Text.Json;
namespace McpDotNet.Extensions.AI;
/// <summary>
/// Represents an AI function that calls a tool through mcpdotnet.
/// </summary>
public class McpAIFunction : AIFunction
{
private readonly Tool _tool;
private readonly IMcpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="McpAIFunction"/> class.
/// </summary>
public McpAIFunction(Tool tool, IMcpClient client)
{
_tool = tool ?? throw new ArgumentNullException(nameof(tool));
_client = client ?? throw new ArgumentNullException(nameof(client));
}
/// <inheritdoc/>
public override string ToString() => _tool.Name;
/// <inheritdoc/>
public override JsonElement JsonSchema => AIFunctionUtilities.MapToJsonElement(_tool);
/// <inheritdoc/>
protected async override Task<object?> InvokeCoreAsync(IEnumerable<KeyValuePair<string, object?>> arguments, CancellationToken cancellationToken)
{
// Convert arguments to dictionary format expected by mcpdotnet
Dictionary<string, object> argDict = new();
foreach (var arg in arguments)
{
if (arg.Value is not null)
{
argDict[arg.Key] = arg.Value;
}
}
// Call the tool through mcpdotnet
var result = await _client.CallToolAsync(
_tool.Name,
argDict.Count == 0 ? new() : argDict,
cancellationToken: cancellationToken
);
// Extract the text content from the result
// For simplicity in this sample, we'll just concatenate all text content
return string.Join("\n", result.Content
.Where(c => c.Type == "text")
.Select(c => c.Text));
}
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<!-- license and package properties -->
<PackageId>McpDotNet.Extensions.AI</PackageId>
<Version>1.0.1.1</Version>
<Authors>PederHP</Authors>
<Description>Microsoft.Extensions.AI integration for the Model Context Protocol (MCP). Enables seamless use of MCP tools as AI functions in any IChatClient implementation.</Description>
<PackageProjectUrl>https://github.com/PederHP/mcpdotnet/src/McpDotNet.Extensions.AI</PackageProjectUrl>
<RepositoryUrl>https://github.com/PederHP/mcpdotnet</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageTags>mcp;ai;microsoft-extensions-ai;chatclient;llm</PackageTags>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<!-- Assembly properties -->
<AssemblyName>McpDotNet.Extensions.AI</AssemblyName>
<RootNamespace>McpDotNet.Extensions.AI</RootNamespace>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="McpDotNet.Extensions.AI.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.3.0-preview.1.25114.11" />
<PackageReference Include="Microsoft.Extensions.AI" Version="9.3.0-preview.1.25114.11" />
<PackageReference Include="mcpdotnet" Version="1.0.1.1" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,100 @@
using McpDotNet.Client;
using McpDotNet.Configuration;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace McpDotNet.Extensions.AI;
/// <summary>
/// Represents a scope that manages a connection session with one or more MCP servers.
/// Compatible with both stdio and SSE transports.
///
/// Disposing the scope will dispose all clients and tools, and close all connections.
/// </summary>
public class McpSessionScope : IAsyncDisposable
{
private readonly List<IMcpClient> _clients = new();
private bool _disposed;
/// <summary>
/// The list of tools exposed by the servers in this scope.
/// </summary>
public IList<AITool> Tools { get; private set; }
/// <summary>
/// The server instructions provided by the servers in this scope.
/// If a server does not provide instructions, they will not be included, so the list may be empty.
/// </summary>
public IReadOnlyList<string> ServerInstructions { get; private set; } = [];
/// <summary>
/// Creates a new session scope with a single server.
/// </summary>
/// <param name="serverConfig">A configuration object describing the MCP server.</param>
/// <param name="options">An options object with the client name and capabilities. Passed to the server.</param>
/// <param name="loggerFactory">A logger factory for mcpdotnet.</param>
/// <returns>A session scope which will keep the connection alive until disposed.</returns>
public static async Task<McpSessionScope> CreateAsync(McpServerConfig serverConfig,
McpClientOptions? options = null,
ILoggerFactory? loggerFactory = null)
{
var scope = new McpSessionScope();
var client = await scope.AddClientAsync(serverConfig, options, loggerFactory);
var tools = await client.ListToolsAsync();
scope.Tools = tools.Tools.Select(t => new McpAIFunction(t, client)).ToList<AITool>();
if (!string.IsNullOrEmpty(client.ServerInstructions))
{
scope.ServerInstructions = [client.ServerInstructions];
}
return scope;
}
/// <summary>
/// Creates a new session scope with multiple servers.
/// </summary>
/// <param name="serverConfigs">Configuration objects describing the MCP servers.</param>
/// <param name="options">An options object with the client name and capabilities. Passed to the servers.</param>
/// <param name="loggerFactory">A logger factory for mcpdotnet.</param>
/// <returns>A session scope which keep the connections alive until disposed.</returns>
public static async Task<McpSessionScope> CreateAsync(IEnumerable<McpServerConfig> serverConfigs,
McpClientOptions? options = null,
ILoggerFactory? loggerFactory = null)
{
var scope = new McpSessionScope();
foreach (var config in serverConfigs)
{
var client = await scope.AddClientAsync(config, options, loggerFactory);
var tools = await client.ListToolsAsync();
scope.Tools = scope.Tools.Concat(tools.Tools.Select(t => new McpAIFunction(t, client))).ToList();
}
scope.ServerInstructions = scope._clients.Select(c => c.ServerInstructions).Where(s => !string.IsNullOrEmpty(s)).ToList()!;
return scope;
}
private async Task<IMcpClient> AddClientAsync(McpServerConfig config,
McpClientOptions? options,
ILoggerFactory? loggerFactory = null)
{
var factory = new McpClientFactory([config],
options ?? new() { ClientInfo = new() { Name = "AnonymousClient", Version = "1.0.0.0" } },
loggerFactory ?? NullLoggerFactory.Instance);
var client = await factory.GetClientAsync(config.Id);
_clients.Add(client);
return client;
}
/// </inheritdoc>
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
foreach (var client in _clients)
{
await client.DisposeAsync();
}
_clients.Clear();
Tools = [];
}
}

View file

@ -0,0 +1,17 @@
using McpDotNet.Client;
using McpDotNet.Protocol.Types;
using Microsoft.Extensions.AI;
namespace McpDotNet.Extensions.AI;
/// <summary>
/// Utility class for converting an MCP Tool to an Microsoft.Extensions.AI.Abstractions AITool.
/// </summary>
public static class McpToolExtensions
{
/// <summary>
/// Converts an MCP Tool to an AITool.
/// </summary>
public static AITool ToAITool(this Tool tool, IMcpClient client)
=> new McpAIFunction(tool, client);
}

View file

@ -0,0 +1,83 @@
# McpDotNet.Extensions.AI
[![NuGet version](https://img.shields.io/nuget/v/McpDotNet.Extensions.AI.svg)](https://www.nuget.org/packages/McpDotNet.Extensions.AI/)
Microsoft.Extensions.AI integration for the Model Context Protocol (MCP). Enables seamless use of MCP tools as AI functions in any IChatClient implementation. Built on top of [mcpdotnet](https://github.com/PederHP/mcpdotnet).
## About MCP
The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). It enables secure integration between LLMs and various data sources and tools.
For more information about MCP:
- [Official Documentation](https://modelcontextprotocol.io/)
- [Protocol Specification](https://spec.modelcontextprotocol.io/)
- [GitHub Organization](https://github.com/modelcontextprotocol)
## Design Goals
The goal of this library is to provide a simple and efficient way to integrate MCP capabilities with Microsoft.Extensions.AI.Abstractions. It is designed to be easy to use, wrapping boilerplate code and providing a clean API for AI developers to use leverage MCP capabilities without having to worry about the underlying protocol.
## Features
- Easy lifecycle management of MCP connections
- Seamless mapping of MCP tools to Microsoft.Extensions.AI.Abstractions AIFunction objects
- Use convenience methods, while still having access to the full MCP protocol through the underlying mcpdotnet library
- Compatible with .NET 8.0 and later
## Getting Started (Client)
To use McpDotNet.Extensions.AI, first install it via NuGet:
```powershell
dotnet add package McpDotNet.Extensions.AI
```
Create a configuration object for the MCP server you want to connect to:
```csharp
var config = new McpServerConfig
{
Id = "everything",
Name = "Everything",
TransportType = "stdio",
TransportOptions = new Dictionary<string, string>
{
["command"] = "npx",
["arguments"] = "-y @modelcontextprotocol/server-everything",
}
};
```
Then create an MCP session scope and use it with a chat client of your choice:
```csharp
await using var sessionScope = await McpSessionScope.CreateAsync(config);
IChatClient openaiClient = new OpenAIClient("sk-your-key")
.AsChatClient("gpt-4o-mini");
IChatClient chatClient = new ChatClientBuilder(openaiClient)
.UseFunctionInvocation()
.Build();
// Create message list
IList<ChatMessage> messages =
[
// Add a system message
new(ChatRole.System, "You are a helpful assistant."),
new(ChatRole.User, "Placeholder for the actual user message.")
];
// Call the chat client
var response = await chatClient.GetResponseAsync(messages,
new() { Tools = sessionScope.Tools });
```
As you can see, all you really need to do is create one or more configuration objects matching the MCP servers you want to use, create an MCP session scope, and then the tools exposed by the server(s) will be available to you through the `Tools` property of the `McpSessionScope` object.
The `McpSessionScope` object implements `IAsyncDisposable`, and managing the connection lifecycle is as simple as using the `await using` pattern. Note that you have to keep the `McpSessionScope` object alive for as long as you want to use the tools it provides.
## Roadmap
- Convenience methods for other capabilities: prompts, sampling, resources, etc.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.