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

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);