Integrate Microsoft.Extensions.AI as a foundational building block (#94)

* Integrate Microsoft.Extensions.AI as a foundational building block

As with logging abstractions coming from M.E.Logging and DI abstractions coming from M.E.DependencyInjection, M.E.AI provides the relevant AI abstractions.

- Adds AsAIFunction and GetAIFunctionsAsync methods for getting functions for tools via a client.
- Uses AIFunctionFactory to implement McpServerBuilderExtensions.WithTools.
- Adds a RequestSamplingAsync overload that accepts ChatMessages/Options.
- Adds an AsSamplingChatClient method that provides an IChatClient usable on the server to request sampling of the client.
- Adds a CreateSamplingHandler method to enable an IChatClient to be easily used to satisfy sampling requests on the client.
- Deprecate McpDotNet.Extensions.AI.

* Address PR feedback
This commit is contained in:
Stephen Toub 2025-03-17 16:34:00 -04:00 • committed by GitHub
commit 4597bbd7c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 801 additions and 927 deletions

View file

@ -99,6 +99,21 @@ Additional examples and documentation will be added as in the near future.
Remember you can connect to any MCP server, not just ones created using mcpdotnet. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.
Tools can be exposed easily as `AIFunction` instances so that they are immediately usable with `IChatClient`s.
```csharp
// Get available functions.
IList<AIFunction> tools = await client.GetAIFunctionsAsync();
// Call the chat client using the tools.
IChatClient chatClient = ...;
var response = await chatClient.GetResponseAsync(
"your prompt here",
new()
{
Tools = [.. tools],
});
```
## Getting Started (Server)
Here is an example of how to create an MCP server and register all tools from the current application.

View file

@ -15,8 +15,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mcpdotnet.TestServer", "tes
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "McpDotNet.Extensions.AI", "src\McpDotNet.Extensions.AI\McpDotNet.Extensions.AI.csproj", "{B3E019B8-3459-4D52-864E-703DDA2C02AD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "McpDotNet.Extensions.AI.Tests", "tests\McpDotNet.Extensions.AI.Tests\McpDotNet.Extensions.AI.Tests.csproj", "{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestServerWithHosting", "samples\TestServerWithHosting\TestServerWithHosting.csproj", "{6499876E-2F76-44A8-B6EB-5B889C6E9B7F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
@ -53,10 +51,6 @@ Global
{B3E019B8-3459-4D52-864E-703DDA2C02AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3E019B8-3459-4D52-864E-703DDA2C02AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3E019B8-3459-4D52-864E-703DDA2C02AD}.Release|Any CPU.Build.0 = Release|Any CPU
{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2}.Release|Any CPU.Build.0 = Release|Any CPU
{6499876E-2F76-44A8-B6EB-5B889C6E9B7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6499876E-2F76-44A8-B6EB-5B889C6E9B7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6499876E-2F76-44A8-B6EB-5B889C6E9B7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -70,7 +64,6 @@ Global
{76E295FA-9E85-7B99-332A-2CDBFCD5860A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{CA0BB450-1903-2F92-A68D-1285976551D6} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{7C229573-A085-4ECC-8131-958CDA2BE731} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{67BEF596-AD39-4BDD-B505-31DE7FF0C8D2} = {2A77AF5C-138A-4EBB-9A13-9205DCD67928}
{6499876E-2F76-44A8-B6EB-5B889C6E9B7F} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution

View file

@ -1,92 +1,79 @@
using McpDotNet.Client;
using McpDotNet.Configuration;
using McpDotNet.Extensions.AI;
using McpDotNet.Protocol.Transport;
using Microsoft.Extensions.AI;
using OpenAI;
internal class Program
try
{
private static async Task<IMcpClient> GetMcpClientAsync()
Console.WriteLine("Initializing MCP 'everything' server");
await using var client = await GetMcpClientAsync();
Console.WriteLine("MCP 'everything' server initialized");
Console.WriteLine("Listing tools...");
var mappedTools = await client.GetAIFunctionsAsync();
Console.WriteLine("Tools available:");
foreach (var tool in mappedTools)
{
McpClientOptions clientOptions = new()
{
ClientInfo = new() { Name = "SimpleToolsConsole", Version = "1.0.0" }
};
McpServerConfig serverConfig = new()
{
Id = "everything",
Name = "Everything",
TransportType = TransportTypes.StdIo,
TransportOptions = new Dictionary<string, string>
{
["command"] = "npx",
["arguments"] = "-y @modelcontextprotocol/server-everything",
}
};
return await McpClientFactory.CreateAsync(serverConfig, clientOptions);
Console.WriteLine($" {tool}");
}
private static async Task Main(string[] args)
Console.WriteLine("Starting chat with GPT-4o-mini...");
// Note: We use then Microsoft.Extensions.AI.OpenAI client here, but it could be any other MEAI client.
// Provide your own OPENAI_API_KEY via an environment variable, secret or file-based appsettings. Do not hardcode it.
IChatClient chatClient = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
.AsChatClient("gpt-4o-mini")
.AsBuilder()
.UseFunctionInvocation()
.Build();
// Create message list
IList<Microsoft.Extensions.AI.ChatMessage> messages =
[
// Add a system message
new(ChatRole.System, "You are a helpful assistant, helping us test MCP server functionality."),
];
// If MCP server provides instructions, add them as an additional system message (you could also add it as a content part)
if (!string.IsNullOrEmpty(client.ServerInstructions))
{
try
{
Console.WriteLine("Initializing MCP 'everything' server");
await using var client = await GetMcpClientAsync();
Console.WriteLine("MCP 'everything' server initialized");
Console.WriteLine("Listing tools...");
var mappedTools = await client.ListToolsAsync().Select(t => t.ToAITool(client)).ToListAsync();
Console.WriteLine("Tools available:");
foreach (var tool in mappedTools)
{
Console.WriteLine(" " + tool);
}
Console.WriteLine("Starting chat with GPT-4o-mini...");
// Note: We use then Microsoft.Extensions.AI.OpenAI client here, but it could be any other MEAI client.
// Provide your own OPENAI_API_KEY via an environment variable, secret or file-based appsettings. Do not hardcode it.
IChatClient openaiClient = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
.AsChatClient("gpt-4o-mini");
// Note: To use the ChatClientBuilder you need to install the Microsoft.Extensions.AI package
IChatClient chatClient = new ChatClientBuilder(openaiClient)
.UseFunctionInvocation()
.Build();
// Create message list
IList<Microsoft.Extensions.AI.ChatMessage> messages =
[
// Add a system message
new(ChatRole.System, "You are a helpful assistant, helping us test MCP server functionality."),
];
// If MCP server provides instructions, add them as an additional system message (you could also add it as a content part)
if (!string.IsNullOrEmpty(client.ServerInstructions))
{
messages.Add(new(ChatRole.System, client.ServerInstructions));
}
// Add a user message
messages.Add(new(ChatRole.User, "Please call the echo tool with the string 'Hello MCP!' and give me the response as-is."));
// Call the chat client
Console.WriteLine("Asking GPT-4o-mini to call the Echo Tool...");
var response = chatClient.GetStreamingResponseAsync(
messages,
new() { Tools = mappedTools });
await foreach (var update in response)
{
Console.Write(update);
}
Console.WriteLine();
Console.WriteLine("Chat with GPT-4o-mini complete");
}
catch (Exception ex)
{
Console.WriteLine("Error occurred: " + ex.Message);
}
messages.Add(new(ChatRole.System, client.ServerInstructions));
}
// Add a user message
messages.Add(new(ChatRole.User, "Please call the echo tool with the string 'Hello MCP!' and give me the response as-is."));
// Call the chat client
Console.WriteLine("Asking GPT-4o-mini to call the Echo Tool...");
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. mappedTools] }))
{
Console.Write(update);
}
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
async Task<IMcpClient> GetMcpClientAsync()
{
McpClientOptions clientOptions = new()
{
ClientInfo = new() { Name = "SimpleToolsConsole", Version = "1.0.0" }
};
McpServerConfig serverConfig = new()
{
Id = "everything",
Name = "Everything",
TransportType = TransportTypes.StdIo,
TransportOptions = new Dictionary<string, string>
{
["command"] = "npx",
["arguments"] = "-y @modelcontextprotocol/server-everything",
}
};
return await McpClientFactory.CreateAsync(serverConfig, clientOptions);
}

View file

@ -1,26 +0,0 @@
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 ?? [],
["required"] = tool.InputSchema?.Required ?? []
};
// Convert to JsonElement
return JsonSerializer.SerializeToElement(schemaObj);
}
}

View file

@ -1,60 +0,0 @@
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 Name => _tool.Name;
/// <inheritdoc/>
public override string Description => _tool.Description ?? string.Empty;
/// <inheritdoc/>
public override JsonElement JsonSchema => AIFunctionUtilities.MapToJsonElement(_tool);
/// <inheritdoc/>
protected async override Task<object?> InvokeCoreAsync(IEnumerable<KeyValuePair<string, object?>> arguments, CancellationToken cancellationToken)
{
if (arguments is null)
{
throw new ArgumentNullException(nameof(arguments));
}
// Convert arguments to dictionary format expected by mcpdotnet
Dictionary<string, object> argDict = [];
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, cancellationToken).ConfigureAwait(false);
// Extract the text content from the result.
return string.Join("\n", result.Content
.Where(c => c.Type == "text")
.Select(c => c.Text));
}
}

View file

@ -33,17 +33,6 @@
<None Include="README.md" Pack="true" PackagePath="/" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="McpDotNet.Extensions.AI.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\mcpdotnet\mcpdotnet.csproj" />
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.3.0-preview.1.25161.3" />
<PackageReference Include="Microsoft.Extensions.AI" Version="9.3.0-preview.1.25161.3" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="System.Text.Json" Version="9.0.3" />
</ItemGroup>

View file

@ -1,123 +0,0 @@
using McpDotNet.Client;
using McpDotNet.Configuration;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
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 sealed class McpSessionScope : IAsyncDisposable
{
private readonly List<IMcpClient> _clients = [];
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)
{
if (serverConfig is null)
{
throw new ArgumentNullException(nameof(serverConfig));
}
var scope = new McpSessionScope();
var client = await AddClientAsync(serverConfig, options, loggerFactory).ConfigureAwait(false);
scope.Tools = [];
await foreach (var tool in client.ListToolsAsync().ConfigureAwait(false))
{
scope.Tools.Add(new McpAIFunction(tool, client));
}
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)
{
if (serverConfigs is null)
{
throw new ArgumentNullException(nameof(serverConfigs));
}
var scope = new McpSessionScope();
foreach (var config in serverConfigs)
{
var client = await AddClientAsync(config, options, loggerFactory).ConfigureAwait(false);
scope.Tools ??= [];
await foreach (var tool in client.ListToolsAsync().ConfigureAwait(false))
{
scope.Tools.Add(new McpAIFunction(tool, client));
}
}
scope.ServerInstructions = scope._clients.Select(c => c.ServerInstructions).Where(s => !string.IsNullOrEmpty(s)).ToList()!;
return scope;
}
private static Task<IMcpClient> AddClientAsync(
McpServerConfig serverConfig,
McpClientOptions? clientOptions,
ILoggerFactory? loggerFactory = null)
{
return McpClientFactory.CreateAsync(
serverConfig,
clientOptions ?? new() { ClientInfo = new() { Name = "AnonymousClient", Version = "1.0.0.0" } },
loggerFactory: loggerFactory);
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
foreach (var client in _clients)
{
await client.DisposeAsync().ConfigureAwait(false);
}
_clients.Clear();
Tools = [];
GC.SuppressFinalize(this);
}
}

View file

@ -1,17 +0,0 @@
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

@ -1,83 +1,4 @@
# 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 = TransportTypes.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.
This package is deprecated and no longer needed. The functionality it exposes is part of the core mcpdotnet library. Please remove references to it.

View file

@ -8,11 +8,6 @@ namespace McpDotNet.Client;
/// </summary>
public interface IMcpClient : IAsyncDisposable
{
/// <summary>
/// Gets a value indicating whether the client has been initialized.
/// </summary>
bool IsInitialized { get; }
/// <summary>
/// Gets the capabilities supported by the server.
/// </summary>

View file

@ -1,7 +1,11 @@
using McpDotNet.Protocol.Messages;
using McpDotNet.Protocol.Types;
using McpDotNet.Utils;
using Microsoft.Extensions.AI;
using System.Runtime.CompilerServices;
using System.Text.Json;
#pragma warning disable CA1508 // Avoid dead conditional code
namespace McpDotNet.Client;
@ -264,6 +268,175 @@ public static class McpClientExtensions
cancellationToken);
}
/// <summary>Gets <see cref="AIFunction"/> instances for all of the tools available through the specified <see cref="IMcpClient"/>.</summary>
/// <param name="client">The client for which <see cref="AIFunction"/> instances should be created.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>A task containing a list of the available functions.</returns>
public static async Task<IList<AIFunction>> GetAIFunctionsAsync(this IMcpClient client, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
List<AIFunction> functions = [];
await foreach (var tool in client.ListToolsAsync(cancellationToken).ConfigureAwait(false))
{
functions.Add(AsAIFunction(client, tool));
}
return functions;
}
/// <summary>Gets an <see cref="AIFunction"/> for invoking <see cref="Tool"/> via this <see cref="IMcpClient"/>.</summary>
/// <param name="client">The client with which to perform the invocation.</param>
/// <param name="tool">The tool to be invoked.</param>
/// <returns>An <see cref="AIFunction"/> for performing the call.</returns>
/// <remarks>
/// This operation does not validate that <paramref name="tool"/> is valid for the specified <paramref name="client"/>.
/// If the tool is not valid for the client, it will fail when invoked.
/// </remarks>
public static AIFunction AsAIFunction(this IMcpClient client, Tool tool)
{
Throw.IfNull(client);
Throw.IfNull(tool);
return new McpAIFunction(client, tool);
}
/// <summary>
/// Converts the contents of a <see cref="CreateMessageRequestParams"/> into a pair of
/// <see cref="IEnumerable{ChatMessage}"/> and <see cref="ChatOptions"/> instances to use
/// as inputs into a <see cref="IChatClient"/> operation.
/// </summary>
/// <param name="requestParams"></param>
/// <returns>The created pair of messages and options.</returns>
internal static (IList<ChatMessage> Messages, ChatOptions? Options) ToChatClientArguments(
this CreateMessageRequestParams requestParams)
{
Throw.IfNull(requestParams);
ChatOptions? options = null;
if (requestParams.MaxTokens is int maxTokens)
{
(options ??= new()).MaxOutputTokens = maxTokens;
}
if (requestParams.Temperature is float temperature)
{
(options ??= new()).Temperature = temperature;
}
if (requestParams.StopSequences is { } stopSequences)
{
(options ??= new()).StopSequences = stopSequences.ToArray();
}
List<ChatMessage> messages = [];
foreach (SamplingMessage sm in requestParams.Messages)
{
ChatMessage message = new()
{
Role = sm.Role == Role.User ? ChatRole.User : ChatRole.Assistant,
};
if (sm.Content is { Type: "text" })
{
message.Contents.Add(new TextContent(sm.Content.Text));
}
else if (sm.Content is { Type: "image", MimeType: not null, Data: not null })
{
message.Contents.Add(new DataContent(Convert.FromBase64String(sm.Content.Data), sm.Content.MimeType));
}
else if (sm.Content is { Type: "resource", Resource: not null })
{
ResourceContents resource = sm.Content.Resource;
if (resource.Text is not null)
{
message.Contents.Add(new TextContent(resource.Text));
}
if (resource.Blob is not null && resource.MimeType is not null)
{
message.Contents.Add(new DataContent(Convert.FromBase64String(resource.Blob), resource.MimeType));
}
}
messages.Add(message);
}
return (messages, options);
}
/// <summary>Converts the contents of a <see cref="ChatResponse"/> into a <see cref="CreateMessageResult"/>.</summary>
/// <param name="chatResponse">The <see cref="ChatResponse"/> whose contents should be extracted.</param>
/// <returns>The created <see cref="CreateMessageResult"/>.</returns>
internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)
{
Throw.IfNull(chatResponse);
// The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports
// only either a single blob of text or a single image. Heuristically, we'll use an image if there is one
// in any of the response messages, or we'll use all the text from them concatenated, otherwise.
ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();
Content? content = null;
if (lastMessage is not null)
{
foreach (var lmc in lastMessage.Contents)
{
if (lmc is DataContent dc && dc.HasTopLevelMediaType("image"))
{
content = new()
{
Type = "image",
MimeType = dc.MediaType,
Data = Convert.ToBase64String(dc.Data
#if NET
.Span),
#else
.ToArray()),
#endif
};
}
}
}
content ??= new()
{
Text = lastMessage?.Text ?? string.Empty,
Type = "text",
};
return new()
{
Content = content,
Model = chatResponse.ModelId ?? "unknown",
Role = lastMessage?.Role == ChatRole.User ? "user" : "assistant",
StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? "maxTokens" : "endTurn",
};
}
/// <summary>
/// Creates a sampling handler for use with <see cref="SamplingCapability.SamplingHandler"/> that will
/// satisfy sampling requests using the specified <see cref="IChatClient"/>.
/// </summary>
/// <param name="chatClient">The <see cref="IChatClient"/> with which to satisfy sampling requests.</param>
/// <returns>The created handler delegate.</returns>
public static Func<CreateMessageRequestParams?, CancellationToken, Task<CreateMessageResult>> CreateSamplingHandler(this IChatClient chatClient)
{
Throw.IfNull(chatClient);
return async (requestParams, cancellationToken) =>
{
Throw.IfNull(requestParams);
var (messages, options) = requestParams.ToChatClientArguments();
var response = await chatClient.GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);
return response.ToCreateMessageResult();
};
}
private static JsonRpcRequest CreateRequest(string method, Dictionary<string, object?>? parameters) =>
new JsonRpcRequest
{
@ -288,4 +461,45 @@ public static class McpClientExtensions
return parameters;
}
/// <summary>Provides an AI function that calls a tool through <see cref="IMcpClient"/>.</summary>
private sealed class McpAIFunction(IMcpClient client, Tool tool) : AIFunction
{
/// <inheritdoc/>
public override string Name => tool.Name;
/// <inheritdoc/>
public override string Description => tool.Description ?? string.Empty;
/// <inheritdoc/>
public override JsonElement JsonSchema =>
JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
["type"] = "object",
["title"] = tool.Name,
["description"] = tool.Description ?? string.Empty,
["properties"] = tool.InputSchema?.Properties ?? [],
["required"] = tool.InputSchema?.Required ?? []
});
/// <inheritdoc/>
protected async override Task<object?> InvokeCoreAsync(
IEnumerable<KeyValuePair<string, object?>> arguments, CancellationToken cancellationToken)
{
Throw.IfNull(arguments);
Dictionary<string, object> argDict = [];
foreach (var arg in arguments)
{
if (arg.Value is not null)
{
argDict[arg.Key] = arg.Value;
}
}
CallToolResponse result = await client.CallToolAsync(tool.Name, argDict, cancellationToken).ConfigureAwait(false);
return JsonSerializer.SerializeToElement(result);
}
}
}

View file

@ -1,13 +1,10 @@
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Reflection;
using System.Text.Json;
using McpDotNet.Configuration;
using McpDotNet.Protocol.Types;
using McpDotNet.Server;
using McpDotNet.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.AI;
namespace McpDotNet;
@ -21,6 +18,7 @@ public static partial class McpServerBuilderExtensions
/// </summary>
/// <typeparam name="TTool">The tool type.</typeparam>
/// <param name="builder">The builder instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
public static IMcpServerBuilder WithTool<TTool>(this IMcpServerBuilder builder)
{
return WithTools(builder, typeof(TTool));
@ -29,6 +27,7 @@ public static partial class McpServerBuilderExtensions
/// Adds all tools marked with <see cref="McpToolTypeAttribute"/> from the current assembly to the server.
/// </summary>
/// <param name="builder">The builder instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder)
{
return WithToolsFromAssembly(builder, Assembly.GetCallingAssembly());
@ -39,46 +38,110 @@ public static partial class McpServerBuilderExtensions
/// </summary>
/// <param name="builder">The builder instance.</param>
/// <param name="toolTypes">Types with marked methods to add as tools to the server.</param>
public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, params Type[] toolTypes)
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="toolTypes"/> is <see langword="null"/>.</exception>
public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, params IEnumerable<Type> toolTypes)
{
Throw.IfNull(builder);
Throw.IfNull(toolTypes);
if (toolTypes is null || toolTypes.Length == 0)
List<AIFunction> functions = [];
foreach (var toolType in toolTypes)
{
throw new ArgumentException("At least one tool type must be provided.", nameof(toolTypes));
if (toolType is null)
{
throw new ArgumentNullException(nameof(toolTypes), $"A tool type provided by the enumerator was null.");
}
foreach (var method in toolType.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (method.GetCustomAttribute<McpToolAttribute>() is not { } attribute)
{
continue;
}
functions.Add(AIFunctionFactory.Create(method, target: null, new()
{
Name = attribute.Name ?? method.Name,
}));
}
}
return WithTools(builder, functions);
}
/// <summary>
/// Adds tools to the server.
/// </summary>
/// <param name="builder">The builder instance.</param>
/// <param name="functions"><see cref="AIFunction"/> instances to use as the tools.</param>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="functions"/> is <see langword="null"/>.</exception>
public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, params IEnumerable<AIFunction> functions)
{
Throw.IfNull(builder);
Throw.IfNull(functions);
List<Tool> tools = [];
Dictionary<string, Func<RequestContext<CallToolRequestParams>, CancellationToken, Task<CallToolResponse>>> callbacks = [];
foreach (var type in toolTypes)
foreach (AIFunction function in functions)
{
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
if (function is null)
{
var attribute = method.GetCustomAttribute<McpToolAttribute>();
if (attribute != null)
{
var tool = CreateTool(method, attribute);
tools.Add(tool);
callbacks.Add(tool.Name, async (request, cancellationToken) => await CallTool(request, method, cancellationToken).ConfigureAwait(false));
// register type because method is not static and so we need an instance
if (!method.IsStatic)
builder.Services.AddScoped(type);
}
throw new ArgumentNullException(nameof(functions), $"A function provided by the enumerator was null.");
}
tools.Add(new()
{
Name = function.Name,
Description = function.Description,
InputSchema = JsonSerializer.Deserialize<JsonSchema>(function.JsonSchema),
});
callbacks.Add(function.Name, async (request, cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();
object? result;
try
{
result = await function.InvokeAsync((request.Params?.Arguments ?? [])!, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (e is not OperationCanceledException)
{
return new CallToolResponse()
{
IsError = true,
Content = [new() { Text = e.Message, Type = "text" }],
};
}
switch (result)
{
case JsonElement je when je.ValueKind == JsonValueKind.Null:
return new() { Content = [] };
case JsonElement je when je.ValueKind == JsonValueKind.Array:
return new() { Content = je.EnumerateArray().Select(x => new Content() { Text = x.ToString(), Type = "text" }).ToList() };
default:
return new() { Content = [new() { Text = result?.ToString(), Type = "text" }] };
}
});
}
builder.WithListToolsHandler((_, _) => Task.FromResult(new ListToolsResult() { Tools = tools }));
builder.WithCallToolHandler(async (request, cancellationToken) =>
{
if (request.Params != null && callbacks.TryGetValue(request.Params.Name, out var callback))
return await callback(request, cancellationToken).ConfigureAwait(false);
if (request.Params is null || !callbacks.TryGetValue(request.Params.Name, out var callback))
{
throw new McpServerException($"Unknown tool '{request.Params?.Name}'");
}
throw new McpServerException($"Unknown tool: {request.Params?.Name}");
return await callback(request, cancellationToken).ConfigureAwait(false);
});
return builder;
@ -89,6 +152,7 @@ public static partial class McpServerBuilderExtensions
/// </summary>
/// <param name="builder">The builder instance.</param>
/// <param name="assembly">The assembly to load the types from. Null to get the current assembly</param>
/// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception>
public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? assembly = null)
{
assembly ??= Assembly.GetCallingAssembly();
@ -97,15 +161,14 @@ public static partial class McpServerBuilderExtensions
foreach (var type in assembly.GetTypes())
{
bool hasToolTypeAttribute = type.GetCustomAttribute<McpToolTypeAttribute>() != null;
if (!hasToolTypeAttribute)
continue;
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
if (type.GetCustomAttribute<McpToolTypeAttribute>() is null)
{
var attribute = method.GetCustomAttribute<McpToolAttribute>();
if (attribute != null)
continue;
}
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (method.GetCustomAttribute<McpToolAttribute>() is not null)
{
toolTypes.Add(type);
break;
@ -113,149 +176,8 @@ public static partial class McpServerBuilderExtensions
}
}
if (toolTypes.Count == 0)
{
throw new ArgumentException("No types with marked methods found in the assembly.", nameof(assembly));
}
return WithTools(builder, [.. toolTypes]);
}
private static Tool CreateTool(MethodInfo method, McpToolAttribute mcpAttribute)
{
Dictionary<string, JsonSchemaProperty> properties = [];
List<string>? requiredProperties = null;
foreach (var parameter in method.GetParameters())
{
if (parameter.ParameterType == typeof(CancellationToken))
continue;
var parameterDescriptionAttr = parameter.GetCustomAttribute<DescriptionAttribute>();
properties.Add(parameter.Name ?? "NoName", new JsonSchemaProperty()
{
Type = GetParameterType(parameter.ParameterType),
Description = parameterDescriptionAttr?.Description,
});
if (!parameter.HasDefaultValue)
{
requiredProperties ??= [];
requiredProperties.Add(parameter.Name ?? "NoName");
}
}
return new Tool()
{
Name = mcpAttribute.Name ?? method.Name,
Description = method.GetCustomAttribute<DescriptionAttribute>()?.Description,
InputSchema = new JsonSchema()
{
Type = "object",
Properties = properties,
Required = requiredProperties
},
};
}
private static string GetParameterType(Type parameterType)
{
return parameterType switch
{
Type t when t == typeof(string) => "string",
Type t when t == typeof(int) || t == typeof(double) || t == typeof(float) => "number",
Type t when t == typeof(bool) => "boolean",
Type t when t.IsArray => "array",
Type t when t == typeof(DateTime) || t == typeof(DateTimeOffset) => "string",
_ => "object"
};
}
private static async Task<CallToolResponse> CallTool(RequestContext<CallToolRequestParams> request, MethodInfo method, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var methodParameters = method.GetParameters();
List<object?> parameters = ResolveParameters(request, methodParameters, cancellationToken);
using var scope = request.Server.ServiceProvider?.CreateScope();
var objectInstance = CreateObjectInstance(method, scope?.ServiceProvider);
object? result;
try
{
const BindingFlags InvokeFlags =
#if NET
BindingFlags.DoNotWrapExceptions |
#endif
BindingFlags.Default;
result = method.Invoke(objectInstance, InvokeFlags, binder: null, [.. parameters], culture: null);
}
catch (TargetInvocationException e) when (e.InnerException is not null)
{
ExceptionDispatchInfo.Capture(e.InnerException).Throw();
throw; // unreachable
}
if (result is Task task)
{
await task.ConfigureAwait(false);
var resultProperty = task.GetType().GetProperty("Result");
result = resultProperty?.GetValue(task);
}
if (result is string resultString)
return new CallToolResponse { Content = [new Content() { Text = resultString, Type = "text" }] };
if (result is string[] resultStringArray)
return new CallToolResponse { Content = [.. resultStringArray.Select(s => new Content() { Text = s, Type = "text" })] };
if (result is null)
return new CallToolResponse { Content = [new Content() { Text = "null" }] };
if (result is JsonElement jsonElement)
return new CallToolResponse { Content = [new Content() { Text = jsonElement.GetRawText(), Type = "text" }] };
return new CallToolResponse { Content = [new Content() { Text = result.ToString(), Type = "text" }] };
}
private static List<object?> ResolveParameters(RequestContext<CallToolRequestParams> request, ParameterInfo[] methodParameters, CancellationToken cancellationToken)
{
var parameters = new List<object?>(methodParameters.Length);
foreach (var parameter in methodParameters)
{
if (parameter.ParameterType == typeof(CancellationToken))
{
parameters.Add(cancellationToken);
}
else if (request.Params?.Arguments != null && request.Params.Arguments.TryGetValue(parameter.Name ?? "NoName", out var value))
{
if (value is JsonElement element)
value = JsonSerializer.Deserialize(element.GetRawText(), parameter.ParameterType);
parameters.Add(Convert.ChangeType(value, parameter.ParameterType, CultureInfo.InvariantCulture));
}
else
{
if (!parameter.HasDefaultValue)
throw new McpServerException($"Missing required argument '{parameter.Name}'.");
parameters.Add(parameter.DefaultValue);
}
}
return parameters;
}
private static object? CreateObjectInstance(MethodInfo method, IServiceProvider? serviceProvider)
{
if (method.IsStatic)
return null;
if (serviceProvider != null)
return ActivatorUtilities.CreateInstance(serviceProvider, method.DeclaringType!);
return Activator.CreateInstance(method.DeclaringType!);
return toolTypes.Count > 0 ?
WithTools(builder, toolTypes) :
builder;
}
}

View file

@ -39,28 +39,4 @@ public class Content
/// </summary>
[JsonPropertyName("resource")]
public ResourceContents? Resource { get; set; }
/// <summary>
/// Validates the content object.
/// </summary>
/// <returns>Whether the type of tool content has the correct data fields provided.</returns>
public bool Validate()
{
if (Type == "text")
{
return !string.IsNullOrEmpty(Text);
}
else if (Type == "image")
{
return !string.IsNullOrEmpty(Data) && !string.IsNullOrEmpty(MimeType);
}
else if (Type == "resource")
{
return Resource != null;
}
else
{
return false;
}
}
}

View file

@ -21,7 +21,7 @@ public class CreateMessageRequestParams
/// The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("maxTokens")]
public int MaxTokens { get; init; }
public int? MaxTokens { get; init; }
/// <summary>
/// Messages requested by the server to be included in the prompt.

View file

@ -10,7 +10,7 @@ public class JsonSchema
/// The type of the schema, should be "object".
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
public string Type { get; set; } = "object";
/// <summary>
/// Map of property names to property definitions.

View file

@ -16,5 +16,5 @@ public class JsonSchemaProperty
/// A human-readable description of the property.
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("description")]
public string? Description { get; set; }
public string? Description { get; set; } = string.Empty;
}

View file

@ -1,4 +1,6 @@
namespace McpDotNet.Protocol.Types;
using System.Text.Json.Serialization;
namespace McpDotNet.Protocol.Types;
/// <summary>
/// Represents a tool that the server is capable of calling. Part of the ListToolsResponse.
@ -9,18 +11,18 @@ public class Tool
/// <summary>
/// The name of the tool.
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("name")]
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
/// <summary>
/// A human-readable description of the tool.
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("description")]
[JsonPropertyName("description")]
public string? Description { get; set; }
/// <summary>
/// A JSON Schema object defining the expected parameters for the tool.
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("inputSchema")]
[JsonPropertyName("inputSchema")]
public JsonSchema? InputSchema { get; set; }
}

View file

@ -1,6 +1,9 @@
using McpDotNet.Protocol.Messages;
using McpDotNet.Protocol.Types;
using McpDotNet.Utils;
using Microsoft.Extensions.AI;
using System.Runtime.CompilerServices;
using System.Text;
namespace McpDotNet.Server;
@ -8,8 +11,10 @@ namespace McpDotNet.Server;
public static class McpServerExtensions
{
/// <summary>
/// Requests the client to create a new message.
/// Requests to sample an LLM via the client.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="server"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">The client does not support sampling.</exception>
public static Task<CreateMessageResult> RequestSamplingAsync(
this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken)
{
@ -17,7 +22,7 @@ public static class McpServerExtensions
if (server.ClientCapabilities?.Sampling is null)
{
throw new McpServerException("Client does not support sampling");
throw new ArgumentException("Client connected to the server does not support sampling.", nameof(server));
}
return server.SendRequestAsync<CreateMessageResult>(
@ -25,9 +30,161 @@ public static class McpServerExtensions
cancellationToken);
}
/// <summary>
/// Requests to sample an LLM via the client.
/// </summary>
/// <param name="server">The server issueing the request.</param>
/// <param name="messages">The messages to send as part of the request.</param>
/// <param name="options">The options to use for the request.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>A task containing the response from the client.</returns>
/// <exception cref="ArgumentNullException"><paramref name="server"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">The client does not support sampling.</exception>
public static async Task<ChatResponse> RequestSamplingAsync(
this IMcpServer server,
IEnumerable<ChatMessage> messages, ChatOptions? options = default, CancellationToken cancellationToken = default)
{
Throw.IfNull(server);
Throw.IfNull(messages);
StringBuilder? systemPrompt = null;
List<SamplingMessage> samplingMessages = [];
foreach (var message in messages)
{
if (message.Role == ChatRole.System)
{
if (systemPrompt is null)
{
systemPrompt = new();
}
else
{
systemPrompt.AppendLine();
}
systemPrompt.Append(message.Text);
continue;
}
if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)
{
Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;
foreach (var content in message.Contents)
{
switch (content)
{
case TextContent textContent:
samplingMessages.Add(new()
{
Role = role,
Content = new()
{
Type = "text",
Text = textContent.Text,
},
});
break;
case DataContent dataContent when dataContent.HasTopLevelMediaType("image"):
samplingMessages.Add(new()
{
Role = role,
Content = new()
{
Type = "image",
MimeType = dataContent.MediaType,
Data = Convert.ToBase64String(dataContent.Data.
#if NET
Span),
#else
ToArray()),
#endif
},
});
break;
}
}
}
}
ModelPreferences? modelPreferences = null;
if (options?.ModelId is { } modelId)
{
modelPreferences = new() { Hints = [new() { Name = modelId }] };
}
var result = await server.RequestSamplingAsync(new()
{
Messages = samplingMessages,
MaxTokens = options?.MaxOutputTokens,
StopSequences = options?.StopSequences?.ToArray(),
SystemPrompt = systemPrompt?.ToString(),
Temperature = options?.Temperature,
ModelPreferences = modelPreferences,
}, cancellationToken).ConfigureAwait(false);
ChatMessage responseMessage = new()
{
Role = result.Role == "user" ? ChatRole.User : ChatRole.Assistant
};
if (result.Content is { Type: "text" })
{
responseMessage.Contents.Add(new TextContent(result.Content.Text));
}
else if (result.Content is { Type: "image", MimeType: not null, Data: not null })
{
responseMessage.Contents.Add(new DataContent(Convert.FromBase64String(result.Content.Data), result.Content.MimeType));
}
else if (result.Content is { Type: "resource" } && result.Content.Resource is { } resourceContents)
{
if (resourceContents.Text is not null)
{
responseMessage.Contents.Add(new TextContent(resourceContents.Text));
}
if (resourceContents.Blob is not null && resourceContents.MimeType is not null)
{
responseMessage.Contents.Add(new DataContent(Convert.FromBase64String(resourceContents.Blob), resourceContents.MimeType));
}
}
return new(responseMessage)
{
ModelId = result.Model,
FinishReason = result.StopReason switch
{
"maxTokens" => ChatFinishReason.Length,
"endTurn" or "stopSequence" or _ => ChatFinishReason.Stop,
}
};
}
/// <summary>Creates an <see cref="IChatClient"/> that can be used to send sampling requests to the client.</summary>
/// <param name="server">The server to be wrapped as an <see cref="IChatClient"/>.</param>
/// <returns>The <see cref="IChatClient"/> that can be used to issue sampling requests to the client.</returns>
/// <exception cref="ArgumentNullException"><paramref name="server"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">The client does not support sampling.</exception>
public static IChatClient AsSamplingChatClient(this IMcpServer server)
{
Throw.IfNull(server);
if (server.ClientCapabilities?.Sampling is null)
{
throw new ArgumentException("Client connected to the server does not support sampling.", nameof(server));
}
return new SamplingChatClient(server);
}
/// <summary>
/// Requests the client to list the roots it exposes.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="server"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">The client does not support roots.</exception>
public static Task<ListRootsResult> RequestRootsAsync(
this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken)
{
@ -35,11 +192,46 @@ public static class McpServerExtensions
if (server.ClientCapabilities?.Roots is null)
{
throw new McpServerException("Client does not support roots");
throw new ArgumentException("Client connected to the server does not support roots.", nameof(server));
}
return server.SendRequestAsync<ListRootsResult>(
new JsonRpcRequest { Method = "roots/list", Params = request },
cancellationToken);
}
/// <summary>Provides an <see cref="IChatClient"/> implementation that's implemented via client sampling.</summary>
/// <param name="server"></param>
private sealed class SamplingChatClient(IMcpServer server) : IChatClient
{
/// <inheritdoc/>
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>
server.RequestSamplingAsync(messages, options, cancellationToken);
/// <inheritdoc/>
async IAsyncEnumerable<ChatResponseUpdate> IChatClient.GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);
foreach (var update in response.ToChatResponseUpdates())
{
yield return update;
}
}
/// <inheritdoc/>
object? IChatClient.GetService(Type serviceType, object? serviceKey)
{
Throw.IfNull(serviceType);
return
serviceKey is not null ? null :
serviceType.IsInstanceOfType(this) ? this :
serviceType.IsInstanceOfType(server) ? server :
null;
}
/// <inheritdoc/>
void IDisposable.Dispose() { } // nop
}
}

View file

@ -38,6 +38,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.3.0-preview.1.25161.3" />
<PackageReference Include="Microsoft.Extensions.AI" Version="9.3.0-preview.1.25161.3" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
<PackageReference Include="System.Net.ServerSentEvents" Version="9.0.3" />

View file

@ -1,95 +0,0 @@
using System.Text.Json;
using McpDotNet.Protocol.Types;
namespace McpDotNet.Extensions.AI.Tests;
public class AIFunctionUtilitiesTests
{
[Fact]
public void MapToJsonElement_WithRequiredProperties_CreatesCorrectSchema()
{
// Arrange
var tool = new Tool()
{
Name = "calculator",
Description = "A simple calculator",
InputSchema = new JsonSchema
{
Properties = new Dictionary<string, JsonSchemaProperty>
{
["a"] = new JsonSchemaProperty { Type = "number" },
["b"] = new JsonSchemaProperty { Type = "number" }
},
Required = ["a", "b"]
}
};
// Act
var result = AIFunctionUtilities.MapToJsonElement(tool);
// Assert
var resultObj = JsonSerializer.Deserialize<JsonElement>(result.GetRawText());
Assert.Equal("object", resultObj.GetProperty("type").GetString());
Assert.Equal("calculator", resultObj.GetProperty("title").GetString());
Assert.Equal("A simple calculator", resultObj.GetProperty("description").GetString());
// Add more detailed property assertions
}
[Fact]
public void MapToJsonElement_WithOptionalProperties_CreatesCorrectSchema()
{
// Arrange
var tool = new Tool()
{
Name = "format",
Description = "Text formatter",
InputSchema = new JsonSchema
{
Properties = new Dictionary<string, JsonSchemaProperty>
{
["text"] = new JsonSchemaProperty { Type = "string" },
["style"] = new JsonSchemaProperty { Type = "string" }
},
Required = ["text"] // only text is required
}
};
// Act
var result = AIFunctionUtilities.MapToJsonElement(tool);
// Assert
var resultObj = JsonSerializer.Deserialize<JsonElement>(result.GetRawText());
Assert.Equal("object", resultObj.GetProperty("type").GetString());
Assert.Equal("format", resultObj.GetProperty("title").GetString());
Assert.Equal("Text formatter", resultObj.GetProperty("description").GetString());
Assert.Contains("text", resultObj.GetProperty("required").EnumerateArray().Select(x => x.GetString()));
Assert.DoesNotContain("style", resultObj.GetProperty("required").EnumerateArray().Select(x => x.GetString()));
}
[Fact]
public void MapToJsonElement_WithNullProperties_HandlesGracefully()
{
// Arrange
var tool = new Tool()
{
Name = "minimal",
Description = "Minimal tool",
InputSchema = new JsonSchema
{
Properties = null,
Required = null
}
};
// Act
var result = AIFunctionUtilities.MapToJsonElement(tool);
// Assert
var resultObj = JsonSerializer.Deserialize<JsonElement>(result.GetRawText());
Assert.Equal("object", resultObj.GetProperty("type").GetString());
Assert.Equal("minimal", resultObj.GetProperty("title").GetString());
Assert.Equal("Minimal tool", resultObj.GetProperty("description").GetString());
Assert.Equal("{}", resultObj.GetProperty("properties").GetRawText());
Assert.Empty(resultObj.GetProperty("required").EnumerateArray());
}
}

Some files were not shown because too many files have changed in this diff Show more