-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathContentBlockTests.cs
More file actions
326 lines (283 loc) · 13.3 KB
/
ContentBlockTests.cs
File metadata and controls
326 lines (283 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using ModelContextProtocol.Protocol;
using System.Text.Json;
namespace ModelContextProtocol.Tests.Protocol;
public class ContentBlockTests
{
[Fact]
public void ResourceLinkBlock_SerializationRoundTrip_PreservesAllProperties()
{
// Arrange
var original = new ResourceLinkBlock
{
Uri = "https://example.com/resource",
Name = "Test Resource",
Title = "Test Resource Title",
Description = "A test resource for validation",
MimeType = "text/plain",
Size = 1024,
Icons = [new Icon { Source = "https://example.com/icon.png", MimeType = "image/png" }]
};
// Act - Serialize to JSON
string json = JsonSerializer.Serialize(original, McpJsonUtilities.DefaultOptions);
// Act - Deserialize back from JSON
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
// Assert
Assert.NotNull(deserialized);
var resourceLink = Assert.IsType<ResourceLinkBlock>(deserialized);
Assert.Equal(original.Uri, resourceLink.Uri);
Assert.Equal(original.Name, resourceLink.Name);
Assert.Equal(original.Title, resourceLink.Title);
Assert.Equal(original.Description, resourceLink.Description);
Assert.Equal(original.MimeType, resourceLink.MimeType);
Assert.Equal(original.Size, resourceLink.Size);
Assert.Equal("resource_link", resourceLink.Type);
Assert.NotNull(resourceLink.Icons);
Assert.Single(resourceLink.Icons);
Assert.Equal("https://example.com/icon.png", resourceLink.Icons[0].Source);
Assert.Equal("image/png", resourceLink.Icons[0].MimeType);
}
[Fact]
public void ResourceLinkBlock_DeserializationWithMinimalProperties_Succeeds()
{
// Arrange - JSON with only required properties
const string Json = """
{
"type": "resource_link",
"uri": "https://example.com/minimal",
"name": "Minimal Resource"
}
""";
// Act
var deserialized = JsonSerializer.Deserialize<ContentBlock>(Json, McpJsonUtilities.DefaultOptions);
// Assert
Assert.NotNull(deserialized);
var resourceLink = Assert.IsType<ResourceLinkBlock>(deserialized);
Assert.Equal("https://example.com/minimal", resourceLink.Uri);
Assert.Equal("Minimal Resource", resourceLink.Name);
Assert.Null(resourceLink.Title);
Assert.Null(resourceLink.Description);
Assert.Null(resourceLink.MimeType);
Assert.Null(resourceLink.Size);
Assert.Null(resourceLink.Icons);
Assert.Equal("resource_link", resourceLink.Type);
}
[Fact]
public void ResourceLinkBlock_DeserializationWithoutName_ThrowsJsonException()
{
// Arrange - JSON missing the required "name" property
const string Json = """
{
"type": "resource_link",
"uri": "https://example.com/missing-name"
}
""";
// Act & Assert
var exception = Assert.Throws<JsonException>(() =>
JsonSerializer.Deserialize<ContentBlock>(Json, McpJsonUtilities.DefaultOptions));
Assert.Contains("Name must be provided for 'resource_link' type", exception.Message);
}
[Fact]
public void ResourceLinkBlock_DeserializationWithTitleAndIcons_Succeeds()
{
// Arrange - JSON with title and icons properties per spec
const string Json = """
{
"type": "resource_link",
"uri": "https://example.com/resource",
"name": "my-resource",
"title": "My Resource",
"icons": [
{ "src": "https://example.com/icon1.png", "mimeType": "image/png", "sizes": ["48x48"], "theme": "light" },
{ "src": "https://example.com/icon2.svg", "mimeType": "image/svg+xml" }
]
}
""";
// Act
var deserialized = JsonSerializer.Deserialize<ContentBlock>(Json, McpJsonUtilities.DefaultOptions);
// Assert
Assert.NotNull(deserialized);
var resourceLink = Assert.IsType<ResourceLinkBlock>(deserialized);
Assert.Equal("https://example.com/resource", resourceLink.Uri);
Assert.Equal("my-resource", resourceLink.Name);
Assert.Equal("My Resource", resourceLink.Title);
Assert.NotNull(resourceLink.Icons);
Assert.Equal(2, resourceLink.Icons.Count);
Assert.Equal("https://example.com/icon1.png", resourceLink.Icons[0].Source);
Assert.Equal("image/png", resourceLink.Icons[0].MimeType);
Assert.NotNull(resourceLink.Icons[0].Sizes);
Assert.Equal("48x48", resourceLink.Icons[0].Sizes![0]);
Assert.Equal("light", resourceLink.Icons[0].Theme);
Assert.Equal("https://example.com/icon2.svg", resourceLink.Icons[1].Source);
Assert.Equal("image/svg+xml", resourceLink.Icons[1].MimeType);
}
[Fact]
public void Deserialize_IgnoresUnknownArrayProperty()
{
// This is a regression test where a server returned an unexpected response with
// `structuredContent` as an array nested inside a content block. This should be
// permitted with the `structuredContent` gracefully ignored in that location.
string responseJson = @"{
""type"": ""text"",
""text"": ""[\n {\n \""Data\"": \""1234567890\""\n }\n]"",
""structuredContent"": [
{
""Data"": ""1234567890""
}
]
}";
var contentBlock = JsonSerializer.Deserialize<ContentBlock>(responseJson, McpJsonUtilities.DefaultOptions);
Assert.NotNull(contentBlock);
var textBlock = Assert.IsType<TextContentBlock>(contentBlock);
Assert.Contains("1234567890", textBlock.Text);
}
[Fact]
public void Deserialize_IgnoresUnknownObjectProperties()
{
string responseJson = @"{
""type"": ""text"",
""text"": ""Sample text"",
""unknownObject"": {
""nestedProp1"": ""value1"",
""nestedProp2"": {
""deeplyNested"": true
}
}
}";
var contentBlock = JsonSerializer.Deserialize<ContentBlock>(responseJson, McpJsonUtilities.DefaultOptions);
Assert.NotNull(contentBlock);
var textBlock = Assert.IsType<TextContentBlock>(contentBlock);
Assert.Contains("Sample text", textBlock.Text);
}
[Fact]
public void ToolResultContentBlock_WithError_SerializationRoundtrips()
{
ToolResultContentBlock toolResult = new()
{
ToolUseId = "call_123",
Content = [new TextContentBlock { Text = "Error: City not found" }],
IsError = true
};
var json = JsonSerializer.Serialize<ContentBlock>(toolResult, McpJsonUtilities.DefaultOptions);
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var result = Assert.IsType<ToolResultContentBlock>(deserialized);
Assert.Equal("call_123", result.ToolUseId);
Assert.True(result.IsError);
Assert.Single(result.Content);
var textBlock = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("Error: City not found", textBlock.Text);
}
[Fact]
public void ToolResultContentBlock_WithStructuredContent_SerializationRoundtrips()
{
ToolResultContentBlock toolResult = new()
{
ToolUseId = "call_123",
Content =
[
new TextContentBlock { Text = "Result data" }
],
StructuredContent = JsonElement.Parse("""{"temperature":18,"condition":"cloudy"}"""),
IsError = false
};
var json = JsonSerializer.Serialize<ContentBlock>(toolResult, McpJsonUtilities.DefaultOptions);
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var result = Assert.IsType<ToolResultContentBlock>(deserialized);
Assert.Equal("call_123", result.ToolUseId);
Assert.Single(result.Content);
var textBlock = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("Result data", textBlock.Text);
Assert.NotNull(result.StructuredContent);
Assert.Equal(18, result.StructuredContent.Value.GetProperty("temperature").GetInt32());
Assert.Equal("cloudy", result.StructuredContent.Value.GetProperty("condition").GetString());
Assert.False(result.IsError);
}
[Fact]
public void ToolResultContentBlock_SerializationRoundTrip()
{
ToolResultContentBlock toolResult = new()
{
ToolUseId = "call_123",
Content =
[
new TextContentBlock { Text = "Result data" },
new ImageContentBlock { Data = System.Text.Encoding.UTF8.GetBytes("base64data"), MimeType = "image/png" }
],
StructuredContent = JsonElement.Parse("""{"temperature":18,"condition":"cloudy"}"""),
IsError = false
};
var json = JsonSerializer.Serialize<ContentBlock>(toolResult, McpJsonUtilities.DefaultOptions);
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var result = Assert.IsType<ToolResultContentBlock>(deserialized);
Assert.Equal("call_123", result.ToolUseId);
Assert.Equal(2, result.Content.Count);
var textBlock = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("Result data", textBlock.Text);
var imageBlock = Assert.IsType<ImageContentBlock>(result.Content[1]);
Assert.Equal("base64data", System.Text.Encoding.UTF8.GetString(imageBlock.Data.ToArray()));
Assert.Equal("image/png", imageBlock.MimeType);
Assert.NotNull(result.StructuredContent);
Assert.Equal(18, result.StructuredContent.Value.GetProperty("temperature").GetInt32());
Assert.Equal("cloudy", result.StructuredContent.Value.GetProperty("condition").GetString());
Assert.False(result.IsError);
}
[Fact]
public void ToolUseContentBlock_SerializationRoundTrip()
{
ToolUseContentBlock toolUse = new()
{
Id = "call_abc123",
Name = "get_weather",
Input = JsonElement.Parse("""{"city":"Paris","units":"metric"}""")
};
var json = JsonSerializer.Serialize<ContentBlock>(toolUse, McpJsonUtilities.DefaultOptions);
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var result = Assert.IsType<ToolUseContentBlock>(deserialized);
Assert.Equal("call_abc123", result.Id);
Assert.Equal("get_weather", result.Name);
Assert.Equal("Paris", result.Input.GetProperty("city").GetString());
Assert.Equal("metric", result.Input.GetProperty("units").GetString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void ImageContentBlock_FromBytes_ThrowsForNullOrWhiteSpaceMimeType(string? mimeType)
{
Assert.ThrowsAny<ArgumentException>(() => ImageContentBlock.FromBytes((byte[])[1, 2, 3], mimeType!));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void AudioContentBlock_FromBytes_ThrowsForNullOrWhiteSpaceMimeType(string? mimeType)
{
Assert.ThrowsAny<ArgumentException>(() => AudioContentBlock.FromBytes((byte[])[1, 2, 3], mimeType!));
}
[Fact]
public void ImageContentBlock_Deserialization_HandlesEscapedForwardSlashInBase64()
{
// Base64 uses '/' which some JSON encoders escape as '\/' (valid JSON).
// The converter must unescape before storing the base64 UTF-8 bytes.
byte[] originalBytes = [0xFF, 0xD8, 0xFF, 0xE0]; // sample bytes that produce '/' in base64
string base64 = Convert.ToBase64String(originalBytes); // "/9j/4A=="
Assert.Contains("/", base64);
// Simulate a JSON encoder that escapes '/' as '\/'
string json = $$"""{"type":"image","data":"{{base64.Replace("/", "\\/")}}","mimeType":"image/jpeg"}""";
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var image = Assert.IsType<ImageContentBlock>(deserialized);
Assert.Equal(base64, System.Text.Encoding.UTF8.GetString(image.Data.ToArray()));
Assert.Equal(originalBytes, image.DecodedData.ToArray());
}
[Fact]
public void AudioContentBlock_Deserialization_HandlesEscapedForwardSlashInBase64()
{
byte[] originalBytes = [0xFF, 0xD8, 0xFF, 0xE0];
string base64 = Convert.ToBase64String(originalBytes);
Assert.Contains("/", base64);
string json = $$"""{"type":"audio","data":"{{base64.Replace("/", "\\/")}}","mimeType":"audio/wav"}""";
var deserialized = JsonSerializer.Deserialize<ContentBlock>(json, McpJsonUtilities.DefaultOptions);
var audio = Assert.IsType<AudioContentBlock>(deserialized);
Assert.Equal(base64, System.Text.Encoding.UTF8.GetString(audio.Data.ToArray()));
Assert.Equal(originalBytes, audio.DecodedData.ToArray());
}
}