using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Net; using Flypaper.Core.Abstractions; using Flypaper.Storage.Queries; using Flypaper.Web.Components.Shared; using ModelContextProtocol; using ModelContextProtocol.Server; namespace Flypaper.Web.Mcp; [McpServerToolType] public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, TimeProvider timeProvider) { private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 1h, 24h, 7d; or all."; [McpServerTool(Name = "get_stats", Title = "Trap statistics", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Summary of the tarpit for a time window: number of catches and rejected connections, unique IPs, total and average hold time, traps active right now and the longest catch.")] public async Task GetStats( [Description(PeriodDescription)] string period = "24h", CancellationToken ct = default) { var since = Since(period); var stats = await queries.GetStatsAsync(since, ct); return new StatsResult( Normalize(period), since, stats.Catches, stats.Rejected, stats.UniqueIps, Round(stats.TotalHoldSeconds), Round(stats.AverageHoldSeconds), governor.ActiveConnections, stats.Longest is null ? null : ToItem(stats.Longest)); } [McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected).")] 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("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, [Description("Maximum number of events, 1 to 500.")] int limit = 50, CancellationToken ct = default) { var filter = new CatchFilter( ParseTime(since, nameof(since)), ParseTime(until, nameof(until)), country, provider, ip is null ? null : ParseIp(ip), target_contains, limit); var catches = (await queries.ListAsync(filter, ct)).Select(ToItem).ToList(); return new CatchListResult(catches.Count, catches); } [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 by: ips, countries, providers, targets, strategies or user_agents.")] [AllowedValues("ips", "countries", "providers", "targets", "strategies", "user_agents")] string dimension, [Description(PeriodDescription)] string period = "24h", [Description("Number of entries, 1 to 500.")] int limit = 10, CancellationToken ct = default) { var parsed = dimension.Trim().ToLowerInvariant() switch { "ips" => TopDimension.Ips, "countries" => TopDimension.Countries, "providers" => TopDimension.Providers, "targets" => TopDimension.Targets, "strategies" => TopDimension.Strategies, "user_agents" => TopDimension.UserAgents, _ => throw new McpException("dimension must be one of ips, countries, providers, targets, strategies, user_agents.") }; var items = await queries.TopAsync(parsed, Since(period), limit, ct); return new TopResult( dimension.Trim().ToLowerInvariant(), Normalize(period), items.Select(i => new TopResultItem( i.Key, parsed == TopDimension.Countries ? CountryNames.Display(i.Key, i.Label) : i.Label, i.Catches, Round(i.TotalHoldSeconds))).ToList()); } [McpServerTool(Name = "longest_catches", Title = "Longest catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("The catches that held a bot the longest within a time window, longest first.")] public async Task LongestCatches( [Description(PeriodDescription)] string period = "7d", [Description("Number of catches, 1 to 500.")] int limit = 10, CancellationToken ct = default) { var catches = (await queries.LongestAsync(Since(period), limit, ct)).Select(ToItem).ToList(); return new CatchListResult(catches.Count, catches); } [McpServerTool(Name = "lookup_ip", Title = "Look up an IP", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Everything Flypaper has stored about one IP address: origin, network provider, totals, first and last seen, and its events (newest first, at most 500). Uses only local data.")] public async Task LookupIp( [Description("IPv4 or IPv6 address.")] string ip, CancellationToken ct = default) { var address = ParseIp(ip); var profile = await queries.LookupIpAsync(address, ct); if (profile is null) { return new IpLookupResult(address, false, null, null, null, null, null, 0, 0, 0, 0, null, null, [], 0); } return new IpLookupResult( profile.Ip, true, profile.CountryCode, CountryNames.Display(profile.CountryCode, profile.Country), profile.City, Asn(profile.Asn), profile.Provider, profile.Catches, profile.Rejected, Round(profile.TotalHoldSeconds), profile.TotalBytesSent, profile.FirstSeen, profile.LastSeen, profile.Events.Select(ToItem).ToList(), profile.EventsOmitted); } private DateTime? Since(string? period) { if (!QueryPeriod.TryParse(period, out var span)) { throw new McpException($"Invalid period '{period}'. {PeriodDescription}"); } return span is { } window ? timeProvider.GetUtcNow().UtcDateTime - window : null; } private static string Normalize(string? period) => string.IsNullOrWhiteSpace(period) ? "all" : period.Trim().ToLowerInvariant(); private static DateTime? ParseTime(string? value, string name) { if (string.IsNullOrWhiteSpace(value)) { return null; } return DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time.UtcDateTime : throw new McpException($"{name} must be an ISO 8601 time, e.g. 2026-11-15T08:00:00Z."); } private static string ParseIp(string value) => IPAddress.TryParse(value.Trim(), out var address) ? (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString() : throw new McpException($"'{value}' is not an IP address."); private static string? Asn(long? asn) => asn is null ? null : $"AS{asn.Value.ToString(CultureInfo.InvariantCulture)}"; private static double Round(double seconds) => Math.Round(seconds, 3); private static CatchItem ToItem(CatchRecord record) => new( record.Id, record.StartedAt, record.EndedAt, Round(record.DurationSeconds), record.BytesSent, record.Outcome.ToString(), record.Strategy, record.Ip, record.CountryCode, CountryNames.Display(record.CountryCode, record.Country), record.City, Asn(record.Asn), record.Provider, record.Target, record.UserAgent); }