|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using ModelContextProtocol.Client; |
| 3 | +using ModelContextProtocol.Protocol; |
| 4 | +using ModelContextProtocol.Server; |
| 5 | +using ModelContextProtocol.Tests.Utils; |
| 6 | +using System.Text.Json; |
| 7 | + |
| 8 | +namespace ModelContextProtocol.Tests; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Tests for McpProtocolException.Data propagation to JSON-RPC error responses. |
| 12 | +/// </summary> |
| 13 | +/// <remarks> |
| 14 | +/// Primitive values (strings, numbers, bools) are extracted from JsonElements and stored directly, |
| 15 | +/// which works on all platforms including .NET Framework. Complex objects and arrays are stored as |
| 16 | +/// JsonElement on .NET Core, but skipped on .NET Framework (where JsonElement is not serializable). |
| 17 | +/// </remarks> |
| 18 | +public class McpProtocolExceptionDataTests : ClientServerTestBase |
| 19 | +{ |
| 20 | + public static bool IsNotNetFramework => !PlatformDetection.IsNetFramework; |
| 21 | + |
| 22 | + public McpProtocolExceptionDataTests(ITestOutputHelper testOutputHelper) |
| 23 | + : base(testOutputHelper) |
| 24 | + { |
| 25 | + } |
| 26 | + |
| 27 | + protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) |
| 28 | + { |
| 29 | + mcpServerBuilder.WithCallToolHandler((request, cancellationToken) => |
| 30 | + { |
| 31 | + var toolName = request.Params?.Name; |
| 32 | + |
| 33 | + switch (toolName) |
| 34 | + { |
| 35 | + case "throw_with_serializable_data": |
| 36 | + throw new McpProtocolException("Resource not found", (McpErrorCode)(-32002)) |
| 37 | + { |
| 38 | + Data = |
| 39 | + { |
| 40 | + { "uri", "file:///path/to/resource" }, |
| 41 | + { "code", 404 } |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + case "throw_with_nonserializable_data": |
| 46 | + throw new McpProtocolException("Resource not found", (McpErrorCode)(-32002)) |
| 47 | + { |
| 48 | + Data = |
| 49 | + { |
| 50 | + // Circular reference - cannot be serialized |
| 51 | + { "nonSerializable", new NonSerializableObject() }, |
| 52 | + // This one should still be included |
| 53 | + { "uri", "file:///path/to/resource" } |
| 54 | + } |
| 55 | + }; |
| 56 | + |
| 57 | + case "throw_with_only_nonserializable_data": |
| 58 | + throw new McpProtocolException("Resource not found", (McpErrorCode)(-32002)) |
| 59 | + { |
| 60 | + Data = |
| 61 | + { |
| 62 | + // Only non-serializable data - should result in null data |
| 63 | + { "nonSerializable", new NonSerializableObject() } |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + default: |
| 68 | + throw new McpProtocolException($"Unknown tool: '{toolName}'", McpErrorCode.InvalidParams); |
| 69 | + } |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + [Fact] |
| 74 | + public async Task Exception_With_Serializable_Data_Propagates_To_Client() |
| 75 | + { |
| 76 | + await using McpClient client = await CreateMcpClientForServer(); |
| 77 | + |
| 78 | + var exception = await Assert.ThrowsAsync<McpProtocolException>(async () => |
| 79 | + await client.CallToolAsync("throw_with_serializable_data", cancellationToken: TestContext.Current.CancellationToken)); |
| 80 | + |
| 81 | + Assert.Equal("Request failed (remote): Resource not found", exception.Message); |
| 82 | + Assert.Equal((McpErrorCode)(-32002), exception.ErrorCode); |
| 83 | + |
| 84 | + // Verify the data was propagated to the exception |
| 85 | + // The Data collection should contain the expected keys |
| 86 | + var hasUri = false; |
| 87 | + var hasCode = false; |
| 88 | + foreach (System.Collections.DictionaryEntry entry in exception.Data) |
| 89 | + { |
| 90 | + if (entry.Key is string key) |
| 91 | + { |
| 92 | + if (key == "uri") hasUri = true; |
| 93 | + if (key == "code") hasCode = true; |
| 94 | + } |
| 95 | + } |
| 96 | + Assert.True(hasUri, "Exception.Data should contain 'uri' key"); |
| 97 | + Assert.True(hasCode, "Exception.Data should contain 'code' key"); |
| 98 | + |
| 99 | + // Verify the values - primitives are extracted as their native types (string, double, bool) |
| 100 | + Assert.Equal("file:///path/to/resource", exception.Data["uri"]); |
| 101 | + Assert.Equal(404.0, exception.Data["code"]); // Numbers are stored as double |
| 102 | + } |
| 103 | + |
| 104 | + [Fact(Skip = "Non-serializable test data not supported on .NET Framework", SkipUnless = nameof(IsNotNetFramework))] |
| 105 | + public async Task Exception_With_NonSerializable_Data_Still_Propagates_Error_To_Client() |
| 106 | + { |
| 107 | + await using McpClient client = await CreateMcpClientForServer(); |
| 108 | + |
| 109 | + // The tool throws McpProtocolException with non-serializable data in Exception.Data. |
| 110 | + // The server should still send a proper error response to the client, with non-serializable |
| 111 | + // values filtered out. |
| 112 | + var exception = await Assert.ThrowsAsync<McpProtocolException>(async () => |
| 113 | + await client.CallToolAsync("throw_with_nonserializable_data", cancellationToken: TestContext.Current.CancellationToken)); |
| 114 | + |
| 115 | + Assert.Equal("Request failed (remote): Resource not found", exception.Message); |
| 116 | + Assert.Equal((McpErrorCode)(-32002), exception.ErrorCode); |
| 117 | + |
| 118 | + // Verify that only the serializable data was propagated (non-serializable was filtered out) |
| 119 | + var hasUri = false; |
| 120 | + var hasNonSerializable = false; |
| 121 | + foreach (System.Collections.DictionaryEntry entry in exception.Data) |
| 122 | + { |
| 123 | + if (entry.Key is string key) |
| 124 | + { |
| 125 | + if (key == "uri") hasUri = true; |
| 126 | + if (key == "nonSerializable") hasNonSerializable = true; |
| 127 | + } |
| 128 | + } |
| 129 | + Assert.True(hasUri, "Exception.Data should contain 'uri' key"); |
| 130 | + Assert.False(hasNonSerializable, "Exception.Data should not contain 'nonSerializable' key"); |
| 131 | + |
| 132 | + Assert.Equal("file:///path/to/resource", exception.Data["uri"]); |
| 133 | + } |
| 134 | + |
| 135 | + [Fact(Skip = "Non-serializable test data not supported on .NET Framework", SkipUnless = nameof(IsNotNetFramework))] |
| 136 | + public async Task Exception_With_Only_NonSerializable_Data_Still_Propagates_Error_To_Client() |
| 137 | + { |
| 138 | + await using McpClient client = await CreateMcpClientForServer(); |
| 139 | + |
| 140 | + // When all data is non-serializable, the error should still be sent (with null data) |
| 141 | + var exception = await Assert.ThrowsAsync<McpProtocolException>(async () => |
| 142 | + await client.CallToolAsync("throw_with_only_nonserializable_data", cancellationToken: TestContext.Current.CancellationToken)); |
| 143 | + |
| 144 | + Assert.Equal("Request failed (remote): Resource not found", exception.Message); |
| 145 | + Assert.Equal((McpErrorCode)(-32002), exception.ErrorCode); |
| 146 | + |
| 147 | + // When all data is non-serializable, the Data collection should be empty |
| 148 | + // (the server's ConvertExceptionData returns null when no serializable data exists) |
| 149 | + Assert.Empty(exception.Data); |
| 150 | + } |
| 151 | + |
| 152 | + /// <summary> |
| 153 | + /// A class that cannot be serialized by System.Text.Json due to circular reference. |
| 154 | + /// </summary> |
| 155 | + private sealed class NonSerializableObject |
| 156 | + { |
| 157 | + public NonSerializableObject() => Self = this; |
| 158 | + public NonSerializableObject Self { get; set; } |
| 159 | + } |
| 160 | +} |
0 commit comments