diff --git a/CHANGELOG.md b/CHANGELOG.md index 4976581..543730f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,23 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +### Fixed + +- MCP results now include fields whose value is `null` (e.g. `since` of `get_stats` with + `period=all`, a missing label in `top`) instead of leaving them out, so they match the + tools' output schemas. +- MCP tools answer unknown or missing parameters with a readable error instead of + "An error occurred invoking …" or silently ignoring them, e.g. `unknown parameter 'by'; + expected 'dimension' (ips|countries|providers|targets|user_agents)`. `top` lists the allowed + values of `dimension` in its input schema. Invalid arguments are logged as warnings. + +### Changed + +- Rejected connections stand out on the dashboard: the "Abgelehnt" metric shows the last + 24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in + German. Top lists and hold times still count only real catches. +- The "Haltezeit gesamt" metric shows the average hold time per catch below it. + ## [0.3.1] - 2026-11-15 ### Changed diff --git a/src/Flypaper.Storage/Dashboard/DashboardData.cs b/src/Flypaper.Storage/Dashboard/DashboardData.cs index b27bcb8..3744061 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardData.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardData.cs @@ -6,6 +6,7 @@ public sealed record DashboardData( int TotalCatches, int CatchesLast24Hours, int Rejected, + int RejectedLast24Hours, int UniqueIps, TimeSpan TotalHoldTime, IReadOnlyList Recent, diff --git a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs index 513ece4..6ff1f30 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs @@ -37,6 +37,7 @@ public sealed class DashboardQueries(IDbContextFactory dbCont await catches.CountAsync(ct), await catches.CountAsync(e => e.StartedAt >= since, ct), await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), + await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct), await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct), diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor index 724a64e..6c3e754 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor @@ -1,5 +1,6 @@ @page "/" @using Flypaper.Core.Abstractions +@using Flypaper.Core.Models @using Flypaper.Http @using Microsoft.Extensions.Options @using Flypaper.Storage.Dashboard @@ -40,11 +41,12 @@
Haltezeit gesamt @Formatting.Duration(data.TotalHoldTime) + Ø @(data.TotalCatches == 0 ? "–" : Formatting.Duration(data.TotalHoldTime / data.TotalCatches)) pro Fang
Abgelehnt @data.Rejected.ToString("N0") - wegen Verbindungslimits + +@data.RejectedLast24Hours.ToString("N0") in 24 h · Verbindungslimit erreicht
@@ -111,7 +113,7 @@ var target = Formatting.Target(trapEvent.Target); var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs)); var bytes = trapEvent.BytesSent.ToString("N0"); - + @started.ToString("dd.MM.") @started.ToString("HH:mm:ss") @trapEvent.RemoteIp @@ -131,12 +133,12 @@
User-Agent: @(trapEvent.ClientInfo ?? "–")
Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")
Dauer: @duration · Bytes: @bytes
-
Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @trapEvent.Outcome
+
Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)
@trapEvent.ClientInfo @duration @bytes - @trapEvent.Outcome + @OutcomeLabel(trapEvent.Outcome) } @@ -166,6 +168,15 @@ new("targets", "Ziele", "Ziel", data.TopTargets, KeyFormatter: Formatting.Target) ]; + private static string OutcomeLabel(TrapOutcome outcome) => outcome switch + { + TrapOutcome.Timeout => "Zeitlimit", + TrapOutcome.ClientAborted => "Abgebrochen", + TrapOutcome.Rejected => "Abgelehnt", + TrapOutcome.Completed => "Beendet", + _ => outcome.ToString() + }; + private static string Origin(TrapEventEntity trapEvent) => string.Join(", ", new[] { trapEvent.City, CountryNames.Display(trapEvent.CountryCode, trapEvent.Country) }.Where(part => !string.IsNullOrEmpty(part))); diff --git a/src/Flypaper.Web/Mcp/FlypaperTools.cs b/src/Flypaper.Web/Mcp/FlypaperTools.cs index c8db7b1..aeebf2d 100644 --- a/src/Flypaper.Web/Mcp/FlypaperTools.cs +++ b/src/Flypaper.Web/Mcp/FlypaperTools.cs @@ -1,4 +1,5 @@ using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Net; using Flypaper.Core.Abstractions; @@ -39,7 +40,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove public async Task ListCatches( [Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null, [Description("Only events that started before this ISO 8601 time.")] string? until = null, - [Description("ISO 3166-1 alpha-2 country code, e.g. CN.")] string? country = null, + [Description("Country as ISO 3166-1 alpha-2 code, e.g. CN or GB.")] string? country = null, [Description("Network provider: an AS number such as AS4134, or part of the provider name.")] string? provider = null, [Description("Exact client IP address.")] string? ip = null, [Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null, @@ -61,7 +62,9 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove [McpServerTool(Name = "top", Title = "Top values", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Most frequent values among the catches of a time window, by number of catches. Rejected connections are not counted.")] public async Task Top( - [Description("What to rank: ips, countries, providers, targets or user_agents.")] string dimension, + [Description("What to rank by: ips, countries, providers, targets or user_agents.")] + [AllowedValues("ips", "countries", "providers", "targets", "user_agents")] + string dimension, [Description(PeriodDescription)] string period = "24h", [Description("Number of entries, 1 to 500.")] int limit = 10, CancellationToken ct = default) diff --git a/src/Flypaper.Web/Mcp/McpArgumentCheck.cs b/src/Flypaper.Web/Mcp/McpArgumentCheck.cs new file mode 100644 index 0000000..ac19b01 --- /dev/null +++ b/src/Flypaper.Web/Mcp/McpArgumentCheck.cs @@ -0,0 +1,45 @@ +using System.Text.Json; + +namespace Flypaper.Web.Mcp; + +public static class McpArgumentCheck +{ + public static string? FindProblem(JsonElement inputSchema, IReadOnlyDictionary? arguments) + { + var properties = inputSchema.TryGetProperty("properties", out var schemaProperties) + ? schemaProperties.EnumerateObject().ToDictionary(p => p.Name, p => p.Value, StringComparer.Ordinal) + : []; + var required = inputSchema.TryGetProperty("required", out var schemaRequired) + ? schemaRequired.EnumerateArray().Select(r => r.GetString()!).ToList() + : []; + var given = arguments?.Keys.ToList() ?? []; + + var unknown = given.Where(name => !properties.ContainsKey(name)).ToList(); + var missing = required.Where(name => !given.Contains(name, StringComparer.Ordinal)).ToList(); + if (unknown.Count == 0 && missing.Count == 0) + { + return null; + } + + var problems = new List(); + if (unknown.Count == 1 && missing.Count == 1) + { + problems.Add($"unknown parameter '{unknown[0]}'; expected '{missing[0]}'{Values(properties[missing[0]])}"); + } + else + { + problems.AddRange(unknown.Select(name => $"unknown parameter '{name}'")); + problems.AddRange(missing.Select(name => $"missing required parameter '{name}'{Values(properties[name])}")); + } + + var allowed = properties.Count == 0 + ? "none" + : string.Join(", ", properties.Select(p => required.Contains(p.Key) ? $"{p.Key} (required)" : p.Key)); + return $"{string.Join("; ", problems)}. Parameters: {allowed}."; + } + + private static string Values(JsonElement property) => + property.TryGetProperty("enum", out var values) + ? $" ({string.Join("|", values.EnumerateArray().Select(v => v.GetString()))})" + : ""; +} diff --git a/src/Flypaper.Web/Mcp/McpExtensions.cs b/src/Flypaper.Web/Mcp/McpExtensions.cs index 3e8787e..4028cd6 100644 --- a/src/Flypaper.Web/Mcp/McpExtensions.cs +++ b/src/Flypaper.Web/Mcp/McpExtensions.cs @@ -1,7 +1,11 @@ +using System.Text.Json; +using System.Text.Json.Serialization; using Flypaper.Storage.Settings; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; +using ModelContextProtocol; using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; namespace Flypaper.Web.Mcp; @@ -16,6 +20,11 @@ public static class McpExtensions "stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " + "and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds."; + private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions) + { + DefaultIgnoreCondition = JsonIgnoreCondition.Never + }; + public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection(McpOptions.SectionName)); @@ -34,11 +43,39 @@ public static class McpExtensions options.ServerInstructions = Instructions; }) .WithHttpTransport(options => options.Stateless = true) - .WithTools(); + .WithTools(ToolJsonOptions) + .WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) => + { + var tool = context.Params?.Name; + var logger = context.Services?.GetRequiredService().CreateLogger(typeof(FlypaperTools)); + + if (context.MatchedPrimitive is McpServerTool matched + && McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem) + { + logger?.LogWarning("MCP tool {Tool} was called with invalid arguments: {Problem}", tool, problem); + return InvalidArguments(tool, problem); + } + + try + { + return await next(context, ct); + } + catch (ArgumentException exception) + { + logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool); + return InvalidArguments(tool, exception.Message); + } + })); return services; } + private static CallToolResult InvalidArguments(string? tool, string message) => new() + { + IsError = true, + Content = [new TextContentBlock { Text = $"Invalid arguments for '{tool}': {message}" }] + }; + public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app) { app.MapMcp(Path).RequireAuthorization(PolicyName); diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index b575278..4c7a8ef 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -441,9 +441,21 @@ tr.open .clip { } .outcome.rejected { + padding: 1px 7px; + border: 1px solid color-mix(in srgb, var(--bad) 45%, transparent); + border-radius: 999px; + background: color-mix(in srgb, var(--bad) 12%, transparent); color: var(--bad); } +.recent-table tr.rejected td { + color: var(--muted); +} + +.recent-table tr.rejected td:first-child { + box-shadow: inset 3px 0 0 var(--bad); +} + @media (max-width: 600px) { .clip { max-width: 180px; diff --git a/test/Flypaper.Tests/Mcp/McpEndpointTests.cs b/test/Flypaper.Tests/Mcp/McpEndpointTests.cs index 57c6888..3dd3739 100644 --- a/test/Flypaper.Tests/Mcp/McpEndpointTests.cs +++ b/test/Flypaper.Tests/Mcp/McpEndpointTests.cs @@ -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 _factory; public McpEndpointTests() { _factory = new WebApplicationFactory().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 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().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(); + 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().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().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> 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 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(); } } diff --git a/test/Flypaper.Tests/Mcp/McpTestData.cs b/test/Flypaper.Tests/Mcp/McpTestData.cs index 6e1368b..baccf46 100644 --- a/test/Flypaper.Tests/Mcp/McpTestData.cs +++ b/test/Flypaper.Tests/Mcp/McpTestData.cs @@ -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 Factory { get; } + public string ConnectionString => $"Data Source={_dbPath}"; + private static void Add( FlypaperDbContext db, string ip,