Skip to content

Clean up (use of) McpException and McpTransportException #321

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 18, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Clean up (use of) McpException
  • Loading branch information
stephentoub committed Apr 17, 2025
commit 20be4c1147a08a0b184ff5f84841f94bbd100d22
2 changes: 1 addition & 1 deletion samples/EverythingServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ await ctx.Server.RequestSamplingAsync([
{
if (ctx.Params?.Level is null)
{
throw new McpException("Missing required argument 'level'");
throw new McpException("Missing required argument 'level'", McpErrorCode.InvalidParams);
}

_minimumLoggingLevel = ctx.Params.Level;
Expand Down
4 changes: 2 additions & 2 deletions src/ModelContextProtocol/Client/McpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,10 @@ await SendMessageAsync(
new JsonRpcNotification { Method = NotificationMethods.InitializedNotification },
initializationCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested)
catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
LogClientInitializationTimeout(EndpointName);
throw new McpException("Initialization timed out", oce);
throw new TimeoutException("Initialization timed out", oce);
}
}
catch (Exception e)
Expand Down
49 changes: 49 additions & 0 deletions src/ModelContextProtocol/McpErrorCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace ModelContextProtocol;

/// <summary>
/// Represents standard JSON-RPC error codes as defined in the MCP specification.
/// </summary>
public enum McpErrorCode
{
/// <summary>
/// Indicates that the JSON received could not be parsed.
/// </summary>
/// <remarks>
/// This error occurs when the input contains malformed JSON or incorrect syntax.
/// </remarks>
ParseError = -32700,

/// <summary>
/// Indicates that the JSON payload does not conform to the expected Request object structure.
/// </summary>
/// <remarks>
/// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.
/// </remarks>
InvalidRequest = -32600,

/// <summary>
/// Indicates that the requested method does not exist or is not available on the server.
/// </summary>
/// <remarks>
/// This error is returned when the method name specified in the request cannot be found.
/// </remarks>
MethodNotFound = -32601,

/// <summary>
/// Indicates that one or more parameters provided in the request are invalid.
/// </summary>
/// <remarks>
/// This error is returned when the parameters do not match the expected method signature or constraints.
/// This includes cases where required parameters are missing or not understood, such as when a name for
/// a tool or prompt is not recognized.
/// </remarks>
InvalidParams = -32602,

/// <summary>
/// Indicates that an internal error occurred while processing the request.
/// </summary>
/// <remarks>
/// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.
/// </remarks>
InternalError = -32603,
}
24 changes: 14 additions & 10 deletions src/ModelContextProtocol/McpException.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
namespace ModelContextProtocol;

/// <summary>
/// Represents an exception that is thrown when a Model Context Protocol (MCP) error occurs.
/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.
/// </summary>
/// <remarks>
/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,
/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.
/// <see cref="Exception.Message"/> or <see cref="ErrorCode"/> from a <see cref="McpException"/> may be
/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need
/// to be included, a different exception type should be used.
/// </remarks>
public class McpException : Exception
{
/// <summary>
Expand Down Expand Up @@ -33,8 +40,8 @@ public McpException(string message, Exception? innerException) : base(message, i
/// Initializes a new instance of the <see cref="McpException"/> class with a specified error message and JSON-RPC error code.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="errorCode">A JSON-RPC error code from <see cref="Protocol.Messages.ErrorCodes"/> class.</param>
public McpException(string message, int? errorCode) : this(message, null, errorCode)
/// <param name="errorCode">A <see cref="McpErrorCode"/>.</param>
public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)
{
}

Expand All @@ -43,18 +50,15 @@ public McpException(string message, int? errorCode) : this(message, null, errorC
/// </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>
/// <param name="errorCode">A JSON-RPC error code from <see cref="Protocol.Messages.ErrorCodes"/> class.</param>
public McpException(string message, Exception? innerException, int? errorCode) : base(message, innerException)
/// <param name="errorCode">A <see cref="McpErrorCode"/>.</param>
public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)
{
ErrorCode = errorCode;
}

/// <summary>
/// Gets the JSON-RPC error code associated with this exception.
/// Gets the error code associated with this exception.
/// </summary>
/// <value>
/// A standard JSON-RPC error code, or <see langword="null"/> if the exception wasn't caused by a JSON-RPC error.
/// </value>
/// <remarks>
/// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:
/// <list type="bullet">
Expand All @@ -65,5 +69,5 @@ public McpException(string message, Exception? innerException, int? errorCode) :
/// <item><description>-32603: Internal error - Internal JSON-RPC error</description></item>
/// </list>
/// </remarks>
public int? ErrorCode { get; }
public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;
}
32 changes: 0 additions & 32 deletions src/ModelContextProtocol/Protocol/Messages/ErrorCodes.cs

This file was deleted.

4 changes: 2 additions & 2 deletions src/ModelContextProtocol/Server/AIFunctionMcpServerPrompt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
BindParameter = (pi, args) =>
GetRequestContext(args)?.Services?.GetService(pi.ParameterType) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
throw new InvalidOperationException("No service of the requested type was found.")),
};
}

Expand All @@ -113,7 +113,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
BindParameter = (pi, args) =>
(GetRequestContext(args)?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
throw new InvalidOperationException("No service of the requested type was found.")),
};
}

Expand Down
12 changes: 8 additions & 4 deletions src/ModelContextProtocol/Server/AIFunctionMcpServerTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
BindParameter = (pi, args) =>
GetRequestContext(args)?.Services?.GetService(pi.ParameterType) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
throw new InvalidOperationException("No service of the requested type was found.")),
};
}

Expand All @@ -134,7 +134,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
BindParameter = (pi, args) =>
(GetRequestContext(args)?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??
(pi.HasDefaultValue ? null :
throw new ArgumentException("No service of the requested type was found.")),
throw new InvalidOperationException("No service of the requested type was found.")),
};
}

Expand Down Expand Up @@ -265,10 +265,14 @@ public override async ValueTask<CallToolResponse> InvokeAsync(
}
catch (Exception e) when (e is not OperationCanceledException)
{
return new CallToolResponse()
string errorMessage = e is McpException ?
$"An error occurred invoking '{request.Params?.Name}': {e.Message}" :
$"An error occurred invoking '{request.Params?.Name}'.";

return new()
{
IsError = true,
Content = [new() { Text = $"An error occurred invoking '{request.Params?.Name}'.", Type = "text" }],
Content = [new() { Text = errorMessage, Type = "text" }],
};
}

Expand Down
34 changes: 25 additions & 9 deletions src/ModelContextProtocol/Server/McpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ private void SetCompletionHandler(McpServerOptions options)
}

var completeHandler = completionsCapability.CompleteHandler ??
throw new McpException("Completions capability was enabled, but Complete handler was not specified.");
throw new InvalidOperationException(
$"{nameof(ServerCapabilities)}.{nameof(ServerCapabilities.Completions)} was enabled, " +
$"but {nameof(CompletionsCapability.CompleteHandler)} was not specified.");

// This capability is not optional, so return an empty result if there is no handler.
RequestHandlers.Set(
Expand All @@ -219,7 +221,9 @@ private void SetResourcesHandler(McpServerOptions options)
if ((listResourcesHandler is not { } && listResourceTemplatesHandler is not { }) ||
resourcesCapability.ReadResourceHandler is not { } readResourceHandler)
{
throw new McpException("Resources capability was enabled, but ListResources and/or ReadResource handlers were not specified.");
throw new InvalidOperationException(
$"{nameof(ServerCapabilities)}.{nameof(ServerCapabilities.Resources)} was enabled, " +
$"but {nameof(ResourcesCapability.ListResourcesHandler)} or {nameof(ResourcesCapability.ReadResourceHandler)} was not specified.");
}

listResourcesHandler ??= static async (_, _) => new ListResourcesResult();
Expand Down Expand Up @@ -252,7 +256,9 @@ private void SetResourcesHandler(McpServerOptions options)
var unsubscribeHandler = resourcesCapability.UnsubscribeFromResourcesHandler;
if (subscribeHandler is null || unsubscribeHandler is null)
{
throw new McpException("Resources capability was enabled with subscribe support, but SubscribeToResources and/or UnsubscribeFromResources handlers were not specified.");
throw new InvalidOperationException(
$"{nameof(ServerCapabilities)}.{nameof(ServerCapabilities.Resources)}.{nameof(ResourcesCapability.Subscribe)} is set, " +
$"but {nameof(ResourcesCapability.SubscribeToResourcesHandler)} or {nameof(ResourcesCapability.UnsubscribeFromResourcesHandler)} was not specified.");
}

RequestHandlers.Set(
Expand All @@ -277,7 +283,10 @@ private void SetPromptsHandler(McpServerOptions options)

if (listPromptsHandler is null != getPromptHandler is null)
{
throw new McpException("ListPrompts and GetPrompt handlers should be specified together.");
throw new InvalidOperationException(
$"{nameof(PromptsCapability)}.{nameof(promptsCapability.ListPromptsHandler)} or " +
$"{nameof(PromptsCapability)}.{nameof(promptsCapability.GetPromptHandler)} was specified without the other. " +
$"Both or neither must be provided.");
}

// Handle prompts provided via DI.
Expand Down Expand Up @@ -310,7 +319,7 @@ await originalListPromptsHandler(request, cancellationToken).ConfigureAwait(fals
return originalGetPromptHandler(request, cancellationToken);
}

throw new McpException($"Unknown prompt '{request.Params?.Name}'");
throw new McpException($"Unknown prompt: '{request.Params?.Name}'", McpErrorCode.InvalidParams);
}

return prompt.GetAsync(request, cancellationToken);
Expand Down Expand Up @@ -344,7 +353,9 @@ await originalListPromptsHandler(request, cancellationToken).ConfigureAwait(fals
// Make sure the handlers are provided if the capability is enabled.
if (listPromptsHandler is null || getPromptHandler is null)
{
throw new McpException("ListPrompts and/or GetPrompt handlers were not specified but the Prompts capability was enabled.");
throw new InvalidOperationException(
$"{nameof(ServerCapabilities)}.{nameof(ServerCapabilities.Prompts)} was enabled, " +
$"but {nameof(PromptsCapability.ListPromptsHandler)} or {nameof(PromptsCapability.GetPromptHandler)} was not specified.");
}
}

Expand All @@ -370,7 +381,10 @@ private void SetToolsHandler(McpServerOptions options)

if (listToolsHandler is null != callToolHandler is null)
{
throw new McpException("ListTools and CallTool handlers should be specified together.");
throw new InvalidOperationException(
$"{nameof(ToolsCapability)}.{nameof(ToolsCapability.ListToolsHandler)} or " +
$"{nameof(ToolsCapability)}.{nameof(ToolsCapability.CallToolHandler)} was specified without the other. " +
$"Both or neither must be provided.");
}

// Handle tools provided via DI.
Expand Down Expand Up @@ -403,7 +417,7 @@ await originalListToolsHandler(request, cancellationToken).ConfigureAwait(false)
return originalCallToolHandler(request, cancellationToken);
}

throw new McpException($"Unknown tool '{request.Params?.Name}'");
throw new McpException($"Unknown tool: '{request.Params?.Name}'", McpErrorCode.InvalidParams);
}

return tool.InvokeAsync(request, cancellationToken);
Expand Down Expand Up @@ -437,7 +451,9 @@ await originalListToolsHandler(request, cancellationToken).ConfigureAwait(false)
// Make sure the handlers are provided if the capability is enabled.
if (listToolsHandler is null || callToolHandler is null)
{
throw new McpException("ListTools and/or CallTool handlers were not specified but the Tools capability was enabled.");
throw new InvalidOperationException(
$"{nameof(ServerCapabilities)}.{nameof(ServerCapabilities.Tools)} was enabled, " +
$"but {nameof(ToolsCapability.ListToolsHandler)} or {nameof(ToolsCapability.CallToolHandler)} was not specified.");
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/ModelContextProtocol/Server/McpServerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static Task<CreateMessageResult> RequestSamplingAsync(

if (server.ClientCapabilities?.Sampling is null)
{
throw new ArgumentException("Client connected to the server does not support sampling.", nameof(server));
throw new InvalidOperationException("Client does not support sampling.");
}

return server.SendRequestAsync(
Expand Down Expand Up @@ -166,7 +166,7 @@ public static IChatClient AsSamplingChatClient(this IMcpServer server)

if (server.ClientCapabilities?.Sampling is null)
{
throw new ArgumentException("Client connected to the server does not support sampling.", nameof(server));
throw new InvalidOperationException("Client does not support sampling.");
}

return new SamplingChatClient(server);
Expand Down Expand Up @@ -204,7 +204,7 @@ public static Task<ListRootsResult> RequestRootsAsync(

if (server.ClientCapabilities?.Roots is null)
{
throw new ArgumentException("Client connected to the server does not support roots.", nameof(server));
throw new InvalidOperationException("Client does not support roots.");
}

return server.SendRequestAsync(
Expand Down
Loading