using System.Text.Json;
using System.Text.Json.Serialization;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
namespace Tests.Mcp;
internal static class McpTestExtensions {
/// Mirrors the server's tool serialization: web defaults plus enums as strings.
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) {
Converters = { new JsonStringEnumConverter() }
};
/// Calls a tool that must succeed and deserializes its structured content.
public static async Task CallOkAsync(
this McpClient client,
string tool,
Dictionary? args = null) {
CallToolResult result = await client.CallToolAsync(tool, args);
AssertOk(tool, result);
Assert.NotNull(result.StructuredContent);
return result.StructuredContent.Value.Deserialize(Json)
?? throw new InvalidOperationException($"'{tool}' returned unusable structured content.");
}
/// Calls a tool that must succeed and returns its text content.
public static async Task CallTextAsync(
this McpClient client,
string tool,
Dictionary? args = null) {
CallToolResult result = await client.CallToolAsync(tool, args);
AssertOk(tool, result);
return Text(result);
}
/// Calls a tool that must fail and returns the error text the agent would see.
public static async Task CallErrorAsync(
this McpClient client,
string tool,
Dictionary? args = null) {
CallToolResult result = await client.CallToolAsync(tool, args);
Assert.True(result.IsError == true, $"Expected '{tool}' to fail, but it succeeded: {Text(result)}");
return Text(result);
}
public static string Text(CallToolResult result) =>
string.Join(Environment.NewLine, result.Content.OfType().Select(t => t.Text));
private static void AssertOk(string tool, CallToolResult result) =>
Assert.False(result.IsError == true, $"'{tool}' failed: {Text(result)}");
}