Add read-only MCP server with token access
Build and deploy / build (push) Successful in 1m31s
Build and deploy / deploy (push) Successful in 20s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 13:34:16 +01:00
1 parent b8328f6998
commit 49a8fa1154
34 files changed
+1625

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
using System.ComponentModel;
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<StatsResult> 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<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("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<TopResult> Top(
[Description("What to rank: ips, countries, providers, targets or 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,
"user_agents" => TopDimension.UserAgents,
_ => throw new McpException("dimension must be one of ips, countries, providers, targets, 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<CatchListResult> 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<IpLookupResult> 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.Ip,
record.CountryCode,
CountryNames.Display(record.CountryCode, record.Country),
record.City,
Asn(record.Asn),
record.Provider,
record.Target,
record.UserAgent);
}
+59
View File
@@ -0,0 +1,59 @@
using Flypaper.Storage.Settings;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using ModelContextProtocol.Protocol;
namespace Flypaper.Web.Mcp;
public static class McpExtensions
{
public const string Path = "/mcp";
private const string PolicyName = "Mcp";
private const string Instructions =
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
"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.";
public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
services.AddSingleton<McpTokenService>();
services.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, McpTokenAuthenticationHandler>(McpTokenAuthenticationHandler.SchemeName, null);
services.AddAuthorizationBuilder()
.AddPolicy(PolicyName, policy => policy
.AddAuthenticationSchemes(McpTokenAuthenticationHandler.SchemeName)
.RequireAuthenticatedUser());
services.AddMcpServer(options =>
{
options.ServerInfo = new Implementation { Name = "flypaper", Version = AppVersion.Current };
options.ServerInstructions = Instructions;
})
.WithHttpTransport(options => options.Stateless = true)
.WithTools<FlypaperTools>();
return services;
}
public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app)
{
app.MapMcp(Path).RequireAuthorization(PolicyName);
app.MapPost("/mcp-tokens/{id:int}/revoke", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
{
if (!await antiforgery.IsRequestValidAsync(context))
{
return Results.BadRequest();
}
await store.RevokeAsync(id, context.RequestAborted);
return Results.LocalRedirect("/settings?mcp=revoked");
});
return app;
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace Flypaper.Web.Mcp;
public sealed class McpOptions
{
public const string SectionName = "Flypaper:Mcp";
public string? Token { get; set; }
}
+51
View File
@@ -0,0 +1,51 @@
namespace Flypaper.Web.Mcp;
public sealed record CatchItem(
long Id,
DateTime StartedAt,
DateTime EndedAt,
double DurationSeconds,
long BytesSent,
string Outcome,
string Ip,
string? CountryCode,
string? Country,
string? City,
string? Asn,
string? Provider,
string? Target,
string? UserAgent);
public sealed record StatsResult(
string Period,
DateTime? Since,
int Catches,
int Rejected,
int UniqueIps,
double TotalHoldSeconds,
double AverageHoldSeconds,
int ActiveTraps,
CatchItem? LongestCatch);
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
public sealed record TopResult(string Dimension, string Period, IReadOnlyList<TopResultItem> Items);
public sealed record IpLookupResult(
string Ip,
bool Known,
string? CountryCode,
string? Country,
string? City,
string? Asn,
string? Provider,
int Catches,
int Rejected,
double TotalHoldSeconds,
long TotalBytesSent,
DateTime? FirstSeen,
DateTime? LastSeen,
IReadOnlyList<CatchItem> Events,
int EventsOmitted);
@@ -0,0 +1,39 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace Flypaper.Web.Mcp;
public sealed class McpTokenAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
McpTokenService tokens) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "McpToken";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var header = Request.Headers.Authorization.ToString();
if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.NoResult();
}
if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
{
return AuthenticateResult.Fail("Invalid MCP token.");
}
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
Response.Headers.WWWAuthenticate = "Bearer";
await Response.WriteAsJsonAsync(new { error = "invalid_token" });
}
}
+39
View File
@@ -0,0 +1,39 @@
using System.Security.Cryptography;
using System.Text;
using Flypaper.Storage.Settings;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
namespace Flypaper.Web.Mcp;
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
{
private const string Prefix = "fpm_";
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
{
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
await store.CreateAsync(name, Hash(token), ct);
return token;
}
public async Task<bool> ValidateAsync(string? token, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(token))
{
return false;
}
if (UsesEnvironmentToken
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
{
return true;
}
return await store.UseAsync(Hash(token), ct) is not null;
}
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
}