114 lines
4.6 KiB
C#
114 lines
4.6 KiB
C#
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
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;
|
|
|
|
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 WebApplicationFactory<Program> _factory;
|
|
|
|
public McpEndpointTests()
|
|
{
|
|
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
|
{
|
|
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
|
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Rejects_requests_without_token()
|
|
{
|
|
using var client = _factory.CreateClient();
|
|
|
|
var response = await client.SendAsync(Rpc("tools/list", token: null));
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
|
response.Headers.WwwAuthenticate.ToString().ShouldStartWith("Bearer");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Rejects_requests_with_wrong_token()
|
|
{
|
|
using var client = _factory.CreateClient();
|
|
await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("real");
|
|
|
|
var response = await client.SendAsync(Rpc("tools/list", token: "fpm_wrong"));
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Serves_initialize_tools_list_and_get_stats_with_valid_token()
|
|
{
|
|
using var client = _factory.CreateClient();
|
|
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
|
|
|
var initialize = await ReadAsync(await client.SendAsync(Rpc("initialize", token, new
|
|
{
|
|
protocolVersion = "2025-06-18",
|
|
capabilities = new { },
|
|
clientInfo = new { name = "test", version = "1.0" }
|
|
})));
|
|
initialize.GetProperty("result").GetProperty("serverInfo").GetProperty("name").GetString().ShouldBe("flypaper");
|
|
|
|
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
|
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
|
|
listed.Select(t => t.GetProperty("name").GetString())
|
|
.ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
|
|
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
|
|
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
|
|
|
|
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("period").GetString().ShouldBe("all");
|
|
}
|
|
|
|
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 request = new HttpRequestMessage(HttpMethod.Post, "/mcp")
|
|
{
|
|
Content = new StringContent(body, Encoding.UTF8, "application/json")
|
|
};
|
|
request.Headers.Accept.ParseAdd("application/json");
|
|
request.Headers.Accept.ParseAdd("text/event-stream");
|
|
request.Headers.Add("MCP-Protocol-Version", "2025-06-18");
|
|
if (token is not null)
|
|
{
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
|
}
|
|
|
|
return request;
|
|
}
|
|
|
|
private static async Task<JsonElement> ReadAsync(HttpResponseMessage response)
|
|
{
|
|
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var text = await response.Content.ReadAsStringAsync();
|
|
var json = response.Content.Headers.ContentType?.MediaType == "text/event-stream"
|
|
? string.Join("", text.Split('\n').Where(l => l.StartsWith("data:", StringComparison.Ordinal)).Select(l => l[5..].Trim()))
|
|
: text;
|
|
return JsonDocument.Parse(json).RootElement.Clone();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_factory.Dispose();
|
|
SqliteConnection.ClearAllPools();
|
|
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
|
{
|
|
File.Delete(_dbPath + suffix);
|
|
}
|
|
}
|
|
}
|