Consolidate McpClientException/McpServerException into McpException (#209)

This commit is contained in:
Stephen Toub 2025-04-03 21:10:57 -04:00 • committed by GitHub
commit 8fcdf95785
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 163 additions and 197 deletions

View file

@ -8,19 +8,21 @@ namespace ModelContextProtocol.Client;
public interface IMcpClient : IMcpEndpoint
{
/// <summary>
/// Gets the capabilities supported by the server.
/// Gets the capabilities supported by the connected server.
/// </summary>
ServerCapabilities? ServerCapabilities { get; }
ServerCapabilities ServerCapabilities { get; }
/// <summary>
/// Gets the version and implementation information of the server.
/// Gets the implementation information of the connected server.
/// </summary>
Implementation? ServerInfo { get; }
Implementation ServerInfo { get; }
/// <summary>
/// Instructions describing how to use the server and its features.
/// This can be used by clients to improve the LLM's understanding of available tools, resources, etc.
/// It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
/// Gets any instructions describing how to use the connected server and its features.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
string? ServerInstructions { get; }
}

View file

@ -18,6 +18,10 @@ internal sealed class McpClient : McpEndpoint, IMcpClient
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>
@ -66,13 +70,13 @@ internal sealed class McpClient : McpEndpoint, IMcpClient
}
/// <inheritdoc/>
public ServerCapabilities? ServerCapabilities { get; private set; }
public ServerCapabilities ServerCapabilities => _serverCapabilities ?? throw new InvalidOperationException("The client is not connected.");
/// <inheritdoc/>
public Implementation? ServerInfo { get; private set; }
public Implementation ServerInfo => _serverInfo ?? throw new InvalidOperationException("The client is not connected.");
/// <inheritdoc/>
public string? ServerInstructions { get; private set; }
public string? ServerInstructions => _serverInstructions;
/// <inheritdoc/>
public override string EndpointName { get; }
@ -112,15 +116,15 @@ internal sealed class McpClient : McpEndpoint, IMcpClient
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;
_serverCapabilities = initializeResponse.Capabilities;
_serverInfo = initializeResponse.ServerInfo;
_serverInstructions = initializeResponse.Instructions;
// Validate protocol version
if (initializeResponse.ProtocolVersion != _options.ProtocolVersion)
{
_logger.ServerProtocolVersionMismatch(EndpointName, _options.ProtocolVersion, initializeResponse.ProtocolVersion);
throw new McpClientException($"Server protocol version mismatch. Expected {_options.ProtocolVersion}, got {initializeResponse.ProtocolVersion}");
throw new McpException($"Server protocol version mismatch. Expected {_options.ProtocolVersion}, got {initializeResponse.ProtocolVersion}");
}
// Send initialized notification
@ -128,10 +132,10 @@ internal sealed class McpClient : McpEndpoint, IMcpClient
new JsonRpcNotification { Method = NotificationMethods.InitializedNotification },
initializationCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (initializationCts.IsCancellationRequested)
catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested)
{
_logger.ClientInitializationTimeout(EndpointName);
throw new McpClientException("Initialization timed out");
throw new McpException("Initialization timed out", oce);
}
}
catch (Exception e)

View file

@ -1,46 +0,0 @@
namespace ModelContextProtocol.Client;
/// <summary>
/// Represents errors that occur in the MCP client.
/// </summary>
public class McpClientException : Exception
{
/// <summary>
/// Gets the error code if this exception was caused by a JSON-RPC error response.
/// </summary>
public int? ErrorCode { get; }
/// <summary>
/// Initializes a new instance of the <see cref="McpClientException"/> class.
/// </summary>
public McpClientException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpClientException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public McpClientException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpClientException"/> class with a specified error message and error code.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="errorCode">The error code associated with the JSON-RPC error response.</param>
public McpClientException(string message, int errorCode) : base(message)
{
ErrorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="McpClientException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public McpClientException(string message, Exception innerException) : base(message, innerException)
{
}
}

View file

@ -15,7 +15,7 @@ public static class McpClientExtensions
/// Sends a ping request to verify server connectivity.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that completes when the ping is successful.</returns>
public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)
{
@ -34,7 +34,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="serializerOptions">The serializer options governing tool parameter serialization.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available tools.</returns>
public static async Task<IList<McpClientTool>> ListToolsAsync(
this IMcpClient client,
@ -75,7 +75,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="serializerOptions">The serializer options governing tool parameter serialization.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available tools.</returns>
/// <remarks>
/// Every iteration through the returned <see cref="IAsyncEnumerable{McpClientTool}"/>
@ -115,7 +115,7 @@ public static class McpClientExtensions
/// Retrieves a list of available prompts from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available prompts.</returns>
public static async Task<IList<McpClientPrompt>> ListPromptsAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
@ -150,7 +150,7 @@ public static class McpClientExtensions
/// Creates an enumerable for asynchronously enumerating all available prompts from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available prompts.</returns>
/// <remarks>
/// Every iteration through the returned <see cref="IAsyncEnumerable{Prompt}"/>
@ -188,7 +188,7 @@ public static class McpClientExtensions
/// <param name="name">The name of the prompt to retrieve</param>
/// <param name="arguments">Optional arguments for the prompt</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the prompt's content and messages.</returns>
public static Task<GetPromptResult> GetPromptAsync(
this IMcpClient client,
@ -216,7 +216,7 @@ public static class McpClientExtensions
/// Retrieves a list of available resource templates from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resource templates.</returns>
public static async Task<IList<ResourceTemplate>> ListResourceTemplatesAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
@ -255,7 +255,7 @@ public static class McpClientExtensions
/// Creates an enumerable for asynchronously enumerating all available resource templates from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available resource templates.</returns>
/// <remarks>
/// Every iteration through the returned <see cref="IAsyncEnumerable{ResourceTemplate}"/>
@ -290,7 +290,7 @@ public static class McpClientExtensions
/// Retrieves a list of available resources from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resources.</returns>
public static async Task<IList<Resource>> ListResourcesAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
@ -329,7 +329,7 @@ public static class McpClientExtensions
/// Creates an enumerable for asynchronously enumerating all available resources from the server.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available resources.</returns>
/// <remarks>
/// Every iteration through the returned <see cref="IAsyncEnumerable{Resource}"/>
@ -365,7 +365,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="uri">The uri of the resource.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public static Task<ReadResourceResult> ReadResourceAsync(
this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
@ -387,7 +387,7 @@ public static class McpClientExtensions
/// <param name="reference">A resource (uri) or prompt (name) reference</param>
/// <param name="argumentName">Name of argument. Must be non-null and non-empty.</param>
/// <param name="argumentValue">Value of argument. Must be non-null.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public static Task<CompleteResult> GetCompletionAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
@ -416,7 +416,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="uri">The uri of the resource.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
@ -435,7 +435,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="uri">The uri of the resource.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
@ -456,7 +456,7 @@ public static class McpClientExtensions
/// <param name="toolName">The name of the tool to call.</param>
/// <param name="arguments">Optional arguments for the tool.</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the tool's response.</returns>
public static Task<CallToolResponse> CallToolAsync(
this IMcpClient client,
@ -622,7 +622,7 @@ public static class McpClientExtensions
/// </summary>
/// <param name="client">The client.</param>
/// <param name="level">The minimum log level of messages to be generated.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);

View file

@ -37,7 +37,7 @@ public static class McpClientFactory
/// </param>
/// <param name="createTransportFunc">An optional factory method which returns transport implementations based on a server configuration.</param>
/// <param name="loggerFactory">A logger factory for creating loggers for clients.</param>
/// <param name="cancellationToken">A token to cancel the operation.</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="serverConfig"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="clientOptions"/> is <see langword="null"/>.</exception>

View file

@ -22,7 +22,7 @@ public sealed class McpClientPrompt
/// </summary>
/// <param name="arguments">Optional arguments for the prompt</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the prompt's content and messages.</returns>
public async ValueTask<GetPromptResult> GetAsync(
IEnumerable<KeyValuePair<string, object?>>? arguments = null,