Add ModelContextProtocol.Core package (#428)

This commit is contained in:
Stephen Halter 2025-06-02 15:16:45 -07:00 • committed by GitHub
commit 703b0fe50b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
180 changed files with 239 additions and 94 deletions

View file

@ -11,6 +11,7 @@
<PackageVersion Include="Microsoft.Bcl.Memory" Version="$(System9Version)" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.3" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" />
<PackageVersion Include="System.IO.Pipelines" Version="8.0.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="System.Threading.Channels" Version="8.0.0" />

View file

@ -29,6 +29,7 @@
<Folder Name="/src/">
<File Path="src/Directory.Build.props" />
<Project Path="src/ModelContextProtocol.AspNetCore/ModelContextProtocol.AspNetCore.csproj" />
<Project Path="src/ModelContextProtocol.Core/ModelContextProtocol.Core.csproj" />
<Project Path="src/ModelContextProtocol/ModelContextProtocol.csproj" />
</Folder>
<Folder Name="/tests/">

View file

@ -4,6 +4,16 @@
The official C# SDK for the [Model Context Protocol](https://modelcontextprotocol.io/), enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers. Please visit our [API documentation](https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.html) for more details on available functionality.
## Packages
This SDK consists of three main packages:
- **[ModelContextProtocol](https://www.nuget.org/packages/ModelContextProtocol/absoluteLatest)** [![NuGet preview version](https://img.shields.io/nuget/vpre/ModelContextProtocol.svg)](https://www.nuget.org/packages/ModelContextProtocol/absoluteLatest) - The main package with hosting and dependency injection extensions. This is the right fit for most projects that don't need HTTP server capabilities. This README serves as documentation for this package.
- **[ModelContextProtocol.AspNetCore](https://www.nuget.org/packages/ModelContextProtocol.AspNetCore/absoluteLatest)** [![NuGet preview version](https://img.shields.io/nuget/vpre/ModelContextProtocol.AspNetCore.svg)](https://www.nuget.org/packages/ModelContextProtocol.AspNetCore/absoluteLatest) - The library for HTTP-based MCP servers. [Documentation](src/ModelContextProtocol.AspNetCore/README.md)
- **[ModelContextProtocol.Core](https://www.nuget.org/packages/ModelContextProtocol.Core/absoluteLatest)** [![NuGet preview version](https://img.shields.io/nuget/vpre/ModelContextProtocol.Core.svg)](https://www.nuget.org/packages/ModelContextProtocol.Core/absoluteLatest) - For people who only need to use the client or low-level server APIs and want the minimum number of dependencies. [Documentation](src/ModelContextProtocol.Core/README.md)
> [!NOTE]
> This project is in preview; breaking changes can be introduced without prior notice.

View file

@ -8,7 +8,6 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
<ProjectReference Include="..\..\src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj" />
</ItemGroup>

View file

@ -20,7 +20,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
<ProjectReference Include="..\..\src\ModelContextProtocol.Core\ModelContextProtocol.Core.csproj" />
</ItemGroup>
</Project>

View file

@ -13,7 +13,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
<ProjectReference Include="..\..\src\ModelContextProtocol.Core\ModelContextProtocol.Core.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -1,4 +1,4 @@
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ModelContextProtocol.AspNetCore;
using ModelContextProtocol.Server;

View file

@ -19,6 +19,7 @@
<ItemGroup>
<None Include="README.md" pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ModelContextProtocol\ModelContextProtocol.csproj" />
</ItemGroup>

View file

@ -0,0 +1,206 @@
using Microsoft.Extensions.AI;
using ModelContextProtocol.Protocol;
#if !NET
using System.Runtime.InteropServices;
#endif
using System.Text.Json;
namespace ModelContextProtocol;
/// <summary>
/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.
/// </summary>
/// <remarks>
/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the <see cref="AIContent"/> model types
/// from the Microsoft.Extensions.AI namespace.
/// </remarks>
public static class AIContentExtensions
{
/// <summary>
/// Converts a <see cref="PromptMessage"/> to a <see cref="ChatMessage"/> object.
/// </summary>
/// <param name="promptMessage">The prompt message to convert.</param>
/// <returns>A <see cref="ChatMessage"/> object created from the prompt message.</returns>
/// <remarks>
/// This method transforms a protocol-specific <see cref="PromptMessage"/> from the Model Context Protocol
/// into a standard <see cref="ChatMessage"/> object that can be used with AI client libraries.
/// </remarks>
public static ChatMessage ToChatMessage(this PromptMessage promptMessage)
{
Throw.IfNull(promptMessage);
return new()
{
RawRepresentation = promptMessage,
Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,
Contents = [ToAIContent(promptMessage.Content)]
};
}
/// <summary>
/// Converts a <see cref="GetPromptResult"/> to a list of <see cref="ChatMessage"/> objects.
/// </summary>
/// <param name="promptResult">The prompt result containing messages to convert.</param>
/// <returns>A list of <see cref="ChatMessage"/> objects created from the prompt messages.</returns>
/// <remarks>
/// This method transforms protocol-specific <see cref="PromptMessage"/> objects from a Model Context Protocol
/// prompt result into standard <see cref="ChatMessage"/> objects that can be used with AI client libraries.
/// </remarks>
public static IList<ChatMessage> ToChatMessages(this GetPromptResult promptResult)
{
Throw.IfNull(promptResult);
return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();
}
/// <summary>
/// Converts a <see cref="ChatMessage"/> to a list of <see cref="PromptMessage"/> objects.
/// </summary>
/// <param name="chatMessage">The chat message to convert.</param>
/// <returns>A list of <see cref="PromptMessage"/> objects created from the chat message's contents.</returns>
/// <remarks>
/// This method transforms standard <see cref="ChatMessage"/> objects used with AI client libraries into
/// protocol-specific <see cref="PromptMessage"/> objects for the Model Context Protocol system.
/// Only representable content items are processed.
/// </remarks>
public static IList<PromptMessage> ToPromptMessages(this ChatMessage chatMessage)
{
Throw.IfNull(chatMessage);
Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;
List<PromptMessage> messages = [];
foreach (var content in chatMessage.Contents)
{
if (content is TextContent or DataContent)
{
messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });
}
}
return messages;
}
/// <summary>Creates a new <see cref="AIContent"/> from the content of a <see cref="Content"/>.</summary>
/// <param name="content">The <see cref="Content"/> to convert.</param>
/// <returns>The created <see cref="AIContent"/>.</returns>
/// <remarks>
/// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI
/// content types, enabling seamless integration between the protocol and AI client libraries.
/// </remarks>
public static AIContent ToAIContent(this Content content)
{
Throw.IfNull(content);
AIContent ac;
if (content is { Type: "image" or "audio", MimeType: not null, Data: not null })
{
ac = new DataContent(Convert.FromBase64String(content.Data), content.MimeType);
}
else if (content is { Type: "resource" } && content.Resource is { } resourceContents)
{
ac = resourceContents.ToAIContent();
}
else
{
ac = new TextContent(content.Text);
}
ac.RawRepresentation = content;
return ac;
}
/// <summary>Creates a new <see cref="AIContent"/> from the content of a <see cref="ResourceContents"/>.</summary>
/// <param name="content">The <see cref="ResourceContents"/> to convert.</param>
/// <returns>The created <see cref="AIContent"/>.</returns>
/// <remarks>
/// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI
/// content types, enabling seamless integration between the protocol and AI client libraries.
/// </remarks>
public static AIContent ToAIContent(this ResourceContents content)
{
Throw.IfNull(content);
AIContent ac = content switch
{
BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? "application/octet-stream"),
TextResourceContents textResource => new TextContent(textResource.Text),
_ => throw new NotSupportedException($"Resource type '{content.GetType().Name}' is not supported.")
};
(ac.AdditionalProperties ??= [])["uri"] = content.Uri;
ac.RawRepresentation = content;
return ac;
}
/// <summary>Creates a list of <see cref="AIContent"/> from a sequence of <see cref="Content"/>.</summary>
/// <param name="contents">The <see cref="Content"/> instances to convert.</param>
/// <returns>The created <see cref="AIContent"/> instances.</returns>
/// <remarks>
/// <para>
/// This method converts a collection of Model Context Protocol content objects into a collection of
/// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as
/// when processing the contents of a message or response.
/// </para>
/// <para>
/// Each <see cref="Content"/> object is converted using <see cref="ToAIContent(Content)"/>,
/// preserving the type-specific conversion logic for text, images, audio, and resources.
/// </para>
/// </remarks>
public static IList<AIContent> ToAIContents(this IEnumerable<Content> contents)
{
Throw.IfNull(contents);
return [.. contents.Select(ToAIContent)];
}
/// <summary>Creates a list of <see cref="AIContent"/> from a sequence of <see cref="ResourceContents"/>.</summary>
/// <param name="contents">The <see cref="ResourceContents"/> instances to convert.</param>
/// <returns>A list of <see cref="AIContent"/> objects created from the resource contents.</returns>
/// <remarks>
/// <para>
/// This method converts a collection of Model Context Protocol resource objects into a collection of
/// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as
/// when processing the contents of a <see cref="ReadResourceResult"/>.
/// </para>
/// <para>
/// Each <see cref="ResourceContents"/> object is converted using <see cref="ToAIContent(ResourceContents)"/>,
/// preserving the type-specific conversion logic: text resources become <see cref="TextContent"/> objects and
/// binary resources become <see cref="DataContent"/> objects.
/// </para>
/// </remarks>
public static IList<AIContent> ToAIContents(this IEnumerable<ResourceContents> contents)
{
Throw.IfNull(contents);
return [.. contents.Select(ToAIContent)];
}
internal static Content ToContent(this AIContent content) =>
content switch
{
TextContent textContent => new()
{
Text = textContent.Text,
Type = "text",
},
DataContent dataContent => new()
{
Data = dataContent.Base64Data.ToString(),
MimeType = dataContent.MediaType,
Type =
dataContent.HasTopLevelMediaType("image") ? "image" :
dataContent.HasTopLevelMediaType("audio") ? "audio" :
"resource",
},
_ => new()
{
Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),
Type = "text",
}
};
}

View file

@ -0,0 +1,143 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Protocol;
using System.Net;
using System.Threading.Channels;
namespace ModelContextProtocol.Client;
/// <summary>
/// A transport that automatically detects whether to use Streamable HTTP or SSE transport
/// by trying Streamable HTTP first and falling back to SSE if that fails.
/// </summary>
internal sealed partial class AutoDetectingClientSessionTransport : ITransport
{
private readonly SseClientTransportOptions _options;
private readonly HttpClient _httpClient;
private readonly ILoggerFactory? _loggerFactory;
private readonly ILogger _logger;
private readonly string _name;
private readonly Channel<JsonRpcMessage> _messageChannel;
public AutoDetectingClientSessionTransport(SseClientTransportOptions transportOptions, HttpClient httpClient, ILoggerFactory? loggerFactory, string endpointName)
{
Throw.IfNull(transportOptions);
Throw.IfNull(httpClient);
_options = transportOptions;
_httpClient = httpClient;
_loggerFactory = loggerFactory;
_logger = (ILogger?)loggerFactory?.CreateLogger<AutoDetectingClientSessionTransport>() ?? NullLogger.Instance;
_name = endpointName;
// Same as TransportBase.cs.
_messageChannel = Channel.CreateUnbounded<JsonRpcMessage>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
});
}
/// <summary>
/// Returns the active transport (either StreamableHttp or SSE)
/// </summary>
internal ITransport? ActiveTransport { get; private set; }
public ChannelReader<JsonRpcMessage> MessageReader => _messageChannel.Reader;
/// <inheritdoc/>
public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
{
if (ActiveTransport is null)
{
return InitializeAsync(message, cancellationToken);
}
return ActiveTransport.SendMessageAsync(message, cancellationToken);
}
private async Task InitializeAsync(JsonRpcMessage message, CancellationToken cancellationToken)
{
// Try StreamableHttp first
var streamableHttpTransport = new StreamableHttpClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory);
try
{
LogAttemptingStreamableHttp(_name);
using var response = await streamableHttpTransport.SendHttpRequestAsync(message, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
LogUsingStreamableHttp(_name);
ActiveTransport = streamableHttpTransport;
}
else
{
// If the status code is not success, fall back to SSE
LogStreamableHttpFailed(_name, response.StatusCode);
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
await InitializeSseTransportAsync(message, cancellationToken).ConfigureAwait(false);
}
}
catch
{
// If nothing threw inside the try block, we've either set streamableHttpTransport as the
// ActiveTransport, or else we will have disposed it in the !IsSuccessStatusCode else block.
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private async Task InitializeSseTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken)
{
var sseTransport = new SseClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory);
try
{
LogAttemptingSSE(_name);
await sseTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);
await sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
LogUsingSSE(_name);
ActiveTransport = sseTransport;
}
catch
{
await sseTransport.DisposeAsync().ConfigureAwait(false);
throw;
}
}
public async ValueTask DisposeAsync()
{
try
{
if (ActiveTransport is not null)
{
await ActiveTransport.DisposeAsync().ConfigureAwait(false);
}
}
finally
{
// In the majority of cases, either the Streamable HTTP transport or SSE transport has completed the channel by now.
// However, this may not be the case if HttpClient throws during the initial request due to misconfiguration.
_messageChannel.Writer.TryComplete();
}
}
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} attempting to connect using Streamable HTTP transport.")]
private partial void LogAttemptingStreamableHttp(string endpointName);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} streamable HTTP transport failed with status code {StatusCode}, falling back to SSE transport.")]
private partial void LogStreamableHttpFailed(string endpointName, HttpStatusCode statusCode);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} using Streamable HTTP transport.")]
private partial void LogUsingStreamableHttp(string endpointName);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} attempting to connect using SSE transport.")]
private partial void LogAttemptingSSE(string endpointName);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} using SSE transport.")]
private partial void LogUsingSSE(string endpointName);
}

View file

@ -0,0 +1,23 @@
namespace ModelContextProtocol.Client;
/// <summary>
/// Specifies the transport mode for HTTP client connections.
/// </summary>
public enum HttpTransportMode
{
/// <summary>
/// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.
/// This is the recommended mode for maximum compatibility.
/// </summary>
AutoDetect,
/// <summary>
/// Use only the Streamable HTTP transport.
/// </summary>
StreamableHttp,
/// <summary>
/// Use only the HTTP with SSE transport.
/// </summary>
Sse
}

View file

@ -0,0 +1,47 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="IClientTransport"/> interface abstracts the communication layer between MCP clients
/// and servers, allowing different transport protocols to be used interchangeably.
/// </para>
/// <para>
/// When creating an <see cref="IMcpClient"/>, <see cref="McpClientFactory"/> is typically used, and is
/// provided with the <see cref="IClientTransport"/> based on expected server configuration.
/// </para>
/// </remarks>
public interface IClientTransport
{
/// <summary>
/// Gets a transport identifier, used for logging purposes.
/// </summary>
string Name { get; }
/// <summary>
/// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>Returns an interface for the duplex message stream.</returns>
/// <remarks>
/// <para>
/// This method is responsible for initializing the connection to the server using the specific transport
/// mechanism implemented by the derived class. The returned <see cref="ITransport"/> interface
/// provides methods to send and receive messages over the established connection.
/// </para>
/// <para>
/// The lifetime of the returned <see cref="ITransport"/> instance is typically managed by the
/// <see cref="McpClient"/> that uses this transport. When the client is disposed, it will dispose
/// the transport session as well.
/// </para>
/// <para>
/// This method is used by <see cref="McpClientFactory"/> to initialize the connection.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">The transport connection could not be established.</exception>
Task<ITransport> ConnectAsync(CancellationToken cancellationToken = default);
}

View file

@ -0,0 +1,47 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.
/// </summary>
public interface IMcpClient : IMcpEndpoint
{
/// <summary>
/// Gets the capabilities supported by the connected server.
/// </summary>
/// <exception cref="InvalidOperationException">The client is not connected.</exception>
ServerCapabilities ServerCapabilities { get; }
/// <summary>
/// Gets the implementation information of the connected server.
/// </summary>
/// <remarks>
/// <para>
/// This property provides identification details about the connected server, including its name and version.
/// It is populated during the initialization handshake and is available after a successful connection.
/// </para>
/// <para>
/// This information can be useful for logging, debugging, compatibility checks, and displaying server
/// information to users.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">The client is not connected.</exception>
Implementation ServerInfo { get; }
/// <summary>
/// Gets any instructions describing how to use the connected server and its features.
/// </summary>
/// <remarks>
/// <para>
/// This property contains instructions provided by the server during initialization that explain
/// how to effectively use its capabilities. These instructions can include details about available
/// tools, expected input formats, limitations, or any other helpful information.
/// </para>
/// <para>
/// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources.
/// It can be thought of like a "hint" to the model and may be added to a system prompt.
/// </para>
/// </remarks>
string? ServerInstructions { get; }
}

View file

@ -0,0 +1,215 @@
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol;
using System.Text.Json;
namespace ModelContextProtocol.Client;
/// <inheritdoc/>
internal sealed partial class McpClient : McpEndpoint, IMcpClient
{
private static Implementation DefaultImplementation { get; } = new()
{
Name = DefaultAssemblyName.Name ?? nameof(McpClient),
Version = DefaultAssemblyName.Version?.ToString() ?? "1.0.0",
};
private readonly IClientTransport _clientTransport;
private readonly McpClientOptions _options;
private ITransport? _sessionTransport;
private CancellationTokenSource? _connectCts;
private ServerCapabilities? _serverCapabilities;
private Implementation? _serverInfo;
private string? _serverInstructions;
/// <summary>
/// Initializes a new instance of the <see cref="McpClient"/> class.
/// </summary>
/// <param name="clientTransport">The transport to use for communication with the server.</param>
/// <param name="options">Options for the client, defining protocol version and capabilities.</param>
/// <param name="loggerFactory">The logger factory.</param>
public McpClient(IClientTransport clientTransport, McpClientOptions? options, ILoggerFactory? loggerFactory)
: base(loggerFactory)
{
options ??= new();
_clientTransport = clientTransport;
_options = options;
EndpointName = clientTransport.Name;
if (options.Capabilities is { } capabilities)
{
if (capabilities.NotificationHandlers is { } notificationHandlers)
{
NotificationHandlers.RegisterRange(notificationHandlers);
}
if (capabilities.Sampling is { } samplingCapability)
{
if (samplingCapability.SamplingHandler is not { } samplingHandler)
{
throw new InvalidOperationException("Sampling capability was set but it did not provide a handler.");
}
RequestHandlers.Set(
RequestMethods.SamplingCreateMessage,
(request, _, cancellationToken) => samplingHandler(
request,
request?.Meta?.ProgressToken is { } token ? new TokenProgress(this, token) : NullProgress.Instance,
cancellationToken),
McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,
McpJsonUtilities.JsonContext.Default.CreateMessageResult);
}
if (capabilities.Roots is { } rootsCapability)
{
if (rootsCapability.RootsHandler is not { } rootsHandler)
{
throw new InvalidOperationException("Roots capability was set but it did not provide a handler.");
}
RequestHandlers.Set(
RequestMethods.RootsList,
(request, _, cancellationToken) => rootsHandler(request, cancellationToken),
McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,
McpJsonUtilities.JsonContext.Default.ListRootsResult);
}
if (capabilities.Elicitation is { } elicitationCapability)
{
if (elicitationCapability.ElicitationHandler is not { } elicitationHandler)
{
throw new InvalidOperationException("Elicitation capability was set but it did not provide a handler.");
}
RequestHandlers.Set(
RequestMethods.ElicitationCreate,
(request, _, cancellationToken) => elicitationHandler(request, cancellationToken),
McpJsonUtilities.JsonContext.Default.ElicitRequestParams,
McpJsonUtilities.JsonContext.Default.ElicitResult);
}
}
}
/// <inheritdoc/>
public ServerCapabilities ServerCapabilities => _serverCapabilities ?? throw new InvalidOperationException("The client is not connected.");
/// <inheritdoc/>
public Implementation ServerInfo => _serverInfo ?? throw new InvalidOperationException("The client is not connected.");
/// <inheritdoc/>
public string? ServerInstructions => _serverInstructions;
/// <inheritdoc/>
public override string EndpointName { get; }
/// <summary>
/// Asynchronously connects to an MCP server, establishes the transport connection, and completes the initialization handshake.
/// </summary>
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
_connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cancellationToken = _connectCts.Token;
try
{
// Connect transport
_sessionTransport = await _clientTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);
InitializeSession(_sessionTransport);
// We don't want the ConnectAsync token to cancel the session after we've successfully connected.
// The base class handles cleaning up the session in DisposeAsync without our help.
StartSession(_sessionTransport, fullSessionCancellationToken: CancellationToken.None);
// Perform initialization sequence
using var initializationCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
initializationCts.CancelAfter(_options.InitializationTimeout);
try
{
// Send initialize request
var initializeResponse = await this.SendRequestAsync(
RequestMethods.Initialize,
new InitializeRequestParams
{
ProtocolVersion = _options.ProtocolVersion,
Capabilities = _options.Capabilities ?? new ClientCapabilities(),
ClientInfo = _options.ClientInfo ?? DefaultImplementation,
},
McpJsonUtilities.JsonContext.Default.InitializeRequestParams,
McpJsonUtilities.JsonContext.Default.InitializeResult,
cancellationToken: initializationCts.Token).ConfigureAwait(false);
// Store server information
if (_logger.IsEnabled(LogLevel.Information))
{
LogServerCapabilitiesReceived(EndpointName,
capabilities: JsonSerializer.Serialize(initializeResponse.Capabilities, McpJsonUtilities.JsonContext.Default.ServerCapabilities),
serverInfo: JsonSerializer.Serialize(initializeResponse.ServerInfo, McpJsonUtilities.JsonContext.Default.Implementation));
}
_serverCapabilities = initializeResponse.Capabilities;
_serverInfo = initializeResponse.ServerInfo;
_serverInstructions = initializeResponse.Instructions;
// Validate protocol version
if (initializeResponse.ProtocolVersion != _options.ProtocolVersion)
{
LogServerProtocolVersionMismatch(EndpointName, _options.ProtocolVersion, initializeResponse.ProtocolVersion);
throw new McpException($"Server protocol version mismatch. Expected {_options.ProtocolVersion}, got {initializeResponse.ProtocolVersion}");
}
// Send initialized notification
await SendMessageAsync(
new JsonRpcNotification { Method = NotificationMethods.InitializedNotification },
initializationCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
LogClientInitializationTimeout(EndpointName);
throw new TimeoutException("Initialization timed out", oce);
}
}
catch (Exception e)
{
LogClientInitializationError(EndpointName, e);
await DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <inheritdoc/>
public override async ValueTask DisposeUnsynchronizedAsync()
{
try
{
if (_connectCts is not null)
{
await _connectCts.CancelAsync().ConfigureAwait(false);
_connectCts.Dispose();
}
await base.DisposeUnsynchronizedAsync().ConfigureAwait(false);
}
finally
{
if (_sessionTransport is not null)
{
await _sessionTransport.DisposeAsync().ConfigureAwait(false);
}
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} client received server '{ServerInfo}' capabilities: '{Capabilities}'.")]
private partial void LogServerCapabilitiesReceived(string endpointName, string capabilities, string serverInfo);
[LoggerMessage(Level = LogLevel.Error, Message = "{EndpointName} client initialization error.")]
private partial void LogClientInitializationError(string endpointName, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "{EndpointName} client initialization timed out.")]
private partial void LogClientInitializationTimeout(string endpointName);
[LoggerMessage(Level = LogLevel.Error, Message = "{EndpointName} client protocol version mismatch with server. Expected '{Expected}', received '{Received}'.")]
private partial void LogServerProtocolVersionMismatch(string endpointName, string expected, string received);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,54 @@
using Microsoft.Extensions.Logging;
namespace ModelContextProtocol.Client;
/// <summary>
/// Provides factory methods for creating Model Context Protocol (MCP) clients.
/// </summary>
/// <remarks>
/// This factory class is the primary way to instantiate <see cref="IMcpClient"/> instances
/// that connect to MCP servers. It handles the creation and connection
/// of appropriate implementations through the supplied transport.
/// </remarks>
public static partial class McpClientFactory
{
/// <summary>Creates an <see cref="IMcpClient"/>, connecting it to the specified server.</summary>
/// <param name="clientTransport">The transport instance used to communicate with the server.</param>
/// <param name="clientOptions">
/// A client configuration object which specifies client capabilities and protocol version.
/// If <see langword="null"/>, details based on the current process will be employed.
/// </param>
/// <param name="loggerFactory">A logger factory for creating loggers for clients.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An <see cref="IMcpClient"/> that's connected to the specified server.</returns>
/// <exception cref="ArgumentNullException"><paramref name="clientTransport"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="clientOptions"/> is <see langword="null"/>.</exception>
public static async Task<IMcpClient> CreateAsync(
IClientTransport clientTransport,
McpClientOptions? clientOptions = null,
ILoggerFactory? loggerFactory = null,
CancellationToken cancellationToken = default)
{
Throw.IfNull(clientTransport);
McpClient client = new(clientTransport, clientOptions, loggerFactory);
try
{
await client.ConnectAsync(cancellationToken).ConfigureAwait(false);
if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)
{
logger.LogClientCreated(client.EndpointName);
}
}
catch
{
await client.DisposeAsync().ConfigureAwait(false);
throw;
}
return client;
}
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} client created and connected.")]
private static partial void LogClientCreated(this ILogger logger, string endpointName);
}

View file

@ -0,0 +1,59 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Client;
/// <summary>
/// Provides configuration options for creating <see cref="IMcpClient"/> instances.
/// </summary>
/// <remarks>
/// These options are typically passed to <see cref="McpClientFactory.CreateAsync"/> when creating a client.
/// They define client capabilities, protocol version, and other client-specific settings.
/// </remarks>
public class McpClientOptions
{
/// <summary>
/// Gets or sets information about this client implementation, including its name and version.
/// </summary>
/// <remarks>
/// <para>
/// This information is sent to the server during initialization to identify the client.
/// It's often displayed in server logs and can be used for debugging and compatibility checks.
/// </para>
/// <para>
/// When not specified, information sourced from the current process will be used.
/// </para>
/// </remarks>
public Implementation? ClientInfo { get; set; }
/// <summary>
/// Gets or sets the client capabilities to advertise to the server.
/// </summary>
public ClientCapabilities? Capabilities { get; set; }
/// <summary>
/// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.
/// </summary>
/// <remarks>
/// The protocol version is a key part of the initialization handshake. The client and server must
/// agree on a compatible protocol version to communicate successfully. If the server doesn't support
/// the requested version, it will respond with a version mismatch error.
/// </remarks>
public string ProtocolVersion { get; set; } = "2024-11-05";
/// <summary>
/// Gets or sets a timeout for the client-server initialization handshake sequence.
/// </summary>
/// <remarks>
/// <para>
/// This timeout determines how long the client will wait for the server to respond during
/// the initialization protocol handshake. If the server doesn't respond within this timeframe,
/// an exception will be thrown.
/// </para>
/// <para>
/// Setting an appropriate timeout prevents the client from hanging indefinitely when
/// connecting to unresponsive servers.
/// </para>
/// <para>The default value is 60 seconds.</para>
/// </remarks>
public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);
}

View file

@ -0,0 +1,78 @@
using ModelContextProtocol.Protocol;
using System.Text.Json;
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.
/// </summary>
/// <remarks>
/// <para>
/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows
/// retrieving the prompt's content by sending a request to the server with optional arguments.
/// Instances of this class are typically obtained by calling <see cref="McpClientExtensions.ListPromptsAsync"/>
/// or <see cref="McpClientExtensions.EnumeratePromptsAsync"/>.
/// </para>
/// <para>
/// Each prompt has a name and optionally a description, and it can be invoked with arguments
/// to produce customized prompt content from the server.
/// </para>
/// </remarks>
public sealed class McpClientPrompt
{
private readonly IMcpClient _client;
internal McpClientPrompt(IMcpClient client, Prompt prompt)
{
_client = client;
ProtocolPrompt = prompt;
}
/// <summary>Gets the underlying protocol <see cref="Prompt"/> type for this instance.</summary>
/// <remarks>
/// <para>
/// This property provides direct access to the underlying protocol representation of the prompt,
/// which can be useful for advanced scenarios or when implementing custom MCP client extensions.
/// </para>
/// <para>
/// For most common use cases, you can use the more convenient <see cref="Name"/> and
/// <see cref="Description"/> properties instead of accessing the <see cref="ProtocolPrompt"/> directly.
/// </para>
/// </remarks>
public Prompt ProtocolPrompt { get; }
/// <summary>Gets the name of the prompt.</summary>
public string Name => ProtocolPrompt.Name;
/// <summary>Gets a description of the prompt.</summary>
public string? Description => ProtocolPrompt.Description;
/// <summary>
/// Gets this prompt's content by sending a request to the server with optional arguments.
/// </summary>
/// <param name="arguments">Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="ValueTask"/> containing the prompt's result with content and messages.</returns>
/// <remarks>
/// <para>
/// This method sends a request to the MCP server to execute this prompt with the provided arguments.
/// The server will process the request and return a result containing messages or other content.
/// </para>
/// <para>
/// This is a convenience method that internally calls <see cref="McpClientExtensions.GetPromptAsync"/>
/// with this prompt's name and arguments.
/// </para>
/// </remarks>
public async ValueTask<GetPromptResult> GetAsync(
IEnumerable<KeyValuePair<string, object?>>? arguments = null,
JsonSerializerOptions? serializerOptions = null,
CancellationToken cancellationToken = default)
{
IReadOnlyDictionary<string, object?>? argDict =
arguments as IReadOnlyDictionary<string, object?> ??
arguments?.ToDictionary();
return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}

View file

@ -0,0 +1,64 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents a named resource that can be retrieved from an MCP server.
/// </summary>
/// <remarks>
/// <para>
/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows
/// retrieving the resource's content by sending a request to the server with the resource's URI.
/// Instances of this class are typically obtained by calling <see cref="McpClientExtensions.ListResourcesAsync"/>
/// or <see cref="McpClientExtensions.EnumerateResourcesAsync"/>.
/// </para>
/// </remarks>
public sealed class McpClientResource
{
private readonly IMcpClient _client;
internal McpClientResource(IMcpClient client, Resource resource)
{
_client = client;
ProtocolResource = resource;
}
/// <summary>Gets the underlying protocol <see cref="Resource"/> type for this instance.</summary>
/// <remarks>
/// <para>
/// This property provides direct access to the underlying protocol representation of the resource,
/// which can be useful for advanced scenarios or when implementing custom MCP client extensions.
/// </para>
/// <para>
/// For most common use cases, you can use the more convenient <see cref="Name"/> and
/// <see cref="Description"/> properties instead of accessing the <see cref="ProtocolResource"/> directly.
/// </para>
/// </remarks>
public Resource ProtocolResource { get; }
/// <summary>Gets the URI of the resource.</summary>
public string Uri => ProtocolResource.Uri;
/// <summary>Gets the name of the resource.</summary>
public string Name => ProtocolResource.Name;
/// <summary>Gets a description of the resource.</summary>
public string? Description => ProtocolResource.Description;
/// <summary>Gets a media (MIME) type of the resource.</summary>
public string? MimeType => ProtocolResource.MimeType;
/// <summary>
/// Gets this resource's content by sending a request to the server.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="ValueTask{ReadResourceResult}"/> containing the resource's result with content and messages.</returns>
/// <remarks>
/// <para>
/// This is a convenience method that internally calls <see cref="McpClientExtensions.ReadResourceAsync(IMcpClient, string, CancellationToken)"/>.
/// </para>
/// </remarks>
public ValueTask<ReadResourceResult> ReadAsync(
CancellationToken cancellationToken = default) =>
_client.ReadResourceAsync(Uri, cancellationToken);
}

View file

@ -0,0 +1,64 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents a named resource template that can be retrieved from an MCP server.
/// </summary>
/// <remarks>
/// <para>
/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows
/// retrieving the resource template's content by sending a request to the server with the resource's URI.
/// Instances of this class are typically obtained by calling <see cref="McpClientExtensions.ListResourceTemplatesAsync"/>
/// or <see cref="McpClientExtensions.EnumerateResourceTemplatesAsync"/>.
/// </para>
/// </remarks>
public sealed class McpClientResourceTemplate
{
private readonly IMcpClient _client;
internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)
{
_client = client;
ProtocolResourceTemplate = resourceTemplate;
}
/// <summary>Gets the underlying protocol <see cref="ResourceTemplate"/> type for this instance.</summary>
/// <remarks>
/// <para>
/// This property provides direct access to the underlying protocol representation of the resource template,
/// which can be useful for advanced scenarios or when implementing custom MCP client extensions.
/// </para>
/// <para>
/// For most common use cases, you can use the more convenient <see cref="UriTemplate"/> and
/// <see cref="Description"/> properties instead of accessing the <see cref="ProtocolResourceTemplate"/> directly.
/// </para>
/// </remarks>
public ResourceTemplate ProtocolResourceTemplate { get; }
/// <summary>Gets the URI template of the resource template.</summary>
public string UriTemplate => ProtocolResourceTemplate.UriTemplate;
/// <summary>Gets the name of the resource template.</summary>
public string Name => ProtocolResourceTemplate.Name;
/// <summary>Gets a description of the resource template.</summary>
public string? Description => ProtocolResourceTemplate.Description;
/// <summary>Gets a media (MIME) type of the resource template.</summary>
public string? MimeType => ProtocolResourceTemplate.MimeType;
/// <summary>
/// Gets this resource template's content by formatting a URI from the template and supplied arguments
/// and sending a request to the server.
/// </summary>
/// <param name="arguments">A dictionary of arguments to pass to the tool. Each key represents a parameter name,
/// and its associated value represents the argument value.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="ValueTask{ReadResourceResult}"/> containing the resource template's result with content and messages.</returns>
public ValueTask<ReadResourceResult> ReadAsync(
IReadOnlyDictionary<string, object?> arguments,
CancellationToken cancellationToken = default) =>
_client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);
}

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