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
@@ -6,6 +6,7 @@ public sealed record DashboardData(
|
||||
int TotalCatches,
|
||||
int CatchesLast24Hours,
|
||||
int Rejected,
|
||||
int RejectedLast24Hours,
|
||||
int UniqueIps,
|
||||
TimeSpan TotalHoldTime,
|
||||
IReadOnlyList<TrapEventEntity> Recent,
|
||||
|
||||
@@ -37,6 +37,7 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> 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),
|
||||
|
||||
@@ -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 @@
|
||||
<div class="metric">
|
||||
<span class="label">Haltezeit gesamt</span>
|
||||
<span class="value">@Formatting.Duration(data.TotalHoldTime)</span>
|
||||
<span class="sub">Ø @(data.TotalCatches == 0 ? "–" : Formatting.Duration(data.TotalHoldTime / data.TotalCatches)) pro Fang</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Abgelehnt</span>
|
||||
<span class="value">@data.Rejected.ToString("N0")</span>
|
||||
<span class="sub">wegen Verbindungslimits</span>
|
||||
<span class="sub">+@data.RejectedLast24Hours.ToString("N0") in 24 h · Verbindungslimit erreicht</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -111,7 +113,7 @@
|
||||
var target = Formatting.Target(trapEvent.Target);
|
||||
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
||||
var bytes = trapEvent.BytesSent.ToString("N0");
|
||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false">
|
||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
|
||||
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
||||
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
||||
<td class="c-origin" title="@Origin(trapEvent)">
|
||||
@@ -131,12 +133,12 @@
|
||||
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
|
||||
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
|
||||
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
|
||||
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @trapEvent.Outcome</div>
|
||||
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
|
||||
</td>
|
||||
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
||||
<td class="c-duration num">@duration</td>
|
||||
<td class="c-bytes num">@bytes</td>
|
||||
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@trapEvent.Outcome</span></td>
|
||||
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@OutcomeLabel(trapEvent.Outcome)</span></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
@@ -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)));
|
||||
|
||||
|
||||
@@ -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<CatchListResult> 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<TopResult> 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)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
public static class McpArgumentCheck
|
||||
{
|
||||
public static string? FindProblem(JsonElement inputSchema, IReadOnlyDictionary<string, JsonElement>? 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<string>();
|
||||
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()))})"
|
||||
: "";
|
||||
}
|
||||
@@ -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<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
||||
@@ -34,11 +43,39 @@ public static class McpExtensions
|
||||
options.ServerInstructions = Instructions;
|
||||
})
|
||||
.WithHttpTransport(options => options.Stateless = true)
|
||||
.WithTools<FlypaperTools>();
|
||||
.WithTools<FlypaperTools>(ToolJsonOptions)
|
||||
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
|
||||
{
|
||||
var tool = context.Params?.Name;
|
||||
var logger = context.Services?.GetRequiredService<ILoggerFactory>().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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user