Fix MCP schema mismatches and argument errors, highlight rejected connections and show average hold time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
570ac20a5c
commit
e86518cab1
10 files changed
+272
-17
No files matched your search
@@ -4,7 +4,6 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using Flypaper.Web.Mcp;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
@@ -12,14 +11,14 @@ namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class McpEndpointTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-http-{Guid.NewGuid():N}.db");
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public McpEndpointTests()
|
||||
{
|
||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", _data.ConnectionString);
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
});
|
||||
}
|
||||
@@ -69,10 +68,141 @@ public sealed class McpEndpointTests : IDisposable
|
||||
|
||||
var stats = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = "get_stats", arguments = new { period = "all" } })));
|
||||
var structured = stats.GetProperty("result").GetProperty("structuredContent");
|
||||
structured.GetProperty("catches").GetInt32().ShouldBe(0);
|
||||
structured.GetProperty("catches").GetInt32().ShouldBe(5);
|
||||
structured.GetProperty("period").GetString().ShouldBe("all");
|
||||
structured.GetProperty("since").ValueKind.ShouldBe(JsonValueKind.Null);
|
||||
}
|
||||
|
||||
public static TheoryData<string, string> ToolCalls => new()
|
||||
{
|
||||
{ "get_stats", """{"period":"all"}""" },
|
||||
{ "get_stats", """{"period":"24h"}""" },
|
||||
{ "list_catches", """{}""" },
|
||||
{ "list_catches", """{"country":"CN","limit":1}""" },
|
||||
{ "top", """{"dimension":"ips","period":"all"}""" },
|
||||
{ "top", """{"dimension":"countries","period":"all"}""" },
|
||||
{ "top", """{"dimension":"countries","period":"24h"}""" },
|
||||
{ "top", """{"dimension":"providers","period":"all"}""" },
|
||||
{ "top", """{"dimension":"targets","period":"all"}""" },
|
||||
{ "top", """{"dimension":"user_agents","period":"all"}""" },
|
||||
{ "longest_catches", """{"period":"all"}""" },
|
||||
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
|
||||
{ "lookup_ip", """{"ip":"192.0.2.1"}""" }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ToolCalls))]
|
||||
public async Task Tool_results_match_their_output_schema(string tool, string arguments)
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
var schema = (await OutputSchemasAsync(client, token))[tool];
|
||||
|
||||
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
|
||||
|
||||
var result = response.GetProperty("result");
|
||||
(result.TryGetProperty("isError", out var isError) && isError.GetBoolean()).ShouldBeFalse(result.ToString());
|
||||
var errors = new List<string>();
|
||||
Validate(schema, result.GetProperty("structuredContent"), "$", errors);
|
||||
errors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Every_listed_tool_is_covered_by_the_schema_test()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
|
||||
var listed = (await OutputSchemasAsync(client, token)).Keys;
|
||||
|
||||
listed.ShouldBe(ToolCalls.Select(row => (string)row[0]!).Distinct(), ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("top", """{"by":"countries","period":"all"}""", "unknown parameter 'by'; expected 'dimension' (ips|countries|providers|targets|user_agents)")]
|
||||
[InlineData("top", """{"period":"all"}""", "missing required parameter 'dimension' (ips|countries|providers|targets|user_agents)")]
|
||||
[InlineData("list_catches", """{"countryCode":"GB"}""", "unknown parameter 'countryCode'")]
|
||||
public async Task Invalid_arguments_return_a_readable_tool_error(string tool, string arguments, string expected)
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
|
||||
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
|
||||
|
||||
var result = response.GetProperty("result");
|
||||
result.GetProperty("isError").GetBoolean().ShouldBeTrue();
|
||||
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive);
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
|
||||
{
|
||||
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
||||
return tools.GetProperty("result").GetProperty("tools").EnumerateArray()
|
||||
.ToDictionary(t => t.GetProperty("name").GetString()!, t => t.GetProperty("outputSchema"));
|
||||
}
|
||||
|
||||
private static void Validate(JsonElement schema, JsonElement value, string path, List<string> errors)
|
||||
{
|
||||
if (schema.TryGetProperty("type", out var type))
|
||||
{
|
||||
var allowed = type.ValueKind == JsonValueKind.Array
|
||||
? type.EnumerateArray().Select(t => t.GetString()!).ToList()
|
||||
: [type.GetString()!];
|
||||
if (!allowed.Any(t => HasType(value, t)))
|
||||
{
|
||||
errors.Add($"{path}: {value.ValueKind} is not {string.Join(" or ", allowed)}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.TryGetProperty("enum", out var values) && !values.EnumerateArray().Any(v => v.ToString() == value.ToString()))
|
||||
{
|
||||
errors.Add($"{path}: {value} is not one of {values}");
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (schema.TryGetProperty("required", out var required))
|
||||
{
|
||||
errors.AddRange(required.EnumerateArray()
|
||||
.Where(name => !value.TryGetProperty(name.GetString()!, out _))
|
||||
.Select(name => $"{path}: missing required property '{name.GetString()}'"));
|
||||
}
|
||||
|
||||
if (schema.TryGetProperty("properties", out var properties))
|
||||
{
|
||||
foreach (var property in properties.EnumerateObject())
|
||||
{
|
||||
if (value.TryGetProperty(property.Name, out var child))
|
||||
{
|
||||
Validate(property.Value, child, $"{path}.{property.Name}", errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Array && schema.TryGetProperty("items", out var items))
|
||||
{
|
||||
var index = 0;
|
||||
foreach (var item in value.EnumerateArray())
|
||||
{
|
||||
Validate(items, item, $"{path}[{index++}]", errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasType(JsonElement value, string type) => type switch
|
||||
{
|
||||
"object" => value.ValueKind == JsonValueKind.Object,
|
||||
"array" => value.ValueKind == JsonValueKind.Array,
|
||||
"string" => value.ValueKind == JsonValueKind.String,
|
||||
"integer" => value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out _),
|
||||
"number" => value.ValueKind == JsonValueKind.Number,
|
||||
"boolean" => value.ValueKind is JsonValueKind.True or JsonValueKind.False,
|
||||
"null" => value.ValueKind == JsonValueKind.Null,
|
||||
_ => throw new NotSupportedException($"Schema type '{type}'")
|
||||
};
|
||||
|
||||
private static HttpRequestMessage Rpc(string method, string? token, object? parameters = null)
|
||||
{
|
||||
var body = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = 1, method, @params = parameters ?? new { } });
|
||||
@@ -104,10 +234,6 @@ public sealed class McpEndpointTests : IDisposable
|
||||
public void Dispose()
|
||||
{
|
||||
_factory.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
_data.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ internal sealed class McpTestData : IDisposable
|
||||
|
||||
public McpTestData()
|
||||
{
|
||||
Factory = new TestDbContextFactory($"Data Source={_dbPath}");
|
||||
Factory = new TestDbContextFactory(ConnectionString);
|
||||
using var db = Factory.CreateDbContext();
|
||||
db.Database.Migrate();
|
||||
|
||||
@@ -30,6 +30,8 @@ internal sealed class McpTestData : IDisposable
|
||||
|
||||
public IDbContextFactory<FlypaperDbContext> Factory { get; }
|
||||
|
||||
public string ConnectionString => $"Data Source={_dbPath}";
|
||||
|
||||
private static void Add(
|
||||
FlypaperDbContext db,
|
||||
string ip,
|
||||
|
||||
Reference in new issue
Block a user