Propagate tool call exceptions through filters (#844)

* Add McpProtocolException specifically for JSON-RPC errors
This commit is contained in:
Stephen Halter 2025-10-14 21:10:55 -05:00 • committed by GitHub
commit 3255adb4d6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 334 additions and 163 deletions

View file

@ -1,14 +1,21 @@
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol;
/// <summary>
/// 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.
/// The <see cref="Exception.Message"/> 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.
///
/// This exception type can be thrown by MCP tools or tool call filters to propagate detailed error messages
/// from <see cref="Exception.Message"/> when a tool execution fails via a <see cref="CallToolResult"/>.
/// For non-tool calls, this exception controls the message propogated via a <see cref="JsonRpcError"/>.
///
/// <see cref="McpProtocolException"/> is a derived type that can be used to also specify the
/// <see cref="McpErrorCode"/> that should be used for the resulting <see cref="JsonRpcError"/>.
/// </remarks>
public class McpException : Exception
{
@ -28,46 +35,13 @@ public class McpException : Exception
}
/// <summary>
/// Initializes a new instance of the <see cref="McpException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// Initializes a new instance of the <see cref="McpException"/> 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>
/// <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 McpException(string message, Exception? innerException) : base(message, innerException)
{
}
/// <summary>
/// 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 <see cref="McpErrorCode"/>.</param>
public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpException"/> class with a specified error message, inner exception, and JSON-RPC error code.
/// </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 <see cref="McpErrorCode"/>.</param>
public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)
{
ErrorCode = errorCode;
}
/// <summary>
/// Gets the error code associated with this exception.
/// </summary>
/// <remarks>
/// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:
/// <list type="bullet">
/// <item><description>-32700: Parse error - Invalid JSON received</description></item>
/// <item><description>-32600: Invalid request - The JSON is not a valid Request object</description></item>
/// <item><description>-32601: Method not found - The method does not exist or is not available</description></item>
/// <item><description>-32602: Invalid params - Invalid method parameters</description></item>
/// <item><description>-32603: Internal error - Internal JSON-RPC error</description></item>
/// </list>
/// </remarks>
public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;
}
}

View file

@ -0,0 +1,73 @@
namespace ModelContextProtocol;
/// <summary>
/// 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="McpProtocolException"/> 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 sealed class McpProtocolException : McpException
{
/// <summary>
/// Initializes a new instance of the <see cref="McpProtocolException"/> class.
/// </summary>
public McpProtocolException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpProtocolException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public McpProtocolException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpProtocolException"/> 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 McpProtocolException(string message, Exception? innerException) : base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpProtocolException"/> 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 <see cref="McpErrorCode"/>.</param>
public McpProtocolException(string message, McpErrorCode errorCode) : this(message, null, errorCode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="McpProtocolException"/> class with a specified error message, inner exception, and JSON-RPC error code.
/// </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 <see cref="McpErrorCode"/>.</param>
public McpProtocolException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)
{
ErrorCode = errorCode;
}
/// <summary>
/// Gets the error code associated with this exception.
/// </summary>
/// <remarks>
/// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:
/// <list type="bullet">
/// <item><description>-32700: Parse error - Invalid JSON received</description></item>
/// <item><description>-32600: Invalid request - The JSON is not a valid Request object</description></item>
/// <item><description>-32601: Method not found - The method does not exist or is not available</description></item>
/// <item><description>-32602: Invalid params - Invalid method parameters</description></item>
/// <item><description>-32603: Internal error - Internal JSON-RPC error</description></item>
/// </list>
/// </remarks>
public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;
}

View file

@ -181,11 +181,17 @@ internal sealed partial class McpSessionHandler : IAsyncDisposable
{
LogRequestHandlerException(EndpointName, request.Method, ex);
JsonRpcErrorDetail detail = ex is McpException mcpe ?
JsonRpcErrorDetail detail = ex is McpProtocolException mcpProtocolException ?
new()
{
Code = (int)mcpe.ErrorCode,
Message = mcpe.Message,
Code = (int)mcpProtocolException.ErrorCode,
Message = mcpProtocolException.Message,
} : ex is McpException mcpException ?
new()
{
Code = (int)McpErrorCode.InternalError,
Message = mcpException.Message,
} :
new()
{
@ -336,7 +342,7 @@ internal sealed partial class McpSessionHandler : IAsyncDisposable
if (!_requestHandlers.TryGetValue(request.Method, out var handler))
{
LogNoHandlerFoundForRequest(EndpointName, request.Method);
throw new McpException($"Method '{request.Method}' is not available.", McpErrorCode.MethodNotFound);
throw new McpProtocolException($"Method '{request.Method}' is not available.", McpErrorCode.MethodNotFound);
}
LogRequestHandlerCalled(EndpointName, request.Method);
@ -446,7 +452,7 @@ internal sealed partial class McpSessionHandler : IAsyncDisposable
if (response is JsonRpcError error)
{
LogSendingRequestFailed(EndpointName, request.Method, error.Error.Message, error.Error.Code);
throw new McpException($"Request failed (remote): {error.Error.Message}", (McpErrorCode)error.Error.Code);
throw new McpProtocolException($"Request failed (remote): {error.Error.Message}", (McpErrorCode)error.Error.Code);
}
if (response is JsonRpcResponse success)
@ -640,7 +646,7 @@ internal sealed partial class McpSessionHandler : IAsyncDisposable
}
int? intErrorCode =
(int?)((e as McpException)?.ErrorCode) is int errorCode ? errorCode :
(int?)((e as McpProtocolException)?.ErrorCode) is int errorCode ? errorCode :
e is JsonException ? (int)McpErrorCode.ParseError :
null;

View file

@ -291,7 +291,7 @@ public abstract partial class McpServer : McpSession, IMcpServer
/// <param name="type">The type of the schema being built.</param>
/// <param name="serializerOptions">The serializer options to use.</param>
/// <returns>The built request schema.</returns>
/// <exception cref="McpException"></exception>
/// <exception cref="McpProtocolException"></exception>
private static ElicitRequestParams.RequestSchema BuildRequestSchema(Type type, JsonSerializerOptions serializerOptions)
{
var schema = new ElicitRequestParams.RequestSchema();
@ -301,7 +301,7 @@ public abstract partial class McpServer : McpSession, IMcpServer
if (typeInfo.Kind != JsonTypeInfoKind.Object)
{
throw new McpException($"Type '{type.FullName}' is not supported for elicitation requests.");
throw new McpProtocolException($"Type '{type.FullName}' is not supported for elicitation requests.");
}
foreach (JsonPropertyInfo pi in typeInfo.Properties)
@ -319,33 +319,33 @@ public abstract partial class McpServer : McpSession, IMcpServer
/// <param name="type">The type to create the schema for.</param>
/// <param name="serializerOptions">The serializer options to use.</param>
/// <returns>The created primitive schema definition.</returns>
/// <exception cref="McpException">Thrown when the type is not supported.</exception>
/// <exception cref="McpProtocolException">Thrown when the type is not supported.</exception>
private static ElicitRequestParams.PrimitiveSchemaDefinition CreatePrimitiveSchema(Type type, JsonSerializerOptions serializerOptions)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests. Nullable types are not supported.");
throw new McpProtocolException($"Type '{type.FullName}' is not a supported property type for elicitation requests. Nullable types are not supported.");
}
var typeInfo = serializerOptions.GetTypeInfo(type);
if (typeInfo.Kind != JsonTypeInfoKind.None)
{
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
throw new McpProtocolException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
}
var jsonElement = AIJsonUtilities.CreateJsonSchema(type, serializerOptions: serializerOptions);
if (!TryValidateElicitationPrimitiveSchema(jsonElement, type, out var error))
{
throw new McpException(error);
throw new McpProtocolException(error);
}
var primitiveSchemaDefinition =
jsonElement.Deserialize(McpJsonUtilities.JsonContext.Default.PrimitiveSchemaDefinition);
if (primitiveSchemaDefinition is null)
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
throw new McpProtocolException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
return primitiveSchemaDefinition;
}

View file

@ -288,7 +288,7 @@ internal sealed partial class McpServerImpl : McpServer
listResourcesHandler ??= (static async (_, __) => new ListResourcesResult());
listResourceTemplatesHandler ??= (static async (_, __) => new ListResourceTemplatesResult());
readResourceHandler ??= (static async (request, _) => throw new McpException($"Unknown resource URI: '{request.Params?.Uri}'", McpErrorCode.InvalidParams));
readResourceHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown resource URI: '{request.Params?.Uri}'", McpErrorCode.InvalidParams));
subscribeHandler ??= (static async (_, __) => new EmptyResult());
unsubscribeHandler ??= (static async (_, __) => new EmptyResult());
var listChanged = resourcesCapability?.ListChanged;
@ -452,7 +452,7 @@ internal sealed partial class McpServerImpl : McpServer
ServerCapabilities.Prompts = new();
listPromptsHandler ??= (static async (_, __) => new ListPromptsResult());
getPromptHandler ??= (static async (request, _) => throw new McpException($"Unknown prompt: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
getPromptHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown prompt: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
var listChanged = promptsCapability?.ListChanged;
// Handle tools provided via DI by augmenting the handlers to incorporate them.
@ -540,7 +540,7 @@ internal sealed partial class McpServerImpl : McpServer
ServerCapabilities.Tools = new();
listToolsHandler ??= (static async (_, __) => new ListToolsResult());
callToolHandler ??= (static async (request, _) => throw new McpException($"Unknown tool: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
callToolHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown tool: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
var listChanged = toolsCapability?.ListChanged;
// Handle tools provided via DI by augmenting the handlers to incorporate them.
@ -580,7 +580,7 @@ internal sealed partial class McpServerImpl : McpServer
listToolsHandler = BuildFilterPipeline(listToolsHandler, options.Filters.ListToolsFilters);
callToolHandler = BuildFilterPipeline(callToolHandler, options.Filters.CallToolFilters, handler =>
(request, cancellationToken) =>
async (request, cancellationToken) =>
{
// Initial handler that sets MatchedPrimitive
if (request.Params?.Name is { } toolName && tools is not null &&
@ -589,37 +589,23 @@ internal sealed partial class McpServerImpl : McpServer
request.MatchedPrimitive = tool;
}
return handler(request, cancellationToken);
}, handler =>
async (request, cancellationToken) =>
{
// Final handler that provides exception handling only for tool execution
// Only wrap tool execution in try-catch, not tool resolution
if (request.MatchedPrimitive is McpServerTool)
try
{
try
{
return await handler(request, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (e is not OperationCanceledException)
{
ToolCallError(request.Params?.Name ?? string.Empty, e);
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 TextContentBlock { Text = errorMessage }],
};
}
return await handler(request, cancellationToken);
}
else
catch (Exception e) when (e is not OperationCanceledException and not McpProtocolException)
{
// For unmatched tools, let exceptions bubble up as protocol errors
return await handler(request, cancellationToken).ConfigureAwait(false);
ToolCallError(request.Params?.Name ?? string.Empty, e);
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 TextContentBlock { Text = errorMessage }],
};
}
});
@ -735,16 +721,10 @@ internal sealed partial class McpServerImpl : McpServer
private static McpRequestHandler<TParams, TResult> BuildFilterPipeline<TParams, TResult>(
McpRequestHandler<TParams, TResult> baseHandler,
List<McpRequestFilter<TParams, TResult>> filters,
McpRequestFilter<TParams, TResult>? initialHandler = null,
McpRequestFilter<TParams, TResult>? finalHandler = null)
McpRequestFilter<TParams, TResult>? initialHandler = null)
{
var current = baseHandler;
if (finalHandler is not null)
{
current = finalHandler(current);
}
for (int i = filters.Count - 1; i >= 0; i--)
{
current = filters[i](current);