using ModelContextProtocol;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;

namespace ClaudeDo.Worker.External;

/// <summary>
/// The MCP SDK's own call-tool catch-all only preserves ex.Message for <see cref="McpException"/> —
/// any other exception type is replaced with a generic "An error occurred invoking 'X'." with no detail.
/// This filter translates the expected validation exceptions thrown across the External/ tool classes
/// (task/list not found, bad status, unknown model, etc.) into McpException so callers see why a call failed.
/// </summary>
public static class ExternalMcpExceptionFilter
{
    public static McpRequestHandler<CallToolRequestParams, CallToolResult> Wrap(
        McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
        async (request, cancellationToken) =>
        {
            try
            {
                return await next(request, cancellationToken);
            }
            catch (InvalidOperationException ex)
            {
                throw new McpException(ex.Message, ex);
            }
            catch (ArgumentException ex)
            {
                throw new McpException(ex.Message, ex);
            }
        };
}
