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,23 @@ All notable changes to Flypaper are documented in this file. The format follows
|
|||||||
|
|
||||||
## [Unreleased]
|
## [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
|
## [0.3.1] - 2026-11-15
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ public sealed record DashboardData(
|
|||||||
int TotalCatches,
|
int TotalCatches,
|
||||||
int CatchesLast24Hours,
|
int CatchesLast24Hours,
|
||||||
int Rejected,
|
int Rejected,
|
||||||
|
int RejectedLast24Hours,
|
||||||
int UniqueIps,
|
int UniqueIps,
|
||||||
TimeSpan TotalHoldTime,
|
TimeSpan TotalHoldTime,
|
||||||
IReadOnlyList<TrapEventEntity> Recent,
|
IReadOnlyList<TrapEventEntity> Recent,
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
|||||||
await catches.CountAsync(ct),
|
await catches.CountAsync(ct),
|
||||||
await catches.CountAsync(e => e.StartedAt >= since, 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, ct),
|
||||||
|
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct),
|
||||||
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
||||||
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
|
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
|
||||||
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
|
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
@page "/"
|
@page "/"
|
||||||
@using Flypaper.Core.Abstractions
|
@using Flypaper.Core.Abstractions
|
||||||
|
@using Flypaper.Core.Models
|
||||||
@using Flypaper.Http
|
@using Flypaper.Http
|
||||||
@using Microsoft.Extensions.Options
|
@using Microsoft.Extensions.Options
|
||||||
@using Flypaper.Storage.Dashboard
|
@using Flypaper.Storage.Dashboard
|
||||||
@@ -40,11 +41,12 @@
|
|||||||
<div class="metric">
|
<div class="metric">
|
||||||
<span class="label">Haltezeit gesamt</span>
|
<span class="label">Haltezeit gesamt</span>
|
||||||
<span class="value">@Formatting.Duration(data.TotalHoldTime)</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>
|
||||||
<div class="metric">
|
<div class="metric">
|
||||||
<span class="label">Abgelehnt</span>
|
<span class="label">Abgelehnt</span>
|
||||||
<span class="value">@data.Rejected.ToString("N0")</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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -111,7 +113,7 @@
|
|||||||
var target = Formatting.Target(trapEvent.Target);
|
var target = Formatting.Target(trapEvent.Target);
|
||||||
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
||||||
var bytes = trapEvent.BytesSent.ToString("N0");
|
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-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-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
||||||
<td class="c-origin" title="@Origin(trapEvent)">
|
<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-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-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-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>
|
||||||
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
||||||
<td class="c-duration num">@duration</td>
|
<td class="c-duration num">@duration</td>
|
||||||
<td class="c-bytes num">@bytes</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>
|
</tr>
|
||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -166,6 +168,15 @@
|
|||||||
new("targets", "Ziele", "Ziel", data.TopTargets, KeyFormatter: Formatting.Target)
|
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) =>
|
private static string Origin(TrapEventEntity trapEvent) =>
|
||||||
string.Join(", ", new[] { trapEvent.City, CountryNames.Display(trapEvent.CountryCode, trapEvent.Country) }.Where(part => !string.IsNullOrEmpty(part)));
|
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;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
@@ -39,7 +40,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
public async Task<CatchListResult> ListCatches(
|
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 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("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("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("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("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)]
|
[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.")]
|
[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(
|
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(PeriodDescription)] string period = "24h",
|
||||||
[Description("Number of entries, 1 to 500.")] int limit = 10,
|
[Description("Number of entries, 1 to 500.")] int limit = 10,
|
||||||
CancellationToken ct = default)
|
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 Flypaper.Storage.Settings;
|
||||||
using Microsoft.AspNetCore.Antiforgery;
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using ModelContextProtocol;
|
||||||
using ModelContextProtocol.Protocol;
|
using ModelContextProtocol.Protocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
|
||||||
namespace Flypaper.Web.Mcp;
|
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 " +
|
"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.";
|
"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)
|
public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
||||||
@@ -34,11 +43,39 @@ public static class McpExtensions
|
|||||||
options.ServerInstructions = Instructions;
|
options.ServerInstructions = Instructions;
|
||||||
})
|
})
|
||||||
.WithHttpTransport(options => options.Stateless = true)
|
.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;
|
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)
|
public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app)
|
||||||
{
|
{
|
||||||
app.MapMcp(Path).RequireAuthorization(PolicyName);
|
app.MapMcp(Path).RequireAuthorization(PolicyName);
|
||||||
|
|||||||
@@ -441,9 +441,21 @@ tr.open .clip {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.outcome.rejected {
|
.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);
|
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) {
|
@media (max-width: 600px) {
|
||||||
.clip {
|
.clip {
|
||||||
max-width: 180px;
|
max-width: 180px;
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ using System.Text;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Flypaper.Web.Mcp;
|
using Flypaper.Web.Mcp;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.Data.Sqlite;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Shouldly;
|
using Shouldly;
|
||||||
|
|
||||||
@@ -12,14 +11,14 @@ namespace Flypaper.Tests.Mcp;
|
|||||||
|
|
||||||
public sealed class McpEndpointTests : IDisposable
|
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;
|
private readonly WebApplicationFactory<Program> _factory;
|
||||||
|
|
||||||
public McpEndpointTests()
|
public McpEndpointTests()
|
||||||
{
|
{
|
||||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
_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");
|
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 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");
|
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("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)
|
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 { } });
|
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()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
_factory.Dispose();
|
_factory.Dispose();
|
||||||
SqliteConnection.ClearAllPools();
|
_data.Dispose();
|
||||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
|
||||||
{
|
|
||||||
File.Delete(_dbPath + suffix);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,7 @@ internal sealed class McpTestData : IDisposable
|
|||||||
|
|
||||||
public McpTestData()
|
public McpTestData()
|
||||||
{
|
{
|
||||||
Factory = new TestDbContextFactory($"Data Source={_dbPath}");
|
Factory = new TestDbContextFactory(ConnectionString);
|
||||||
using var db = Factory.CreateDbContext();
|
using var db = Factory.CreateDbContext();
|
||||||
db.Database.Migrate();
|
db.Database.Migrate();
|
||||||
|
|
||||||
@@ -30,6 +30,8 @@ internal sealed class McpTestData : IDisposable
|
|||||||
|
|
||||||
public IDbContextFactory<FlypaperDbContext> Factory { get; }
|
public IDbContextFactory<FlypaperDbContext> Factory { get; }
|
||||||
|
|
||||||
|
public string ConnectionString => $"Data Source={_dbPath}";
|
||||||
|
|
||||||
private static void Add(
|
private static void Add(
|
||||||
FlypaperDbContext db,
|
FlypaperDbContext db,
|
||||||
string ip,
|
string ip,
|
||||||
|
|||||||
Reference in new issue
Block a user